2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2006 - 2008, Digium, Inc.
6 * Russell Bryant <russell@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Cross-platform console channel driver
23 * \author Russell Bryant <russell@digium.com>
25 * \note Some of the code in this file came from chan_oss and chan_alsa.
26 * chan_oss, Mark Spencer <markster@digium.com>
27 * chan_oss, Luigi Rizzo
28 * chan_alsa, Matthew Fredrickson <creslin@digium.com>
30 * \ingroup channel_drivers
32 * Portaudio http://www.portaudio.com/
34 * To install portaudio v19 from svn, check it out using the following command:
35 * - svn co https://www.portaudio.com/repos/portaudio/branches/v19-devel
37 * \note Since this works with any audio system that libportaudio supports,
38 * including ALSA and OSS, this may someday deprecate chan_alsa and chan_oss.
39 * However, before that can be done, it needs to *at least* have all of the
40 * features that these other channel drivers have. The features implemented
41 * in at least one of the other console channel drivers that are not yet
42 * implemented here are:
44 * - Set Auto-answer from the dialplan
45 * - transfer CLI command
46 * - boost CLI command and .conf option
47 * - console_video support
51 * \li The channel chan_console uses the configuration file \ref console.conf
52 * \addtogroup configuration_file
55 /*! \page console.conf console.conf
56 * \verbinclude console.conf.sample
60 <depend>portaudio</depend>
61 <support_level>extended</support_level>
66 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
68 #include <sys/signal.h> /* SIGURG */
70 #include <portaudio.h>
72 #include "asterisk/module.h"
73 #include "asterisk/channel.h"
74 #include "asterisk/pbx.h"
75 #include "asterisk/causes.h"
76 #include "asterisk/cli.h"
77 #include "asterisk/musiconhold.h"
78 #include "asterisk/callerid.h"
79 #include "asterisk/astobj2.h"
82 * \brief The sample rate to request from PortAudio
84 * \todo Make this optional. If this is only going to talk to 8 kHz endpoints,
85 * then it makes sense to use 8 kHz natively.
87 #define SAMPLE_RATE 16000
90 * \brief The number of samples to configure the portaudio stream for
92 * 320 samples (20 ms) is the most common frame size in Asterisk. So, the code
93 * in this module reads 320 sample frames from the portaudio stream and queues
94 * them up on the Asterisk channel. Frames of any size can be written to a
95 * portaudio stream, but the portaudio documentation does say that for high
96 * performance applications, the data should be written to Pa_WriteStream in
97 * the same size as what is used to initialize the stream.
99 #define NUM_SAMPLES 320
101 /*! \brief Mono Input */
102 #define INPUT_CHANNELS 1
104 /*! \brief Mono Output */
105 #define OUTPUT_CHANNELS 1
108 * \brief Maximum text message length
109 * \note This should be changed if there is a common definition somewhere
110 * that defines the maximum length of a text message.
112 #define TEXT_SIZE 256
114 /*! \brief Dance, Kirby, Dance! @{ */
115 #define V_BEGIN " --- <(\"<) --- "
116 #define V_END " --- (>\")> ---\n"
119 static const char config_file[] = "console.conf";
122 * \brief Console pvt structure
124 * Currently, this is a singleton object. However, multiple instances will be
125 * needed when this module is updated for multiple device support.
127 static struct console_pvt {
128 AST_DECLARE_STRING_FIELDS(
129 /*! Name of the device */
130 AST_STRING_FIELD(name);
131 AST_STRING_FIELD(input_device);
132 AST_STRING_FIELD(output_device);
133 /*! Default context for outgoing calls */
134 AST_STRING_FIELD(context);
135 /*! Default extension for outgoing calls */
136 AST_STRING_FIELD(exten);
137 /*! Default CallerID number */
138 AST_STRING_FIELD(cid_num);
139 /*! Default CallerID name */
140 AST_STRING_FIELD(cid_name);
141 /*! Default MOH class to listen to, if:
142 * - No MOH class set on the channel
143 * - Peer channel putting this device on hold did not suggest a class */
144 AST_STRING_FIELD(mohinterpret);
145 /*! Default language */
146 AST_STRING_FIELD(language);
147 /*! Default parkinglot */
148 AST_STRING_FIELD(parkinglot);
150 /*! Current channel for this device */
151 struct ast_channel *owner;
152 /*! Current PortAudio stream for this device */
154 /*! A frame for preparing to queue on to the channel */
156 /*! Running = 1, Not running = 0 */
157 unsigned int streamstate:1;
158 /*! On-hook = 0, Off-hook = 1 */
159 unsigned int hookstate:1;
160 /*! Unmuted = 0, Muted = 1 */
161 unsigned int muted:1;
162 /*! Automatically answer incoming calls */
163 unsigned int autoanswer:1;
164 /*! Ignore context in the console dial CLI command */
165 unsigned int overridecontext:1;
166 /*! Set during a reload so that we know to destroy this if it is no longer
167 * in the configuration file. */
168 unsigned int destroy:1;
169 /*! ID for the stream monitor thread */
173 AST_MUTEX_DEFINE_STATIC(globals_lock);
175 static struct ao2_container *pvts;
176 #define NUM_PVT_BUCKETS 7
178 static struct console_pvt *active_pvt;
179 AST_RWLOCK_DEFINE_STATIC(active_lock);
182 * \brief Global jitterbuffer configuration
184 * \note Disabled by default.
185 * \note Values shown here match the defaults shown in console.conf.sample
187 static struct ast_jb_conf default_jbconf = {
190 .resync_threshold = 1000,
194 static struct ast_jb_conf global_jbconf;
196 /*! Channel Technology Callbacks @{ */
197 static struct ast_channel *console_request(const char *type, struct ast_format_cap *cap,
198 const struct ast_channel *requestor, const char *data, int *cause);
199 static int console_digit_begin(struct ast_channel *c, char digit);
200 static int console_digit_end(struct ast_channel *c, char digit, unsigned int duration);
201 static int console_text(struct ast_channel *c, const char *text);
202 static int console_hangup(struct ast_channel *c);
203 static int console_answer(struct ast_channel *c);
204 static struct ast_frame *console_read(struct ast_channel *chan);
205 static int console_call(struct ast_channel *c, const char *dest, int timeout);
206 static int console_write(struct ast_channel *chan, struct ast_frame *f);
207 static int console_indicate(struct ast_channel *chan, int cond,
208 const void *data, size_t datalen);
209 static int console_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
212 static struct ast_channel_tech console_tech = {
214 .description = "Console Channel Driver",
215 .requester = console_request,
216 .send_digit_begin = console_digit_begin,
217 .send_digit_end = console_digit_end,
218 .send_text = console_text,
219 .hangup = console_hangup,
220 .answer = console_answer,
221 .read = console_read,
222 .call = console_call,
223 .write = console_write,
224 .indicate = console_indicate,
225 .fixup = console_fixup,
228 /*! \brief lock a console_pvt struct */
229 #define console_pvt_lock(pvt) ao2_lock(pvt)
231 /*! \brief unlock a console_pvt struct */
232 #define console_pvt_unlock(pvt) ao2_unlock(pvt)
234 static inline struct console_pvt *ref_pvt(struct console_pvt *pvt)
241 static inline struct console_pvt *unref_pvt(struct console_pvt *pvt)
247 static struct console_pvt *find_pvt(const char *name)
249 struct console_pvt tmp_pvt = {
253 return ao2_find(pvts, &tmp_pvt, OBJ_POINTER);
257 * \brief Stream monitor thread
259 * \arg data A pointer to the console_pvt structure that contains the portaudio
260 * stream that needs to be monitored.
262 * This function runs in its own thread to monitor data coming in from a
263 * portaudio stream. When enough data is available, it is queued up to
264 * be read from the Asterisk channel.
266 static void *stream_monitor(void *data)
268 struct console_pvt *pvt = data;
269 char buf[NUM_SAMPLES * sizeof(int16_t)];
271 struct ast_frame f = {
272 .frametype = AST_FRAME_VOICE,
273 .src = "console_stream_monitor",
275 .datalen = sizeof(buf),
276 .samples = sizeof(buf) / sizeof(int16_t),
278 ast_format_set(&f.subclass.format, AST_FORMAT_SLINEAR16, 0);
281 pthread_testcancel();
282 res = Pa_ReadStream(pvt->stream, buf, sizeof(buf) / sizeof(int16_t));
283 pthread_testcancel();
289 if (res == paNoError)
290 ast_queue_frame(pvt->owner, &f);
296 static int open_stream(struct console_pvt *pvt)
298 int res = paInternalError;
300 if (!strcasecmp(pvt->input_device, "default") &&
301 !strcasecmp(pvt->output_device, "default")) {
302 res = Pa_OpenDefaultStream(&pvt->stream, INPUT_CHANNELS, OUTPUT_CHANNELS,
303 paInt16, SAMPLE_RATE, NUM_SAMPLES, NULL, NULL);
305 PaStreamParameters input_params = {
307 .sampleFormat = paInt16,
308 .suggestedLatency = (1.0 / 50.0), /* 20 ms */
309 .device = paNoDevice,
311 PaStreamParameters output_params = {
313 .sampleFormat = paInt16,
314 .suggestedLatency = (1.0 / 50.0), /* 20 ms */
315 .device = paNoDevice,
317 PaDeviceIndex idx, num_devices, def_input, def_output;
319 if (!(num_devices = Pa_GetDeviceCount()))
322 def_input = Pa_GetDefaultInputDevice();
323 def_output = Pa_GetDefaultOutputDevice();
326 idx < num_devices && (input_params.device == paNoDevice
327 || output_params.device == paNoDevice);
330 const PaDeviceInfo *dev = Pa_GetDeviceInfo(idx);
332 if (dev->maxInputChannels) {
333 if ( (idx == def_input && !strcasecmp(pvt->input_device, "default")) ||
334 !strcasecmp(pvt->input_device, dev->name) )
335 input_params.device = idx;
338 if (dev->maxOutputChannels) {
339 if ( (idx == def_output && !strcasecmp(pvt->output_device, "default")) ||
340 !strcasecmp(pvt->output_device, dev->name) )
341 output_params.device = idx;
345 if (input_params.device == paNoDevice)
346 ast_log(LOG_ERROR, "No input device found for console device '%s'\n", pvt->name);
347 if (output_params.device == paNoDevice)
348 ast_log(LOG_ERROR, "No output device found for console device '%s'\n", pvt->name);
350 res = Pa_OpenStream(&pvt->stream, &input_params, &output_params,
351 SAMPLE_RATE, NUM_SAMPLES, paNoFlag, NULL, NULL);
357 static int start_stream(struct console_pvt *pvt)
362 console_pvt_lock(pvt);
364 /* It is possible for console_hangup to be called before the
365 * stream is started, if this is the case pvt->owner will be NULL
366 * and start_stream should be aborted. */
367 if (pvt->streamstate || !pvt->owner)
370 pvt->streamstate = 1;
371 ast_debug(1, "Starting stream\n");
373 res = open_stream(pvt);
374 if (res != paNoError) {
375 ast_log(LOG_WARNING, "Failed to open stream - (%d) %s\n",
376 res, Pa_GetErrorText(res));
381 res = Pa_StartStream(pvt->stream);
382 if (res != paNoError) {
383 ast_log(LOG_WARNING, "Failed to start stream - (%d) %s\n",
384 res, Pa_GetErrorText(res));
389 if (ast_pthread_create_background(&pvt->thread, NULL, stream_monitor, pvt)) {
390 ast_log(LOG_ERROR, "Failed to start stream monitor thread\n");
395 console_pvt_unlock(pvt);
400 static int stop_stream(struct console_pvt *pvt)
402 if (!pvt->streamstate || pvt->thread == AST_PTHREADT_NULL)
405 pthread_cancel(pvt->thread);
406 pthread_kill(pvt->thread, SIGURG);
407 pthread_join(pvt->thread, NULL);
409 console_pvt_lock(pvt);
410 Pa_AbortStream(pvt->stream);
411 Pa_CloseStream(pvt->stream);
413 pvt->streamstate = 0;
414 console_pvt_unlock(pvt);
420 * \note Called with the pvt struct locked
422 static struct ast_channel *console_new(struct console_pvt *pvt, const char *ext, const char *ctx, int state, const char *linkedid)
424 struct ast_channel *chan;
426 if (!(chan = ast_channel_alloc(1, state, pvt->cid_num, pvt->cid_name, NULL,
427 ext, ctx, linkedid, 0, "Console/%s", pvt->name))) {
431 ast_channel_tech_set(chan, &console_tech);
432 ast_format_set(ast_channel_readformat(chan), AST_FORMAT_SLINEAR16, 0);
433 ast_format_set(ast_channel_writeformat(chan), AST_FORMAT_SLINEAR16, 0);
434 ast_format_cap_add(ast_channel_nativeformats(chan), ast_channel_readformat(chan));
435 ast_channel_tech_pvt_set(chan, ref_pvt(pvt));
439 if (!ast_strlen_zero(pvt->language))
440 ast_channel_language_set(chan, pvt->language);
442 ast_jb_configure(chan, &global_jbconf);
444 if (state != AST_STATE_DOWN) {
445 if (ast_pbx_start(chan)) {
446 ast_channel_hangupcause_set(chan, AST_CAUSE_SWITCH_CONGESTION);
456 static struct ast_channel *console_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause)
458 struct ast_channel *chan = NULL;
459 struct console_pvt *pvt;
462 if (!(pvt = find_pvt(data))) {
463 ast_log(LOG_ERROR, "Console device '%s' not found\n", data);
467 if (!(ast_format_cap_has_joint(cap, console_tech.capabilities))) {
468 ast_log(LOG_NOTICE, "Channel requested with unsupported format(s): '%s'\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
473 ast_log(LOG_NOTICE, "Console channel already active!\n");
474 *cause = AST_CAUSE_BUSY;
478 console_pvt_lock(pvt);
479 chan = console_new(pvt, NULL, NULL, AST_STATE_DOWN, requestor ? ast_channel_linkedid(requestor) : NULL);
480 console_pvt_unlock(pvt);
483 ast_log(LOG_WARNING, "Unable to create new Console channel!\n");
491 static int console_digit_begin(struct ast_channel *c, char digit)
493 ast_verb(1, V_BEGIN "Console Received Beginning of Digit %c" V_END, digit);
495 return -1; /* non-zero to request inband audio */
498 static int console_digit_end(struct ast_channel *c, char digit, unsigned int duration)
500 ast_verb(1, V_BEGIN "Console Received End of Digit %c (duration %u)" V_END,
503 return -1; /* non-zero to request inband audio */
506 static int console_text(struct ast_channel *c, const char *text)
508 ast_verb(1, V_BEGIN "Console Received Text '%s'" V_END, text);
513 static int console_hangup(struct ast_channel *c)
515 struct console_pvt *pvt = ast_channel_tech_pvt(c);
517 ast_verb(1, V_BEGIN "Hangup on Console" V_END);
523 ast_channel_tech_pvt_set(c, unref_pvt(pvt));
528 static int console_answer(struct ast_channel *c)
530 struct console_pvt *pvt = ast_channel_tech_pvt(c);
532 ast_verb(1, V_BEGIN "Call from Console has been Answered" V_END);
534 ast_setstate(c, AST_STATE_UP);
536 return start_stream(pvt);
540 * \brief Implementation of the ast_channel_tech read() callback
542 * Calling this function is harmless. However, if it does get called, it
543 * is an indication that something weird happened that really shouldn't
544 * have and is worth looking into.
546 * Why should this function not get called? Well, let me explain. There are
547 * a couple of ways to pass on audio that has come from this channel. The way
548 * that this channel driver uses is that once the audio is available, it is
549 * wrapped in an ast_frame and queued onto the channel using ast_queue_frame().
551 * The other method would be signalling to the core that there is audio waiting,
552 * and that it needs to call the channel's read() callback to get it. The way
553 * the channel gets signalled is that one or more file descriptors are placed
554 * in the fds array on the ast_channel which the core will poll() on. When the
555 * fd indicates that input is available, the read() callback is called. This
556 * is especially useful when there is a dedicated file descriptor where the
557 * audio is read from. An example would be the socket for an RTP stream.
559 static struct ast_frame *console_read(struct ast_channel *chan)
561 ast_debug(1, "I should not be called ...\n");
563 return &ast_null_frame;
566 static int console_call(struct ast_channel *c, const char *dest, int timeout)
568 struct console_pvt *pvt = ast_channel_tech_pvt(c);
569 enum ast_control_frame_type ctrl;
571 ast_verb(1, V_BEGIN "Call to device '%s' on console from '%s' <%s>" V_END,
573 S_COR(ast_channel_caller(c)->id.name.valid, ast_channel_caller(c)->id.name.str, ""),
574 S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, ""));
576 console_pvt_lock(pvt);
578 if (pvt->autoanswer) {
580 console_pvt_unlock(pvt);
581 ast_verb(1, V_BEGIN "Auto-answered" V_END);
582 ctrl = AST_CONTROL_ANSWER;
584 console_pvt_unlock(pvt);
585 ast_verb(1, V_BEGIN "Type 'console answer' to answer, or use the 'autoanswer' option "
586 "for future calls" V_END);
587 ctrl = AST_CONTROL_RINGING;
588 ast_indicate(c, AST_CONTROL_RINGING);
591 ast_queue_control(c, ctrl);
593 return start_stream(pvt);
596 static int console_write(struct ast_channel *chan, struct ast_frame *f)
598 struct console_pvt *pvt = ast_channel_tech_pvt(chan);
600 Pa_WriteStream(pvt->stream, f->data.ptr, f->samples);
605 static int console_indicate(struct ast_channel *chan, int cond, const void *data, size_t datalen)
607 struct console_pvt *pvt = ast_channel_tech_pvt(chan);
611 case AST_CONTROL_BUSY:
612 case AST_CONTROL_CONGESTION:
613 case AST_CONTROL_RINGING:
614 case AST_CONTROL_INCOMPLETE:
615 case AST_CONTROL_PVT_CAUSE_CODE:
617 res = -1; /* Ask for inband indications */
619 case AST_CONTROL_PROGRESS:
620 case AST_CONTROL_PROCEEDING:
621 case AST_CONTROL_VIDUPDATE:
622 case AST_CONTROL_SRCUPDATE:
624 case AST_CONTROL_HOLD:
625 ast_verb(1, V_BEGIN "Console Has Been Placed on Hold" V_END);
626 ast_moh_start(chan, data, pvt->mohinterpret);
628 case AST_CONTROL_UNHOLD:
629 ast_verb(1, V_BEGIN "Console Has Been Retrieved from Hold" V_END);
633 ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n",
634 cond, ast_channel_name(chan));
635 /* The core will play inband indications for us if appropriate */
642 static int console_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
644 struct console_pvt *pvt = ast_channel_tech_pvt(newchan);
646 pvt->owner = newchan;
652 * split a string in extension-context, returns pointers to malloc'ed
654 * If we do not have 'overridecontext' then the last @ is considered as
655 * a context separator, and the context is overridden.
656 * This is usually not very necessary as you can play with the dialplan,
657 * and it is nice not to need it because you have '@' in SIP addresses.
658 * Return value is the buffer address.
660 * \note came from chan_oss
662 static char *ast_ext_ctx(struct console_pvt *pvt, const char *src, char **ext, char **ctx)
664 if (ext == NULL || ctx == NULL)
665 return NULL; /* error */
669 if (src && *src != '\0')
670 *ext = ast_strdup(src);
675 if (!pvt->overridecontext) {
676 /* parse from the right */
677 *ctx = strrchr(*ext, '@');
685 static struct console_pvt *get_active_pvt(void)
687 struct console_pvt *pvt;
689 ast_rwlock_rdlock(&active_lock);
690 pvt = ref_pvt(active_pvt);
691 ast_rwlock_unlock(&active_lock);
696 static char *cli_console_autoanswer(struct ast_cli_entry *e, int cmd,
697 struct ast_cli_args *a)
699 struct console_pvt *pvt = get_active_pvt();
700 char *res = CLI_SUCCESS;
704 e->command = "console {set|show} autoanswer [on|off]";
706 "Usage: console {set|show} autoanswer [on|off]\n"
707 " Enables or disables autoanswer feature. If used without\n"
708 " argument, displays the current on/off status of autoanswer.\n"
709 " The default value of autoanswer is in 'oss.conf'.\n";
717 ast_cli(a->fd, "No console device is set as active.\n");
721 if (a->argc == e->args - 1) {
722 ast_cli(a->fd, "Auto answer is %s.\n", pvt->autoanswer ? "on" : "off");
727 if (a->argc != e->args) {
729 return CLI_SHOWUSAGE;
732 if (!strcasecmp(a->argv[e->args-1], "on"))
734 else if (!strcasecmp(a->argv[e->args - 1], "off"))
744 static char *cli_console_flash(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
746 struct console_pvt *pvt = get_active_pvt();
748 if (cmd == CLI_INIT) {
749 e->command = "console flash";
751 "Usage: console flash\n"
752 " Flashes the call currently placed on the console.\n";
754 } else if (cmd == CLI_GENERATE)
758 ast_cli(a->fd, "No console device is set as active\n");
762 if (a->argc != e->args)
763 return CLI_SHOWUSAGE;
766 ast_cli(a->fd, "No call to flash\n");
773 ast_queue_control(pvt->owner, AST_CONTROL_FLASH);
780 static char *cli_console_dial(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
783 const char *mye = NULL, *myc = NULL;
784 struct console_pvt *pvt = get_active_pvt();
786 if (cmd == CLI_INIT) {
787 e->command = "console dial";
789 "Usage: console dial [extension[@context]]\n"
790 " Dials a given extension (and context if specified)\n";
792 } else if (cmd == CLI_GENERATE)
796 ast_cli(a->fd, "No console device is currently set as active\n");
800 if (a->argc > e->args + 1)
801 return CLI_SHOWUSAGE;
803 if (pvt->owner) { /* already in a call */
805 struct ast_frame f = { AST_FRAME_DTMF };
808 if (a->argc == e->args) { /* argument is mandatory here */
809 ast_cli(a->fd, "Already in a call. You can only dial digits until you hangup.\n");
813 s = a->argv[e->args];
814 /* send the string one char at a time */
815 for (i = 0; i < strlen(s); i++) {
816 f.subclass.integer = s[i];
817 ast_queue_frame(pvt->owner, &f);
823 /* if we have an argument split it into extension and context */
824 if (a->argc == e->args + 1) {
825 char *ext = NULL, *con = NULL;
826 s = ast_ext_ctx(pvt, a->argv[e->args], &ext, &con);
827 ast_debug(1, "provided '%s', exten '%s' context '%s'\n",
828 a->argv[e->args], mye, myc);
833 /* supply default values if needed */
834 if (ast_strlen_zero(mye))
836 if (ast_strlen_zero(myc))
839 if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
840 console_pvt_lock(pvt);
842 console_new(pvt, mye, myc, AST_STATE_RINGING, NULL);
843 console_pvt_unlock(pvt);
845 ast_cli(a->fd, "No such extension '%s' in context '%s'\n", mye, myc);
854 static char *cli_console_hangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
856 struct console_pvt *pvt = get_active_pvt();
858 if (cmd == CLI_INIT) {
859 e->command = "console hangup";
861 "Usage: console hangup\n"
862 " Hangs up any call currently placed on the console.\n";
864 } else if (cmd == CLI_GENERATE)
868 ast_cli(a->fd, "No console device is set as active\n");
872 if (a->argc != e->args)
873 return CLI_SHOWUSAGE;
875 if (!pvt->owner && !pvt->hookstate) {
876 ast_cli(a->fd, "No call to hang up\n");
883 ast_queue_hangup(pvt->owner);
890 static char *cli_console_mute(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
893 struct console_pvt *pvt = get_active_pvt();
894 char *res = CLI_SUCCESS;
896 if (cmd == CLI_INIT) {
897 e->command = "console {mute|unmute}";
899 "Usage: console {mute|unmute}\n"
900 " Mute/unmute the microphone.\n";
902 } else if (cmd == CLI_GENERATE)
906 ast_cli(a->fd, "No console device is set as active\n");
910 if (a->argc != e->args)
911 return CLI_SHOWUSAGE;
913 s = a->argv[e->args-1];
914 if (!strcasecmp(s, "mute"))
916 else if (!strcasecmp(s, "unmute"))
921 ast_verb(1, V_BEGIN "The Console is now %s" V_END,
922 pvt->muted ? "Muted" : "Unmuted");
929 static char *cli_list_available(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
931 PaDeviceIndex idx, num, def_input, def_output;
933 if (cmd == CLI_INIT) {
934 e->command = "console list available";
936 "Usage: console list available\n"
937 " List all available devices.\n";
939 } else if (cmd == CLI_GENERATE)
942 if (a->argc != e->args)
943 return CLI_SHOWUSAGE;
946 "=============================================================\n"
947 "=== Available Devices =======================================\n"
948 "=============================================================\n"
951 num = Pa_GetDeviceCount();
953 ast_cli(a->fd, "(None)\n");
957 def_input = Pa_GetDefaultInputDevice();
958 def_output = Pa_GetDefaultOutputDevice();
959 for (idx = 0; idx < num; idx++) {
960 const PaDeviceInfo *dev = Pa_GetDeviceInfo(idx);
963 ast_cli(a->fd, "=== ---------------------------------------------------------\n"
964 "=== Device Name: %s\n", dev->name);
965 if (dev->maxInputChannels)
966 ast_cli(a->fd, "=== ---> %sInput Device\n", (idx == def_input) ? "Default " : "");
967 if (dev->maxOutputChannels)
968 ast_cli(a->fd, "=== ---> %sOutput Device\n", (idx == def_output) ? "Default " : "");
969 ast_cli(a->fd, "=== ---------------------------------------------------------\n===\n");
972 ast_cli(a->fd, "=============================================================\n\n");
977 static char *cli_list_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
979 struct ao2_iterator i;
980 struct console_pvt *pvt;
982 if (cmd == CLI_INIT) {
983 e->command = "console list devices";
985 "Usage: console list devices\n"
986 " List all configured devices.\n";
988 } else if (cmd == CLI_GENERATE)
991 if (a->argc != e->args)
992 return CLI_SHOWUSAGE;
995 "=============================================================\n"
996 "=== Configured Devices ======================================\n"
997 "=============================================================\n"
1000 i = ao2_iterator_init(pvts, 0);
1001 while ((pvt = ao2_iterator_next(&i))) {
1002 console_pvt_lock(pvt);
1004 ast_cli(a->fd, "=== ---------------------------------------------------------\n"
1005 "=== Device Name: %s\n"
1006 "=== ---> Active: %s\n"
1007 "=== ---> Input Device: %s\n"
1008 "=== ---> Output Device: %s\n"
1009 "=== ---> Context: %s\n"
1010 "=== ---> Extension: %s\n"
1011 "=== ---> CallerID Num: %s\n"
1012 "=== ---> CallerID Name: %s\n"
1013 "=== ---> MOH Interpret: %s\n"
1014 "=== ---> Language: %s\n"
1015 "=== ---> Parkinglot: %s\n"
1016 "=== ---> Muted: %s\n"
1017 "=== ---> Auto-Answer: %s\n"
1018 "=== ---> Override Context: %s\n"
1019 "=== ---------------------------------------------------------\n===\n",
1020 pvt->name, (pvt == active_pvt) ? "Yes" : "No",
1021 pvt->input_device, pvt->output_device, pvt->context,
1022 pvt->exten, pvt->cid_num, pvt->cid_name, pvt->mohinterpret,
1023 pvt->language, pvt->parkinglot, pvt->muted ? "Yes" : "No", pvt->autoanswer ? "Yes" : "No",
1024 pvt->overridecontext ? "Yes" : "No");
1026 console_pvt_unlock(pvt);
1029 ao2_iterator_destroy(&i);
1031 ast_cli(a->fd, "=============================================================\n\n");
1036 * \brief answer command from the console
1038 static char *cli_console_answer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1040 struct console_pvt *pvt = get_active_pvt();
1044 e->command = "console answer";
1046 "Usage: console answer\n"
1047 " Answers an incoming call on the console channel.\n";
1051 return NULL; /* no completion */
1055 ast_cli(a->fd, "No console device is set as active\n");
1059 if (a->argc != e->args) {
1061 return CLI_SHOWUSAGE;
1065 ast_cli(a->fd, "No one is calling us\n");
1072 ast_indicate(pvt->owner, -1);
1074 ast_queue_control(pvt->owner, AST_CONTROL_ANSWER);
1082 * \brief Console send text CLI command
1084 * \note concatenate all arguments into a single string. argv is NULL-terminated
1085 * so we can use it right away
1087 static char *cli_console_sendtext(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1089 char buf[TEXT_SIZE];
1090 struct console_pvt *pvt = get_active_pvt();
1091 struct ast_frame f = {
1092 .frametype = AST_FRAME_TEXT,
1094 .src = "console_send_text",
1098 if (cmd == CLI_INIT) {
1099 e->command = "console send text";
1101 "Usage: console send text <message>\n"
1102 " Sends a text message for display on the remote terminal.\n";
1104 } else if (cmd == CLI_GENERATE)
1108 ast_cli(a->fd, "No console device is set as active\n");
1112 if (a->argc < e->args + 1) {
1114 return CLI_SHOWUSAGE;
1118 ast_cli(a->fd, "Not in a call\n");
1123 ast_join(buf, sizeof(buf) - 1, a->argv + e->args);
1124 if (ast_strlen_zero(buf)) {
1126 return CLI_SHOWUSAGE;
1131 f.datalen = len + 1;
1133 ast_queue_frame(pvt->owner, &f);
1140 static void set_active(struct console_pvt *pvt, const char *value)
1142 if (pvt == &globals) {
1143 ast_log(LOG_ERROR, "active is only valid as a per-device setting\n");
1147 if (!ast_true(value))
1150 ast_rwlock_wrlock(&active_lock);
1152 unref_pvt(active_pvt);
1153 active_pvt = ref_pvt(pvt);
1154 ast_rwlock_unlock(&active_lock);
1157 static char *cli_console_active(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1159 struct console_pvt *pvt;
1163 e->command = "console {set|show} active";
1165 "Usage: console {set|show} active [<device>]\n"
1166 " Set or show the active console device for the Asterisk CLI.\n";
1169 if (a->pos == e->args) {
1170 struct ao2_iterator i;
1173 i = ao2_iterator_init(pvts, 0);
1174 while ((pvt = ao2_iterator_next(&i))) {
1175 if (++x > a->n && !strncasecmp(pvt->name, a->word, strlen(a->word)))
1176 res = ast_strdup(pvt->name);
1179 ao2_iterator_destroy(&i);
1183 ao2_iterator_destroy(&i);
1188 if (a->argc < e->args)
1189 return CLI_SHOWUSAGE;
1192 pvt = get_active_pvt();
1195 ast_cli(a->fd, "No device is currently set as the active console device.\n");
1197 console_pvt_lock(pvt);
1198 ast_cli(a->fd, "The active console device is '%s'.\n", pvt->name);
1199 console_pvt_unlock(pvt);
1200 pvt = unref_pvt(pvt);
1206 if (!(pvt = find_pvt(a->argv[e->args - 1]))) {
1207 ast_cli(a->fd, "Could not find a device called '%s'.\n", a->argv[e->args]);
1211 set_active(pvt, "yes");
1213 console_pvt_lock(pvt);
1214 ast_cli(a->fd, "The active console device has been set to '%s'\n", pvt->name);
1215 console_pvt_unlock(pvt);
1222 static struct ast_cli_entry cli_console[] = {
1223 AST_CLI_DEFINE(cli_console_dial, "Dial an extension from the console"),
1224 AST_CLI_DEFINE(cli_console_hangup, "Hangup a call on the console"),
1225 AST_CLI_DEFINE(cli_console_mute, "Disable/Enable mic input"),
1226 AST_CLI_DEFINE(cli_console_answer, "Answer an incoming console call"),
1227 AST_CLI_DEFINE(cli_console_sendtext, "Send text to a connected party"),
1228 AST_CLI_DEFINE(cli_console_flash, "Send a flash to the connected party"),
1229 AST_CLI_DEFINE(cli_console_autoanswer, "Turn autoanswer on or off"),
1230 AST_CLI_DEFINE(cli_list_available, "List available devices"),
1231 AST_CLI_DEFINE(cli_list_devices, "List configured devices"),
1232 AST_CLI_DEFINE(cli_console_active, "View or Set the active console device"),
1236 * \brief Set default values for a pvt struct
1238 * \note This function expects the pvt lock to be held.
1240 static void set_pvt_defaults(struct console_pvt *pvt)
1242 if (pvt == &globals) {
1243 ast_string_field_set(pvt, mohinterpret, "default");
1244 ast_string_field_set(pvt, context, "default");
1245 ast_string_field_set(pvt, exten, "s");
1246 ast_string_field_set(pvt, language, "");
1247 ast_string_field_set(pvt, cid_num, "");
1248 ast_string_field_set(pvt, cid_name, "");
1249 ast_string_field_set(pvt, parkinglot, "");
1251 pvt->overridecontext = 0;
1252 pvt->autoanswer = 0;
1254 ast_mutex_lock(&globals_lock);
1256 ast_string_field_set(pvt, mohinterpret, globals.mohinterpret);
1257 ast_string_field_set(pvt, context, globals.context);
1258 ast_string_field_set(pvt, exten, globals.exten);
1259 ast_string_field_set(pvt, language, globals.language);
1260 ast_string_field_set(pvt, cid_num, globals.cid_num);
1261 ast_string_field_set(pvt, cid_name, globals.cid_name);
1262 ast_string_field_set(pvt, parkinglot, globals.parkinglot);
1264 pvt->overridecontext = globals.overridecontext;
1265 pvt->autoanswer = globals.autoanswer;
1267 ast_mutex_unlock(&globals_lock);
1271 static void store_callerid(struct console_pvt *pvt, const char *value)
1276 ast_callerid_split(value, cid_name, sizeof(cid_name),
1277 cid_num, sizeof(cid_num));
1279 ast_string_field_set(pvt, cid_name, cid_name);
1280 ast_string_field_set(pvt, cid_num, cid_num);
1284 * \brief Store a configuration parameter in a pvt struct
1286 * \note This function expects the pvt lock to be held.
1288 static void store_config_core(struct console_pvt *pvt, const char *var, const char *value)
1290 if (pvt == &globals && !ast_jb_read_conf(&global_jbconf, var, value))
1293 CV_START(var, value);
1295 CV_STRFIELD("context", pvt, context);
1296 CV_STRFIELD("extension", pvt, exten);
1297 CV_STRFIELD("mohinterpret", pvt, mohinterpret);
1298 CV_STRFIELD("language", pvt, language);
1299 CV_F("callerid", store_callerid(pvt, value));
1300 CV_BOOL("overridecontext", pvt->overridecontext);
1301 CV_BOOL("autoanswer", pvt->autoanswer);
1302 CV_STRFIELD("parkinglot", pvt, parkinglot);
1304 if (pvt != &globals) {
1305 CV_F("active", set_active(pvt, value))
1306 CV_STRFIELD("input_device", pvt, input_device);
1307 CV_STRFIELD("output_device", pvt, output_device);
1310 ast_log(LOG_WARNING, "Unknown option '%s'\n", var);
1315 static void pvt_destructor(void *obj)
1317 struct console_pvt *pvt = obj;
1319 ast_string_field_free_memory(pvt);
1322 static int init_pvt(struct console_pvt *pvt, const char *name)
1324 pvt->thread = AST_PTHREADT_NULL;
1326 if (ast_string_field_init(pvt, 32))
1329 ast_string_field_set(pvt, name, S_OR(name, ""));
1334 static void build_device(struct ast_config *cfg, const char *name)
1336 struct ast_variable *v;
1337 struct console_pvt *pvt;
1340 if ((pvt = find_pvt(name))) {
1341 console_pvt_lock(pvt);
1342 set_pvt_defaults(pvt);
1345 if (!(pvt = ao2_alloc(sizeof(*pvt), pvt_destructor)))
1347 init_pvt(pvt, name);
1348 set_pvt_defaults(pvt);
1352 for (v = ast_variable_browse(cfg, name); v; v = v->next)
1353 store_config_core(pvt, v->name, v->value);
1356 ao2_link(pvts, pvt);
1358 console_pvt_unlock(pvt);
1363 static int pvt_mark_destroy_cb(void *obj, void *arg, int flags)
1365 struct console_pvt *pvt = obj;
1370 static void destroy_pvts(void)
1372 struct ao2_iterator i;
1373 struct console_pvt *pvt;
1375 i = ao2_iterator_init(pvts, 0);
1376 while ((pvt = ao2_iterator_next(&i))) {
1378 ao2_unlink(pvts, pvt);
1379 ast_rwlock_wrlock(&active_lock);
1380 if (active_pvt == pvt)
1381 active_pvt = unref_pvt(pvt);
1382 ast_rwlock_unlock(&active_lock);
1386 ao2_iterator_destroy(&i);
1390 * \brief Load the configuration
1391 * \param reload if this was called due to a reload
1393 * \retval -1 failure
1395 static int load_config(int reload)
1397 struct ast_config *cfg;
1398 struct ast_variable *v;
1399 struct ast_flags config_flags = { 0 };
1400 char *context = NULL;
1402 /* default values */
1403 memcpy(&global_jbconf, &default_jbconf, sizeof(global_jbconf));
1404 ast_mutex_lock(&globals_lock);
1405 set_pvt_defaults(&globals);
1406 ast_mutex_unlock(&globals_lock);
1408 if (!(cfg = ast_config_load(config_file, config_flags))) {
1409 ast_log(LOG_NOTICE, "Unable to open configuration file %s!\n", config_file);
1411 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
1412 ast_log(LOG_NOTICE, "Config file %s has an invalid format\n", config_file);
1416 ao2_callback(pvts, OBJ_NODATA, pvt_mark_destroy_cb, NULL);
1418 ast_mutex_lock(&globals_lock);
1419 for (v = ast_variable_browse(cfg, "general"); v; v = v->next)
1420 store_config_core(&globals, v->name, v->value);
1421 ast_mutex_unlock(&globals_lock);
1423 while ((context = ast_category_browse(cfg, context))) {
1424 if (strcasecmp(context, "general"))
1425 build_device(cfg, context);
1428 ast_config_destroy(cfg);
1435 static int pvt_hash_cb(const void *obj, const int flags)
1437 const struct console_pvt *pvt = obj;
1439 return ast_str_case_hash(pvt->name);
1442 static int pvt_cmp_cb(void *obj, void *arg, int flags)
1444 struct console_pvt *pvt = obj, *pvt2 = arg;
1446 return !strcasecmp(pvt->name, pvt2->name) ? CMP_MATCH | CMP_STOP : 0;
1449 static void stop_streams(void)
1451 struct console_pvt *pvt;
1452 struct ao2_iterator i;
1454 i = ao2_iterator_init(pvts, 0);
1455 while ((pvt = ao2_iterator_next(&i))) {
1460 ao2_iterator_destroy(&i);
1463 static int unload_module(void)
1465 console_tech.capabilities = ast_format_cap_destroy(console_tech.capabilities);
1466 ast_channel_unregister(&console_tech);
1467 ast_cli_unregister_multiple(cli_console, ARRAY_LEN(cli_console));
1473 /* Will unref all the pvts so they will get destroyed, too */
1476 pvt_destructor(&globals);
1482 * \brief Load the module
1484 * Module loading including tests for configuration or dependencies.
1485 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1486 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1487 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1488 * configuration file or other non-critical problem return
1489 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1491 static int load_module(void)
1493 struct ast_format tmpfmt;
1496 if (!(console_tech.capabilities = ast_format_cap_alloc())) {
1497 return AST_MODULE_LOAD_DECLINE;
1499 ast_format_cap_add(console_tech.capabilities, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR16, 0));
1501 init_pvt(&globals, NULL);
1503 if (!(pvts = ao2_container_alloc(NUM_PVT_BUCKETS, pvt_hash_cb, pvt_cmp_cb)))
1509 res = Pa_Initialize();
1510 if (res != paNoError) {
1511 ast_log(LOG_WARNING, "Failed to initialize audio system - (%d) %s\n",
1512 res, Pa_GetErrorText(res));
1513 goto return_error_pa_init;
1516 if (ast_channel_register(&console_tech)) {
1517 ast_log(LOG_ERROR, "Unable to register channel type 'Console'\n");
1518 goto return_error_chan_reg;
1521 if (ast_cli_register_multiple(cli_console, ARRAY_LEN(cli_console)))
1522 goto return_error_cli_reg;
1524 return AST_MODULE_LOAD_SUCCESS;
1526 return_error_cli_reg:
1527 ast_cli_unregister_multiple(cli_console, ARRAY_LEN(cli_console));
1528 return_error_chan_reg:
1529 ast_channel_unregister(&console_tech);
1530 return_error_pa_init:
1536 pvt_destructor(&globals);
1538 return AST_MODULE_LOAD_DECLINE;
1541 static int reload(void)
1543 return load_config(1);
1546 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Console Channel Driver",
1547 .load = load_module,
1548 .unload = unload_module,
1550 .load_pri = AST_MODPRI_CHANNEL_DRIVER,