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