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