app_record.c 15 KB

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