910e72cb1ed5a5186852d95cd80c68ea001e72b0
[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         char *last_slash;
284         int errflag = 0;
285         struct ast_format format_slin;
286
287         ast_format_set(&format_slin, AST_FORMAT_SLINEAR, 0);
288         ast_verb(2, "Begin MixMonitor Recording %s\n", mixmonitor->name);
289
290         fs = &mixmonitor->mixmonitor_ds->fs;
291
292         /* The audiohook must enter and exit the loop locked */
293         ast_audiohook_lock(&mixmonitor->audiohook);
294         while (mixmonitor->audiohook.status == AST_AUDIOHOOK_STATUS_RUNNING && !mixmonitor->mixmonitor_ds->fs_quit) {
295                 struct ast_frame *fr = NULL;
296
297                 if (!(fr = ast_audiohook_read_frame(&mixmonitor->audiohook, SAMPLES_PER_FRAME, AST_AUDIOHOOK_DIRECTION_BOTH, &format_slin))) {
298                         ast_audiohook_trigger_wait(&mixmonitor->audiohook);
299
300                         if (mixmonitor->audiohook.status != AST_AUDIOHOOK_STATUS_RUNNING) {
301                                 break;
302                         }
303                         continue;
304                 }
305
306                 /* audiohook lock is not required for the next block.
307                  * Unlock it, but remember to lock it before looping or exiting */
308                 ast_audiohook_unlock(&mixmonitor->audiohook);
309
310                 if (!ast_test_flag(mixmonitor, MUXFLAG_BRIDGED) || (mixmonitor->autochan->chan && ast_bridged_channel(mixmonitor->autochan->chan))) {
311                         ast_mutex_lock(&mixmonitor->mixmonitor_ds->lock);
312                         /* Initialize the file if not already done so */
313                         if (!*fs && !errflag && !mixmonitor->mixmonitor_ds->fs_quit) {
314                                 oflags = O_CREAT | O_WRONLY;
315                                 oflags |= ast_test_flag(mixmonitor, MUXFLAG_APPEND) ? O_APPEND : O_TRUNC;
316
317                                 last_slash = strrchr(mixmonitor->filename, '/');
318                                 if ((ext = strrchr(mixmonitor->filename, '.')) && (ext > last_slash))
319                                         *(ext++) = '\0';
320                                 else
321                                         ext = "raw";
322
323                                 if (!(*fs = ast_writefile(mixmonitor->filename, ext, NULL, oflags, 0, 0666))) {
324                                         ast_log(LOG_ERROR, "Cannot open %s.%s\n", mixmonitor->filename, ext);
325                                         errflag = 1;
326                                 }
327                         }
328
329                         /* Write out the frame(s) */
330                         if (*fs) {
331                                 struct ast_frame *cur;
332
333                                 for (cur = fr; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
334                                         ast_writestream(*fs, cur);
335                                 }
336                         }
337                         ast_mutex_unlock(&mixmonitor->mixmonitor_ds->lock);
338                 }
339                 /* All done! free it. */
340                 ast_frame_free(fr, 0);
341
342                 ast_audiohook_lock(&mixmonitor->audiohook);
343         }
344         ast_audiohook_unlock(&mixmonitor->audiohook);
345
346         ast_autochan_destroy(mixmonitor->autochan);
347
348         /* Datastore cleanup.  close the filestream and wait for ds destruction */
349         ast_mutex_lock(&mixmonitor->mixmonitor_ds->lock);
350         mixmonitor_ds_close_fs(mixmonitor->mixmonitor_ds);
351         if (!mixmonitor->mixmonitor_ds->destruction_ok) {
352                 ast_cond_wait(&mixmonitor->mixmonitor_ds->destruction_condition, &mixmonitor->mixmonitor_ds->lock);
353         }
354         ast_mutex_unlock(&mixmonitor->mixmonitor_ds->lock);
355
356         /* kill the audiohook */
357         destroy_monitor_audiohook(mixmonitor);
358
359         if (mixmonitor->post_process) {
360                 ast_verb(2, "Executing [%s]\n", mixmonitor->post_process);
361                 ast_safe_system(mixmonitor->post_process);
362         }
363
364         ast_verb(2, "End MixMonitor Recording %s\n", mixmonitor->name);
365         mixmonitor_free(mixmonitor);
366         return NULL;
367 }
368
369 static int setup_mixmonitor_ds(struct mixmonitor *mixmonitor, struct ast_channel *chan)
370 {
371         struct ast_datastore *datastore = NULL;
372         struct mixmonitor_ds *mixmonitor_ds;
373
374         if (!(mixmonitor_ds = ast_calloc(1, sizeof(*mixmonitor_ds)))) {
375                 return -1;
376         }
377
378         ast_mutex_init(&mixmonitor_ds->lock);
379         ast_cond_init(&mixmonitor_ds->destruction_condition, NULL);
380
381         if (!(datastore = ast_datastore_alloc(&mixmonitor_ds_info, NULL))) {
382                 ast_mutex_destroy(&mixmonitor_ds->lock);
383                 ast_cond_destroy(&mixmonitor_ds->destruction_condition);
384                 ast_free(mixmonitor_ds);
385                 return -1;
386         }
387
388         mixmonitor_ds->audiohook = &mixmonitor->audiohook;
389         datastore->data = mixmonitor_ds;
390
391         ast_channel_lock(chan);
392         ast_channel_datastore_add(chan, datastore);
393         ast_channel_unlock(chan);
394
395         mixmonitor->mixmonitor_ds = mixmonitor_ds;
396         return 0;
397 }
398
399 static void launch_monitor_thread(struct ast_channel *chan, const char *filename, unsigned int flags,
400                                   int readvol, int writevol, const char *post_process) 
401 {
402         pthread_t thread;
403         struct mixmonitor *mixmonitor;
404         char postprocess2[1024] = "";
405         size_t len;
406
407         len = sizeof(*mixmonitor) + strlen(chan->name) + strlen(filename) + 2;
408
409         postprocess2[0] = 0;
410         /* If a post process system command is given attach it to the structure */
411         if (!ast_strlen_zero(post_process)) {
412                 char *p1, *p2;
413
414                 p1 = ast_strdupa(post_process);
415                 for (p2 = p1; *p2 ; p2++) {
416                         if (*p2 == '^' && *(p2+1) == '{') {
417                                 *p2 = '$';
418                         }
419                 }
420                 pbx_substitute_variables_helper(chan, p1, postprocess2, sizeof(postprocess2) - 1);
421                 if (!ast_strlen_zero(postprocess2))
422                         len += strlen(postprocess2) + 1;
423         }
424
425         /* Pre-allocate mixmonitor structure and spy */
426         if (!(mixmonitor = ast_calloc(1, len))) {
427                 return;
428         }
429
430         /* Setup the actual spy before creating our thread */
431         if (ast_audiohook_init(&mixmonitor->audiohook, AST_AUDIOHOOK_TYPE_SPY, mixmonitor_spy_type, 0)) {
432                 mixmonitor_free(mixmonitor);
433                 return;
434         }
435
436         /* Copy over flags and channel name */
437         mixmonitor->flags = flags;
438         if (!(mixmonitor->autochan = ast_autochan_setup(chan))) {
439                 mixmonitor_free(mixmonitor);
440                 return;
441         }
442
443         if (setup_mixmonitor_ds(mixmonitor, chan)) {
444                 ast_autochan_destroy(mixmonitor->autochan);
445                 mixmonitor_free(mixmonitor);
446                 return;
447         }
448         mixmonitor->name = (char *) mixmonitor + sizeof(*mixmonitor);
449         strcpy(mixmonitor->name, chan->name);
450         if (!ast_strlen_zero(postprocess2)) {
451                 mixmonitor->post_process = mixmonitor->name + strlen(mixmonitor->name) + strlen(filename) + 2;
452                 strcpy(mixmonitor->post_process, postprocess2);
453         }
454
455         mixmonitor->filename = (char *) mixmonitor + sizeof(*mixmonitor) + strlen(chan->name) + 1;
456         strcpy(mixmonitor->filename, filename);
457
458         ast_set_flag(&mixmonitor->audiohook, AST_AUDIOHOOK_TRIGGER_SYNC);
459
460         if (readvol)
461                 mixmonitor->audiohook.options.read_volume = readvol;
462         if (writevol)
463                 mixmonitor->audiohook.options.write_volume = writevol;
464
465         if (startmon(chan, &mixmonitor->audiohook)) {
466                 ast_log(LOG_WARNING, "Unable to add '%s' spy to channel '%s'\n",
467                         mixmonitor_spy_type, chan->name);
468                 ast_audiohook_destroy(&mixmonitor->audiohook);
469                 mixmonitor_free(mixmonitor);
470                 return;
471         }
472
473         ast_pthread_create_detached_background(&thread, NULL, mixmonitor_thread, mixmonitor);
474 }
475
476 static int mixmonitor_exec(struct ast_channel *chan, const char *data)
477 {
478         int x, readvol = 0, writevol = 0;
479         struct ast_flags flags = {0};
480         char *parse, *tmp, *slash;
481         AST_DECLARE_APP_ARGS(args,
482                 AST_APP_ARG(filename);
483                 AST_APP_ARG(options);
484                 AST_APP_ARG(post_process);
485         );
486         
487         if (ast_strlen_zero(data)) {
488                 ast_log(LOG_WARNING, "MixMonitor requires an argument (filename)\n");
489                 return -1;
490         }
491
492         parse = ast_strdupa(data);
493
494         AST_STANDARD_APP_ARGS(args, parse);
495         
496         if (ast_strlen_zero(args.filename)) {
497                 ast_log(LOG_WARNING, "MixMonitor requires an argument (filename)\n");
498                 return -1;
499         }
500
501         if (args.options) {
502                 char *opts[OPT_ARG_ARRAY_SIZE] = { NULL, };
503
504                 ast_app_parse_options(mixmonitor_opts, &flags, opts, args.options);
505
506                 if (ast_test_flag(&flags, MUXFLAG_READVOLUME)) {
507                         if (ast_strlen_zero(opts[OPT_ARG_READVOLUME])) {
508                                 ast_log(LOG_WARNING, "No volume level was provided for the heard volume ('v') option.\n");
509                         } else if ((sscanf(opts[OPT_ARG_READVOLUME], "%2d", &x) != 1) || (x < -4) || (x > 4)) {
510                                 ast_log(LOG_NOTICE, "Heard volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_READVOLUME]);
511                         } else {
512                                 readvol = get_volfactor(x);
513                         }
514                 }
515                 
516                 if (ast_test_flag(&flags, MUXFLAG_WRITEVOLUME)) {
517                         if (ast_strlen_zero(opts[OPT_ARG_WRITEVOLUME])) {
518                                 ast_log(LOG_WARNING, "No volume level was provided for the spoken volume ('V') option.\n");
519                         } else if ((sscanf(opts[OPT_ARG_WRITEVOLUME], "%2d", &x) != 1) || (x < -4) || (x > 4)) {
520                                 ast_log(LOG_NOTICE, "Spoken volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_WRITEVOLUME]);
521                         } else {
522                                 writevol = get_volfactor(x);
523                         }
524                 }
525                 
526                 if (ast_test_flag(&flags, MUXFLAG_VOLUME)) {
527                         if (ast_strlen_zero(opts[OPT_ARG_VOLUME])) {
528                                 ast_log(LOG_WARNING, "No volume level was provided for the combined volume ('W') option.\n");
529                         } else if ((sscanf(opts[OPT_ARG_VOLUME], "%2d", &x) != 1) || (x < -4) || (x > 4)) {
530                                 ast_log(LOG_NOTICE, "Combined volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_VOLUME]);
531                         } else {
532                                 readvol = writevol = get_volfactor(x);
533                         }
534                 }
535         }
536
537         /* if not provided an absolute path, use the system-configured monitoring directory */
538         if (args.filename[0] != '/') {
539                 char *build;
540
541                 build = alloca(strlen(ast_config_AST_MONITOR_DIR) + strlen(args.filename) + 3);
542                 sprintf(build, "%s/%s", ast_config_AST_MONITOR_DIR, args.filename);
543                 args.filename = build;
544         }
545
546         tmp = ast_strdupa(args.filename);
547         if ((slash = strrchr(tmp, '/')))
548                 *slash = '\0';
549         ast_mkdir(tmp, 0777);
550
551         pbx_builtin_setvar_helper(chan, "MIXMONITOR_FILENAME", args.filename);
552         launch_monitor_thread(chan, args.filename, flags.flags, readvol, writevol, args.post_process);
553
554         return 0;
555 }
556
557 static int stop_mixmonitor_exec(struct ast_channel *chan, const char *data)
558 {
559         struct ast_datastore *datastore = NULL;
560
561         ast_channel_lock(chan);
562         ast_audiohook_detach_source(chan, mixmonitor_spy_type);
563         if ((datastore = ast_channel_datastore_find(chan, &mixmonitor_ds_info, NULL))) {
564                 struct mixmonitor_ds *mixmonitor_ds = datastore->data;
565
566                 ast_mutex_lock(&mixmonitor_ds->lock);
567
568                 /* closing the filestream here guarantees the file is avaliable to the dialplan
569                  * after calling StopMixMonitor */
570                 mixmonitor_ds_close_fs(mixmonitor_ds);
571
572                 /* The mixmonitor thread may be waiting on the audiohook trigger.
573                  * In order to exit from the mixmonitor loop before waiting on channel
574                  * destruction, poke the audiohook trigger. */
575                 if (mixmonitor_ds->audiohook) {
576                         ast_audiohook_lock(mixmonitor_ds->audiohook);
577                         ast_cond_signal(&mixmonitor_ds->audiohook->trigger);
578                         ast_audiohook_unlock(mixmonitor_ds->audiohook);
579                         mixmonitor_ds->audiohook = NULL;
580                 }
581
582                 ast_mutex_unlock(&mixmonitor_ds->lock);
583
584                 /* Remove the datastore so the monitor thread can exit */
585                 if (!ast_channel_datastore_remove(chan, datastore)) {
586                         ast_datastore_free(datastore);
587                 }
588         }
589         ast_channel_unlock(chan);
590
591         return 0;
592 }
593
594 static char *handle_cli_mixmonitor(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
595 {
596         struct ast_channel *chan;
597
598         switch (cmd) {
599         case CLI_INIT:
600                 e->command = "mixmonitor {start|stop}";
601                 e->usage =
602                         "Usage: mixmonitor <start|stop> <chan_name> [args]\n"
603                         "       The optional arguments are passed to the MixMonitor\n"
604                         "       application when the 'start' command is used.\n";
605                 return NULL;
606         case CLI_GENERATE:
607                 return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
608         }
609
610         if (a->argc < 3)
611                 return CLI_SHOWUSAGE;
612
613         if (!(chan = ast_channel_get_by_name_prefix(a->argv[2], strlen(a->argv[2])))) {
614                 ast_cli(a->fd, "No channel matching '%s' found.\n", a->argv[2]);
615                 /* Technically this is a failure, but we don't want 2 errors printing out */
616                 return CLI_SUCCESS;
617         }
618
619         ast_channel_lock(chan);
620
621         if (!strcasecmp(a->argv[1], "start")) {
622                 mixmonitor_exec(chan, a->argv[3]);
623                 ast_channel_unlock(chan);
624         } else {
625                 ast_channel_unlock(chan);
626                 ast_audiohook_detach_source(chan, mixmonitor_spy_type);
627         }
628
629         chan = ast_channel_unref(chan);
630
631         return CLI_SUCCESS;
632 }
633
634 /*! \brief  Mute / unmute  a MixMonitor channel */
635 static int manager_mute_mixmonitor(struct mansession *s, const struct message *m)
636 {
637         struct ast_channel *c = NULL;
638
639         const char *name = astman_get_header(m, "Channel");
640         const char *id = astman_get_header(m, "ActionID");
641         const char *state = astman_get_header(m, "State");
642         const char *direction = astman_get_header(m,"Direction");
643
644         int clearmute = 1;
645
646         enum ast_audiohook_flags flag;
647
648         if (ast_strlen_zero(direction)) {
649                 astman_send_error(s, m, "No direction specified. Must be read, write or both");
650                 return AMI_SUCCESS;
651         }
652
653         if (!strcasecmp(direction, "read")) {
654                 flag = AST_AUDIOHOOK_MUTE_READ;
655         } else  if (!strcasecmp(direction, "write")) {
656                 flag = AST_AUDIOHOOK_MUTE_WRITE;
657         } else  if (!strcasecmp(direction, "both")) {
658                 flag = AST_AUDIOHOOK_MUTE_READ | AST_AUDIOHOOK_MUTE_WRITE;
659         } else {
660                 astman_send_error(s, m, "Invalid direction specified. Must be read, write or both");
661                 return AMI_SUCCESS;
662         }
663
664         if (ast_strlen_zero(name)) {
665                 astman_send_error(s, m, "No channel specified");
666                 return AMI_SUCCESS;
667         }
668
669         if (ast_strlen_zero(state)) {
670                 astman_send_error(s, m, "No state specified");
671                 return AMI_SUCCESS;
672         }
673
674         clearmute = ast_false(state);
675         c = ast_channel_get_by_name(name);
676
677         if (!c) {
678                 astman_send_error(s, m, "No such channel");
679                 return AMI_SUCCESS;
680         }
681
682         if (ast_audiohook_set_mute(c, mixmonitor_spy_type, flag, clearmute)) {
683                 c = ast_channel_unref(c);
684                 astman_send_error(s, m, "Cannot set mute flag");
685                 return AMI_SUCCESS;
686         }
687
688         astman_append(s, "Response: Success\r\n");
689
690         if (!ast_strlen_zero(id)) {
691                 astman_append(s, "ActionID: %s\r\n", id);
692         }
693
694         astman_append(s, "\r\n");
695
696         c = ast_channel_unref(c);
697
698         return AMI_SUCCESS;
699 }
700
701 static struct ast_cli_entry cli_mixmonitor[] = {
702         AST_CLI_DEFINE(handle_cli_mixmonitor, "Execute a MixMonitor command")
703 };
704
705 static int unload_module(void)
706 {
707         int res;
708
709         ast_cli_unregister_multiple(cli_mixmonitor, ARRAY_LEN(cli_mixmonitor));
710         res = ast_unregister_application(stop_app);
711         res |= ast_unregister_application(app);
712         res |= ast_manager_unregister("MixMonitorMute");
713         
714         return res;
715 }
716
717 static int load_module(void)
718 {
719         int res;
720
721         ast_cli_register_multiple(cli_mixmonitor, ARRAY_LEN(cli_mixmonitor));
722         res = ast_register_application_xml(app, mixmonitor_exec);
723         res |= ast_register_application_xml(stop_app, stop_mixmonitor_exec);
724         res |= ast_manager_register_xml("MixMonitorMute", 0, manager_mute_mixmonitor);
725
726         return res;
727 }
728
729 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Mixed Audio Monitoring Application");