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