Asterisk data retrieval API.
[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 #include "asterisk/manager.h"
50
51 /*** DOCUMENTATION
52         <application name="MixMonitor" language="en_US">
53                 <synopsis>
54                         Record a call and mix the audio during the recording.  Use of StopMixMonitor is required
55                         to guarantee the audio file is available for processing during dialplan execution.
56                 </synopsis>
57                 <syntax>
58                         <parameter name="file" required="true" argsep=".">
59                                 <argument name="filename" required="true">
60                                         <para>If <replaceable>filename</replaceable> is an absolute path, uses that path, otherwise
61                                         creates the file in the configured monitoring directory from <filename>asterisk.conf.</filename></para>
62                                 </argument>
63                                 <argument name="extension" required="true" />
64                         </parameter>
65                         <parameter name="options">
66                                 <optionlist>
67                                         <option name="a">
68                                                 <para>Append to the file instead of overwriting it.</para>
69                                         </option>
70                                         <option name="b">
71                                                 <para>Only save audio to the file while the channel is bridged.</para>
72                                                 <note><para>Does not include conferences or sounds played to each bridged party</para></note>
73                                                 <note><para>If you utilize this option inside a Local channel, you must make sure the Local
74                                                 channel is not optimized away. To do this, be sure to call your Local channel with the
75                                                 <literal>/n</literal> option. For example: Dial(Local/start@mycontext/n)</para></note>
76                                         </option>
77                                         <option name="v">
78                                                 <para>Adjust the <emphasis>heard</emphasis> volume by a factor of <replaceable>x</replaceable>
79                                                 (range <literal>-4</literal> to <literal>4</literal>)</para>
80                                                 <argument name="x" required="true" />
81                                         </option>
82                                         <option name="V">
83                                                 <para>Adjust the <emphasis>spoken</emphasis> volume 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                                         <option name="W">
88                                                 <para>Adjust both, <emphasis>heard and spoken</emphasis> volumes by a factor
89                                                 of <replaceable>x</replaceable> (range <literal>-4</literal> to <literal>4</literal>)</para>
90                                                 <argument name="x" required="true" />
91                                         </option>
92                                 </optionlist>
93                         </parameter>
94                         <parameter name="command">
95                                 <para>Will be executed when the recording is over.</para>
96                                 <para>Any strings matching <literal>^{X}</literal> will be unescaped to <variable>X</variable>.</para>
97                                 <para>All variables will be evaluated at the time MixMonitor is called.</para>
98                         </parameter>
99                 </syntax>
100                 <description>
101                         <para>Records the audio on the current channel to the specified file.</para>
102                         <variablelist>
103                                 <variable name="MIXMONITOR_FILENAME">
104                                         <para>Will contain the filename used to record.</para>
105                                 </variable>
106                         </variablelist> 
107                 </description>
108                 <see-also>
109                         <ref type="application">Monitor</ref>
110                         <ref type="application">StopMixMonitor</ref>
111                         <ref type="application">PauseMonitor</ref>
112                         <ref type="application">UnpauseMonitor</ref>
113                 </see-also>
114         </application>
115         <application name="StopMixMonitor" language="en_US">
116                 <synopsis>
117                         Stop recording a call through MixMonitor, and free the recording's file handle.
118                 </synopsis>
119                 <syntax />
120                 <description>
121                         <para>Stops the audio recording that was started with a call to <literal>MixMonitor()</literal>
122                         on the current channel.</para>
123                 </description>
124                 <see-also>
125                         <ref type="application">MixMonitor</ref>
126                 </see-also>
127         </application>
128         <manager name="MixMonitorMute" language="en_US">
129                 <synopsis>
130                         Mute / unMute a Mixmonitor recording.
131                 </synopsis>
132                 <syntax>
133                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
134                         <parameter name="Channel" required="true">
135                                 <para>Used to specify the channel to mute.</para>
136                         </parameter>
137                         <parameter name="Direction">
138                                 <para>Which part of the recording to mute:  read, write or both (from channel, to channel or both channels).</para>
139                         </parameter>
140                         <parameter name="State">
141                                 <para>Turn mute on or off : 1 to turn on, 0 to turn off.</para>
142                         </parameter>
143                 </syntax>
144                 <description>
145                         <para>This action may be used to mute a MixMonitor recording.</para>
146                 </description>
147         </manager>
148
149  ***/
150
151 #define get_volfactor(x) x ? ((x > 0) ? (1 << x) : ((1 << abs(x)) * -1)) : 0
152
153 static const char * const app = "MixMonitor";
154
155 static const char * const stop_app = "StopMixMonitor";
156
157 static const char * const mixmonitor_spy_type = "MixMonitor";
158
159 struct mixmonitor {
160         struct ast_audiohook audiohook;
161         char *filename;
162         char *post_process;
163         char *name;
164         unsigned int flags;
165         struct ast_autochan *autochan;
166         struct mixmonitor_ds *mixmonitor_ds;
167 };
168
169 enum mixmonitor_flags {
170         MUXFLAG_APPEND = (1 << 1),
171         MUXFLAG_BRIDGED = (1 << 2),
172         MUXFLAG_VOLUME = (1 << 3),
173         MUXFLAG_READVOLUME = (1 << 4),
174         MUXFLAG_WRITEVOLUME = (1 << 5),
175 };
176
177 enum mixmonitor_args {
178         OPT_ARG_READVOLUME = 0,
179         OPT_ARG_WRITEVOLUME,
180         OPT_ARG_VOLUME,
181         OPT_ARG_ARRAY_SIZE,
182 };
183
184 AST_APP_OPTIONS(mixmonitor_opts, {
185         AST_APP_OPTION('a', MUXFLAG_APPEND),
186         AST_APP_OPTION('b', MUXFLAG_BRIDGED),
187         AST_APP_OPTION_ARG('v', MUXFLAG_READVOLUME, OPT_ARG_READVOLUME),
188         AST_APP_OPTION_ARG('V', MUXFLAG_WRITEVOLUME, OPT_ARG_WRITEVOLUME),
189         AST_APP_OPTION_ARG('W', MUXFLAG_VOLUME, OPT_ARG_VOLUME),
190 });
191
192 struct mixmonitor_ds {
193         unsigned int destruction_ok;
194         ast_cond_t destruction_condition;
195         ast_mutex_t lock;
196
197         /* The filestream is held in the datastore so it can be stopped
198          * immediately during stop_mixmonitor or channel destruction. */
199         int fs_quit;
200         struct ast_filestream *fs;
201         struct ast_audiohook *audiohook;
202 };
203
204 /*!
205  * \internal
206  * \pre mixmonitor_ds must be locked before calling this function
207  */
208 static void mixmonitor_ds_close_fs(struct mixmonitor_ds *mixmonitor_ds)
209 {
210         if (mixmonitor_ds->fs) {
211                 ast_closestream(mixmonitor_ds->fs);
212                 mixmonitor_ds->fs = NULL;
213                 mixmonitor_ds->fs_quit = 1;
214                 ast_verb(2, "MixMonitor close filestream\n");
215         }
216 }
217
218 static void mixmonitor_ds_destroy(void *data)
219 {
220         struct mixmonitor_ds *mixmonitor_ds = data;
221
222         ast_mutex_lock(&mixmonitor_ds->lock);
223         mixmonitor_ds->audiohook = NULL;
224         mixmonitor_ds->destruction_ok = 1;
225         ast_cond_signal(&mixmonitor_ds->destruction_condition);
226         ast_mutex_unlock(&mixmonitor_ds->lock);
227 }
228
229 static struct ast_datastore_info mixmonitor_ds_info = {
230         .type = "mixmonitor",
231         .destroy = mixmonitor_ds_destroy,
232 };
233
234 static void destroy_monitor_audiohook(struct mixmonitor *mixmonitor)
235 {
236         if (mixmonitor->mixmonitor_ds) {
237                 ast_mutex_lock(&mixmonitor->mixmonitor_ds->lock);
238                 mixmonitor->mixmonitor_ds->audiohook = NULL;
239                 ast_mutex_unlock(&mixmonitor->mixmonitor_ds->lock);
240         }
241         /* kill the audiohook.*/
242         ast_audiohook_lock(&mixmonitor->audiohook);
243         ast_audiohook_detach(&mixmonitor->audiohook);
244         ast_audiohook_unlock(&mixmonitor->audiohook);
245         ast_audiohook_destroy(&mixmonitor->audiohook);
246 }
247
248 static int startmon(struct ast_channel *chan, struct ast_audiohook *audiohook) 
249 {
250         struct ast_channel *peer = NULL;
251         int res = 0;
252
253         if (!chan)
254                 return -1;
255
256         ast_audiohook_attach(chan, audiohook);
257
258         if (!res && ast_test_flag(chan, AST_FLAG_NBRIDGE) && (peer = ast_bridged_channel(chan)))
259                 ast_softhangup(peer, AST_SOFTHANGUP_UNBRIDGE);  
260
261         return res;
262 }
263
264 #define SAMPLES_PER_FRAME 160
265
266 static void mixmonitor_free(struct mixmonitor *mixmonitor)
267 {
268         if (mixmonitor) {
269                 if (mixmonitor->mixmonitor_ds) {
270                         ast_mutex_destroy(&mixmonitor->mixmonitor_ds->lock);
271                         ast_cond_destroy(&mixmonitor->mixmonitor_ds->destruction_condition);
272                         ast_free(mixmonitor->mixmonitor_ds);
273                 }
274                 ast_free(mixmonitor);
275         }
276 }
277 static void *mixmonitor_thread(void *obj) 
278 {
279         struct mixmonitor *mixmonitor = obj;
280         struct ast_filestream **fs = NULL;
281         unsigned int oflags;
282         char *ext;
283         int errflag = 0;
284
285         ast_verb(2, "Begin MixMonitor Recording %s\n", mixmonitor->name);
286
287         fs = &mixmonitor->mixmonitor_ds->fs;
288
289         /* The audiohook must enter and exit the loop locked */
290         ast_audiohook_lock(&mixmonitor->audiohook);
291         while (mixmonitor->audiohook.status == AST_AUDIOHOOK_STATUS_RUNNING && !mixmonitor->mixmonitor_ds->fs_quit) {
292                 struct ast_frame *fr = NULL;
293
294                 if (!(fr = ast_audiohook_read_frame(&mixmonitor->audiohook, SAMPLES_PER_FRAME, AST_AUDIOHOOK_DIRECTION_BOTH, AST_FORMAT_SLINEAR))) {
295                         ast_audiohook_trigger_wait(&mixmonitor->audiohook);
296
297                         if (mixmonitor->audiohook.status != AST_AUDIOHOOK_STATUS_RUNNING) {
298                                 break;
299                         }
300                         continue;
301                 }
302
303                 /* audiohook lock is not required for the next block.
304                  * Unlock it, but remember to lock it before looping or exiting */
305                 ast_audiohook_unlock(&mixmonitor->audiohook);
306
307                 if (!ast_test_flag(mixmonitor, MUXFLAG_BRIDGED) || (mixmonitor->autochan->chan && ast_bridged_channel(mixmonitor->autochan->chan))) {
308                         ast_mutex_lock(&mixmonitor->mixmonitor_ds->lock);
309                         /* Initialize the file if not already done so */
310                         if (!*fs && !errflag && !mixmonitor->mixmonitor_ds->fs_quit) {
311                                 oflags = O_CREAT | O_WRONLY;
312                                 oflags |= ast_test_flag(mixmonitor, MUXFLAG_APPEND) ? O_APPEND : O_TRUNC;
313
314                                 if ((ext = strrchr(mixmonitor->filename, '.')))
315                                         *(ext++) = '\0';
316                                 else
317                                         ext = "raw";
318
319                                 if (!(*fs = ast_writefile(mixmonitor->filename, ext, NULL, oflags, 0, 0666))) {
320                                         ast_log(LOG_ERROR, "Cannot open %s.%s\n", mixmonitor->filename, ext);
321                                         errflag = 1;
322                                 }
323                         }
324
325                         /* Write out the frame(s) */
326                         if (*fs) {
327                                 struct ast_frame *cur;
328
329                                 for (cur = fr; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
330                                         ast_writestream(*fs, cur);
331                                 }
332                         }
333                         ast_mutex_unlock(&mixmonitor->mixmonitor_ds->lock);
334                 }
335                 /* All done! free it. */
336                 ast_frame_free(fr, 0);
337
338                 ast_audiohook_lock(&mixmonitor->audiohook);
339         }
340         ast_audiohook_unlock(&mixmonitor->audiohook);
341
342         ast_autochan_destroy(mixmonitor->autochan);
343
344         /* Datastore cleanup.  close the filestream and wait for ds destruction */
345         ast_mutex_lock(&mixmonitor->mixmonitor_ds->lock);
346         mixmonitor_ds_close_fs(mixmonitor->mixmonitor_ds);
347         if (!mixmonitor->mixmonitor_ds->destruction_ok) {
348                 ast_cond_wait(&mixmonitor->mixmonitor_ds->destruction_condition, &mixmonitor->mixmonitor_ds->lock);
349         }
350         ast_mutex_unlock(&mixmonitor->mixmonitor_ds->lock);
351
352         /* kill the audiohook */
353         destroy_monitor_audiohook(mixmonitor);
354
355         if (mixmonitor->post_process) {
356                 ast_verb(2, "Executing [%s]\n", mixmonitor->post_process);
357                 ast_safe_system(mixmonitor->post_process);
358         }
359
360         ast_verb(2, "End MixMonitor Recording %s\n", mixmonitor->name);
361         mixmonitor_free(mixmonitor);
362         return NULL;
363 }
364
365 static int setup_mixmonitor_ds(struct mixmonitor *mixmonitor, struct ast_channel *chan)
366 {
367         struct ast_datastore *datastore = NULL;
368         struct mixmonitor_ds *mixmonitor_ds;
369
370         if (!(mixmonitor_ds = ast_calloc(1, sizeof(*mixmonitor_ds)))) {
371                 return -1;
372         }
373
374         ast_mutex_init(&mixmonitor_ds->lock);
375         ast_cond_init(&mixmonitor_ds->destruction_condition, NULL);
376
377         if (!(datastore = ast_datastore_alloc(&mixmonitor_ds_info, NULL))) {
378                 ast_mutex_destroy(&mixmonitor_ds->lock);
379                 ast_cond_destroy(&mixmonitor_ds->destruction_condition);
380                 ast_free(mixmonitor_ds);
381                 return -1;
382         }
383
384         mixmonitor_ds->audiohook = &mixmonitor->audiohook;
385         datastore->data = mixmonitor_ds;
386
387         ast_channel_lock(chan);
388         ast_channel_datastore_add(chan, datastore);
389         ast_channel_unlock(chan);
390
391         mixmonitor->mixmonitor_ds = mixmonitor_ds;
392         return 0;
393 }
394
395 static void launch_monitor_thread(struct ast_channel *chan, const char *filename, unsigned int flags,
396                                   int readvol, int writevol, const char *post_process) 
397 {
398         pthread_t thread;
399         struct mixmonitor *mixmonitor;
400         char postprocess2[1024] = "";
401         size_t len;
402
403         len = sizeof(*mixmonitor) + strlen(chan->name) + strlen(filename) + 2;
404
405         postprocess2[0] = 0;
406         /* If a post process system command is given attach it to the structure */
407         if (!ast_strlen_zero(post_process)) {
408                 char *p1, *p2;
409
410                 p1 = ast_strdupa(post_process);
411                 for (p2 = p1; *p2 ; p2++) {
412                         if (*p2 == '^' && *(p2+1) == '{') {
413                                 *p2 = '$';
414                         }
415                 }
416                 pbx_substitute_variables_helper(chan, p1, postprocess2, sizeof(postprocess2) - 1);
417                 if (!ast_strlen_zero(postprocess2))
418                         len += strlen(postprocess2) + 1;
419         }
420
421         /* Pre-allocate mixmonitor structure and spy */
422         if (!(mixmonitor = ast_calloc(1, len))) {
423                 return;
424         }
425
426         /* Setup the actual spy before creating our thread */
427         if (ast_audiohook_init(&mixmonitor->audiohook, AST_AUDIOHOOK_TYPE_SPY, mixmonitor_spy_type)) {
428                 mixmonitor_free(mixmonitor);
429                 return;
430         }
431
432         /* Copy over flags and channel name */
433         mixmonitor->flags = flags;
434         if (!(mixmonitor->autochan = ast_autochan_setup(chan))) {
435                 mixmonitor_free(mixmonitor);
436                 return;
437         }
438
439         if (setup_mixmonitor_ds(mixmonitor, chan)) {
440                 ast_autochan_destroy(mixmonitor->autochan);
441                 mixmonitor_free(mixmonitor);
442                 return;
443         }
444         mixmonitor->name = (char *) mixmonitor + sizeof(*mixmonitor);
445         strcpy(mixmonitor->name, chan->name);
446         if (!ast_strlen_zero(postprocess2)) {
447                 mixmonitor->post_process = mixmonitor->name + strlen(mixmonitor->name) + strlen(filename) + 2;
448                 strcpy(mixmonitor->post_process, postprocess2);
449         }
450
451         mixmonitor->filename = (char *) mixmonitor + sizeof(*mixmonitor) + strlen(chan->name) + 1;
452         strcpy(mixmonitor->filename, filename);
453
454         ast_set_flag(&mixmonitor->audiohook, AST_AUDIOHOOK_TRIGGER_SYNC);
455
456         if (readvol)
457                 mixmonitor->audiohook.options.read_volume = readvol;
458         if (writevol)
459                 mixmonitor->audiohook.options.write_volume = writevol;
460
461         if (startmon(chan, &mixmonitor->audiohook)) {
462                 ast_log(LOG_WARNING, "Unable to add '%s' spy to channel '%s'\n",
463                         mixmonitor_spy_type, chan->name);
464                 ast_audiohook_destroy(&mixmonitor->audiohook);
465                 mixmonitor_free(mixmonitor);
466                 return;
467         }
468
469         ast_pthread_create_detached_background(&thread, NULL, mixmonitor_thread, mixmonitor);
470 }
471
472 static int mixmonitor_exec(struct ast_channel *chan, const char *data)
473 {
474         int x, readvol = 0, writevol = 0;
475         struct ast_flags flags = {0};
476         char *parse, *tmp, *slash;
477         AST_DECLARE_APP_ARGS(args,
478                 AST_APP_ARG(filename);
479                 AST_APP_ARG(options);
480                 AST_APP_ARG(post_process);
481         );
482         
483         if (ast_strlen_zero(data)) {
484                 ast_log(LOG_WARNING, "MixMonitor requires an argument (filename)\n");
485                 return -1;
486         }
487
488         parse = ast_strdupa(data);
489
490         AST_STANDARD_APP_ARGS(args, parse);
491         
492         if (ast_strlen_zero(args.filename)) {
493                 ast_log(LOG_WARNING, "MixMonitor requires an argument (filename)\n");
494                 return -1;
495         }
496
497         if (args.options) {
498                 char *opts[OPT_ARG_ARRAY_SIZE] = { NULL, };
499
500                 ast_app_parse_options(mixmonitor_opts, &flags, opts, args.options);
501
502                 if (ast_test_flag(&flags, MUXFLAG_READVOLUME)) {
503                         if (ast_strlen_zero(opts[OPT_ARG_READVOLUME])) {
504                                 ast_log(LOG_WARNING, "No volume level was provided for the heard volume ('v') option.\n");
505                         } else if ((sscanf(opts[OPT_ARG_READVOLUME], "%2d", &x) != 1) || (x < -4) || (x > 4)) {
506                                 ast_log(LOG_NOTICE, "Heard volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_READVOLUME]);
507                         } else {
508                                 readvol = get_volfactor(x);
509                         }
510                 }
511                 
512                 if (ast_test_flag(&flags, MUXFLAG_WRITEVOLUME)) {
513                         if (ast_strlen_zero(opts[OPT_ARG_WRITEVOLUME])) {
514                                 ast_log(LOG_WARNING, "No volume level was provided for the spoken volume ('V') option.\n");
515                         } else if ((sscanf(opts[OPT_ARG_WRITEVOLUME], "%2d", &x) != 1) || (x < -4) || (x > 4)) {
516                                 ast_log(LOG_NOTICE, "Spoken volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_WRITEVOLUME]);
517                         } else {
518                                 writevol = get_volfactor(x);
519                         }
520                 }
521                 
522                 if (ast_test_flag(&flags, MUXFLAG_VOLUME)) {
523                         if (ast_strlen_zero(opts[OPT_ARG_VOLUME])) {
524                                 ast_log(LOG_WARNING, "No volume level was provided for the combined volume ('W') option.\n");
525                         } else if ((sscanf(opts[OPT_ARG_VOLUME], "%2d", &x) != 1) || (x < -4) || (x > 4)) {
526                                 ast_log(LOG_NOTICE, "Combined volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_VOLUME]);
527                         } else {
528                                 readvol = writevol = get_volfactor(x);
529                         }
530                 }
531         }
532
533         /* if not provided an absolute path, use the system-configured monitoring directory */
534         if (args.filename[0] != '/') {
535                 char *build;
536
537                 build = alloca(strlen(ast_config_AST_MONITOR_DIR) + strlen(args.filename) + 3);
538                 sprintf(build, "%s/%s", ast_config_AST_MONITOR_DIR, args.filename);
539                 args.filename = build;
540         }
541
542         tmp = ast_strdupa(args.filename);
543         if ((slash = strrchr(tmp, '/')))
544                 *slash = '\0';
545         ast_mkdir(tmp, 0777);
546
547         pbx_builtin_setvar_helper(chan, "MIXMONITOR_FILENAME", args.filename);
548         launch_monitor_thread(chan, args.filename, flags.flags, readvol, writevol, args.post_process);
549
550         return 0;
551 }
552
553 static int stop_mixmonitor_exec(struct ast_channel *chan, const char *data)
554 {
555         struct ast_datastore *datastore = NULL;
556
557         ast_channel_lock(chan);
558         ast_audiohook_detach_source(chan, mixmonitor_spy_type);
559         if ((datastore = ast_channel_datastore_find(chan, &mixmonitor_ds_info, NULL))) {
560                 struct mixmonitor_ds *mixmonitor_ds = datastore->data;
561
562                 ast_mutex_lock(&mixmonitor_ds->lock);
563
564                 /* closing the filestream here guarantees the file is avaliable to the dialplan
565                  * after calling StopMixMonitor */
566                 mixmonitor_ds_close_fs(mixmonitor_ds);
567
568                 /* The mixmonitor thread may be waiting on the audiohook trigger.
569                  * In order to exit from the mixmonitor loop before waiting on channel
570                  * destruction, poke the audiohook trigger. */
571                 if (mixmonitor_ds->audiohook) {
572                         ast_audiohook_lock(mixmonitor_ds->audiohook);
573                         ast_cond_signal(&mixmonitor_ds->audiohook->trigger);
574                         ast_audiohook_unlock(mixmonitor_ds->audiohook);
575                         mixmonitor_ds->audiohook = NULL;
576                 }
577
578                 ast_mutex_unlock(&mixmonitor_ds->lock);
579
580                 /* Remove the datastore so the monitor thread can exit */
581                 if (!ast_channel_datastore_remove(chan, datastore)) {
582                         ast_datastore_free(datastore);
583                 }
584         }
585         ast_channel_unlock(chan);
586
587         return 0;
588 }
589
590 static char *handle_cli_mixmonitor(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
591 {
592         struct ast_channel *chan;
593
594         switch (cmd) {
595         case CLI_INIT:
596                 e->command = "mixmonitor {start|stop}";
597                 e->usage =
598                         "Usage: mixmonitor <start|stop> <chan_name> [args]\n"
599                         "       The optional arguments are passed to the MixMonitor\n"
600                         "       application when the 'start' command is used.\n";
601                 return NULL;
602         case CLI_GENERATE:
603                 return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
604         }
605
606         if (a->argc < 3)
607                 return CLI_SHOWUSAGE;
608
609         if (!(chan = ast_channel_get_by_name_prefix(a->argv[2], strlen(a->argv[2])))) {
610                 ast_cli(a->fd, "No channel matching '%s' found.\n", a->argv[2]);
611                 /* Technically this is a failure, but we don't want 2 errors printing out */
612                 return CLI_SUCCESS;
613         }
614
615         ast_channel_lock(chan);
616
617         if (!strcasecmp(a->argv[1], "start")) {
618                 mixmonitor_exec(chan, a->argv[3]);
619                 ast_channel_unlock(chan);
620         } else {
621                 ast_channel_unlock(chan);
622                 ast_audiohook_detach_source(chan, mixmonitor_spy_type);
623         }
624
625         chan = ast_channel_unref(chan);
626
627         return CLI_SUCCESS;
628 }
629
630 /*! \brief  Mute / unmute  a MixMonitor channel */
631 static int manager_mute_mixmonitor(struct mansession *s, const struct message *m)
632 {
633         struct ast_channel *c = NULL;
634
635         const char *name = astman_get_header(m, "Channel");
636         const char *id = astman_get_header(m, "ActionID");
637         const char *state = astman_get_header(m, "State");
638         const char *direction = astman_get_header(m,"Direction");
639
640         int clearmute = 1;
641
642         enum ast_audiohook_flags flag;
643
644         if (ast_strlen_zero(direction)) {
645                 astman_send_error(s, m, "No direction specified. Must be read, write or both");
646                 return AMI_SUCCESS;
647         }
648
649         if (!strcasecmp(direction, "read")) {
650                 flag = AST_AUDIOHOOK_MUTE_READ;
651         } else  if (!strcasecmp(direction, "write")) {
652                 flag = AST_AUDIOHOOK_MUTE_WRITE;
653         } else  if (!strcasecmp(direction, "both")) {
654                 flag = AST_AUDIOHOOK_MUTE_READ | AST_AUDIOHOOK_MUTE_WRITE;
655         } else {
656                 astman_send_error(s, m, "Invalid direction specified. Must be read, write or both");
657                 return AMI_SUCCESS;
658         }
659
660         if (ast_strlen_zero(name)) {
661                 astman_send_error(s, m, "No channel specified");
662                 return AMI_SUCCESS;
663         }
664
665         if (ast_strlen_zero(state)) {
666                 astman_send_error(s, m, "No state specified");
667                 return AMI_SUCCESS;
668         }
669
670         clearmute = ast_false(state);
671         c = ast_channel_get_by_name(name);
672
673         if (!c) {
674                 astman_send_error(s, m, "No such channel");
675                 return AMI_SUCCESS;
676         }
677
678         if (ast_audiohook_set_mute(c, mixmonitor_spy_type, flag, clearmute)) {
679                 c = ast_channel_unref(c);
680                 astman_send_error(s, m, "Cannot set mute flag");
681                 return AMI_SUCCESS;
682         }
683
684         astman_append(s, "Response: Success\r\n");
685
686         if (!ast_strlen_zero(id)) {
687                 astman_append(s, "ActionID: %s\r\n", id);
688         }
689
690         astman_append(s, "\r\n");
691
692         c = ast_channel_unref(c);
693
694         return AMI_SUCCESS;
695 }
696
697 static struct ast_cli_entry cli_mixmonitor[] = {
698         AST_CLI_DEFINE(handle_cli_mixmonitor, "Execute a MixMonitor command")
699 };
700
701 static int unload_module(void)
702 {
703         int res;
704
705         ast_cli_unregister_multiple(cli_mixmonitor, ARRAY_LEN(cli_mixmonitor));
706         res = ast_unregister_application(stop_app);
707         res |= ast_unregister_application(app);
708         res |= ast_manager_unregister("MixMonitorMute");
709         
710         return res;
711 }
712
713 static int load_module(void)
714 {
715         int res;
716
717         ast_cli_register_multiple(cli_mixmonitor, ARRAY_LEN(cli_mixmonitor));
718         res = ast_register_application_xml(app, mixmonitor_exec);
719         res |= ast_register_application_xml(stop_app, stop_mixmonitor_exec);
720         res |= ast_manager_register_xml("MixMonitorMute", 0, manager_mute_mixmonitor);
721
722         return res;
723 }
724
725 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Mixed Audio Monitoring Application");