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