504cb902c450384b046bf57d84d45f9cc3da1a0b
[asterisk/asterisk.git] / channels / chan_oss.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2007, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * FreeBSD changes and multiple device support by Luigi Rizzo, 2005.05.25
9  * note-this code best seen with ts=8 (8-spaces tabs) in the editor
10  *
11  * See http://www.asterisk.org for more information about
12  * the Asterisk project. Please do not directly contact
13  * any of the maintainers of this project for assistance;
14  * the project provides a web site, mailing lists and IRC
15  * channels for your use.
16  *
17  * This program is free software, distributed under the terms of
18  * the GNU General Public License Version 2. See the LICENSE file
19  * at the top of the source tree.
20  */
21
22 // #define HAVE_VIDEO_CONSOLE   // uncomment to enable video
23 /*! \file
24  *
25  * \brief Channel driver for OSS sound cards
26  *
27  * \author Mark Spencer <markster@digium.com>
28  * \author Luigi Rizzo
29  *
30  * \ingroup channel_drivers
31  */
32
33 /*!
34  * \li The channel chan_oss uses the configuration file \ref oss.conf
35  * \addtogroup configuration_file
36  */
37
38 /*! \page oss.conf oss.conf
39  * \verbinclude oss.conf.sample
40  */
41
42 /*** MODULEINFO
43         <depend>oss</depend>
44         <support_level>extended</support_level>
45  ***/
46
47 #include "asterisk.h"
48
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
50
51 #include <ctype.h>              /* isalnum() used here */
52 #include <math.h>
53 #include <sys/ioctl.h>          
54
55 #ifdef __linux
56 #include <linux/soundcard.h>
57 #elif defined(__FreeBSD__) || defined(__CYGWIN__) || defined(__GLIBC__)
58 #include <sys/soundcard.h>
59 #else
60 #include <soundcard.h>
61 #endif
62
63 #include "asterisk/channel.h"
64 #include "asterisk/file.h"
65 #include "asterisk/callerid.h"
66 #include "asterisk/module.h"
67 #include "asterisk/pbx.h"
68 #include "asterisk/cli.h"
69 #include "asterisk/causes.h"
70 #include "asterisk/musiconhold.h"
71 #include "asterisk/app.h"
72
73 #include "console_video.h"
74
75 /*! Global jitterbuffer configuration - by default, jb is disabled
76  *  \note Values shown here match the defaults shown in oss.conf.sample */
77 static struct ast_jb_conf default_jbconf =
78 {
79         .flags = 0,
80         .max_size = 200,
81         .resync_threshold = 1000,
82         .impl = "fixed",
83         .target_extra = 40,
84 };
85 static struct ast_jb_conf global_jbconf;
86
87 /*
88  * Basic mode of operation:
89  *
90  * we have one keyboard (which receives commands from the keyboard)
91  * and multiple headset's connected to audio cards.
92  * Cards/Headsets are named as the sections of oss.conf.
93  * The section called [general] contains the default parameters.
94  *
95  * At any time, the keyboard is attached to one card, and you
96  * can switch among them using the command 'console foo'
97  * where 'foo' is the name of the card you want.
98  *
99  * oss.conf parameters are
100 START_CONFIG
101
102 [general]
103     ; General config options, with default values shown.
104     ; You should use one section per device, with [general] being used
105     ; for the first device and also as a template for other devices.
106     ;
107     ; All but 'debug' can go also in the device-specific sections.
108     ;
109     ; debug = 0x0               ; misc debug flags, default is 0
110
111     ; Set the device to use for I/O
112     ; device = /dev/dsp
113
114     ; Optional mixer command to run upon startup (e.g. to set
115     ; volume levels, mutes, etc.
116     ; mixer =
117
118     ; Software mic volume booster (or attenuator), useful for sound
119     ; cards or microphones with poor sensitivity. The volume level
120     ; is in dB, ranging from -20.0 to +20.0
121     ; boost = n                 ; mic volume boost in dB
122
123     ; Set the callerid for outgoing calls
124     ; callerid = John Doe <555-1234>
125
126     ; autoanswer = no           ; no autoanswer on call
127     ; autohangup = yes          ; hangup when other party closes
128     ; extension = s             ; default extension to call
129     ; context = default         ; default context for outgoing calls
130     ; language = ""             ; default language
131
132     ; Default Music on Hold class to use when this channel is placed on hold in
133     ; the case that the music class is not set on the channel with
134     ; Set(CHANNEL(musicclass)=whatever) in the dialplan and the peer channel
135     ; putting this one on hold did not suggest a class to use.
136     ;
137     ; mohinterpret=default
138
139     ; If you set overridecontext to 'yes', then the whole dial string
140     ; will be interpreted as an extension, which is extremely useful
141     ; to dial SIP, IAX and other extensions which use the '@' character.
142     ; The default is 'no' just for backward compatibility, but the
143     ; suggestion is to change it.
144     ; overridecontext = no      ; if 'no', the last @ will start the context
145                                 ; if 'yes' the whole string is an extension.
146
147     ; low level device parameters in case you have problems with the
148     ; device driver on your operating system. You should not touch these
149     ; unless you know what you are doing.
150     ; queuesize = 10            ; frames in device driver
151     ; frags = 8                 ; argument to SETFRAGMENT
152
153     ;------------------------------ JITTER BUFFER CONFIGURATION --------------------------
154     ; jbenable = yes              ; Enables the use of a jitterbuffer on the receiving side of an
155                                   ; OSS channel. Defaults to "no". An enabled jitterbuffer will
156                                   ; be used only if the sending side can create and the receiving
157                                   ; side can not accept jitter. The OSS channel can't accept jitter,
158                                   ; thus an enabled jitterbuffer on the receive OSS side will always
159                                   ; be used if the sending side can create jitter.
160
161     ; jbmaxsize = 200             ; Max length of the jitterbuffer in milliseconds.
162
163     ; jbresyncthreshold = 1000    ; Jump in the frame timestamps over which the jitterbuffer is
164                                   ; resynchronized. Useful to improve the quality of the voice, with
165                                   ; big jumps in/broken timestamps, usualy sent from exotic devices
166                                   ; and programs. Defaults to 1000.
167
168     ; jbimpl = fixed              ; Jitterbuffer implementation, used on the receiving side of an OSS
169                                   ; channel. Two implementations are currenlty available - "fixed"
170                                   ; (with size always equals to jbmax-size) and "adaptive" (with
171                                   ; variable size, actually the new jb of IAX2). Defaults to fixed.
172
173     ; jblog = no                  ; Enables jitterbuffer frame logging. Defaults to "no".
174     ;-----------------------------------------------------------------------------------
175
176 [card1]
177     ; device = /dev/dsp1        ; alternate device
178
179 END_CONFIG
180
181 .. and so on for the other cards.
182
183  */
184
185 /*
186  * The following parameters are used in the driver:
187  *
188  *  FRAME_SIZE  the size of an audio frame, in samples.
189  *              160 is used almost universally, so you should not change it.
190  *
191  *  FRAGS       the argument for the SETFRAGMENT ioctl.
192  *              Overridden by the 'frags' parameter in oss.conf
193  *
194  *              Bits 0-7 are the base-2 log of the device's block size,
195  *              bits 16-31 are the number of blocks in the driver's queue.
196  *              There are a lot of differences in the way this parameter
197  *              is supported by different drivers, so you may need to
198  *              experiment a bit with the value.
199  *              A good default for linux is 30 blocks of 64 bytes, which
200  *              results in 6 frames of 320 bytes (160 samples).
201  *              FreeBSD works decently with blocks of 256 or 512 bytes,
202  *              leaving the number unspecified.
203  *              Note that this only refers to the device buffer size,
204  *              this module will then try to keep the lenght of audio
205  *              buffered within small constraints.
206  *
207  *  QUEUE_SIZE  The max number of blocks actually allowed in the device
208  *              driver's buffer, irrespective of the available number.
209  *              Overridden by the 'queuesize' parameter in oss.conf
210  *
211  *              Should be >=2, and at most as large as the hw queue above
212  *              (otherwise it will never be full).
213  */
214
215 #define FRAME_SIZE      160
216 #define QUEUE_SIZE      10
217
218 #if defined(__FreeBSD__)
219 #define FRAGS   0x8
220 #else
221 #define FRAGS   ( ( (6 * 5) << 16 ) | 0x6 )
222 #endif
223
224 /*
225  * XXX text message sizes are probably 256 chars, but i am
226  * not sure if there is a suitable definition anywhere.
227  */
228 #define TEXT_SIZE       256
229
230 #if 0
231 #define TRYOPEN 1                               /* try to open on startup */
232 #endif
233 #define O_CLOSE 0x444                   /* special 'close' mode for device */
234 /* Which device to use */
235 #if defined( __OpenBSD__ ) || defined( __NetBSD__ )
236 #define DEV_DSP "/dev/audio"
237 #else
238 #define DEV_DSP "/dev/dsp"
239 #endif
240
241 static char *config = "oss.conf";       /* default config file */
242
243 static int oss_debug;
244
245 /*!
246  * \brief descriptor for one of our channels.
247  *
248  * There is one used for 'default' values (from the [general] entry in
249  * the configuration file), and then one instance for each device
250  * (the default is cloned from [general], others are only created
251  * if the relevant section exists).
252  */
253 struct chan_oss_pvt {
254         struct chan_oss_pvt *next;
255
256         char *name;
257         int total_blocks;                       /*!< total blocks in the output device */
258         int sounddev;
259         enum { M_UNSET, M_FULL, M_READ, M_WRITE } duplex;
260         int autoanswer;             /*!< Boolean: whether to answer the immediately upon calling */
261         int autohangup;             /*!< Boolean: whether to hangup the call when the remote end hangs up */
262         int hookstate;              /*!< Boolean: 1 if offhook; 0 if onhook */
263         char *mixer_cmd;                        /*!< initial command to issue to the mixer */
264         unsigned int queuesize;         /*!< max fragments in queue */
265         unsigned int frags;                     /*!< parameter for SETFRAGMENT */
266
267         int warned;                                     /*!< various flags used for warnings */
268 #define WARN_used_blocks        1
269 #define WARN_speed              2
270 #define WARN_frag               4
271         int w_errors;                           /*!< overfull in the write path */
272         struct timeval lastopen;
273
274         int overridecontext;
275         int mute;
276
277         /*! boost support. BOOST_SCALE * 10 ^(BOOST_MAX/20) must
278          *  be representable in 16 bits to avoid overflows.
279          */
280 #define BOOST_SCALE     (1<<9)
281 #define BOOST_MAX       40                      /*!< slightly less than 7 bits */
282         int boost;                                      /*!< input boost, scaled by BOOST_SCALE */
283         char device[64];                        /*!< device to open */
284
285         pthread_t sthread;
286
287         struct ast_channel *owner;
288
289         struct video_desc *env;                 /*!< parameters for video support */
290
291         char ext[AST_MAX_EXTENSION];
292         char ctx[AST_MAX_CONTEXT];
293         char language[MAX_LANGUAGE];
294         char cid_name[256];         /*!< Initial CallerID name */
295         char cid_num[256];          /*!< Initial CallerID number  */
296         char mohinterpret[MAX_MUSICCLASS];
297
298         /*! buffers used in oss_write */
299         char oss_write_buf[FRAME_SIZE * 2];
300         int oss_write_dst;
301         /*! buffers used in oss_read - AST_FRIENDLY_OFFSET space for headers
302          *  plus enough room for a full frame
303          */
304         char oss_read_buf[FRAME_SIZE * 2 + AST_FRIENDLY_OFFSET];
305         int readpos;                            /*!< read position above */
306         struct ast_frame read_f;        /*!< returned by oss_read */
307 };
308
309 /*! forward declaration */
310 static struct chan_oss_pvt *find_desc(const char *dev);
311
312 static char *oss_active;         /*!< the active device */
313
314 /*! \brief return the pointer to the video descriptor */
315 struct video_desc *get_video_desc(struct ast_channel *c)
316 {
317         struct chan_oss_pvt *o = c ? ast_channel_tech_pvt(c) : find_desc(oss_active);
318         return o ? o->env : NULL;
319 }
320 static struct chan_oss_pvt oss_default = {
321         .sounddev = -1,
322         .duplex = M_UNSET,                      /* XXX check this */
323         .autoanswer = 1,
324         .autohangup = 1,
325         .queuesize = QUEUE_SIZE,
326         .frags = FRAGS,
327         .ext = "s",
328         .ctx = "default",
329         .readpos = AST_FRIENDLY_OFFSET, /* start here on reads */
330         .lastopen = { 0, 0 },
331         .boost = BOOST_SCALE,
332 };
333
334
335 static int setformat(struct chan_oss_pvt *o, int mode);
336
337 static struct ast_channel *oss_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor,
338                                                                            const char *data, int *cause);
339 static int oss_digit_begin(struct ast_channel *c, char digit);
340 static int oss_digit_end(struct ast_channel *c, char digit, unsigned int duration);
341 static int oss_text(struct ast_channel *c, const char *text);
342 static int oss_hangup(struct ast_channel *c);
343 static int oss_answer(struct ast_channel *c);
344 static struct ast_frame *oss_read(struct ast_channel *chan);
345 static int oss_call(struct ast_channel *c, const char *dest, int timeout);
346 static int oss_write(struct ast_channel *chan, struct ast_frame *f);
347 static int oss_indicate(struct ast_channel *chan, int cond, const void *data, size_t datalen);
348 static int oss_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
349 static char tdesc[] = "OSS Console Channel Driver";
350
351 /* cannot do const because need to update some fields at runtime */
352 static struct ast_channel_tech oss_tech = {
353         .type = "Console",
354         .description = tdesc,
355         .requester = oss_request,
356         .send_digit_begin = oss_digit_begin,
357         .send_digit_end = oss_digit_end,
358         .send_text = oss_text,
359         .hangup = oss_hangup,
360         .answer = oss_answer,
361         .read = oss_read,
362         .call = oss_call,
363         .write = oss_write,
364         .write_video = console_write_video,
365         .indicate = oss_indicate,
366         .fixup = oss_fixup,
367 };
368
369 /*!
370  * \brief returns a pointer to the descriptor with the given name
371  */
372 static struct chan_oss_pvt *find_desc(const char *dev)
373 {
374         struct chan_oss_pvt *o = NULL;
375
376         if (!dev)
377                 ast_log(LOG_WARNING, "null dev\n");
378
379         for (o = oss_default.next; o && o->name && dev && strcmp(o->name, dev) != 0; o = o->next);
380
381         if (!o)
382                 ast_log(LOG_WARNING, "could not find <%s>\n", dev ? dev : "--no-device--");
383
384         return o;
385 }
386
387 /* !
388  * \brief split a string in extension-context, returns pointers to malloc'ed
389  *        strings.
390  *
391  * If we do not have 'overridecontext' then the last @ is considered as
392  * a context separator, and the context is overridden.
393  * This is usually not very necessary as you can play with the dialplan,
394  * and it is nice not to need it because you have '@' in SIP addresses.
395  *
396  * \return the buffer address.
397  */
398 static char *ast_ext_ctx(const char *src, char **ext, char **ctx)
399 {
400         struct chan_oss_pvt *o = find_desc(oss_active);
401
402         if (ext == NULL || ctx == NULL)
403                 return NULL;                    /* error */
404
405         *ext = *ctx = NULL;
406
407         if (src && *src != '\0')
408                 *ext = ast_strdup(src);
409
410         if (*ext == NULL)
411                 return NULL;
412
413         if (!o->overridecontext) {
414                 /* parse from the right */
415                 *ctx = strrchr(*ext, '@');
416                 if (*ctx)
417                         *(*ctx)++ = '\0';
418         }
419
420         return *ext;
421 }
422
423 /*!
424  * \brief Returns the number of blocks used in the audio output channel
425  */
426 static int used_blocks(struct chan_oss_pvt *o)
427 {
428         struct audio_buf_info info;
429
430         if (ioctl(o->sounddev, SNDCTL_DSP_GETOSPACE, &info)) {
431                 if (!(o->warned & WARN_used_blocks)) {
432                         ast_log(LOG_WARNING, "Error reading output space\n");
433                         o->warned |= WARN_used_blocks;
434                 }
435                 return 1;
436         }
437
438         if (o->total_blocks == 0) {
439                 if (0)                                  /* debugging */
440                         ast_log(LOG_WARNING, "fragtotal %d size %d avail %d\n", info.fragstotal, info.fragsize, info.fragments);
441                 o->total_blocks = info.fragments;
442         }
443
444         return o->total_blocks - info.fragments;
445 }
446
447 /*! Write an exactly FRAME_SIZE sized frame */
448 static int soundcard_writeframe(struct chan_oss_pvt *o, short *data)
449 {
450         int res;
451
452         if (o->sounddev < 0)
453                 setformat(o, O_RDWR);
454         if (o->sounddev < 0)
455                 return 0;                               /* not fatal */
456         /*
457          * Nothing complex to manage the audio device queue.
458          * If the buffer is full just drop the extra, otherwise write.
459          * XXX in some cases it might be useful to write anyways after
460          * a number of failures, to restart the output chain.
461          */
462         res = used_blocks(o);
463         if (res > o->queuesize) {       /* no room to write a block */
464                 if (o->w_errors++ == 0 && (oss_debug & 0x4))
465                         ast_log(LOG_WARNING, "write: used %d blocks (%d)\n", res, o->w_errors);
466                 return 0;
467         }
468         o->w_errors = 0;
469         return write(o->sounddev, (void *)data, FRAME_SIZE * 2);
470 }
471
472 /*!
473  * reset and close the device if opened,
474  * then open and initialize it in the desired mode,
475  * trigger reads and writes so we can start using it.
476  */
477 static int setformat(struct chan_oss_pvt *o, int mode)
478 {
479         int fmt, desired, res, fd;
480
481         if (o->sounddev >= 0) {
482                 ioctl(o->sounddev, SNDCTL_DSP_RESET, 0);
483                 close(o->sounddev);
484                 o->duplex = M_UNSET;
485                 o->sounddev = -1;
486         }
487         if (mode == O_CLOSE)            /* we are done */
488                 return 0;
489         if (ast_tvdiff_ms(ast_tvnow(), o->lastopen) < 1000)
490                 return -1;                              /* don't open too often */
491         o->lastopen = ast_tvnow();
492         fd = o->sounddev = open(o->device, mode | O_NONBLOCK);
493         if (fd < 0) {
494                 ast_log(LOG_WARNING, "Unable to re-open DSP device %s: %s\n", o->device, strerror(errno));
495                 return -1;
496         }
497         if (o->owner)
498                 ast_channel_set_fd(o->owner, 0, fd);
499
500 #if __BYTE_ORDER == __LITTLE_ENDIAN
501         fmt = AFMT_S16_LE;
502 #else
503         fmt = AFMT_S16_BE;
504 #endif
505         res = ioctl(fd, SNDCTL_DSP_SETFMT, &fmt);
506         if (res < 0) {
507                 ast_log(LOG_WARNING, "Unable to set format to 16-bit signed\n");
508                 return -1;
509         }
510         switch (mode) {
511         case O_RDWR:
512                 res = ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
513                 /* Check to see if duplex set (FreeBSD Bug) */
514                 res = ioctl(fd, SNDCTL_DSP_GETCAPS, &fmt);
515                 if (res == 0 && (fmt & DSP_CAP_DUPLEX)) {
516                         ast_verb(2, "Console is full duplex\n");
517                         o->duplex = M_FULL;
518                 };
519                 break;
520
521         case O_WRONLY:
522                 o->duplex = M_WRITE;
523                 break;
524
525         case O_RDONLY:
526                 o->duplex = M_READ;
527                 break;
528         }
529
530         fmt = 0;
531         res = ioctl(fd, SNDCTL_DSP_STEREO, &fmt);
532         if (res < 0) {
533                 ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
534                 return -1;
535         }
536         fmt = desired = DEFAULT_SAMPLE_RATE;    /* 8000 Hz desired */
537         res = ioctl(fd, SNDCTL_DSP_SPEED, &fmt);
538
539         if (res < 0) {
540                 ast_log(LOG_WARNING, "Failed to set sample rate to %d\n", desired);
541                 return -1;
542         }
543         if (fmt != desired) {
544                 if (!(o->warned & WARN_speed)) {
545                         ast_log(LOG_WARNING,
546                             "Requested %d Hz, got %d Hz -- sound may be choppy\n",
547                             desired, fmt);
548                         o->warned |= WARN_speed;
549                 }
550         }
551         /*
552          * on Freebsd, SETFRAGMENT does not work very well on some cards.
553          * Default to use 256 bytes, let the user override
554          */
555         if (o->frags) {
556                 fmt = o->frags;
557                 res = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &fmt);
558                 if (res < 0) {
559                         if (!(o->warned & WARN_frag)) {
560                                 ast_log(LOG_WARNING,
561                                         "Unable to set fragment size -- sound may be choppy\n");
562                                 o->warned |= WARN_frag;
563                         }
564                 }
565         }
566         /* on some cards, we need SNDCTL_DSP_SETTRIGGER to start outputting */
567         res = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;
568         res = ioctl(fd, SNDCTL_DSP_SETTRIGGER, &res);
569         /* it may fail if we are in half duplex, never mind */
570         return 0;
571 }
572
573 /*
574  * some of the standard methods supported by channels.
575  */
576 static int oss_digit_begin(struct ast_channel *c, char digit)
577 {
578         return 0;
579 }
580
581 static int oss_digit_end(struct ast_channel *c, char digit, unsigned int duration)
582 {
583         /* no better use for received digits than print them */
584         ast_verbose(" << Console Received digit %c of duration %u ms >> \n", 
585                 digit, duration);
586         return 0;
587 }
588
589 static int oss_text(struct ast_channel *c, const char *text)
590 {
591         /* print received messages */
592         ast_verbose(" << Console Received text %s >> \n", text);
593         return 0;
594 }
595
596 /*!
597  * \brief handler for incoming calls. Either autoanswer, or start ringing
598  */
599 static int oss_call(struct ast_channel *c, const char *dest, int timeout)
600 {
601         struct chan_oss_pvt *o = ast_channel_tech_pvt(c);
602         struct ast_frame f = { AST_FRAME_CONTROL, };
603         AST_DECLARE_APP_ARGS(args,
604                 AST_APP_ARG(name);
605                 AST_APP_ARG(flags);
606         );
607         char *parse = ast_strdupa(dest);
608
609         AST_NONSTANDARD_APP_ARGS(args, parse, '/');
610
611         ast_verbose(" << Call to device '%s' dnid '%s' rdnis '%s' on console from '%s' <%s> >>\n",
612                 dest,
613                 S_OR(ast_channel_dialed(c)->number.str, ""),
614                 S_COR(ast_channel_redirecting(c)->from.number.valid, ast_channel_redirecting(c)->from.number.str, ""),
615                 S_COR(ast_channel_caller(c)->id.name.valid, ast_channel_caller(c)->id.name.str, ""),
616                 S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, ""));
617         if (!ast_strlen_zero(args.flags) && strcasecmp(args.flags, "answer") == 0) {
618                 f.subclass.integer = AST_CONTROL_ANSWER;
619                 ast_queue_frame(c, &f);
620         } else if (!ast_strlen_zero(args.flags) && strcasecmp(args.flags, "noanswer") == 0) {
621                 f.subclass.integer = AST_CONTROL_RINGING;
622                 ast_queue_frame(c, &f);
623                 ast_indicate(c, AST_CONTROL_RINGING);
624         } else if (o->autoanswer) {
625                 ast_verbose(" << Auto-answered >> \n");
626                 f.subclass.integer = AST_CONTROL_ANSWER;
627                 ast_queue_frame(c, &f);
628                 o->hookstate = 1;
629         } else {
630                 ast_verbose("<< Type 'answer' to answer, or use 'autoanswer' for future calls >> \n");
631                 f.subclass.integer = AST_CONTROL_RINGING;
632                 ast_queue_frame(c, &f);
633                 ast_indicate(c, AST_CONTROL_RINGING);
634         }
635         return 0;
636 }
637
638 /*!
639  * \brief remote side answered the phone
640  */
641 static int oss_answer(struct ast_channel *c)
642 {
643         struct chan_oss_pvt *o = ast_channel_tech_pvt(c);
644         ast_verbose(" << Console call has been answered >> \n");
645         ast_setstate(c, AST_STATE_UP);
646         o->hookstate = 1;
647         return 0;
648 }
649
650 static int oss_hangup(struct ast_channel *c)
651 {
652         struct chan_oss_pvt *o = ast_channel_tech_pvt(c);
653
654         ast_channel_tech_pvt_set(c, NULL);
655         o->owner = NULL;
656         ast_verbose(" << Hangup on console >> \n");
657         console_video_uninit(o->env);
658         ast_module_unref(ast_module_info->self);
659         if (o->hookstate) {
660                 if (o->autoanswer || o->autohangup) {
661                         /* Assume auto-hangup too */
662                         o->hookstate = 0;
663                         setformat(o, O_CLOSE);
664                 }
665         }
666         return 0;
667 }
668
669 /*! \brief used for data coming from the network */
670 static int oss_write(struct ast_channel *c, struct ast_frame *f)
671 {
672         int src;
673         struct chan_oss_pvt *o = ast_channel_tech_pvt(c);
674
675         /*
676          * we could receive a block which is not a multiple of our
677          * FRAME_SIZE, so buffer it locally and write to the device
678          * in FRAME_SIZE chunks.
679          * Keep the residue stored for future use.
680          */
681         src = 0;                                        /* read position into f->data */
682         while (src < f->datalen) {
683                 /* Compute spare room in the buffer */
684                 int l = sizeof(o->oss_write_buf) - o->oss_write_dst;
685
686                 if (f->datalen - src >= l) {    /* enough to fill a frame */
687                         memcpy(o->oss_write_buf + o->oss_write_dst, f->data.ptr + src, l);
688                         soundcard_writeframe(o, (short *) o->oss_write_buf);
689                         src += l;
690                         o->oss_write_dst = 0;
691                 } else {                                /* copy residue */
692                         l = f->datalen - src;
693                         memcpy(o->oss_write_buf + o->oss_write_dst, f->data.ptr + src, l);
694                         src += l;                       /* but really, we are done */
695                         o->oss_write_dst += l;
696                 }
697         }
698         return 0;
699 }
700
701 static struct ast_frame *oss_read(struct ast_channel *c)
702 {
703         int res;
704         struct chan_oss_pvt *o = ast_channel_tech_pvt(c);
705         struct ast_frame *f = &o->read_f;
706
707         /* XXX can be simplified returning &ast_null_frame */
708         /* prepare a NULL frame in case we don't have enough data to return */
709         memset(f, '\0', sizeof(struct ast_frame));
710         f->frametype = AST_FRAME_NULL;
711         f->src = oss_tech.type;
712
713         res = read(o->sounddev, o->oss_read_buf + o->readpos, sizeof(o->oss_read_buf) - o->readpos);
714         if (res < 0)                            /* audio data not ready, return a NULL frame */
715                 return f;
716
717         o->readpos += res;
718         if (o->readpos < sizeof(o->oss_read_buf))       /* not enough samples */
719                 return f;
720
721         if (o->mute)
722                 return f;
723
724         o->readpos = AST_FRIENDLY_OFFSET;       /* reset read pointer for next frame */
725         if (ast_channel_state(c) != AST_STATE_UP)       /* drop data if frame is not up */
726                 return f;
727         /* ok we can build and deliver the frame to the caller */
728         f->frametype = AST_FRAME_VOICE;
729         ast_format_set(&f->subclass.format, AST_FORMAT_SLINEAR, 0);
730         f->samples = FRAME_SIZE;
731         f->datalen = FRAME_SIZE * 2;
732         f->data.ptr = o->oss_read_buf + AST_FRIENDLY_OFFSET;
733         if (o->boost != BOOST_SCALE) {  /* scale and clip values */
734                 int i, x;
735                 int16_t *p = (int16_t *) f->data.ptr;
736                 for (i = 0; i < f->samples; i++) {
737                         x = (p[i] * o->boost) / BOOST_SCALE;
738                         if (x > 32767)
739                                 x = 32767;
740                         else if (x < -32768)
741                                 x = -32768;
742                         p[i] = x;
743                 }
744         }
745
746         f->offset = AST_FRIENDLY_OFFSET;
747         return f;
748 }
749
750 static int oss_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
751 {
752         struct chan_oss_pvt *o = ast_channel_tech_pvt(newchan);
753         o->owner = newchan;
754         return 0;
755 }
756
757 static int oss_indicate(struct ast_channel *c, int cond, const void *data, size_t datalen)
758 {
759         struct chan_oss_pvt *o = ast_channel_tech_pvt(c);
760         int res = 0;
761
762         switch (cond) {
763         case AST_CONTROL_INCOMPLETE:
764         case AST_CONTROL_BUSY:
765         case AST_CONTROL_CONGESTION:
766         case AST_CONTROL_RINGING:
767         case AST_CONTROL_PVT_CAUSE_CODE:
768         case -1:
769                 res = -1;
770                 break;
771         case AST_CONTROL_PROGRESS:
772         case AST_CONTROL_PROCEEDING:
773         case AST_CONTROL_VIDUPDATE:
774         case AST_CONTROL_SRCUPDATE:
775                 break;
776         case AST_CONTROL_HOLD:
777                 ast_verbose(" << Console Has Been Placed on Hold >> \n");
778                 ast_moh_start(c, data, o->mohinterpret);
779                 break;
780         case AST_CONTROL_UNHOLD:
781                 ast_verbose(" << Console Has Been Retrieved from Hold >> \n");
782                 ast_moh_stop(c);
783                 break;
784         default:
785                 ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, ast_channel_name(c));
786                 return -1;
787         }
788
789         return res;
790 }
791
792 /*!
793  * \brief allocate a new channel.
794  */
795 static struct ast_channel *oss_new(struct chan_oss_pvt *o, char *ext, char *ctx, int state, const char *linkedid)
796 {
797         struct ast_channel *c;
798
799         c = ast_channel_alloc(1, state, o->cid_num, o->cid_name, "", ext, ctx, linkedid, 0, "Console/%s", o->device + 5);
800         if (c == NULL)
801                 return NULL;
802         ast_channel_tech_set(c, &oss_tech);
803         if (o->sounddev < 0)
804                 setformat(o, O_RDWR);
805         ast_channel_set_fd(c, 0, o->sounddev); /* -1 if device closed, override later */
806
807         ast_format_set(ast_channel_readformat(c), AST_FORMAT_SLINEAR, 0);
808         ast_format_set(ast_channel_writeformat(c), AST_FORMAT_SLINEAR, 0);
809         ast_format_cap_add(ast_channel_nativeformats(c), ast_channel_readformat(c));
810
811         /* if the console makes the call, add video to the offer */
812         /* if (state == AST_STATE_RINGING) TODO XXX CONSOLE VIDEO IS DISABLED UNTIL IT GETS A MAINTAINER
813                 c->nativeformats |= console_video_formats; */
814
815         ast_channel_tech_pvt_set(c, o);
816
817         if (!ast_strlen_zero(o->language))
818                 ast_channel_language_set(c, o->language);
819         /* Don't use ast_set_callerid() here because it will
820          * generate a needless NewCallerID event */
821         if (!ast_strlen_zero(o->cid_num)) {
822                 ast_channel_caller(c)->ani.number.valid = 1;
823                 ast_channel_caller(c)->ani.number.str = ast_strdup(o->cid_num);
824         }
825         if (!ast_strlen_zero(ext)) {
826                 ast_channel_dialed(c)->number.str = ast_strdup(ext);
827         }
828
829         o->owner = c;
830         ast_module_ref(ast_module_info->self);
831         ast_jb_configure(c, &global_jbconf);
832         if (state != AST_STATE_DOWN) {
833                 if (ast_pbx_start(c)) {
834                         ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(c));
835                         ast_hangup(c);
836                         o->owner = c = NULL;
837                 }
838         }
839         console_video_start(get_video_desc(c), c); /* XXX cleanup */
840
841         return c;
842 }
843
844 static struct ast_channel *oss_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause)
845 {
846         struct ast_channel *c;
847         struct chan_oss_pvt *o;
848         AST_DECLARE_APP_ARGS(args,
849                 AST_APP_ARG(name);
850                 AST_APP_ARG(flags);
851         );
852         char *parse = ast_strdupa(data);
853         char buf[256];
854         struct ast_format tmpfmt;
855
856         AST_NONSTANDARD_APP_ARGS(args, parse, '/');
857         o = find_desc(args.name);
858
859         ast_log(LOG_WARNING, "oss_request ty <%s> data 0x%p <%s>\n", type, data, data);
860         if (o == NULL) {
861                 ast_log(LOG_NOTICE, "Device %s not found\n", args.name);
862                 /* XXX we could default to 'dsp' perhaps ? */
863                 return NULL;
864         }
865         if (!(ast_format_cap_iscompatible(cap, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0)))) {
866                 ast_log(LOG_NOTICE, "Format %s unsupported\n", ast_getformatname_multiple(buf, sizeof(buf), cap));
867                 return NULL;
868         }
869         if (o->owner) {
870                 ast_log(LOG_NOTICE, "Already have a call (chan %p) on the OSS channel\n", o->owner);
871                 *cause = AST_CAUSE_BUSY;
872                 return NULL;
873         }
874         c = oss_new(o, NULL, NULL, AST_STATE_DOWN, requestor ? ast_channel_linkedid(requestor) : NULL);
875         if (c == NULL) {
876                 ast_log(LOG_WARNING, "Unable to create new OSS channel\n");
877                 return NULL;
878         }
879         return c;
880 }
881
882 static void store_config_core(struct chan_oss_pvt *o, const char *var, const char *value);
883
884 /*! Generic console command handler. Basically a wrapper for a subset
885  *  of config file options which are also available from the CLI
886  */
887 static char *console_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
888 {
889         struct chan_oss_pvt *o = find_desc(oss_active);
890         const char *var, *value;
891         switch (cmd) {
892         case CLI_INIT:
893                 e->command = CONSOLE_VIDEO_CMDS;
894                 e->usage = 
895                         "Usage: " CONSOLE_VIDEO_CMDS "...\n"
896                         "       Generic handler for console commands.\n";
897                 return NULL;
898
899         case CLI_GENERATE:
900                 return NULL;
901         }
902
903         if (a->argc < e->args)
904                 return CLI_SHOWUSAGE;
905         if (o == NULL) {
906                 ast_log(LOG_WARNING, "Cannot find device %s (should not happen!)\n",
907                         oss_active);
908                 return CLI_FAILURE;
909         }
910         var = a->argv[e->args-1];
911         value = a->argc > e->args ? a->argv[e->args] : NULL;
912         if (value)      /* handle setting */
913                 store_config_core(o, var, value);
914         if (!console_video_cli(o->env, var, a->fd))     /* print video-related values */
915                 return CLI_SUCCESS;
916         /* handle other values */
917         if (!strcasecmp(var, "device")) {
918                 ast_cli(a->fd, "device is [%s]\n", o->device);
919         }
920         return CLI_SUCCESS;
921 }
922
923 static char *console_autoanswer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
924 {
925         struct chan_oss_pvt *o = find_desc(oss_active);
926
927         switch (cmd) {
928         case CLI_INIT:
929                 e->command = "console {set|show} autoanswer [on|off]";
930                 e->usage =
931                         "Usage: console {set|show} autoanswer [on|off]\n"
932                         "       Enables or disables autoanswer feature.  If used without\n"
933                         "       argument, displays the current on/off status of autoanswer.\n"
934                         "       The default value of autoanswer is in 'oss.conf'.\n";
935                 return NULL;
936
937         case CLI_GENERATE:
938                 return NULL;
939         }
940
941         if (a->argc == e->args - 1) {
942                 ast_cli(a->fd, "Auto answer is %s.\n", o->autoanswer ? "on" : "off");
943                 return CLI_SUCCESS;
944         }
945         if (a->argc != e->args)
946                 return CLI_SHOWUSAGE;
947         if (o == NULL) {
948                 ast_log(LOG_WARNING, "Cannot find device %s (should not happen!)\n",
949                     oss_active);
950                 return CLI_FAILURE;
951         }
952         if (!strcasecmp(a->argv[e->args-1], "on"))
953                 o->autoanswer = 1;
954         else if (!strcasecmp(a->argv[e->args - 1], "off"))
955                 o->autoanswer = 0;
956         else
957                 return CLI_SHOWUSAGE;
958         return CLI_SUCCESS;
959 }
960
961 /*! \brief helper function for the answer key/cli command */
962 static char *console_do_answer(int fd)
963 {
964         struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_ANSWER } };
965         struct chan_oss_pvt *o = find_desc(oss_active);
966         if (!o->owner) {
967                 if (fd > -1)
968                         ast_cli(fd, "No one is calling us\n");
969                 return CLI_FAILURE;
970         }
971         o->hookstate = 1;
972         ast_queue_frame(o->owner, &f);
973         return CLI_SUCCESS;
974 }
975
976 /*!
977  * \brief answer command from the console
978  */
979 static char *console_answer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
980 {
981         switch (cmd) {
982         case CLI_INIT:
983                 e->command = "console answer";
984                 e->usage =
985                         "Usage: console answer\n"
986                         "       Answers an incoming call on the console (OSS) channel.\n";
987                 return NULL;
988
989         case CLI_GENERATE:
990                 return NULL;    /* no completion */
991         }
992         if (a->argc != e->args)
993                 return CLI_SHOWUSAGE;
994         return console_do_answer(a->fd);
995 }
996
997 /*!
998  * \brief Console send text CLI command
999  *
1000  * \note concatenate all arguments into a single string. argv is NULL-terminated
1001  * so we can use it right away
1002  */
1003 static char *console_sendtext(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1004 {
1005         struct chan_oss_pvt *o = find_desc(oss_active);
1006         char buf[TEXT_SIZE];
1007
1008         if (cmd == CLI_INIT) {
1009                 e->command = "console send text";
1010                 e->usage =
1011                         "Usage: console send text <message>\n"
1012                         "       Sends a text message for display on the remote terminal.\n";
1013                 return NULL;
1014         } else if (cmd == CLI_GENERATE)
1015                 return NULL;
1016
1017         if (a->argc < e->args + 1)
1018                 return CLI_SHOWUSAGE;
1019         if (!o->owner) {
1020                 ast_cli(a->fd, "Not in a call\n");
1021                 return CLI_FAILURE;
1022         }
1023         ast_join(buf, sizeof(buf) - 1, a->argv + e->args);
1024         if (!ast_strlen_zero(buf)) {
1025                 struct ast_frame f = { 0, };
1026                 int i = strlen(buf);
1027                 buf[i] = '\n';
1028                 f.frametype = AST_FRAME_TEXT;
1029                 f.subclass.integer = 0;
1030                 f.data.ptr = buf;
1031                 f.datalen = i + 1;
1032                 ast_queue_frame(o->owner, &f);
1033         }
1034         return CLI_SUCCESS;
1035 }
1036
1037 static char *console_hangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1038 {
1039         struct chan_oss_pvt *o = find_desc(oss_active);
1040
1041         if (cmd == CLI_INIT) {
1042                 e->command = "console hangup";
1043                 e->usage =
1044                         "Usage: console hangup\n"
1045                         "       Hangs up any call currently placed on the console.\n";
1046                 return NULL;
1047         } else if (cmd == CLI_GENERATE)
1048                 return NULL;
1049
1050         if (a->argc != e->args)
1051                 return CLI_SHOWUSAGE;
1052         if (!o->owner && !o->hookstate) { /* XXX maybe only one ? */
1053                 ast_cli(a->fd, "No call to hang up\n");
1054                 return CLI_FAILURE;
1055         }
1056         o->hookstate = 0;
1057         if (o->owner)
1058                 ast_queue_hangup_with_cause(o->owner, AST_CAUSE_NORMAL_CLEARING);
1059         setformat(o, O_CLOSE);
1060         return CLI_SUCCESS;
1061 }
1062
1063 static char *console_flash(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1064 {
1065         struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH } };
1066         struct chan_oss_pvt *o = find_desc(oss_active);
1067
1068         if (cmd == CLI_INIT) {
1069                 e->command = "console flash";
1070                 e->usage =
1071                         "Usage: console flash\n"
1072                         "       Flashes the call currently placed on the console.\n";
1073                 return NULL;
1074         } else if (cmd == CLI_GENERATE)
1075                 return NULL;
1076
1077         if (a->argc != e->args)
1078                 return CLI_SHOWUSAGE;
1079         if (!o->owner) {                        /* XXX maybe !o->hookstate too ? */
1080                 ast_cli(a->fd, "No call to flash\n");
1081                 return CLI_FAILURE;
1082         }
1083         o->hookstate = 0;
1084         if (o->owner)
1085                 ast_queue_frame(o->owner, &f);
1086         return CLI_SUCCESS;
1087 }
1088
1089 static char *console_dial(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1090 {
1091         char *s = NULL;
1092         char *mye = NULL, *myc = NULL;
1093         struct chan_oss_pvt *o = find_desc(oss_active);
1094
1095         if (cmd == CLI_INIT) {
1096                 e->command = "console dial";
1097                 e->usage =
1098                         "Usage: console dial [extension[@context]]\n"
1099                         "       Dials a given extension (and context if specified)\n";
1100                 return NULL;
1101         } else if (cmd == CLI_GENERATE)
1102                 return NULL;
1103
1104         if (a->argc > e->args + 1)
1105                 return CLI_SHOWUSAGE;
1106         if (o->owner) { /* already in a call */
1107                 int i;
1108                 struct ast_frame f = { AST_FRAME_DTMF, { 0 } };
1109                 const char *digits;
1110
1111                 if (a->argc == e->args) {       /* argument is mandatory here */
1112                         ast_cli(a->fd, "Already in a call. You can only dial digits until you hangup.\n");
1113                         return CLI_FAILURE;
1114                 }
1115                 digits = a->argv[e->args];
1116                 /* send the string one char at a time */
1117                 for (i = 0; i < strlen(digits); i++) {
1118                         f.subclass.integer = digits[i];
1119                         ast_queue_frame(o->owner, &f);
1120                 }
1121                 return CLI_SUCCESS;
1122         }
1123         /* if we have an argument split it into extension and context */
1124         if (a->argc == e->args + 1)
1125                 s = ast_ext_ctx(a->argv[e->args], &mye, &myc);
1126         /* supply default values if needed */
1127         if (mye == NULL)
1128                 mye = o->ext;
1129         if (myc == NULL)
1130                 myc = o->ctx;
1131         if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
1132                 o->hookstate = 1;
1133                 oss_new(o, mye, myc, AST_STATE_RINGING, NULL);
1134         } else
1135                 ast_cli(a->fd, "No such extension '%s' in context '%s'\n", mye, myc);
1136         if (s)
1137                 ast_free(s);
1138         return CLI_SUCCESS;
1139 }
1140
1141 static char *console_mute(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1142 {
1143         struct chan_oss_pvt *o = find_desc(oss_active);
1144         const char *s;
1145         int toggle = 0;
1146         
1147         if (cmd == CLI_INIT) {
1148                 e->command = "console {mute|unmute} [toggle]";
1149                 e->usage =
1150                         "Usage: console {mute|unmute} [toggle]\n"
1151                         "       Mute/unmute the microphone.\n";
1152                 return NULL;
1153         } else if (cmd == CLI_GENERATE)
1154                 return NULL;
1155
1156         if (a->argc > e->args)
1157                 return CLI_SHOWUSAGE;
1158         if (a->argc == e->args) {
1159                 if (strcasecmp(a->argv[e->args-1], "toggle"))
1160                         return CLI_SHOWUSAGE;
1161                 toggle = 1;
1162         }
1163         s = a->argv[e->args-2];
1164         if (!strcasecmp(s, "mute"))
1165                 o->mute = toggle ? !o->mute : 1;
1166         else if (!strcasecmp(s, "unmute"))
1167                 o->mute = toggle ? !o->mute : 0;
1168         else
1169                 return CLI_SHOWUSAGE;
1170         ast_cli(a->fd, "Console mic is %s\n", o->mute ? "off" : "on");
1171         return CLI_SUCCESS;
1172 }
1173
1174 static char *console_transfer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1175 {
1176         struct chan_oss_pvt *o = find_desc(oss_active);
1177         struct ast_channel *b = NULL;
1178         char *tmp, *ext, *ctx;
1179
1180         switch (cmd) {
1181         case CLI_INIT:
1182                 e->command = "console transfer";
1183                 e->usage =
1184                         "Usage: console transfer <extension>[@context]\n"
1185                         "       Transfers the currently connected call to the given extension (and\n"
1186                         "       context if specified)\n";
1187                 return NULL;
1188         case CLI_GENERATE:
1189                 return NULL;
1190         }
1191
1192         if (a->argc != 3)
1193                 return CLI_SHOWUSAGE;
1194         if (o == NULL)
1195                 return CLI_FAILURE;
1196         if (o->owner == NULL || (b = ast_bridged_channel(o->owner)) == NULL) {
1197                 ast_cli(a->fd, "There is no call to transfer\n");
1198                 return CLI_SUCCESS;
1199         }
1200
1201         tmp = ast_ext_ctx(a->argv[2], &ext, &ctx);
1202         if (ctx == NULL)                        /* supply default context if needed */
1203                 ctx = ast_strdupa(ast_channel_context(o->owner));
1204         if (!ast_exists_extension(b, ctx, ext, 1,
1205                 S_COR(ast_channel_caller(b)->id.number.valid, ast_channel_caller(b)->id.number.str, NULL))) {
1206                 ast_cli(a->fd, "No such extension exists\n");
1207         } else {
1208                 ast_cli(a->fd, "Whee, transferring %s to %s@%s.\n", ast_channel_name(b), ext, ctx);
1209                 if (ast_async_goto(b, ctx, ext, 1))
1210                         ast_cli(a->fd, "Failed to transfer :(\n");
1211         }
1212         if (tmp)
1213                 ast_free(tmp);
1214         return CLI_SUCCESS;
1215 }
1216
1217 static char *console_active(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1218 {
1219         switch (cmd) {
1220         case CLI_INIT:
1221                 e->command = "console {set|show} active [<device>]";
1222                 e->usage =
1223                         "Usage: console active [device]\n"
1224                         "       If used without a parameter, displays which device is the current\n"
1225                         "       console.  If a device is specified, the console sound device is changed to\n"
1226                         "       the device specified.\n";
1227                 return NULL;
1228         case CLI_GENERATE:
1229                 return NULL;
1230         }
1231
1232         if (a->argc == 3)
1233                 ast_cli(a->fd, "active console is [%s]\n", oss_active);
1234         else if (a->argc != 4)
1235                 return CLI_SHOWUSAGE;
1236         else {
1237                 struct chan_oss_pvt *o;
1238                 if (strcmp(a->argv[3], "show") == 0) {
1239                         for (o = oss_default.next; o; o = o->next)
1240                                 ast_cli(a->fd, "device [%s] exists\n", o->name);
1241                         return CLI_SUCCESS;
1242                 }
1243                 o = find_desc(a->argv[3]);
1244                 if (o == NULL)
1245                         ast_cli(a->fd, "No device [%s] exists\n", a->argv[3]);
1246                 else
1247                         oss_active = o->name;
1248         }
1249         return CLI_SUCCESS;
1250 }
1251
1252 /*!
1253  * \brief store the boost factor
1254  */
1255 static void store_boost(struct chan_oss_pvt *o, const char *s)
1256 {
1257         double boost = 0;
1258         if (sscanf(s, "%30lf", &boost) != 1) {
1259                 ast_log(LOG_WARNING, "invalid boost <%s>\n", s);
1260                 return;
1261         }
1262         if (boost < -BOOST_MAX) {
1263                 ast_log(LOG_WARNING, "boost %s too small, using %d\n", s, -BOOST_MAX);
1264                 boost = -BOOST_MAX;
1265         } else if (boost > BOOST_MAX) {
1266                 ast_log(LOG_WARNING, "boost %s too large, using %d\n", s, BOOST_MAX);
1267                 boost = BOOST_MAX;
1268         }
1269         boost = exp(log(10) * boost / 20) * BOOST_SCALE;
1270         o->boost = boost;
1271         ast_log(LOG_WARNING, "setting boost %s to %d\n", s, o->boost);
1272 }
1273
1274 static char *console_boost(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1275 {
1276         struct chan_oss_pvt *o = find_desc(oss_active);
1277
1278         switch (cmd) {
1279         case CLI_INIT:
1280                 e->command = "console boost";
1281                 e->usage =
1282                         "Usage: console boost [boost in dB]\n"
1283                         "       Sets or display mic boost in dB\n";
1284                 return NULL;
1285         case CLI_GENERATE:
1286                 return NULL;
1287         }
1288
1289         if (a->argc == 2)
1290                 ast_cli(a->fd, "boost currently %5.1f\n", 20 * log10(((double) o->boost / (double) BOOST_SCALE)));
1291         else if (a->argc == 3)
1292                 store_boost(o, a->argv[2]);
1293         return CLI_SUCCESS;
1294 }
1295
1296 static struct ast_cli_entry cli_oss[] = {
1297         AST_CLI_DEFINE(console_answer, "Answer an incoming console call"),
1298         AST_CLI_DEFINE(console_hangup, "Hangup a call on the console"),
1299         AST_CLI_DEFINE(console_flash, "Flash a call on the console"),
1300         AST_CLI_DEFINE(console_dial, "Dial an extension on the console"),
1301         AST_CLI_DEFINE(console_mute, "Disable/Enable mic input"),
1302         AST_CLI_DEFINE(console_transfer, "Transfer a call to a different extension"),   
1303         AST_CLI_DEFINE(console_cmd, "Generic console command"),
1304         AST_CLI_DEFINE(console_sendtext, "Send text to the remote device"),
1305         AST_CLI_DEFINE(console_autoanswer, "Sets/displays autoanswer"),
1306         AST_CLI_DEFINE(console_boost, "Sets/displays mic boost in dB"),
1307         AST_CLI_DEFINE(console_active, "Sets/displays active console"),
1308 };
1309
1310 /*!
1311  * store the mixer argument from the config file, filtering possibly
1312  * invalid or dangerous values (the string is used as argument for
1313  * system("mixer %s")
1314  */
1315 static void store_mixer(struct chan_oss_pvt *o, const char *s)
1316 {
1317         int i;
1318
1319         for (i = 0; i < strlen(s); i++) {
1320                 if (!isalnum(s[i]) && strchr(" \t-/", s[i]) == NULL) {
1321                         ast_log(LOG_WARNING, "Suspect char %c in mixer cmd, ignoring:\n\t%s\n", s[i], s);
1322                         return;
1323                 }
1324         }
1325         if (o->mixer_cmd)
1326                 ast_free(o->mixer_cmd);
1327         o->mixer_cmd = ast_strdup(s);
1328         ast_log(LOG_WARNING, "setting mixer %s\n", s);
1329 }
1330
1331 /*!
1332  * store the callerid components
1333  */
1334 static void store_callerid(struct chan_oss_pvt *o, const char *s)
1335 {
1336         ast_callerid_split(s, o->cid_name, sizeof(o->cid_name), o->cid_num, sizeof(o->cid_num));
1337 }
1338
1339 static void store_config_core(struct chan_oss_pvt *o, const char *var, const char *value)
1340 {
1341         CV_START(var, value);
1342
1343         /* handle jb conf */
1344         if (!ast_jb_read_conf(&global_jbconf, var, value))
1345                 return;
1346
1347         if (!console_video_config(&o->env, var, value))
1348                 return; /* matched there */
1349         CV_BOOL("autoanswer", o->autoanswer);
1350         CV_BOOL("autohangup", o->autohangup);
1351         CV_BOOL("overridecontext", o->overridecontext);
1352         CV_STR("device", o->device);
1353         CV_UINT("frags", o->frags);
1354         CV_UINT("debug", oss_debug);
1355         CV_UINT("queuesize", o->queuesize);
1356         CV_STR("context", o->ctx);
1357         CV_STR("language", o->language);
1358         CV_STR("mohinterpret", o->mohinterpret);
1359         CV_STR("extension", o->ext);
1360         CV_F("mixer", store_mixer(o, value));
1361         CV_F("callerid", store_callerid(o, value))  ;
1362         CV_F("boost", store_boost(o, value));
1363
1364         CV_END;
1365 }
1366
1367 /*!
1368  * grab fields from the config file, init the descriptor and open the device.
1369  */
1370 static struct chan_oss_pvt *store_config(struct ast_config *cfg, char *ctg)
1371 {
1372         struct ast_variable *v;
1373         struct chan_oss_pvt *o;
1374
1375         if (ctg == NULL) {
1376                 o = &oss_default;
1377                 ctg = "general";
1378         } else {
1379                 if (!(o = ast_calloc(1, sizeof(*o))))
1380                         return NULL;
1381                 *o = oss_default;
1382                 /* "general" is also the default thing */
1383                 if (strcmp(ctg, "general") == 0) {
1384                         o->name = ast_strdup("dsp");
1385                         oss_active = o->name;
1386                         goto openit;
1387                 }
1388                 o->name = ast_strdup(ctg);
1389         }
1390
1391         strcpy(o->mohinterpret, "default");
1392
1393         o->lastopen = ast_tvnow();      /* don't leave it 0 or tvdiff may wrap */
1394         /* fill other fields from configuration */
1395         for (v = ast_variable_browse(cfg, ctg); v; v = v->next) {
1396                 store_config_core(o, v->name, v->value);
1397         }
1398         if (ast_strlen_zero(o->device))
1399                 ast_copy_string(o->device, DEV_DSP, sizeof(o->device));
1400         if (o->mixer_cmd) {
1401                 char *cmd;
1402
1403                 if (ast_asprintf(&cmd, "mixer %s", o->mixer_cmd) >= 0) {
1404                         ast_log(LOG_WARNING, "running [%s]\n", cmd);
1405                         if (system(cmd) < 0) {
1406                                 ast_log(LOG_WARNING, "system() failed: %s\n", strerror(errno));
1407                         }
1408                         ast_free(cmd);
1409                 }
1410         }
1411
1412         /* if the config file requested to start the GUI, do it */
1413         if (get_gui_startup(o->env))
1414                 console_video_start(o->env, NULL);
1415
1416         if (o == &oss_default)          /* we are done with the default */
1417                 return NULL;
1418
1419 openit:
1420 #ifdef TRYOPEN
1421         if (setformat(o, O_RDWR) < 0) { /* open device */
1422                 ast_verb(1, "Device %s not detected\n", ctg);
1423                 ast_verb(1, "Turn off OSS support by adding " "'noload=chan_oss.so' in /etc/asterisk/modules.conf\n");
1424                 goto error;
1425         }
1426         if (o->duplex != M_FULL)
1427                 ast_log(LOG_WARNING, "XXX I don't work right with non " "full-duplex sound cards XXX\n");
1428 #endif /* TRYOPEN */
1429
1430         /* link into list of devices */
1431         if (o != &oss_default) {
1432                 o->next = oss_default.next;
1433                 oss_default.next = o;
1434         }
1435         return o;
1436
1437 #ifdef TRYOPEN
1438 error:
1439         if (o != &oss_default)
1440                 ast_free(o);
1441         return NULL;
1442 #endif
1443 }
1444
1445 /*!
1446  * \brief Load the module
1447  *
1448  * Module loading including tests for configuration or dependencies.
1449  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1450  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1451  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the 
1452  * configuration file or other non-critical problem return 
1453  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1454  */
1455 static int load_module(void)
1456 {
1457         struct ast_config *cfg = NULL;
1458         char *ctg = NULL;
1459         struct ast_flags config_flags = { 0 };
1460         struct ast_format tmpfmt;
1461
1462         /* Copy the default jb config over global_jbconf */
1463         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1464
1465         /* load config file */
1466         if (!(cfg = ast_config_load(config, config_flags))) {
1467                 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
1468                 return AST_MODULE_LOAD_DECLINE;
1469         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
1470                 ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config);
1471                 return AST_MODULE_LOAD_DECLINE;
1472         }
1473
1474         do {
1475                 store_config(cfg, ctg);
1476         } while ( (ctg = ast_category_browse(cfg, ctg)) != NULL);
1477
1478         ast_config_destroy(cfg);
1479
1480         if (find_desc(oss_active) == NULL) {
1481                 ast_log(LOG_NOTICE, "Device %s not found\n", oss_active);
1482                 /* XXX we could default to 'dsp' perhaps ? */
1483                 /* XXX should cleanup allocated memory etc. */
1484                 return AST_MODULE_LOAD_FAILURE;
1485         }
1486
1487         if (!(oss_tech.capabilities = ast_format_cap_alloc())) {
1488                 return AST_MODULE_LOAD_FAILURE;
1489         }
1490         ast_format_cap_add(oss_tech.capabilities, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0));
1491
1492         /* TODO XXX CONSOLE VIDEO IS DISABLE UNTIL IT HAS A MAINTAINER
1493          * add console_video_formats to oss_tech.capabilities once this occurs. */
1494
1495         if (ast_channel_register(&oss_tech)) {
1496                 ast_log(LOG_ERROR, "Unable to register channel type 'OSS'\n");
1497                 return AST_MODULE_LOAD_DECLINE;
1498         }
1499
1500         ast_cli_register_multiple(cli_oss, ARRAY_LEN(cli_oss));
1501
1502         return AST_MODULE_LOAD_SUCCESS;
1503 }
1504
1505
1506 static int unload_module(void)
1507 {
1508         struct chan_oss_pvt *o, *next;
1509
1510         ast_channel_unregister(&oss_tech);
1511         ast_cli_unregister_multiple(cli_oss, ARRAY_LEN(cli_oss));
1512
1513         o = oss_default.next;
1514         while (o) {
1515                 close(o->sounddev);
1516                 if (o->owner)
1517                         ast_softhangup(o->owner, AST_SOFTHANGUP_APPUNLOAD);
1518                 if (o->owner)
1519                         return -1;
1520                 next = o->next;
1521                 ast_free(o->name);
1522                 ast_free(o);
1523                 o = next;
1524         }
1525         oss_tech.capabilities = ast_format_cap_destroy(oss_tech.capabilities);
1526         return 0;
1527 }
1528
1529 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "OSS Console Channel Driver");