d6e4ed044f14c173e116f1fd376adb936e3325dd
[asterisk/asterisk.git] / apps / app_mixmonitor.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2005, Anthony Minessale II
5  * Copyright (C) 2005 - 2006, Digium, Inc.
6  *
7  * Mark Spencer <markster@digium.com>
8  * Kevin P. Fleming <kpfleming@digium.com>
9  *
10  * Based on app_muxmon.c provided by
11  * Anthony Minessale II <anthmct@yahoo.com>
12  *
13  * See http://www.asterisk.org for more information about
14  * the Asterisk project. Please do not directly contact
15  * any of the maintainers of this project for assistance;
16  * the project provides a web site, mailing lists and IRC
17  * channels for your use.
18  *
19  * This program is free software, distributed under the terms of
20  * the GNU General Public License Version 2. See the LICENSE file
21  * at the top of the source tree.
22  */
23
24 /*! \file
25  *
26  * \brief MixMonitor() - Record a call and mix the audio during the recording
27  * \ingroup applications
28  *
29  * \author Mark Spencer <markster@digium.com>
30  * \author Kevin P. Fleming <kpfleming@digium.com>
31  *
32  * \note Based on app_muxmon.c provided by
33  * Anthony Minessale II <anthmct@yahoo.com>
34  */
35
36 #include "asterisk.h"
37
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39
40 #include "asterisk/paths.h"     /* use ast_config_AST_MONITOR_DIR */
41 #include "asterisk/file.h"
42 #include "asterisk/audiohook.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/module.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/app.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/autochan.h"
49
50 /*** DOCUMENTATION
51         <application name="MixMonitor" language="en_US">
52                 <synopsis>
53                         Record a call and mix the audio during the recording.
54                 </synopsis>
55                 <syntax>
56                         <parameter name="file" required="true" argsep=".">
57                                 <argument name="filename" required="true">
58                                         <para>If <replaceable>filename</replaceable> is an absolute path, uses that path, otherwise
59                                         creates the file in the configured monitoring directory from <filename>asterisk.conf.</filename></para>
60                                 </argument>
61                                 <argument name="extension" required="true" />
62                         </parameter>
63                         <parameter name="options">
64                                 <optionlist>
65                                         <option name="a">
66                                                 <para>Append to the file instead of overwriting it.</para>
67                                         </option>
68                                         <option name="b">
69                                                 <para>Only save audio to the file while the channel is bridged.</para>
70                                                 <note><para>Does not include conferences or sounds played to each bridged party</para></note>
71                                                 <note><para>If you utilize this option inside a Local channel, you must make sure the Local
72                                                 channel is not optimized away. To do this, be sure to call your Local channel with the
73                                                 <literal>/n</literal> option. For example: Dial(Local/start@mycontext/n)</para></note>
74                                         </option>
75                                         <option name="v">
76                                                 <para>Adjust the <emphasis>heard</emphasis> volume by a factor of <replaceable>x</replaceable>
77                                                 (range <literal>-4</literal> to <literal>4</literal>)</para>
78                                                 <argument name="x" required="true" />
79                                         </option>
80                                         <option name="V">
81                                                 <para>Adjust the <emphasis>spoken</emphasis> volume by a factor
82                                                 of <replaceable>x</replaceable> (range <literal>-4</literal> to <literal>4</literal>)</para>
83                                                 <argument name="x" required="true" />
84                                         </option>
85                                         <option name="W">
86                                                 <para>Adjust both, <emphasis>heard and spoken</emphasis> volumes by a factor
87                                                 of <replaceable>x</replaceable> (range <literal>-4</literal> to <literal>4</literal>)</para>
88                                                 <argument name="x" required="true" />
89                                         </option>
90                                 </optionlist>
91                         </parameter>
92                         <parameter name="command">
93                                 <para>Will be executed when the recording is over.</para>
94                                 <para>Any strings matching <literal>^{X}</literal> will be unescaped to <variable>X</variable>.</para>
95                                 <para>All variables will be evaluated at the time MixMonitor is called.</para>
96                         </parameter>
97                 </syntax>
98                 <description>
99                         <para>Records the audio on the current channel to the specified file.</para>
100                         <variablelist>
101                                 <variable name="MIXMONITOR_FILENAME">
102                                         <para>Will contain the filename used to record.</para>
103                                 </variable>
104                         </variablelist> 
105                 </description>
106                 <see-also>
107                         <ref type="application">Monitor</ref>
108                         <ref type="application">StopMixMonitor</ref>
109                         <ref type="application">PauseMonitor</ref>
110                         <ref type="application">UnpauseMonitor</ref>
111                 </see-also>
112         </application>
113         <application name="StopMixMonitor" language="en_US">
114                 <synopsis>
115                         Stop recording a call through MixMonitor.
116                 </synopsis>
117                 <syntax />
118                 <description>
119                         <para>Stops the audio recording that was started with a call to <literal>MixMonitor()</literal>
120                         on the current channel.</para>
121                 </description>
122                 <see-also>
123                         <ref type="application">MixMonitor</ref>
124                 </see-also>
125         </application>
126                 
127  ***/
128
129 #define get_volfactor(x) x ? ((x > 0) ? (1 << x) : ((1 << abs(x)) * -1)) : 0
130
131 static const char * const app = "MixMonitor";
132
133 static const char * const stop_app = "StopMixMonitor";
134
135 struct module_symbols *me;
136
137 static const char * const mixmonitor_spy_type = "MixMonitor";
138
139 struct mixmonitor {
140         struct ast_audiohook audiohook;
141         char *filename;
142         char *post_process;
143         char *name;
144         unsigned int flags;
145         struct ast_autochan *autochan;
146 };
147
148 enum {
149         MUXFLAG_APPEND = (1 << 1),
150         MUXFLAG_BRIDGED = (1 << 2),
151         MUXFLAG_VOLUME = (1 << 3),
152         MUXFLAG_READVOLUME = (1 << 4),
153         MUXFLAG_WRITEVOLUME = (1 << 5),
154 } mixmonitor_flags;
155
156 enum {
157         OPT_ARG_READVOLUME = 0,
158         OPT_ARG_WRITEVOLUME,
159         OPT_ARG_VOLUME,
160         OPT_ARG_ARRAY_SIZE,
161 } mixmonitor_args;
162
163 AST_APP_OPTIONS(mixmonitor_opts, {
164         AST_APP_OPTION('a', MUXFLAG_APPEND),
165         AST_APP_OPTION('b', MUXFLAG_BRIDGED),
166         AST_APP_OPTION_ARG('v', MUXFLAG_READVOLUME, OPT_ARG_READVOLUME),
167         AST_APP_OPTION_ARG('V', MUXFLAG_WRITEVOLUME, OPT_ARG_WRITEVOLUME),
168         AST_APP_OPTION_ARG('W', MUXFLAG_VOLUME, OPT_ARG_VOLUME),
169 });
170
171 static int startmon(struct ast_channel *chan, struct ast_audiohook *audiohook) 
172 {
173         struct ast_channel *peer = NULL;
174         int res = 0;
175
176         if (!chan)
177                 return -1;
178
179         ast_audiohook_attach(chan, audiohook);
180
181         if (!res && ast_test_flag(chan, AST_FLAG_NBRIDGE) && (peer = ast_bridged_channel(chan)))
182                 ast_softhangup(peer, AST_SOFTHANGUP_UNBRIDGE);  
183
184         return res;
185 }
186
187 #define SAMPLES_PER_FRAME 160
188
189 static void *mixmonitor_thread(void *obj) 
190 {
191         struct mixmonitor *mixmonitor = obj;
192         struct ast_filestream *fs = NULL;
193         unsigned int oflags;
194         char *ext;
195         int errflag = 0;
196
197         ast_verb(2, "Begin MixMonitor Recording %s\n", mixmonitor->name);
198         
199         ast_audiohook_lock(&mixmonitor->audiohook);
200
201         while (mixmonitor->audiohook.status == AST_AUDIOHOOK_STATUS_RUNNING) {
202                 struct ast_frame *fr = NULL;
203
204                 ast_audiohook_trigger_wait(&mixmonitor->audiohook);
205
206                 if (mixmonitor->audiohook.status != AST_AUDIOHOOK_STATUS_RUNNING)
207                         break;
208
209                 if (!(fr = ast_audiohook_read_frame(&mixmonitor->audiohook, SAMPLES_PER_FRAME, AST_AUDIOHOOK_DIRECTION_BOTH, AST_FORMAT_SLINEAR)))
210                         continue;
211
212                 if (!ast_test_flag(mixmonitor, MUXFLAG_BRIDGED) || (mixmonitor->autochan->chan && ast_bridged_channel(mixmonitor->autochan->chan))) {
213                         /* Initialize the file if not already done so */
214                         if (!fs && !errflag) {
215                                 oflags = O_CREAT | O_WRONLY;
216                                 oflags |= ast_test_flag(mixmonitor, MUXFLAG_APPEND) ? O_APPEND : O_TRUNC;
217                                 
218                                 if ((ext = strrchr(mixmonitor->filename, '.')))
219                                         *(ext++) = '\0';
220                                 else
221                                         ext = "raw";
222                                 
223                                 if (!(fs = ast_writefile(mixmonitor->filename, ext, NULL, oflags, 0, 0666))) {
224                                         ast_log(LOG_ERROR, "Cannot open %s.%s\n", mixmonitor->filename, ext);
225                                         errflag = 1;
226                                 }
227                         }
228                         
229                         /* Write out frame */
230                         if (fs)
231                                 ast_writestream(fs, fr);
232                 }
233                 /* All done! free it. */
234                 ast_frame_free(fr, 0);
235
236         }
237
238         ast_audiohook_detach(&mixmonitor->audiohook);
239         ast_audiohook_unlock(&mixmonitor->audiohook);
240         ast_audiohook_destroy(&mixmonitor->audiohook);
241
242         ast_verb(2, "End MixMonitor Recording %s\n", mixmonitor->name);
243
244         if (fs)
245                 ast_closestream(fs);
246
247         if (mixmonitor->post_process) {
248                 ast_verb(2, "Executing [%s]\n", mixmonitor->post_process);
249                 ast_safe_system(mixmonitor->post_process);
250         }
251
252         ast_autochan_destroy(mixmonitor->autochan);
253         ast_free(mixmonitor);
254
255         return NULL;
256 }
257
258 static void launch_monitor_thread(struct ast_channel *chan, const char *filename, unsigned int flags,
259                                   int readvol, int writevol, const char *post_process) 
260 {
261         pthread_t thread;
262         struct mixmonitor *mixmonitor;
263         char postprocess2[1024] = "";
264         size_t len;
265
266         len = sizeof(*mixmonitor) + strlen(chan->name) + strlen(filename) + 2;
267
268         postprocess2[0] = 0;
269         /* If a post process system command is given attach it to the structure */
270         if (!ast_strlen_zero(post_process)) {
271                 char *p1, *p2;
272
273                 p1 = ast_strdupa(post_process);
274                 for (p2 = p1; *p2 ; p2++) {
275                         if (*p2 == '^' && *(p2+1) == '{') {
276                                 *p2 = '$';
277                         }
278                 }
279                 pbx_substitute_variables_helper(chan, p1, postprocess2, sizeof(postprocess2) - 1);
280                 if (!ast_strlen_zero(postprocess2))
281                         len += strlen(postprocess2) + 1;
282         }
283
284         /* Pre-allocate mixmonitor structure and spy */
285         if (!(mixmonitor = ast_calloc(1, len))) {
286                 return;
287         }
288
289         /* Copy over flags and channel name */
290         mixmonitor->flags = flags;
291         if (!(mixmonitor->autochan = ast_autochan_setup(chan))) {
292                 return;
293         }
294         mixmonitor->name = (char *) mixmonitor + sizeof(*mixmonitor);
295         strcpy(mixmonitor->name, chan->name);
296         if (!ast_strlen_zero(postprocess2)) {
297                 mixmonitor->post_process = mixmonitor->name + strlen(mixmonitor->name) + strlen(filename) + 2;
298                 strcpy(mixmonitor->post_process, postprocess2);
299         }
300
301         mixmonitor->filename = (char *) mixmonitor + sizeof(*mixmonitor) + strlen(chan->name) + 1;
302         strcpy(mixmonitor->filename, filename);
303
304         /* Setup the actual spy before creating our thread */
305         if (ast_audiohook_init(&mixmonitor->audiohook, AST_AUDIOHOOK_TYPE_SPY, mixmonitor_spy_type)) {
306                 ast_free(mixmonitor);
307                 return;
308         }
309
310         ast_set_flag(&mixmonitor->audiohook, AST_AUDIOHOOK_TRIGGER_SYNC);
311
312         if (readvol)
313                 mixmonitor->audiohook.options.read_volume = readvol;
314         if (writevol)
315                 mixmonitor->audiohook.options.write_volume = writevol;
316
317         if (startmon(chan, &mixmonitor->audiohook)) {
318                 ast_log(LOG_WARNING, "Unable to add '%s' spy to channel '%s'\n",
319                         mixmonitor_spy_type, chan->name);
320                 ast_audiohook_destroy(&mixmonitor->audiohook);
321                 ast_free(mixmonitor);
322                 return;
323         }
324
325         ast_pthread_create_detached_background(&thread, NULL, mixmonitor_thread, mixmonitor);
326 }
327
328 static int mixmonitor_exec(struct ast_channel *chan, const char *data)
329 {
330         int x, readvol = 0, writevol = 0;
331         struct ast_flags flags = {0};
332         char *parse, *tmp, *slash;
333         AST_DECLARE_APP_ARGS(args,
334                 AST_APP_ARG(filename);
335                 AST_APP_ARG(options);
336                 AST_APP_ARG(post_process);
337         );
338         
339         if (ast_strlen_zero(data)) {
340                 ast_log(LOG_WARNING, "MixMonitor requires an argument (filename)\n");
341                 return -1;
342         }
343
344         parse = ast_strdupa(data);
345
346         AST_STANDARD_APP_ARGS(args, parse);
347         
348         if (ast_strlen_zero(args.filename)) {
349                 ast_log(LOG_WARNING, "MixMonitor requires an argument (filename)\n");
350                 return -1;
351         }
352
353         if (args.options) {
354                 char *opts[OPT_ARG_ARRAY_SIZE] = { NULL, };
355
356                 ast_app_parse_options(mixmonitor_opts, &flags, opts, args.options);
357
358                 if (ast_test_flag(&flags, MUXFLAG_READVOLUME)) {
359                         if (ast_strlen_zero(opts[OPT_ARG_READVOLUME])) {
360                                 ast_log(LOG_WARNING, "No volume level was provided for the heard volume ('v') option.\n");
361                         } else if ((sscanf(opts[OPT_ARG_READVOLUME], "%d", &x) != 1) || (x < -4) || (x > 4)) {
362                                 ast_log(LOG_NOTICE, "Heard volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_READVOLUME]);
363                         } else {
364                                 readvol = get_volfactor(x);
365                         }
366                 }
367                 
368                 if (ast_test_flag(&flags, MUXFLAG_WRITEVOLUME)) {
369                         if (ast_strlen_zero(opts[OPT_ARG_WRITEVOLUME])) {
370                                 ast_log(LOG_WARNING, "No volume level was provided for the spoken volume ('V') option.\n");
371                         } else if ((sscanf(opts[OPT_ARG_WRITEVOLUME], "%d", &x) != 1) || (x < -4) || (x > 4)) {
372                                 ast_log(LOG_NOTICE, "Spoken volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_WRITEVOLUME]);
373                         } else {
374                                 writevol = get_volfactor(x);
375                         }
376                 }
377                 
378                 if (ast_test_flag(&flags, MUXFLAG_VOLUME)) {
379                         if (ast_strlen_zero(opts[OPT_ARG_VOLUME])) {
380                                 ast_log(LOG_WARNING, "No volume level was provided for the combined volume ('W') option.\n");
381                         } else if ((sscanf(opts[OPT_ARG_VOLUME], "%d", &x) != 1) || (x < -4) || (x > 4)) {
382                                 ast_log(LOG_NOTICE, "Combined volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_VOLUME]);
383                         } else {
384                                 readvol = writevol = get_volfactor(x);
385                         }
386                 }
387         }
388
389         /* if not provided an absolute path, use the system-configured monitoring directory */
390         if (args.filename[0] != '/') {
391                 char *build;
392
393                 build = alloca(strlen(ast_config_AST_MONITOR_DIR) + strlen(args.filename) + 3);
394                 sprintf(build, "%s/%s", ast_config_AST_MONITOR_DIR, args.filename);
395                 args.filename = build;
396         }
397
398         tmp = ast_strdupa(args.filename);
399         if ((slash = strrchr(tmp, '/')))
400                 *slash = '\0';
401         ast_mkdir(tmp, 0777);
402
403         pbx_builtin_setvar_helper(chan, "MIXMONITOR_FILENAME", args.filename);
404         launch_monitor_thread(chan, args.filename, flags.flags, readvol, writevol, args.post_process);
405
406         return 0;
407 }
408
409 static int stop_mixmonitor_exec(struct ast_channel *chan, const char *data)
410 {
411         ast_audiohook_detach_source(chan, mixmonitor_spy_type);
412         return 0;
413 }
414
415 static char *handle_cli_mixmonitor(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
416 {
417         struct ast_channel *chan;
418
419         switch (cmd) {
420         case CLI_INIT:
421                 e->command = "mixmonitor {start|stop} {<chan_name>} [args]";
422                 e->usage =
423                         "Usage: mixmonitor <start|stop> <chan_name> [args]\n"
424                         "       The optional arguments are passed to the MixMonitor\n"
425                         "       application when the 'start' command is used.\n";
426                 return NULL;
427         case CLI_GENERATE:
428                 return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
429         }
430
431         if (a->argc < 3)
432                 return CLI_SHOWUSAGE;
433
434         if (!(chan = ast_channel_get_by_name_prefix(a->argv[2], strlen(a->argv[2])))) {
435                 ast_cli(a->fd, "No channel matching '%s' found.\n", a->argv[2]);
436                 /* Technically this is a failure, but we don't want 2 errors printing out */
437                 return CLI_SUCCESS;
438         }
439
440         ast_channel_lock(chan);
441
442         if (!strcasecmp(a->argv[1], "start")) {
443                 mixmonitor_exec(chan, a->argv[3]);
444                 ast_channel_unlock(chan);
445         } else {
446                 ast_channel_unlock(chan);
447                 ast_audiohook_detach_source(chan, mixmonitor_spy_type);
448         }
449
450         chan = ast_channel_unref(chan);
451
452         return CLI_SUCCESS;
453 }
454
455 static struct ast_cli_entry cli_mixmonitor[] = {
456         AST_CLI_DEFINE(handle_cli_mixmonitor, "Execute a MixMonitor command")
457 };
458
459 static int unload_module(void)
460 {
461         int res;
462
463         ast_cli_unregister_multiple(cli_mixmonitor, ARRAY_LEN(cli_mixmonitor));
464         res = ast_unregister_application(stop_app);
465         res |= ast_unregister_application(app);
466         
467         return res;
468 }
469
470 static int load_module(void)
471 {
472         int res;
473
474         ast_cli_register_multiple(cli_mixmonitor, ARRAY_LEN(cli_mixmonitor));
475         res = ast_register_application_xml(app, mixmonitor_exec);
476         res |= ast_register_application_xml(stop_app, stop_mixmonitor_exec);
477
478         return res;
479 }
480
481 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Mixed Audio Monitoring Application");