app_record.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. /*! \file
  19. *
  20. * \brief Trivial application to record a sound file
  21. *
  22. * \author Matthew Fredrickson <creslin@digium.com>
  23. *
  24. * \ingroup applications
  25. */
  26. /*** MODULEINFO
  27. <support_level>core</support_level>
  28. ***/
  29. #include "asterisk.h"
  30. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  31. #include "asterisk/file.h"
  32. #include "asterisk/pbx.h"
  33. #include "asterisk/module.h"
  34. #include "asterisk/app.h"
  35. #include "asterisk/channel.h"
  36. #include "asterisk/dsp.h" /* use dsp routines for silence detection */
  37. #include "asterisk/format_cache.h"
  38. /*** DOCUMENTATION
  39. <application name="Record" language="en_US">
  40. <synopsis>
  41. Record to a file.
  42. </synopsis>
  43. <syntax>
  44. <parameter name="filename" required="true" argsep=".">
  45. <argument name="filename" required="true" />
  46. <argument name="format" required="true">
  47. <para>Is the format of the file type to be recorded (wav, gsm, etc).</para>
  48. </argument>
  49. </parameter>
  50. <parameter name="silence">
  51. <para>Is the number of seconds of silence to allow before returning.</para>
  52. </parameter>
  53. <parameter name="maxduration">
  54. <para>Is the maximum recording duration in seconds. If missing
  55. or 0 there is no maximum.</para>
  56. </parameter>
  57. <parameter name="options">
  58. <optionlist>
  59. <option name="a">
  60. <para>Append to existing recording rather than replacing.</para>
  61. </option>
  62. <option name="n">
  63. <para>Do not answer, but record anyway if line not yet answered.</para>
  64. </option>
  65. <option name="o">
  66. <para>Exit when 0 is pressed, setting the variable <variable>RECORD_STATUS</variable>
  67. to <literal>OPERATOR</literal> instead of <literal>DTMF</literal></para>
  68. </option>
  69. <option name="q">
  70. <para>quiet (do not play a beep tone).</para>
  71. </option>
  72. <option name="s">
  73. <para>skip recording if the line is not yet answered.</para>
  74. </option>
  75. <option name="t">
  76. <para>use alternate '*' terminator key (DTMF) instead of default '#'</para>
  77. </option>
  78. <option name="x">
  79. <para>Ignore all terminator keys (DTMF) and keep recording until hangup.</para>
  80. </option>
  81. <option name="k">
  82. <para>Keep recorded file upon hangup.</para>
  83. </option>
  84. <option name="y">
  85. <para>Terminate recording if *any* DTMF digit is received.</para>
  86. </option>
  87. </optionlist>
  88. </parameter>
  89. </syntax>
  90. <description>
  91. <para>If filename contains <literal>%d</literal>, these characters will be replaced with a number
  92. incremented by one each time the file is recorded.
  93. Use <astcli>core show file formats</astcli> to see the available formats on your system
  94. User can press <literal>#</literal> to terminate the recording and continue to the next priority.
  95. If the user hangs up during a recording, all data will be lost and the application will terminate.</para>
  96. <variablelist>
  97. <variable name="RECORDED_FILE">
  98. <para>Will be set to the final filename of the recording.</para>
  99. </variable>
  100. <variable name="RECORD_STATUS">
  101. <para>This is the final status of the command</para>
  102. <value name="DTMF">A terminating DTMF was received ('#' or '*', depending upon option 't')</value>
  103. <value name="SILENCE">The maximum silence occurred in the recording.</value>
  104. <value name="SKIP">The line was not yet answered and the 's' option was specified.</value>
  105. <value name="TIMEOUT">The maximum length was reached.</value>
  106. <value name="HANGUP">The channel was hung up.</value>
  107. <value name="ERROR">An unrecoverable error occurred, which resulted in a WARNING to the logs.</value>
  108. </variable>
  109. </variablelist>
  110. </description>
  111. </application>
  112. ***/
  113. #define OPERATOR_KEY '0'
  114. static char *app = "Record";
  115. enum {
  116. OPTION_APPEND = (1 << 0),
  117. OPTION_NOANSWER = (1 << 1),
  118. OPTION_QUIET = (1 << 2),
  119. OPTION_SKIP = (1 << 3),
  120. OPTION_STAR_TERMINATE = (1 << 4),
  121. OPTION_IGNORE_TERMINATE = (1 << 5),
  122. OPTION_KEEP = (1 << 6),
  123. FLAG_HAS_PERCENT = (1 << 7),
  124. OPTION_ANY_TERMINATE = (1 << 8),
  125. OPTION_OPERATOR_EXIT = (1 << 9),
  126. };
  127. AST_APP_OPTIONS(app_opts,{
  128. AST_APP_OPTION('a', OPTION_APPEND),
  129. AST_APP_OPTION('k', OPTION_KEEP),
  130. AST_APP_OPTION('n', OPTION_NOANSWER),
  131. AST_APP_OPTION('o', OPTION_OPERATOR_EXIT),
  132. AST_APP_OPTION('q', OPTION_QUIET),
  133. AST_APP_OPTION('s', OPTION_SKIP),
  134. AST_APP_OPTION('t', OPTION_STAR_TERMINATE),
  135. AST_APP_OPTION('y', OPTION_ANY_TERMINATE),
  136. AST_APP_OPTION('x', OPTION_IGNORE_TERMINATE),
  137. });
  138. /*!
  139. * \internal
  140. * \brief Used to determine what action to take when DTMF is received while recording
  141. * \since 13.0.0
  142. *
  143. * \param chan channel being recorded
  144. * \param flags option flags in use by the record application
  145. * \param dtmf_integer the integer value of the DTMF key received
  146. * \param terminator key currently set to be pressed for normal termination
  147. *
  148. * \retval 0 do not exit
  149. * \retval -1 do exit
  150. */
  151. static int record_dtmf_response(struct ast_channel *chan, struct ast_flags *flags, int dtmf_integer, int terminator)
  152. {
  153. if ((dtmf_integer == OPERATOR_KEY) &&
  154. (ast_test_flag(flags, OPTION_OPERATOR_EXIT))) {
  155. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "OPERATOR");
  156. return -1;
  157. }
  158. if ((dtmf_integer == terminator) ||
  159. (ast_test_flag(flags, OPTION_ANY_TERMINATE))) {
  160. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "DTMF");
  161. return -1;
  162. }
  163. return 0;
  164. }
  165. static int record_exec(struct ast_channel *chan, const char *data)
  166. {
  167. int res = 0;
  168. int count = 0;
  169. char *ext = NULL, *opts[0];
  170. char *parse, *dir, *file;
  171. int i = 0;
  172. char tmp[256];
  173. struct ast_filestream *s = NULL;
  174. struct ast_frame *f = NULL;
  175. struct ast_dsp *sildet = NULL; /* silence detector dsp */
  176. int totalsilence = 0;
  177. int dspsilence = 0;
  178. int silence = 0; /* amount of silence to allow */
  179. int gotsilence = 0; /* did we timeout for silence? */
  180. int maxduration = 0; /* max duration of recording in milliseconds */
  181. int gottimeout = 0; /* did we timeout for maxduration exceeded? */
  182. int terminator = '#';
  183. RAII_VAR(struct ast_format *, rfmt, NULL, ao2_cleanup);
  184. int ioflags;
  185. struct ast_silence_generator *silgen = NULL;
  186. struct ast_flags flags = { 0, };
  187. AST_DECLARE_APP_ARGS(args,
  188. AST_APP_ARG(filename);
  189. AST_APP_ARG(silence);
  190. AST_APP_ARG(maxduration);
  191. AST_APP_ARG(options);
  192. );
  193. int ms;
  194. struct timeval start;
  195. /* The next few lines of code parse out the filename and header from the input string */
  196. if (ast_strlen_zero(data)) { /* no data implies no filename or anything is present */
  197. ast_log(LOG_WARNING, "Record requires an argument (filename)\n");
  198. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
  199. return -1;
  200. }
  201. parse = ast_strdupa(data);
  202. AST_STANDARD_APP_ARGS(args, parse);
  203. if (args.argc == 4)
  204. ast_app_parse_options(app_opts, &flags, opts, args.options);
  205. if (!ast_strlen_zero(args.filename)) {
  206. if (strstr(args.filename, "%d"))
  207. ast_set_flag(&flags, FLAG_HAS_PERCENT);
  208. ext = strrchr(args.filename, '.'); /* to support filename with a . in the filename, not format */
  209. if (!ext)
  210. ext = strchr(args.filename, ':');
  211. if (ext) {
  212. *ext = '\0';
  213. ext++;
  214. }
  215. }
  216. if (!ext) {
  217. ast_log(LOG_WARNING, "No extension specified to filename!\n");
  218. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
  219. return -1;
  220. }
  221. if (args.silence) {
  222. if ((sscanf(args.silence, "%30d", &i) == 1) && (i > -1)) {
  223. silence = i * 1000;
  224. } else if (!ast_strlen_zero(args.silence)) {
  225. ast_log(LOG_WARNING, "'%s' is not a valid silence duration\n", args.silence);
  226. }
  227. }
  228. if (args.maxduration) {
  229. if ((sscanf(args.maxduration, "%30d", &i) == 1) && (i > -1))
  230. /* Convert duration to milliseconds */
  231. maxduration = i * 1000;
  232. else if (!ast_strlen_zero(args.maxduration))
  233. ast_log(LOG_WARNING, "'%s' is not a valid maximum duration\n", args.maxduration);
  234. }
  235. if (ast_test_flag(&flags, OPTION_STAR_TERMINATE))
  236. terminator = '*';
  237. if (ast_test_flag(&flags, OPTION_IGNORE_TERMINATE))
  238. terminator = '\0';
  239. /* done parsing */
  240. /* these are to allow the use of the %d in the config file for a wild card of sort to
  241. create a new file with the inputed name scheme */
  242. if (ast_test_flag(&flags, FLAG_HAS_PERCENT)) {
  243. AST_DECLARE_APP_ARGS(fname,
  244. AST_APP_ARG(piece)[100];
  245. );
  246. char *tmp2 = ast_strdupa(args.filename);
  247. char countstring[15];
  248. int idx;
  249. /* Separate each piece out by the format specifier */
  250. AST_NONSTANDARD_APP_ARGS(fname, tmp2, '%');
  251. do {
  252. int tmplen;
  253. /* First piece has no leading percent, so it's copied verbatim */
  254. ast_copy_string(tmp, fname.piece[0], sizeof(tmp));
  255. tmplen = strlen(tmp);
  256. for (idx = 1; idx < fname.argc; idx++) {
  257. if (fname.piece[idx][0] == 'd') {
  258. /* Substitute the count */
  259. snprintf(countstring, sizeof(countstring), "%d", count);
  260. ast_copy_string(tmp + tmplen, countstring, sizeof(tmp) - tmplen);
  261. tmplen += strlen(countstring);
  262. } else if (tmplen + 2 < sizeof(tmp)) {
  263. /* Unknown format specifier - just copy it verbatim */
  264. tmp[tmplen++] = '%';
  265. tmp[tmplen++] = fname.piece[idx][0];
  266. }
  267. /* Copy the remaining portion of the piece */
  268. ast_copy_string(tmp + tmplen, &(fname.piece[idx][1]), sizeof(tmp) - tmplen);
  269. }
  270. count++;
  271. } while (ast_fileexists(tmp, ext, ast_channel_language(chan)) > 0);
  272. pbx_builtin_setvar_helper(chan, "RECORDED_FILE", tmp);
  273. } else
  274. ast_copy_string(tmp, args.filename, sizeof(tmp));
  275. /* end of routine mentioned */
  276. if (ast_channel_state(chan) != AST_STATE_UP) {
  277. if (ast_test_flag(&flags, OPTION_SKIP)) {
  278. /* At the user's option, skip if the line is not up */
  279. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "SKIP");
  280. return 0;
  281. } else if (!ast_test_flag(&flags, OPTION_NOANSWER)) {
  282. /* Otherwise answer unless we're supposed to record while on-hook */
  283. res = ast_answer(chan);
  284. }
  285. }
  286. if (res) {
  287. ast_log(LOG_WARNING, "Could not answer channel '%s'\n", ast_channel_name(chan));
  288. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
  289. goto out;
  290. }
  291. if (!ast_test_flag(&flags, OPTION_QUIET)) {
  292. /* Some code to play a nice little beep to signify the start of the record operation */
  293. res = ast_streamfile(chan, "beep", ast_channel_language(chan));
  294. if (!res) {
  295. res = ast_waitstream(chan, "");
  296. } else {
  297. ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", ast_channel_name(chan));
  298. }
  299. ast_stopstream(chan);
  300. }
  301. /* The end of beep code. Now the recording starts */
  302. if (silence > 0) {
  303. rfmt = ao2_bump(ast_channel_readformat(chan));
  304. res = ast_set_read_format(chan, ast_format_slin);
  305. if (res < 0) {
  306. ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
  307. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
  308. return -1;
  309. }
  310. sildet = ast_dsp_new();
  311. if (!sildet) {
  312. ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
  313. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
  314. return -1;
  315. }
  316. ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
  317. }
  318. /* Create the directory if it does not exist. */
  319. dir = ast_strdupa(tmp);
  320. if ((file = strrchr(dir, '/')))
  321. *file++ = '\0';
  322. ast_mkdir (dir, 0777);
  323. ioflags = ast_test_flag(&flags, OPTION_APPEND) ? O_CREAT|O_APPEND|O_WRONLY : O_CREAT|O_TRUNC|O_WRONLY;
  324. s = ast_writefile(tmp, ext, NULL, ioflags, 0, AST_FILE_MODE);
  325. if (!s) {
  326. ast_log(LOG_WARNING, "Could not create file %s\n", args.filename);
  327. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
  328. goto out;
  329. }
  330. if (ast_opt_transmit_silence)
  331. silgen = ast_channel_start_silence_generator(chan);
  332. /* Request a video update */
  333. ast_indicate(chan, AST_CONTROL_VIDUPDATE);
  334. if (maxduration <= 0)
  335. maxduration = -1;
  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. if (maxduration > 0 && ms == 0) {
  343. break;
  344. }
  345. f = ast_read(chan);
  346. if (!f) {
  347. res = -1;
  348. break;
  349. }
  350. if (f->frametype == AST_FRAME_VOICE) {
  351. res = ast_writestream(s, f);
  352. if (res) {
  353. ast_log(LOG_WARNING, "Problem writing frame\n");
  354. ast_frfree(f);
  355. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
  356. break;
  357. }
  358. if (silence > 0) {
  359. dspsilence = 0;
  360. ast_dsp_silence(sildet, f, &dspsilence);
  361. if (dspsilence) {
  362. totalsilence = dspsilence;
  363. } else {
  364. totalsilence = 0;
  365. }
  366. if (totalsilence > silence) {
  367. /* Ended happily with silence */
  368. ast_frfree(f);
  369. gotsilence = 1;
  370. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "SILENCE");
  371. break;
  372. }
  373. }
  374. } else if (f->frametype == AST_FRAME_VIDEO) {
  375. res = ast_writestream(s, f);
  376. if (res) {
  377. ast_log(LOG_WARNING, "Problem writing frame\n");
  378. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
  379. ast_frfree(f);
  380. break;
  381. }
  382. } else if (f->frametype == AST_FRAME_DTMF) {
  383. if (record_dtmf_response(chan, &flags, f->subclass.integer, terminator)) {
  384. ast_frfree(f);
  385. break;
  386. }
  387. }
  388. ast_frfree(f);
  389. }
  390. if (maxduration > 0 && !ms) {
  391. gottimeout = 1;
  392. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "TIMEOUT");
  393. }
  394. if (!f) {
  395. ast_debug(1, "Got hangup\n");
  396. res = -1;
  397. pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "HANGUP");
  398. if (!ast_test_flag(&flags, OPTION_KEEP)) {
  399. ast_filedelete(args.filename, NULL);
  400. }
  401. }
  402. if (gotsilence) {
  403. ast_stream_rewind(s, silence - 1000);
  404. ast_truncstream(s);
  405. } else if (!gottimeout && f) {
  406. /*
  407. * Strip off the last 1/4 second of it, if we didn't end because of a timeout,
  408. * or a hangup. This must mean we ended because of a DTMF tone and while this
  409. * 1/4 second stripping is very old code the most likely explanation is that it
  410. * relates to stripping a partial DTMF tone.
  411. */
  412. ast_stream_rewind(s, 250);
  413. ast_truncstream(s);
  414. }
  415. ast_closestream(s);
  416. if (silgen)
  417. ast_channel_stop_silence_generator(chan, silgen);
  418. out:
  419. if ((silence > 0) && rfmt) {
  420. res = ast_set_read_format(chan, rfmt);
  421. if (res) {
  422. ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(chan));
  423. }
  424. }
  425. if (sildet) {
  426. ast_dsp_free(sildet);
  427. }
  428. return res;
  429. }
  430. static int unload_module(void)
  431. {
  432. return ast_unregister_application(app);
  433. }
  434. static int load_module(void)
  435. {
  436. return ast_register_application_xml(app, record_exec);
  437. }
  438. AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Trivial Record Application");