Sat Apr 26 2014 22:01:27

Asterisk developer's documentation


app_record.c
Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2005, Digium, Inc.
00005  *
00006  * Matthew Fredrickson <creslin@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Trivial application to record a sound file
00022  *
00023  * \author Matthew Fredrickson <creslin@digium.com>
00024  *
00025  * \ingroup applications
00026  */
00027 
00028 /*** MODULEINFO
00029    <support_level>core</support_level>
00030  ***/
00031  
00032 #include "asterisk.h"
00033 
00034 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 376014 $")
00035 
00036 #include "asterisk/file.h"
00037 #include "asterisk/pbx.h"
00038 #include "asterisk/module.h"
00039 #include "asterisk/app.h"
00040 #include "asterisk/channel.h"
00041 #include "asterisk/dsp.h"  /* use dsp routines for silence detection */
00042 
00043 /*** DOCUMENTATION
00044    <application name="Record" language="en_US">
00045       <synopsis>
00046          Record to a file.
00047       </synopsis>
00048       <syntax>
00049          <parameter name="filename" required="true" argsep=".">
00050             <argument name="filename" required="true" />
00051             <argument name="format" required="true">
00052                <para>Is the format of the file type to be recorded (wav, gsm, etc).</para>
00053             </argument>
00054          </parameter>
00055          <parameter name="silence">
00056             <para>Is the number of seconds of silence to allow before returning.</para>
00057          </parameter>
00058          <parameter name="maxduration">
00059             <para>Is the maximum recording duration in seconds. If missing
00060             or 0 there is no maximum.</para>
00061          </parameter>
00062          <parameter name="options">
00063             <optionlist>
00064                <option name="a">
00065                   <para>Append to existing recording rather than replacing.</para>
00066                </option>
00067                <option name="n">
00068                   <para>Do not answer, but record anyway if line not yet answered.</para>
00069                </option>
00070                <option name="q">
00071                   <para>quiet (do not play a beep tone).</para>
00072                </option>
00073                <option name="s">
00074                   <para>skip recording if the line is not yet answered.</para>
00075                </option>
00076                <option name="t">
00077                   <para>use alternate '*' terminator key (DTMF) instead of default '#'</para>
00078                </option>
00079                <option name="x">
00080                   <para>Ignore all terminator keys (DTMF) and keep recording until hangup.</para>
00081                </option>
00082                <option name="k">
00083                        <para>Keep recorded file upon hangup.</para>
00084                </option>
00085                <option name="y">
00086                        <para>Terminate recording if *any* DTMF digit is received.</para>
00087                </option>
00088             </optionlist>
00089          </parameter>
00090       </syntax>
00091       <description>
00092          <para>If filename contains <literal>%d</literal>, these characters will be replaced with a number
00093          incremented by one each time the file is recorded.
00094          Use <astcli>core show file formats</astcli> to see the available formats on your system
00095          User can press <literal>#</literal> to terminate the recording and continue to the next priority.
00096          If the user hangs up during a recording, all data will be lost and the application will terminate.</para>
00097          <variablelist>
00098             <variable name="RECORDED_FILE">
00099                <para>Will be set to the final filename of the recording.</para>
00100             </variable>
00101             <variable name="RECORD_STATUS">
00102                <para>This is the final status of the command</para>
00103                <value name="DTMF">A terminating DTMF was received ('#' or '*', depending upon option 't')</value>
00104                <value name="SILENCE">The maximum silence occurred in the recording.</value>
00105                <value name="SKIP">The line was not yet answered and the 's' option was specified.</value>
00106                <value name="TIMEOUT">The maximum length was reached.</value>
00107                <value name="HANGUP">The channel was hung up.</value>
00108                <value name="ERROR">An unrecoverable error occurred, which resulted in a WARNING to the logs.</value>
00109             </variable>
00110          </variablelist>
00111       </description>
00112    </application>
00113 
00114  ***/
00115 
00116 static char *app = "Record";
00117 
00118 enum {
00119    OPTION_APPEND = (1 << 0),
00120    OPTION_NOANSWER = (1 << 1),
00121    OPTION_QUIET = (1 << 2),
00122    OPTION_SKIP = (1 << 3),
00123    OPTION_STAR_TERMINATE = (1 << 4),
00124    OPTION_IGNORE_TERMINATE = (1 << 5),
00125    OPTION_KEEP = (1 << 6),
00126    FLAG_HAS_PERCENT = (1 << 7),
00127    OPTION_ANY_TERMINATE = (1 << 8),
00128 };
00129 
00130 AST_APP_OPTIONS(app_opts,{
00131    AST_APP_OPTION('a', OPTION_APPEND),
00132    AST_APP_OPTION('k', OPTION_KEEP),   
00133    AST_APP_OPTION('n', OPTION_NOANSWER),
00134    AST_APP_OPTION('q', OPTION_QUIET),
00135    AST_APP_OPTION('s', OPTION_SKIP),
00136    AST_APP_OPTION('t', OPTION_STAR_TERMINATE),
00137    AST_APP_OPTION('y', OPTION_ANY_TERMINATE),
00138    AST_APP_OPTION('x', OPTION_IGNORE_TERMINATE),
00139 });
00140 
00141 static int record_exec(struct ast_channel *chan, const char *data)
00142 {
00143    int res = 0;
00144    int count = 0;
00145    char *ext = NULL, *opts[0];
00146    char *parse, *dir, *file;
00147    int i = 0;
00148    char tmp[256];
00149 
00150    struct ast_filestream *s = NULL;
00151    struct ast_frame *f = NULL;
00152    
00153    struct ast_dsp *sildet = NULL;      /* silence detector dsp */
00154    int totalsilence = 0;
00155    int dspsilence = 0;
00156    int silence = 0;     /* amount of silence to allow */
00157    int gotsilence = 0;     /* did we timeout for silence? */
00158    int maxduration = 0;    /* max duration of recording in milliseconds */
00159    int gottimeout = 0;     /* did we timeout for maxduration exceeded? */
00160    int terminator = '#';
00161    struct ast_format rfmt;
00162    int ioflags;
00163    struct ast_silence_generator *silgen = NULL;
00164    struct ast_flags flags = { 0, };
00165    AST_DECLARE_APP_ARGS(args,
00166       AST_APP_ARG(filename);
00167       AST_APP_ARG(silence);
00168       AST_APP_ARG(maxduration);
00169       AST_APP_ARG(options);
00170    );
00171    int ms;
00172    struct timeval start;
00173 
00174    ast_format_clear(&rfmt);
00175 
00176    /* The next few lines of code parse out the filename and header from the input string */
00177    if (ast_strlen_zero(data)) { /* no data implies no filename or anything is present */
00178       ast_log(LOG_WARNING, "Record requires an argument (filename)\n");
00179       pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
00180       return -1;
00181    }
00182 
00183    parse = ast_strdupa(data);
00184    AST_STANDARD_APP_ARGS(args, parse);
00185    if (args.argc == 4)
00186       ast_app_parse_options(app_opts, &flags, opts, args.options);
00187 
00188    if (!ast_strlen_zero(args.filename)) {
00189       if (strstr(args.filename, "%d"))
00190          ast_set_flag(&flags, FLAG_HAS_PERCENT);
00191       ext = strrchr(args.filename, '.'); /* to support filename with a . in the filename, not format */
00192       if (!ext)
00193          ext = strchr(args.filename, ':');
00194       if (ext) {
00195          *ext = '\0';
00196          ext++;
00197       }
00198    }
00199    if (!ext) {
00200       ast_log(LOG_WARNING, "No extension specified to filename!\n");
00201       pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
00202       return -1;
00203    }
00204    if (args.silence) {
00205       if ((sscanf(args.silence, "%30d", &i) == 1) && (i > -1)) {
00206          silence = i * 1000;
00207       } else if (!ast_strlen_zero(args.silence)) {
00208          ast_log(LOG_WARNING, "'%s' is not a valid silence duration\n", args.silence);
00209       }
00210    }
00211    
00212    if (args.maxduration) {
00213       if ((sscanf(args.maxduration, "%30d", &i) == 1) && (i > -1))
00214          /* Convert duration to milliseconds */
00215          maxduration = i * 1000;
00216       else if (!ast_strlen_zero(args.maxduration))
00217          ast_log(LOG_WARNING, "'%s' is not a valid maximum duration\n", args.maxduration);
00218    }
00219 
00220    if (ast_test_flag(&flags, OPTION_STAR_TERMINATE))
00221       terminator = '*';
00222    if (ast_test_flag(&flags, OPTION_IGNORE_TERMINATE))
00223       terminator = '\0';
00224 
00225    /* done parsing */
00226 
00227    /* these are to allow the use of the %d in the config file for a wild card of sort to
00228      create a new file with the inputed name scheme */
00229    if (ast_test_flag(&flags, FLAG_HAS_PERCENT)) {
00230       AST_DECLARE_APP_ARGS(fname,
00231          AST_APP_ARG(piece)[100];
00232       );
00233       char *tmp2 = ast_strdupa(args.filename);
00234       char countstring[15];
00235       int idx;
00236 
00237       /* Separate each piece out by the format specifier */
00238       AST_NONSTANDARD_APP_ARGS(fname, tmp2, '%');
00239       do {
00240          int tmplen;
00241          /* First piece has no leading percent, so it's copied verbatim */
00242          ast_copy_string(tmp, fname.piece[0], sizeof(tmp));
00243          tmplen = strlen(tmp);
00244          for (idx = 1; idx < fname.argc; idx++) {
00245             if (fname.piece[idx][0] == 'd') {
00246                /* Substitute the count */
00247                snprintf(countstring, sizeof(countstring), "%d", count);
00248                ast_copy_string(tmp + tmplen, countstring, sizeof(tmp) - tmplen);
00249                tmplen += strlen(countstring);
00250             } else if (tmplen + 2 < sizeof(tmp)) {
00251                /* Unknown format specifier - just copy it verbatim */
00252                tmp[tmplen++] = '%';
00253                tmp[tmplen++] = fname.piece[idx][0];
00254             }
00255             /* Copy the remaining portion of the piece */
00256             ast_copy_string(tmp + tmplen, &(fname.piece[idx][1]), sizeof(tmp) - tmplen);
00257          }
00258          count++;
00259       } while (ast_fileexists(tmp, ext, ast_channel_language(chan)) > 0);
00260       pbx_builtin_setvar_helper(chan, "RECORDED_FILE", tmp);
00261    } else
00262       ast_copy_string(tmp, args.filename, sizeof(tmp));
00263    /* end of routine mentioned */
00264 
00265    if (ast_channel_state(chan) != AST_STATE_UP) {
00266       if (ast_test_flag(&flags, OPTION_SKIP)) {
00267          /* At the user's option, skip if the line is not up */
00268          pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "SKIP");
00269          return 0;
00270       } else if (!ast_test_flag(&flags, OPTION_NOANSWER)) {
00271          /* Otherwise answer unless we're supposed to record while on-hook */
00272          res = ast_answer(chan);
00273       }
00274    }
00275 
00276    if (res) {
00277       ast_log(LOG_WARNING, "Could not answer channel '%s'\n", ast_channel_name(chan));
00278       pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
00279       goto out;
00280    }
00281 
00282    if (!ast_test_flag(&flags, OPTION_QUIET)) {
00283       /* Some code to play a nice little beep to signify the start of the record operation */
00284       res = ast_streamfile(chan, "beep", ast_channel_language(chan));
00285       if (!res) {
00286          res = ast_waitstream(chan, "");
00287       } else {
00288          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", ast_channel_name(chan));
00289       }
00290       ast_stopstream(chan);
00291    }
00292 
00293    /* The end of beep code.  Now the recording starts */
00294 
00295    if (silence > 0) {
00296       ast_format_copy(&rfmt, ast_channel_readformat(chan));
00297       res = ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
00298       if (res < 0) {
00299          ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
00300          pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
00301          return -1;
00302       }
00303       sildet = ast_dsp_new();
00304       if (!sildet) {
00305          ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
00306          pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
00307          return -1;
00308       }
00309       ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
00310    } 
00311 
00312    /* Create the directory if it does not exist. */
00313    dir = ast_strdupa(tmp);
00314    if ((file = strrchr(dir, '/')))
00315       *file++ = '\0';
00316    ast_mkdir (dir, 0777);
00317 
00318    ioflags = ast_test_flag(&flags, OPTION_APPEND) ? O_CREAT|O_APPEND|O_WRONLY : O_CREAT|O_TRUNC|O_WRONLY;
00319    s = ast_writefile(tmp, ext, NULL, ioflags, 0, AST_FILE_MODE);
00320 
00321    if (!s) {
00322       ast_log(LOG_WARNING, "Could not create file %s\n", args.filename);
00323       pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
00324       goto out;
00325    }
00326 
00327    if (ast_opt_transmit_silence)
00328       silgen = ast_channel_start_silence_generator(chan);
00329 
00330    /* Request a video update */
00331    ast_indicate(chan, AST_CONTROL_VIDUPDATE);
00332 
00333    if (maxduration <= 0)
00334       maxduration = -1;
00335 
00336    start = ast_tvnow();
00337    while ((ms = ast_remaining_ms(start, maxduration))) {
00338       ms = ast_waitfor(chan, ms);
00339       if (ms < 0) {
00340          break;
00341       }
00342 
00343       if (maxduration > 0 && ms == 0) {
00344          break;
00345       }
00346 
00347       f = ast_read(chan);
00348       if (!f) {
00349          res = -1;
00350          break;
00351       }
00352       if (f->frametype == AST_FRAME_VOICE) {
00353          res = ast_writestream(s, f);
00354 
00355          if (res) {
00356             ast_log(LOG_WARNING, "Problem writing frame\n");
00357             ast_frfree(f);
00358             pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
00359             break;
00360          }
00361 
00362          if (silence > 0) {
00363             dspsilence = 0;
00364             ast_dsp_silence(sildet, f, &dspsilence);
00365             if (dspsilence) {
00366                totalsilence = dspsilence;
00367             } else {
00368                totalsilence = 0;
00369             }
00370             if (totalsilence > silence) {
00371                /* Ended happily with silence */
00372                ast_frfree(f);
00373                gotsilence = 1;
00374                pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "SILENCE");
00375                break;
00376             }
00377          }
00378       } else if (f->frametype == AST_FRAME_VIDEO) {
00379          res = ast_writestream(s, f);
00380 
00381          if (res) {
00382             ast_log(LOG_WARNING, "Problem writing frame\n");
00383             pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
00384             ast_frfree(f);
00385             break;
00386          }
00387       } else if ((f->frametype == AST_FRAME_DTMF) &&
00388             ((f->subclass.integer == terminator) ||
00389              (ast_test_flag(&flags, OPTION_ANY_TERMINATE)))) {
00390          ast_frfree(f);
00391          pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "DTMF");
00392          break;
00393       }
00394       ast_frfree(f);
00395    }
00396 
00397    if (maxduration > 0 && !ms) {
00398       gottimeout = 1;
00399       pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "TIMEOUT");
00400    }
00401 
00402    if (!f) {
00403       ast_debug(1, "Got hangup\n");
00404       res = -1;
00405       pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "HANGUP");
00406       if (!ast_test_flag(&flags, OPTION_KEEP)) {
00407          ast_filedelete(args.filename, NULL);
00408       }
00409    }
00410 
00411    if (gotsilence) {
00412       ast_stream_rewind(s, silence - 1000);
00413       ast_truncstream(s);
00414    } else if (!gottimeout) {
00415       /* Strip off the last 1/4 second of it */
00416       ast_stream_rewind(s, 250);
00417       ast_truncstream(s);
00418    }
00419    ast_closestream(s);
00420 
00421    if (silgen)
00422       ast_channel_stop_silence_generator(chan, silgen);
00423 
00424 out:
00425    if ((silence > 0) && rfmt.id) {
00426       res = ast_set_read_format(chan, &rfmt);
00427       if (res) {
00428          ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(chan));
00429       }
00430    }
00431 
00432    if (sildet) {
00433       ast_dsp_free(sildet);
00434    }
00435    return res;
00436 }
00437 
00438 static int unload_module(void)
00439 {
00440    return ast_unregister_application(app);
00441 }
00442 
00443 static int load_module(void)
00444 {
00445    return ast_register_application_xml(app, record_exec);
00446 }
00447 
00448 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Trivial Record Application");