Sat Nov 1 06:28:27 2008

Asterisk developer's documentation


chan_oss.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2005, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * FreeBSD changes and multiple device support by Luigi Rizzo, 2005.05.25
00009  * note-this code best seen with ts=8 (8-spaces tabs) in the editor
00010  *
00011  * See http://www.asterisk.org for more information about
00012  * the Asterisk project. Please do not directly contact
00013  * any of the maintainers of this project for assistance;
00014  * the project provides a web site, mailing lists and IRC
00015  * channels for your use.
00016  *
00017  * This program is free software, distributed under the terms of
00018  * the GNU General Public License Version 2. See the LICENSE file
00019  * at the top of the source tree.
00020  */
00021 
00022 /*! \file
00023  *
00024  * \brief Channel driver for OSS sound cards
00025  *
00026  * \author Mark Spencer <markster@digium.com>
00027  * \author Luigi Rizzo
00028  *
00029  * \par See also
00030  * \arg \ref Config_oss
00031  *
00032  * \ingroup channel_drivers
00033  */
00034 
00035 /*** MODULEINFO
00036    <depend>ossaudio</depend>
00037  ***/
00038 
00039 #include "asterisk.h"
00040 
00041 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 108796 $")
00042 
00043 #include <stdio.h>
00044 #include <ctype.h>
00045 #include <math.h>
00046 #include <string.h>
00047 #include <unistd.h>
00048 #include <sys/ioctl.h>
00049 #include <fcntl.h>
00050 #include <sys/time.h>
00051 #include <stdlib.h>
00052 #include <errno.h>
00053 
00054 #ifdef __linux
00055 #include <linux/soundcard.h>
00056 #elif defined(__FreeBSD__)
00057 #include <sys/soundcard.h>
00058 #else
00059 #include <soundcard.h>
00060 #endif
00061 
00062 #include "asterisk/lock.h"
00063 #include "asterisk/frame.h"
00064 #include "asterisk/logger.h"
00065 #include "asterisk/callerid.h"
00066 #include "asterisk/channel.h"
00067 #include "asterisk/module.h"
00068 #include "asterisk/options.h"
00069 #include "asterisk/pbx.h"
00070 #include "asterisk/config.h"
00071 #include "asterisk/cli.h"
00072 #include "asterisk/utils.h"
00073 #include "asterisk/causes.h"
00074 #include "asterisk/endian.h"
00075 #include "asterisk/stringfields.h"
00076 #include "asterisk/abstract_jb.h"
00077 #include "asterisk/musiconhold.h"
00078 
00079 /* ringtones we use */
00080 #include "busy.h"
00081 #include "ringtone.h"
00082 #include "ring10.h"
00083 #include "answer.h"
00084 
00085 /*! Global jitterbuffer configuration - by default, jb is disabled */
00086 static struct ast_jb_conf default_jbconf =
00087 {
00088    .flags = 0,
00089    .max_size = -1,
00090    .resync_threshold = -1,
00091    .impl = "",
00092 };
00093 static struct ast_jb_conf global_jbconf;
00094 
00095 /*
00096  * Basic mode of operation:
00097  *
00098  * we have one keyboard (which receives commands from the keyboard)
00099  * and multiple headset's connected to audio cards.
00100  * Cards/Headsets are named as the sections of oss.conf.
00101  * The section called [general] contains the default parameters.
00102  *
00103  * At any time, the keyboard is attached to one card, and you
00104  * can switch among them using the command 'console foo'
00105  * where 'foo' is the name of the card you want.
00106  *
00107  * oss.conf parameters are
00108 START_CONFIG
00109 
00110 [general]
00111     ; General config options, with default values shown.
00112     ; You should use one section per device, with [general] being used
00113     ; for the first device and also as a template for other devices.
00114     ;
00115     ; All but 'debug' can go also in the device-specific sections.
00116     ;
00117     ; debug = 0x0    ; misc debug flags, default is 0
00118 
00119     ; Set the device to use for I/O
00120     ; device = /dev/dsp
00121 
00122     ; Optional mixer command to run upon startup (e.g. to set
00123     ; volume levels, mutes, etc.
00124     ; mixer =
00125 
00126     ; Software mic volume booster (or attenuator), useful for sound
00127     ; cards or microphones with poor sensitivity. The volume level
00128     ; is in dB, ranging from -20.0 to +20.0
00129     ; boost = n         ; mic volume boost in dB
00130 
00131     ; Set the callerid for outgoing calls
00132     ; callerid = John Doe <555-1234>
00133 
00134     ; autoanswer = no      ; no autoanswer on call
00135     ; autohangup = yes     ; hangup when other party closes
00136     ; extension = s     ; default extension to call
00137     ; context = default    ; default context for outgoing calls
00138     ; language = ""     ; default language
00139 
00140     ; Default Music on Hold class to use when this channel is placed on hold in
00141     ; the case that the music class is not set on the channel with
00142     ; Set(CHANNEL(musicclass)=whatever) in the dialplan and the peer channel
00143     ; putting this one on hold did not suggest a class to use.
00144     ;
00145     ; mohinterpret=default
00146 
00147     ; If you set overridecontext to 'yes', then the whole dial string
00148     ; will be interpreted as an extension, which is extremely useful
00149     ; to dial SIP, IAX and other extensions which use the '@' character.
00150     ; The default is 'no' just for backward compatibility, but the
00151     ; suggestion is to change it.
00152     ; overridecontext = no ; if 'no', the last @ will start the context
00153             ; if 'yes' the whole string is an extension.
00154 
00155     ; low level device parameters in case you have problems with the
00156     ; device driver on your operating system. You should not touch these
00157     ; unless you know what you are doing.
00158     ; queuesize = 10    ; frames in device driver
00159     ; frags = 8         ; argument to SETFRAGMENT
00160 
00161     ;------------------------------ JITTER BUFFER CONFIGURATION --------------------------
00162     ; jbenable = yes              ; Enables the use of a jitterbuffer on the receiving side of an
00163                                   ; OSS channel. Defaults to "no". An enabled jitterbuffer will
00164                                   ; be used only if the sending side can create and the receiving
00165                                   ; side can not accept jitter. The OSS channel can't accept jitter,
00166                                   ; thus an enabled jitterbuffer on the receive OSS side will always
00167                                   ; be used if the sending side can create jitter.
00168 
00169     ; jbmaxsize = 200             ; Max length of the jitterbuffer in milliseconds.
00170 
00171     ; jbresyncthreshold = 1000    ; Jump in the frame timestamps over which the jitterbuffer is
00172                                   ; resynchronized. Useful to improve the quality of the voice, with
00173                                   ; big jumps in/broken timestamps, usualy sent from exotic devices
00174                                   ; and programs. Defaults to 1000.
00175 
00176     ; jbimpl = fixed              ; Jitterbuffer implementation, used on the receiving side of an OSS
00177                                   ; channel. Two implementations are currenlty available - "fixed"
00178                                   ; (with size always equals to jbmax-size) and "adaptive" (with
00179                                   ; variable size, actually the new jb of IAX2). Defaults to fixed.
00180 
00181     ; jblog = no                  ; Enables jitterbuffer frame logging. Defaults to "no".
00182     ;-----------------------------------------------------------------------------------
00183 
00184 [card1]
00185     ; device = /dev/dsp1   ; alternate device
00186 
00187 END_CONFIG
00188 
00189 .. and so on for the other cards.
00190 
00191  */
00192 
00193 /*
00194  * Helper macros to parse config arguments. They will go in a common
00195  * header file if their usage is globally accepted. In the meantime,
00196  * we define them here. Typical usage is as below.
00197  * Remember to open a block right before M_START (as it declares
00198  * some variables) and use the M_* macros WITHOUT A SEMICOLON:
00199  *
00200  * {
00201  *    M_START(v->name, v->value) 
00202  *
00203  *    M_BOOL("dothis", x->flag1)
00204  *    M_STR("name", x->somestring)
00205  *    M_F("bar", some_c_code)
00206  *    M_END(some_final_statement)
00207  *    ... other code in the block
00208  * }
00209  *
00210  * XXX NOTE these macros should NOT be replicated in other parts of asterisk. 
00211  * Likely we will come up with a better way of doing config file parsing.
00212  */
00213 #define M_START(var, val) \
00214         char *__s = var; char *__val = val;
00215 #define M_END(x)   x;
00216 #define M_F(tag, f)        if (!strcasecmp((__s), tag)) { f; } else
00217 #define M_BOOL(tag, dst)   M_F(tag, (dst) = ast_true(__val) )
00218 #define M_UINT(tag, dst)   M_F(tag, (dst) = strtoul(__val, NULL, 0) )
00219 #define M_STR(tag, dst)    M_F(tag, ast_copy_string(dst, __val, sizeof(dst)))
00220 
00221 /*
00222  * The following parameters are used in the driver:
00223  *
00224  *  FRAME_SIZE the size of an audio frame, in samples.
00225  *    160 is used almost universally, so you should not change it.
00226  *
00227  *  FRAGS   the argument for the SETFRAGMENT ioctl.
00228  *    Overridden by the 'frags' parameter in oss.conf
00229  *
00230  *    Bits 0-7 are the base-2 log of the device's block size,
00231  *    bits 16-31 are the number of blocks in the driver's queue.
00232  *    There are a lot of differences in the way this parameter
00233  *    is supported by different drivers, so you may need to
00234  *    experiment a bit with the value.
00235  *    A good default for linux is 30 blocks of 64 bytes, which
00236  *    results in 6 frames of 320 bytes (160 samples).
00237  *    FreeBSD works decently with blocks of 256 or 512 bytes,
00238  *    leaving the number unspecified.
00239  *    Note that this only refers to the device buffer size,
00240  *    this module will then try to keep the lenght of audio
00241  *    buffered within small constraints.
00242  *
00243  *  QUEUE_SIZE The max number of blocks actually allowed in the device
00244  *    driver's buffer, irrespective of the available number.
00245  *    Overridden by the 'queuesize' parameter in oss.conf
00246  *
00247  *    Should be >=2, and at most as large as the hw queue above
00248  *    (otherwise it will never be full).
00249  */
00250 
00251 #define FRAME_SIZE   160
00252 #define  QUEUE_SIZE  10
00253 
00254 #if defined(__FreeBSD__)
00255 #define  FRAGS 0x8
00256 #else
00257 #define  FRAGS ( ( (6 * 5) << 16 ) | 0x6 )
00258 #endif
00259 
00260 /*
00261  * XXX text message sizes are probably 256 chars, but i am
00262  * not sure if there is a suitable definition anywhere.
00263  */
00264 #define TEXT_SIZE 256
00265 
00266 #if 0
00267 #define  TRYOPEN  1           /* try to open on startup */
00268 #endif
00269 #define  O_CLOSE  0x444       /* special 'close' mode for device */
00270 /* Which device to use */
00271 #if defined( __OpenBSD__ ) || defined( __NetBSD__ )
00272 #define DEV_DSP "/dev/audio"
00273 #else
00274 #define DEV_DSP "/dev/dsp"
00275 #endif
00276 
00277 #ifndef MIN
00278 #define MIN(a,b) ((a) < (b) ? (a) : (b))
00279 #endif
00280 #ifndef MAX
00281 #define MAX(a,b) ((a) > (b) ? (a) : (b))
00282 #endif
00283 
00284 static char *config = "oss.conf";   /* default config file */
00285 
00286 static int oss_debug;
00287 
00288 /*
00289  * Each sound is made of 'datalen' samples of sound, repeated as needed to
00290  * generate 'samplen' samples of data, then followed by 'silencelen' samples
00291  * of silence. The loop is repeated if 'repeat' is set.
00292  */
00293 struct sound {
00294    int ind;
00295    char *desc;
00296    short *data;
00297    int datalen;
00298    int samplen;
00299    int silencelen;
00300    int repeat;
00301 };
00302 
00303 static struct sound sounds[] = {
00304    { AST_CONTROL_RINGING, "RINGING", ringtone, sizeof(ringtone)/2, 16000, 32000, 1 },
00305    { AST_CONTROL_BUSY, "BUSY", busy, sizeof(busy)/2, 4000, 4000, 1 },
00306    { AST_CONTROL_CONGESTION, "CONGESTION", busy, sizeof(busy)/2, 2000, 2000, 1 },
00307    { AST_CONTROL_RING, "RING10", ring10, sizeof(ring10)/2, 16000, 32000, 1 },
00308    { AST_CONTROL_ANSWER, "ANSWER", answer, sizeof(answer)/2, 2200, 0, 0 },
00309    { -1, NULL, 0, 0, 0, 0 },  /* end marker */
00310 };
00311 
00312 
00313 /*
00314  * descriptor for one of our channels.
00315  * There is one used for 'default' values (from the [general] entry in
00316  * the configuration file), and then one instance for each device
00317  * (the default is cloned from [general], others are only created
00318  * if the relevant section exists).
00319  */
00320 struct chan_oss_pvt {
00321    struct chan_oss_pvt *next;
00322 
00323    char *name;
00324    /*
00325     * cursound indicates which in struct sound we play. -1 means nothing,
00326     * any other value is a valid sound, in which case sampsent indicates
00327     * the next sample to send in [0..samplen + silencelen]
00328     * nosound is set to disable the audio data from the channel
00329     * (so we can play the tones etc.).
00330     */
00331    int sndcmd[2];          /* Sound command pipe */
00332    int cursound;           /* index of sound to send */
00333    int sampsent;           /* # of sound samples sent  */
00334    int nosound;            /* set to block audio from the PBX */
00335 
00336    int total_blocks;       /* total blocks in the output device */
00337    int sounddev;
00338    enum { M_UNSET, M_FULL, M_READ, M_WRITE } duplex;
00339    int autoanswer;
00340    int autohangup;
00341    int hookstate;
00342    char *mixer_cmd;        /* initial command to issue to the mixer */
00343    unsigned int queuesize;    /* max fragments in queue */
00344    unsigned int frags;        /* parameter for SETFRAGMENT */
00345 
00346    int warned;             /* various flags used for warnings */
00347 #define WARN_used_blocks   1
00348 #define WARN_speed      2
00349 #define WARN_frag    4
00350    int w_errors;           /* overfull in the write path */
00351    struct timeval lastopen;
00352 
00353    int overridecontext;
00354    int mute;
00355 
00356    /* boost support. BOOST_SCALE * 10 ^(BOOST_MAX/20) must
00357     * be representable in 16 bits to avoid overflows.
00358     */
00359 #define  BOOST_SCALE (1<<9)
00360 #define  BOOST_MAX   40       /* slightly less than 7 bits */
00361    int boost;              /* input boost, scaled by BOOST_SCALE */
00362    char device[64];        /* device to open */
00363 
00364    pthread_t sthread;
00365 
00366    struct ast_channel *owner;
00367    char ext[AST_MAX_EXTENSION];
00368    char ctx[AST_MAX_CONTEXT];
00369    char language[MAX_LANGUAGE];
00370    char cid_name[256];        /*XXX */
00371    char cid_num[256];         /*XXX */
00372    char mohinterpret[MAX_MUSICCLASS];
00373 
00374    /* buffers used in oss_write */
00375    char oss_write_buf[FRAME_SIZE * 2];
00376    int oss_write_dst;
00377    /* buffers used in oss_read - AST_FRIENDLY_OFFSET space for headers
00378     * plus enough room for a full frame
00379     */
00380    char oss_read_buf[FRAME_SIZE * 2 + AST_FRIENDLY_OFFSET];
00381    int readpos;            /* read position above */
00382    struct ast_frame read_f;   /* returned by oss_read */
00383 };
00384 
00385 static struct chan_oss_pvt oss_default = {
00386    .cursound = -1,
00387    .sounddev = -1,
00388    .duplex = M_UNSET,         /* XXX check this */
00389    .autoanswer = 1,
00390    .autohangup = 1,
00391    .queuesize = QUEUE_SIZE,
00392    .frags = FRAGS,
00393    .ext = "s",
00394    .ctx = "default",
00395    .readpos = AST_FRIENDLY_OFFSET,  /* start here on reads */
00396    .lastopen = { 0, 0 },
00397    .boost = BOOST_SCALE,
00398 };
00399 
00400 static char *oss_active;    /* the active device */
00401 
00402 static int setformat(struct chan_oss_pvt *o, int mode);
00403 
00404 static struct ast_channel *oss_request(const char *type, int format, void *data
00405 , int *cause);
00406 static int oss_digit_begin(struct ast_channel *c, char digit);
00407 static int oss_digit_end(struct ast_channel *c, char digit, unsigned int duration);
00408 static int oss_text(struct ast_channel *c, const char *text);
00409 static int oss_hangup(struct ast_channel *c);
00410 static int oss_answer(struct ast_channel *c);
00411 static struct ast_frame *oss_read(struct ast_channel *chan);
00412 static int oss_call(struct ast_channel *c, char *dest, int timeout);
00413 static int oss_write(struct ast_channel *chan, struct ast_frame *f);
00414 static int oss_indicate(struct ast_channel *chan, int cond, const void *data, size_t datalen);
00415 static int oss_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
00416 static char tdesc[] = "OSS Console Channel Driver";
00417 
00418 static const struct ast_channel_tech oss_tech = {
00419    .type = "Console",
00420    .description = tdesc,
00421    .capabilities = AST_FORMAT_SLINEAR,
00422    .requester = oss_request,
00423    .send_digit_begin = oss_digit_begin,
00424    .send_digit_end = oss_digit_end,
00425    .send_text = oss_text,
00426    .hangup = oss_hangup,
00427    .answer = oss_answer,
00428    .read = oss_read,
00429    .call = oss_call,
00430    .write = oss_write,
00431    .indicate = oss_indicate,
00432    .fixup = oss_fixup,
00433 };
00434 
00435 /*
00436  * returns a pointer to the descriptor with the given name
00437  */
00438 static struct chan_oss_pvt *find_desc(char *dev)
00439 {
00440    struct chan_oss_pvt *o = NULL;
00441 
00442    if (!dev)
00443       ast_log(LOG_WARNING, "null dev\n");
00444 
00445    for (o = oss_default.next; o && o->name && dev && strcmp(o->name, dev) != 0; o = o->next);
00446 
00447    if (!o)
00448       ast_log(LOG_WARNING, "could not find <%s>\n", dev ? dev : "--no-device--");
00449 
00450    return o;
00451 }
00452 
00453 /*
00454  * split a string in extension-context, returns pointers to malloc'ed
00455  * strings.
00456  * If we do not have 'overridecontext' then the last @ is considered as
00457  * a context separator, and the context is overridden.
00458  * This is usually not very necessary as you can play with the dialplan,
00459  * and it is nice not to need it because you have '@' in SIP addresses.
00460  * Return value is the buffer address.
00461  */
00462 static char *ast_ext_ctx(const char *src, char **ext, char **ctx)
00463 {
00464    struct chan_oss_pvt *o = find_desc(oss_active);
00465 
00466    if (ext == NULL || ctx == NULL)
00467       return NULL;         /* error */
00468 
00469    *ext = *ctx = NULL;
00470 
00471    if (src && *src != '\0')
00472       *ext = ast_strdup(src);
00473 
00474    if (*ext == NULL)
00475       return NULL;
00476 
00477    if (!o->overridecontext) {
00478       /* parse from the right */
00479       *ctx = strrchr(*ext, '@');
00480       if (*ctx)
00481          *(*ctx)++ = '\0';
00482    }
00483 
00484    return *ext;
00485 }
00486 
00487 /*
00488  * Returns the number of blocks used in the audio output channel
00489  */
00490 static int used_blocks(struct chan_oss_pvt *o)
00491 {
00492    struct audio_buf_info info;
00493 
00494    if (ioctl(o->sounddev, SNDCTL_DSP_GETOSPACE, &info)) {
00495       if (!(o->warned & WARN_used_blocks)) {
00496          ast_log(LOG_WARNING, "Error reading output space\n");
00497          o->warned |= WARN_used_blocks;
00498       }
00499       return 1;
00500    }
00501 
00502    if (o->total_blocks == 0) {
00503       if (0)               /* debugging */
00504          ast_log(LOG_WARNING, "fragtotal %d size %d avail %d\n", info.fragstotal, info.fragsize, info.fragments);
00505       o->total_blocks = info.fragments;
00506    }
00507 
00508    return o->total_blocks - info.fragments;
00509 }
00510 
00511 /* Write an exactly FRAME_SIZE sized frame */
00512 static int soundcard_writeframe(struct chan_oss_pvt *o, short *data)
00513 {
00514    int res;
00515 
00516    if (o->sounddev < 0)
00517       setformat(o, O_RDWR);
00518    if (o->sounddev < 0)
00519       return 0;            /* not fatal */
00520    /*
00521     * Nothing complex to manage the audio device queue.
00522     * If the buffer is full just drop the extra, otherwise write.
00523     * XXX in some cases it might be useful to write anyways after
00524     * a number of failures, to restart the output chain.
00525     */
00526    res = used_blocks(o);
00527    if (res > o->queuesize) {  /* no room to write a block */
00528       if (o->w_errors++ == 0 && (oss_debug & 0x4))
00529          ast_log(LOG_WARNING, "write: used %d blocks (%d)\n", res, o->w_errors);
00530       return 0;
00531    }
00532    o->w_errors = 0;
00533    return write(o->sounddev, ((void *) data), FRAME_SIZE * 2);
00534 }
00535 
00536 /*
00537  * Handler for 'sound writable' events from the sound thread.
00538  * Builds a frame from the high level description of the sounds,
00539  * and passes it to the audio device.
00540  * The actual sound is made of 1 or more sequences of sound samples
00541  * (s->datalen, repeated to make s->samplen samples) followed by
00542  * s->silencelen samples of silence. The position in the sequence is stored
00543  * in o->sampsent, which goes between 0 .. s->samplen+s->silencelen.
00544  * In case we fail to write a frame, don't update o->sampsent.
00545  */
00546 static void send_sound(struct chan_oss_pvt *o)
00547 {
00548    short myframe[FRAME_SIZE];
00549    int ofs, l, start;
00550    int l_sampsent = o->sampsent;
00551    struct sound *s;
00552 
00553    if (o->cursound < 0)    /* no sound to send */
00554       return;
00555 
00556    s = &sounds[o->cursound];
00557 
00558    for (ofs = 0; ofs < FRAME_SIZE; ofs += l) {
00559       l = s->samplen - l_sampsent;  /* # of available samples */
00560       if (l > 0) {
00561          start = l_sampsent % s->datalen; /* source offset */
00562          if (l > FRAME_SIZE - ofs)  /* don't overflow the frame */
00563             l = FRAME_SIZE - ofs;
00564          if (l > s->datalen - start)   /* don't overflow the source */
00565             l = s->datalen - start;
00566          bcopy(s->data + start, myframe + ofs, l * 2);
00567          if (0)
00568             ast_log(LOG_WARNING, "send_sound sound %d/%d of %d into %d\n", l_sampsent, l, s->samplen, ofs);
00569          l_sampsent += l;
00570       } else {          /* end of samples, maybe some silence */
00571          static const short silence[FRAME_SIZE] = { 0, };
00572 
00573          l += s->silencelen;
00574          if (l > 0) {
00575             if (l > FRAME_SIZE - ofs)
00576                l = FRAME_SIZE - ofs;
00577             bcopy(silence, myframe + ofs, l * 2);
00578             l_sampsent += l;
00579          } else {       /* silence is over, restart sound if loop */
00580             if (s->repeat == 0) {   /* last block */
00581                o->cursound = -1;
00582                o->nosound = 0;   /* allow audio data */
00583                if (ofs < FRAME_SIZE)   /* pad with silence */
00584                   bcopy(silence, myframe + ofs, (FRAME_SIZE - ofs) * 2);
00585             }
00586             l_sampsent = 0;
00587          }
00588       }
00589    }
00590    l = soundcard_writeframe(o, myframe);
00591    if (l > 0)
00592       o->sampsent = l_sampsent;  /* update status */
00593 }
00594 
00595 static void *sound_thread(void *arg)
00596 {
00597    char ign[4096];
00598    struct chan_oss_pvt *o = (struct chan_oss_pvt *) arg;
00599 
00600    /*
00601     * Just in case, kick the driver by trying to read from it.
00602     * Ignore errors - this read is almost guaranteed to fail.
00603     */
00604    read(o->sounddev, ign, sizeof(ign));
00605    for (;;) {
00606       fd_set rfds, wfds;
00607       int maxfd, res;
00608 
00609       FD_ZERO(&rfds);
00610       FD_ZERO(&wfds);
00611       FD_SET(o->sndcmd[0], &rfds);
00612       maxfd = o->sndcmd[0];   /* pipe from the main process */
00613       if (o->cursound > -1 && o->sounddev < 0)
00614          setformat(o, O_RDWR);   /* need the channel, try to reopen */
00615       else if (o->cursound == -1 && o->owner == NULL)
00616          setformat(o, O_CLOSE);  /* can close */
00617       if (o->sounddev > -1) {
00618          if (!o->owner) {  /* no one owns the audio, so we must drain it */
00619             FD_SET(o->sounddev, &rfds);
00620             maxfd = MAX(o->sounddev, maxfd);
00621          }
00622          if (o->cursound > -1) {
00623             FD_SET(o->sounddev, &wfds);
00624             maxfd = MAX(o->sounddev, maxfd);
00625          }
00626       }
00627       /* ast_select emulates linux behaviour in terms of timeout handling */
00628       res = ast_select(maxfd + 1, &rfds, &wfds, NULL, NULL);
00629       if (res < 1) {
00630          ast_log(LOG_WARNING, "select failed: %s\n", strerror(errno));
00631          sleep(1);
00632          continue;
00633       }
00634       if (FD_ISSET(o->sndcmd[0], &rfds)) {
00635          /* read which sound to play from the pipe */
00636          int i, what = -1;
00637 
00638          read(o->sndcmd[0], &what, sizeof(what));
00639          for (i = 0; sounds[i].ind != -1; i++) {
00640             if (sounds[i].ind == what) {
00641                o->cursound = i;
00642                o->sampsent = 0;
00643                o->nosound = 1;   /* block audio from pbx */
00644                break;
00645             }
00646          }
00647          if (sounds[i].ind == -1)
00648             ast_log(LOG_WARNING, "invalid sound index: %d\n", what);
00649       }
00650       if (o->sounddev > -1) {
00651          if (FD_ISSET(o->sounddev, &rfds))   /* read and ignore errors */
00652             read(o->sounddev, ign, sizeof(ign));
00653          if (FD_ISSET(o->sounddev, &wfds))
00654             send_sound(o);
00655       }
00656    }
00657    return NULL;            /* Never reached */
00658 }
00659 
00660 /*
00661  * reset and close the device if opened,
00662  * then open and initialize it in the desired mode,
00663  * trigger reads and writes so we can start using it.
00664  */
00665 static int setformat(struct chan_oss_pvt *o, int mode)
00666 {
00667    int fmt, desired, res, fd;
00668 
00669    if (o->sounddev >= 0) {
00670       ioctl(o->sounddev, SNDCTL_DSP_RESET, 0);
00671       close(o->sounddev);
00672       o->duplex = M_UNSET;
00673       o->sounddev = -1;
00674    }
00675    if (mode == O_CLOSE)    /* we are done */
00676       return 0;
00677    if (ast_tvdiff_ms(ast_tvnow(), o->lastopen) < 1000)
00678       return -1;           /* don't open too often */
00679    o->lastopen = ast_tvnow();
00680    fd = o->sounddev = open(o->device, mode | O_NONBLOCK);
00681    if (fd < 0) {
00682       ast_log(LOG_WARNING, "Unable to re-open DSP device %s: %s\n", o->device, strerror(errno));
00683       return -1;
00684    }
00685    if (o->owner)
00686       o->owner->fds[0] = fd;
00687 
00688 #if __BYTE_ORDER == __LITTLE_ENDIAN
00689    fmt = AFMT_S16_LE;
00690 #else
00691    fmt = AFMT_S16_BE;
00692 #endif
00693    res = ioctl(fd, SNDCTL_DSP_SETFMT, &fmt);
00694    if (res < 0) {
00695       ast_log(LOG_WARNING, "Unable to set format to 16-bit signed\n");
00696       return -1;
00697    }
00698    switch (mode) {
00699       case O_RDWR:
00700          res = ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
00701          /* Check to see if duplex set (FreeBSD Bug) */
00702          res = ioctl(fd, SNDCTL_DSP_GETCAPS, &fmt);
00703          if (res == 0 && (fmt & DSP_CAP_DUPLEX)) {
00704             if (option_verbose > 1)
00705                ast_verbose(VERBOSE_PREFIX_2 "Console is full duplex\n");
00706             o->duplex = M_FULL;
00707          };
00708          break;
00709       case O_WRONLY:
00710          o->duplex = M_WRITE;
00711          break;
00712       case O_RDONLY:
00713          o->duplex = M_READ;
00714          break;
00715    }
00716 
00717    fmt = 0;
00718    res = ioctl(fd, SNDCTL_DSP_STEREO, &fmt);
00719    if (res < 0) {
00720       ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
00721       return -1;
00722    }
00723    fmt = desired = DEFAULT_SAMPLE_RATE;   /* 8000 Hz desired */
00724    res = ioctl(fd, SNDCTL_DSP_SPEED, &fmt);
00725 
00726    if (res < 0) {
00727       ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
00728       return -1;
00729    }
00730    if (fmt != desired) {
00731       if (!(o->warned & WARN_speed)) {
00732          ast_log(LOG_WARNING,
00733              "Requested %d Hz, got %d Hz -- sound may be choppy\n",
00734              desired, fmt);
00735          o->warned |= WARN_speed;
00736       }
00737    }
00738    /*
00739     * on Freebsd, SETFRAGMENT does not work very well on some cards.
00740     * Default to use 256 bytes, let the user override
00741     */
00742    if (o->frags) {
00743       fmt = o->frags;
00744       res = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &fmt);
00745       if (res < 0) {
00746          if (!(o->warned & WARN_frag)) {
00747             ast_log(LOG_WARNING,
00748                "Unable to set fragment size -- sound may be choppy\n");
00749             o->warned |= WARN_frag;
00750          }
00751       }
00752    }
00753    /* on some cards, we need SNDCTL_DSP_SETTRIGGER to start outputting */
00754    res = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;
00755    res = ioctl(fd, SNDCTL_DSP_SETTRIGGER, &res);
00756    /* it may fail if we are in half duplex, never mind */
00757    return 0;
00758 }
00759 
00760 /*
00761  * some of the standard methods supported by channels.
00762  */
00763 static int oss_digit_begin(struct ast_channel *c, char digit)
00764 {
00765    return 0;
00766 }
00767 
00768 static int oss_digit_end(struct ast_channel *c, char digit, unsigned int duration)
00769 {
00770    /* no better use for received digits than print them */
00771    ast_verbose(" << Console Received digit %c of duration %u ms >> \n", 
00772       digit, duration);
00773    return 0;
00774 }
00775 
00776 static int oss_text(struct ast_channel *c, const char *text)
00777 {
00778    /* print received messages */
00779    ast_verbose(" << Console Received text %s >> \n", text);
00780    return 0;
00781 }
00782 
00783 /* Play ringtone 'x' on device 'o' */
00784 static void ring(struct chan_oss_pvt *o, int x)
00785 {
00786    write(o->sndcmd[1], &x, sizeof(x));
00787 }
00788 
00789 
00790 /*
00791  * handler for incoming calls. Either autoanswer, or start ringing
00792  */
00793 static int oss_call(struct ast_channel *c, char *dest, int timeout)
00794 {
00795    struct chan_oss_pvt *o = c->tech_pvt;
00796    struct ast_frame f = { 0, };
00797 
00798    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);
00799    if (o->autoanswer) {
00800       ast_verbose(" << Auto-answered >> \n");
00801       f.frametype = AST_FRAME_CONTROL;
00802       f.subclass = AST_CONTROL_ANSWER;
00803       ast_queue_frame(c, &f);
00804    } else {
00805       ast_verbose("<< Type 'answer' to answer, or use 'autoanswer' for future calls >> \n");
00806       f.frametype = AST_FRAME_CONTROL;
00807       f.subclass = AST_CONTROL_RINGING;
00808       ast_queue_frame(c, &f);
00809       ring(o, AST_CONTROL_RING);
00810    }
00811    return 0;
00812 }
00813 
00814 /*
00815  * remote side answered the phone
00816  */
00817 static int oss_answer(struct ast_channel *c)
00818 {
00819    struct chan_oss_pvt *o = c->tech_pvt;
00820 
00821    ast_verbose(" << Console call has been answered >> \n");
00822 #if 0
00823    /* play an answer tone (XXX do we really need it ?) */
00824    ring(o, AST_CONTROL_ANSWER);
00825 #endif
00826    ast_setstate(c, AST_STATE_UP);
00827    o->cursound = -1;
00828    o->nosound = 0;
00829    return 0;
00830 }
00831 
00832 static int oss_hangup(struct ast_channel *c)
00833 {
00834    struct chan_oss_pvt *o = c->tech_pvt;
00835 
00836    o->cursound = -1;
00837    o->nosound = 0;
00838    c->tech_pvt = NULL;
00839    o->owner = NULL;
00840    ast_verbose(" << Hangup on console >> \n");
00841    ast_module_unref(ast_module_info->self);
00842    if (o->hookstate) {
00843       if (o->autoanswer || o->autohangup) {
00844          /* Assume auto-hangup too */
00845          o->hookstate = 0;
00846          setformat(o, O_CLOSE);
00847       } else {
00848          /* Make congestion noise */
00849          ring(o, AST_CONTROL_CONGESTION);
00850       }
00851    }
00852    return 0;
00853 }
00854 
00855 /* used for data coming from the network */
00856 static int oss_write(struct ast_channel *c, struct ast_frame *f)
00857 {
00858    int src;
00859    struct chan_oss_pvt *o = c->tech_pvt;
00860 
00861    /* Immediately return if no sound is enabled */
00862    if (o->nosound)
00863       return 0;
00864    /* Stop any currently playing sound */
00865    o->cursound = -1;
00866    /*
00867     * we could receive a block which is not a multiple of our
00868     * FRAME_SIZE, so buffer it locally and write to the device
00869     * in FRAME_SIZE chunks.
00870     * Keep the residue stored for future use.
00871     */
00872    src = 0;             /* read position into f->data */
00873    while (src < f->datalen) {
00874       /* Compute spare room in the buffer */
00875       int l = sizeof(o->oss_write_buf) - o->oss_write_dst;
00876 
00877       if (f->datalen - src >= l) {  /* enough to fill a frame */
00878          memcpy(o->oss_write_buf + o->oss_write_dst, f->data + src, l);
00879          soundcard_writeframe(o, (short *) o->oss_write_buf);
00880          src += l;
00881          o->oss_write_dst = 0;
00882       } else {          /* copy residue */
00883          l = f->datalen - src;
00884          memcpy(o->oss_write_buf + o->oss_write_dst, f->data + src, l);
00885          src += l;         /* but really, we are done */
00886          o->oss_write_dst += l;
00887       }
00888    }
00889    return 0;
00890 }
00891 
00892 static struct ast_frame *oss_read(struct ast_channel *c)
00893 {
00894    int res;
00895    struct chan_oss_pvt *o = c->tech_pvt;
00896    struct ast_frame *f = &o->read_f;
00897 
00898    /* XXX can be simplified returning &ast_null_frame */
00899    /* prepare a NULL frame in case we don't have enough data to return */
00900    bzero(f, sizeof(struct ast_frame));
00901    f->frametype = AST_FRAME_NULL;
00902    f->src = oss_tech.type;
00903 
00904    res = read(o->sounddev, o->oss_read_buf + o->readpos, sizeof(o->oss_read_buf) - o->readpos);
00905    if (res < 0)            /* audio data not ready, return a NULL frame */
00906       return f;
00907 
00908    o->readpos += res;
00909    if (o->readpos < sizeof(o->oss_read_buf)) /* not enough samples */
00910       return f;
00911 
00912    if (o->mute)
00913       return f;
00914 
00915    o->readpos = AST_FRIENDLY_OFFSET;   /* reset read pointer for next frame */
00916    if (c->_state != AST_STATE_UP)   /* drop data if frame is not up */
00917       return f;
00918    /* ok we can build and deliver the frame to the caller */
00919    f->frametype = AST_FRAME_VOICE;
00920    f->subclass = AST_FORMAT_SLINEAR;
00921    f->samples = FRAME_SIZE;
00922    f->datalen = FRAME_SIZE * 2;
00923    f->data = o->oss_read_buf + AST_FRIENDLY_OFFSET;
00924    if (o->boost != BOOST_SCALE) {   /* scale and clip values */
00925       int i, x;
00926       int16_t *p = (int16_t *) f->data;
00927       for (i = 0; i < f->samples; i++) {
00928          x = (p[i] * o->boost) / BOOST_SCALE;
00929          if (x > 32767)
00930             x = 32767;
00931          else if (x < -32768)
00932             x = -32768;
00933          p[i] = x;
00934       }
00935    }
00936 
00937    f->offset = AST_FRIENDLY_OFFSET;
00938    return f;
00939 }
00940 
00941 static int oss_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
00942 {
00943    struct chan_oss_pvt *o = newchan->tech_pvt;
00944    o->owner = newchan;
00945    return 0;
00946 }
00947 
00948 static int oss_indicate(struct ast_channel *c, int cond, const void *data, size_t datalen)
00949 {
00950    struct chan_oss_pvt *o = c->tech_pvt;
00951    int res = -1;
00952 
00953    switch (cond) {
00954    case AST_CONTROL_BUSY:
00955    case AST_CONTROL_CONGESTION:
00956    case AST_CONTROL_RINGING:
00957          res = cond;
00958          break;
00959          
00960    case -1:
00961       o->cursound = -1;
00962       o->nosound = 0;      /* when cursound is -1 nosound must be 0 */
00963       return 0;
00964       
00965    case AST_CONTROL_VIDUPDATE:
00966       res = -1;
00967       break;
00968    case AST_CONTROL_HOLD:
00969       ast_verbose(" << Console Has Been Placed on Hold >> \n");
00970       ast_moh_start(c, data, o->mohinterpret);
00971          break;
00972    case AST_CONTROL_UNHOLD:
00973       ast_verbose(" << Console Has Been Retrieved from Hold >> \n");
00974       ast_moh_stop(c);
00975       break;
00976    case AST_CONTROL_SRCUPDATE:
00977       break;
00978    default:
00979