Mon Mar 31 07:37:59 2008

Asterisk developer's documentation


chan_phone.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  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Generic Linux Telephony Interface driver
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  * 
00025  * \ingroup channel_drivers
00026  */
00027 
00028 #include "asterisk.h"
00029 
00030 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00031 
00032 #include <stdio.h>
00033 #include <string.h>
00034 #include <ctype.h>
00035 #include <sys/socket.h>
00036 #include <sys/time.h>
00037 #include <errno.h>
00038 #include <unistd.h>
00039 #include <stdlib.h>
00040 #include <arpa/inet.h>
00041 #include <fcntl.h>
00042 #include <sys/ioctl.h>
00043 #include <signal.h>
00044 #ifdef HAVE_LINUX_COMPILER_H
00045 #include <linux/compiler.h>
00046 #endif
00047 #include <linux/telephony.h>
00048 /* Still use some IXJ specific stuff */
00049 #include <linux/version.h>
00050 #include <linux/ixjuser.h>
00051 
00052 #include "asterisk/lock.h"
00053 #include "asterisk/channel.h"
00054 #include "asterisk/config.h"
00055 #include "asterisk/logger.h"
00056 #include "asterisk/module.h"
00057 #include "asterisk/pbx.h"
00058 #include "asterisk/options.h"
00059 #include "asterisk/utils.h"
00060 #include "asterisk/callerid.h"
00061 #include "asterisk/causes.h"
00062 #include "asterisk/stringfields.h"
00063 #include "asterisk/musiconhold.h"
00064 
00065 #include "DialTone.h"
00066 
00067 #ifdef QTI_PHONEJACK_TJ_PCI   /* check for the newer quicknet driver v.3.1.0 which has this symbol */
00068 #define QNDRV_VER 310
00069 #else
00070 #define QNDRV_VER 100
00071 #endif
00072 
00073 #if QNDRV_VER > 100
00074 #ifdef __linux__
00075 #define IXJ_PHONE_RING_START(x)  ioctl(p->fd, PHONE_RING_START, &x);
00076 #else /* FreeBSD and others */
00077 #define IXJ_PHONE_RING_START(x)  ioctl(p->fd, PHONE_RING_START, x);
00078 #endif /* __linux__ */
00079 #else /* older driver */
00080 #define IXJ_PHONE_RING_START(x)  ioctl(p->fd, PHONE_RING_START, &x);
00081 #endif
00082 
00083 #define DEFAULT_CALLER_ID "Unknown"
00084 #define PHONE_MAX_BUF 480
00085 #define DEFAULT_GAIN 0x100
00086 
00087 static const char tdesc[] = "Standard Linux Telephony API Driver";
00088 static const char config[] = "phone.conf";
00089 
00090 /* Default context for dialtone mode */
00091 static char context[AST_MAX_EXTENSION] = "default";
00092 
00093 /* Default language */
00094 static char language[MAX_LANGUAGE] = "";
00095 
00096 static int echocancel = AEC_OFF;
00097 
00098 static int silencesupression = 0;
00099 
00100 static int prefformat = AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW;
00101 
00102 /* Protect the interface list (of phone_pvt's) */
00103 AST_MUTEX_DEFINE_STATIC(iflock);
00104 
00105 /* Protect the monitoring thread, so only one process can kill or start it, and not
00106    when it's doing something critical. */
00107 AST_MUTEX_DEFINE_STATIC(monlock);
00108 
00109 /* Boolean value whether the monitoring thread shall continue. */
00110 static unsigned int monitor;
00111    
00112 /* This is the thread for the monitor which checks for input on the channels
00113    which are not currently in use.  */
00114 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00115 
00116 static int restart_monitor(void);
00117 
00118 /* The private structures of the Phone Jack channels are linked for
00119    selecting outgoing channels */
00120    
00121 #define MODE_DIALTONE   1
00122 #define MODE_IMMEDIATE  2
00123 #define MODE_FXO  3
00124 #define MODE_FXS        4
00125 #define MODE_SIGMA      5
00126 
00127 static struct phone_pvt {
00128    int fd;                    /* Raw file descriptor for this device */
00129    struct ast_channel *owner;    /* Channel we belong to, possibly NULL */
00130    int mode;                  /* Is this in the  */
00131    int lastformat;               /* Last output format */
00132    int lastinput;             /* Last input format */
00133    int ministate;             /* Miniature state, for dialtone mode */
00134    char dev[256];             /* Device name */
00135    struct phone_pvt *next;       /* Next channel in list */
00136    struct ast_frame fr;       /* Frame */
00137    char offset[AST_FRIENDLY_OFFSET];
00138    char buf[PHONE_MAX_BUF];               /* Static buffer for reading frames */
00139    int obuflen;
00140    int dialtone;
00141    int txgain, rxgain;             /* gain control for playing, recording  */
00142                            /* 0x100 - 1.0, 0x200 - 2.0, 0x80 - 0.5 */
00143    int cpt;                /* Call Progress Tone playing? */
00144    int silencesupression;
00145    char context[AST_MAX_EXTENSION];
00146    char obuf[PHONE_MAX_BUF * 2];
00147    char ext[AST_MAX_EXTENSION];
00148    char language[MAX_LANGUAGE];
00149    char cid_num[AST_MAX_EXTENSION];
00150    char cid_name[AST_MAX_EXTENSION];
00151 } *iflist = NULL;
00152 
00153 static char cid_num[AST_MAX_EXTENSION];
00154 static char cid_name[AST_MAX_EXTENSION];
00155 
00156 static struct ast_channel *phone_request(const char *type, int format, void *data, int *cause);
00157 static int phone_digit_begin(struct ast_channel *ast, char digit);
00158 static int phone_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
00159 static int phone_call(struct ast_channel *ast, char *dest, int timeout);
00160 static int phone_hangup(struct ast_channel *ast);
00161 static int phone_answer(struct ast_channel *ast);
00162 static struct ast_frame *phone_read(struct ast_channel *ast);
00163 static int phone_write(struct ast_channel *ast, struct ast_frame *frame);
00164 static struct ast_frame *phone_exception(struct ast_channel *ast);
00165 static int phone_send_text(struct ast_channel *ast, const char *text);
00166 static int phone_fixup(struct ast_channel *old, struct ast_channel *new);
00167 static int phone_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
00168 
00169 static const struct ast_channel_tech phone_tech = {
00170    .type = "Phone",
00171    .description = tdesc,
00172    .capabilities = AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW,
00173    .requester = phone_request,
00174    .send_digit_begin = phone_digit_begin,
00175    .send_digit_end = phone_digit_end,
00176    .call = phone_call,
00177    .hangup = phone_hangup,
00178    .answer = phone_answer,
00179    .read = phone_read,
00180    .write = phone_write,
00181    .exception = phone_exception,
00182    .indicate = phone_indicate,
00183    .fixup = phone_fixup
00184 };
00185 
00186 static struct ast_channel_tech phone_tech_fxs = {
00187    .type = "Phone",
00188    .description = tdesc,
00189    .requester = phone_request,
00190    .send_digit_begin = phone_digit_begin,
00191    .send_digit_end = phone_digit_end,
00192    .call = phone_call,
00193    .hangup = phone_hangup,
00194    .answer = phone_answer,
00195    .read = phone_read,
00196    .write = phone_write,
00197    .exception = phone_exception,
00198    .write_video = phone_write,
00199    .send_text = phone_send_text,
00200    .indicate = phone_indicate,
00201    .fixup = phone_fixup
00202 };
00203 
00204 static struct ast_channel_tech *cur_tech;
00205 
00206 static int phone_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen)
00207 {
00208    struct phone_pvt *p = chan->tech_pvt;
00209    int res=-1;
00210    ast_log(LOG_DEBUG, "Requested indication %d on channel %s\n", condition, chan->name);
00211    switch(condition) {
00212    case AST_CONTROL_FLASH:
00213       ioctl(p->fd, IXJCTL_PSTN_SET_STATE, PSTN_ON_HOOK);
00214       usleep(320000);
00215       ioctl(p->fd, IXJCTL_PSTN_SET_STATE, PSTN_OFF_HOOK);
00216          p->lastformat = -1;
00217          res = 0;
00218          break;
00219    case AST_CONTROL_HOLD:
00220       ast_moh_start(chan, data, NULL);
00221       break;
00222    case AST_CONTROL_UNHOLD:
00223       ast_moh_stop(chan);
00224       break;
00225    case AST_CONTROL_SRCUPDATE:
00226       res = 0;
00227       break;
00228    default:
00229       ast_log(LOG_WARNING, "Condition %d is not supported on channel %s\n", condition, chan->name);
00230    }
00231    return res;
00232 }
00233 
00234 static int phone_fixup(struct ast_channel *old, struct ast_channel *new)
00235 {
00236    struct phone_pvt *pvt = old->tech_pvt;
00237    if (pvt && pvt->owner == old)
00238       pvt->owner = new;
00239    return 0;
00240 }
00241 
00242 static int phone_digit_begin(struct ast_channel *chan, char digit)
00243 {
00244    /* XXX Modify this callback to let Asterisk support controlling the length of DTMF */
00245    return 0;
00246 }
00247 
00248 static int phone_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
00249 {
00250    struct phone_pvt *p;
00251    int outdigit;
00252    p = ast->tech_pvt;
00253    ast_log(LOG_DEBUG, "Dialed %c\n", digit);
00254    switch(digit) {
00255    case '0':
00256    case '1':
00257    case '2':
00258    case '3':
00259    case '4':
00260    case '5':
00261    case '6':
00262    case '7':
00263    case '8':
00264    case '9':
00265       outdigit = digit - '0';
00266       break;
00267    case '*':
00268       outdigit = 11;
00269       break;
00270    case '#':
00271       outdigit = 12;
00272       break;
00273    case 'f':   /*flash*/
00274    case 'F':
00275       ioctl(p->fd, IXJCTL_PSTN_SET_STATE, PSTN_ON_HOOK);
00276       usleep(320000);
00277       ioctl(p->fd, IXJCTL_PSTN_SET_STATE, PSTN_OFF_HOOK);
00278       p->lastformat = -1;
00279       return 0;
00280    default:
00281       ast_log(LOG_WARNING, "Unknown digit '%c'\n", digit);
00282       return -1;
00283    }
00284    ast_log(LOG_DEBUG, "Dialed %d\n", outdigit);
00285    ioctl(p->fd, PHONE_PLAY_TONE, outdigit);
00286    p->lastformat = -1;
00287    return 0;
00288 }
00289 
00290 static int phone_call(struct ast_channel *ast, char *dest, int timeout)
00291 {
00292    struct phone_pvt *p;
00293 
00294    PHONE_CID cid;
00295    time_t UtcTime;
00296    struct tm tm;
00297    int start;
00298 
00299    time(&UtcTime);
00300    ast_localtime(&UtcTime, &tm, NULL);
00301 
00302    memset(&cid, 0, sizeof(PHONE_CID));
00303    if(&tm != NULL) {
00304       snprintf(cid.month, sizeof(cid.month), "%02d",(tm.tm_mon + 1));
00305       snprintf(cid.day, sizeof(cid.day),     "%02d", tm.tm_mday);
00306       snprintf(cid.hour, sizeof(cid.hour),   "%02d", tm.tm_hour);
00307       snprintf(cid.min, sizeof(cid.min),     "%02d", tm.tm_min);
00308    }
00309    /* the standard format of ast->callerid is:  "name" <number>, but not always complete */
00310    if (ast_strlen_zero(ast->cid.cid_name))
00311       strcpy(cid.name, DEFAULT_CALLER_ID);
00312    else
00313       ast_copy_string(cid.name, ast->cid.cid_name, sizeof(cid.name));
00314 
00315    if (ast->cid.cid_num) 
00316       ast_copy_string(cid.number, ast->cid.cid_num, sizeof(cid.number));
00317 
00318    p = ast->tech_pvt;
00319 
00320    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
00321       ast_log(LOG_WARNING, "phone_call called on %s, neither down nor reserved\n", ast->name);
00322       return -1;
00323    }
00324    if (option_debug)
00325       ast_log(LOG_DEBUG, "Ringing %s on %s (%d)\n", dest, ast->name, ast->fds[0]);
00326 
00327    start = IXJ_PHONE_RING_START(cid);
00328    if (start == -1)
00329       return -1;
00330    
00331    if (p->mode == MODE_FXS) {
00332       char *digit = strchr(dest, '/');
00333       if (digit)
00334       {
00335         digit++;
00336         while (*digit)
00337           phone_digit_end(ast, *digit++, 0);
00338       }
00339    }
00340  
00341    ast_setstate(ast, AST_STATE_RINGING);
00342    ast_queue_control(ast, AST_CONTROL_RINGING);
00343    return 0;
00344 }
00345 
00346 static int phone_hangup(struct ast_channel *ast)
00347 {
00348    struct phone_pvt *p;
00349    p = ast->tech_pvt;
00350    if (option_debug)
00351       ast_log(LOG_DEBUG, "phone_hangup(%s)\n", ast->name);
00352    if (!ast->tech_pvt) {
00353       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
00354       return 0;
00355    }
00356    /* XXX Is there anything we can do to really hang up except stop recording? */
00357    ast_setstate(ast, AST_STATE_DOWN);
00358    if (ioctl(p->fd, PHONE_REC_STOP))
00359       ast_log(LOG_WARNING, "Failed to stop recording\n");
00360    if (ioctl(p->fd, PHONE_PLAY_STOP))
00361       ast_log(LOG_WARNING, "Failed to stop playing\n");
00362    if (ioctl(p->fd, PHONE_RING_STOP))
00363       ast_log(LOG_WARNING, "Failed to stop ringing\n");
00364    if (ioctl(p->fd, PHONE_CPT_STOP))
00365       ast_log(LOG_WARNING, "Failed to stop sounds\n");
00366 
00367    /* If it's an FXO, hang them up */
00368    if (p->mode == MODE_FXO) {
00369       if (ioctl(p->fd, PHONE_PSTN_SET_STATE, PSTN_ON_HOOK)) 
00370          ast_log(LOG_DEBUG, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n",ast->name, strerror(errno));
00371    }
00372 
00373    /* If they're off hook, give a busy signal */
00374    if (ioctl(p->fd, PHONE_HOOKSTATE)) {
00375       if (option_debug)
00376          ast_log(LOG_DEBUG, "Got hunghup, giving busy signal\n");
00377       ioctl(p->fd, PHONE_BUSY);
00378       p->cpt = 1;
00379    }
00380    p->lastformat = -1;
00381    p->lastinput = -1;
00382    p->ministate = 0;
00383    p->obuflen = 0;
00384    p->dialtone = 0;
00385    memset(p->ext, 0, sizeof(p->ext));
00386    ((struct phone_pvt *)(ast->tech_pvt))->owner = NULL;
00387    ast_module_unref(ast_module_info->self);
00388    if (option_verbose > 2) 
00389       ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
00390    ast->tech_pvt = NULL;
00391    ast_setstate(ast, AST_STATE_DOWN);
00392    restart_monitor();
00393    return 0;
00394 }
00395 
00396 static int phone_setup(struct ast_channel *ast)
00397 {
00398    struct phone_pvt *p;
00399    p = ast->tech_pvt;
00400    ioctl(p->fd, PHONE_CPT_STOP);
00401    /* Nothing to answering really, just start recording */
00402    if (ast->rawreadformat == AST_FORMAT_G723_1) {
00403       /* Prefer g723 */
00404       ioctl(p->fd, PHONE_REC_STOP);
00405       if (p->lastinput != AST_FORMAT_G723_1) {
00406          p->lastinput = AST_FORMAT_G723_1;
00407          if (ioctl(p->fd, PHONE_REC_CODEC, G723_63)) {
00408             ast_log(LOG_WARNING, "Failed to set codec to g723.1\n");
00409             return -1;
00410          }
00411       }
00412    } else if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
00413       ioctl(p->fd, PHONE_REC_STOP);
00414       if (p->lastinput != AST_FORMAT_SLINEAR) {
00415          p->lastinput = AST_FORMAT_SLINEAR;
00416          if (ioctl(p->fd, PHONE_REC_CODEC, LINEAR16)) {
00417             ast_log(LOG_WARNING, "Failed to set codec to signed linear 16\n");
00418             return -1;
00419          }
00420       }
00421    } else if (ast->rawreadformat == AST_FORMAT_ULAW) {
00422       ioctl(p->fd, PHONE_REC_STOP);
00423       if (p->lastinput != AST_FORMAT_ULAW) {
00424          p->lastinput = AST_FORMAT_ULAW;
00425          if (ioctl(p->fd, PHONE_REC_CODEC, ULAW)) {
00426             ast_log(LOG_WARNING, "Failed to set codec to uLaw\n");
00427             return -1;
00428          }
00429       }
00430    } else if (p->mode == MODE_FXS) {
00431       ioctl(p->fd, PHONE_REC_STOP);
00432       if (p->lastinput != ast->rawreadformat) {
00433          p->lastinput = ast->rawreadformat;
00434          if (ioctl(p->fd, PHONE_REC_CODEC, ast->rawreadformat)) {
00435             ast_log(LOG_WARNING, "Failed to set codec to %d\n", 
00436                ast->rawreadformat);
00437             return -1;
00438          }
00439       }
00440    } else {
00441       ast_log(LOG_WARNING, "Can't do format %s\n", ast_getformatname(ast->rawreadformat));
00442       return -1;
00443    }
00444    if (ioctl(p->fd, PHONE_REC_START)) {
00445       ast_log(LOG_WARNING, "Failed to start recording\n");
00446       return -1;
00447    }
00448    /* set the DTMF times (the default is too short) */
00449    ioctl(p->fd, PHONE_SET_TONE_ON_TIME, 300);
00450    ioctl(p->fd, PHONE_SET_TONE_OFF_TIME, 200);
00451    return 0;
00452 }
00453 
00454 static int phone_answer(struct ast_channel *ast)
00455 {
00456    struct phone_pvt *p;
00457    p = ast->tech_pvt;
00458    /* In case it's a LineJack, take it off hook */
00459    if (p->mode == MODE_FXO) {
00460       if (ioctl(p->fd, PHONE_PSTN_SET_STATE, PSTN_OFF_HOOK)) 
00461          ast_log(LOG_DEBUG, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n", ast->name, strerror(errno));
00462       else
00463          ast_log(LOG_DEBUG, "Took linejack off hook\n");
00464    }
00465    phone_setup(ast);
00466    if (option_debug)
00467       ast_log(LOG_DEBUG, "phone_answer(%s)\n", ast->name);
00468    ast->rings = 0;
00469    ast_setstate(ast, AST_STATE_UP);
00470    return 0;
00471 }
00472 
00473 #if 0
00474 static char phone_2digit(char c)
00475 {
00476    if (c == 12)
00477       return '#';
00478    else if (c == 11)
00479       return '*';
00480    else if ((c < 10) && (c >= 0))
00481       return '0' + c - 1;
00482    else
00483       return '?';
00484 }
00485 #endif
00486 
00487 static struct ast_frame  *phone_exception(struct ast_channel *ast)
00488 {
00489    int res;
00490    union telephony_exception phonee;
00491    struct phone_pvt *p = ast->tech_pvt;
00492    char digit;
00493 
00494    /* Some nice norms */
00495    p->fr.datalen = 0;
00496    p->fr.samples = 0;
00497    p->fr.data =  NULL;
00498    p->fr.src = "Phone";
00499    p->fr.offset = 0;
00500    p->fr.mallocd=0;
00501    p->fr.delivery = ast_tv(0,0);
00502    
00503    phonee.bytes = ioctl(p->fd, PHONE_EXCEPTION);
00504    if (phonee.bits.dtmf_ready)  {
00505       if (option_debug)
00506          ast_log(LOG_DEBUG, "phone_exception(): DTMF\n");
00507    
00508       /* We've got a digit -- Just handle this nicely and easily */
00509       digit =  ioctl(p->fd, PHONE_GET_DTMF_ASCII);
00510       p->fr.subclass = digit;
00511       p->fr.frametype = AST_FRAME_DTMF;
00512       return &p->fr;
00513    }
00514    if (phonee.bits.hookstate) {
00515       if (option_debug)
00516          ast_log(LOG_DEBUG, "Hookstate changed\n");
00517       res = ioctl(p->fd, PHONE_HOOKSTATE);
00518       /* See if we've gone on hook, if so, notify by returning NULL */
00519       if (option_debug)
00520          ast_log(LOG_DEBUG, "New hookstate: %d\n", res);
00521       if (!res && (p->mode != MODE_FXO))
00522          return NULL;
00523       else {
00524          if (ast->_state == AST_STATE_RINGING) {
00525             /* They've picked up the phone */
00526             p->fr.frametype = AST_FRAME_CONTROL;
00527             p->fr.subclass = AST_CONTROL_ANSWER;
00528             phone_setup(ast);
00529             ast_setstate(ast, AST_STATE_UP);
00530             return &p->fr;
00531          }  else 
00532             ast_log(LOG_WARNING, "Got off hook in weird state %d\n", ast->_state);
00533       }
00534    }
00535 #if 1
00536    if (phonee.bits.pstn_ring)
00537       ast_verbose("Unit is ringing\n");
00538    if (phonee.bits.caller_id) {
00539       ast_verbose("We have caller ID\n");
00540    }
00541    if (phonee.bits.pstn_wink)
00542       ast_verbose("Detected Wink\n");
00543 #endif
00544    /* Strange -- nothing there.. */
00545    p->fr.frametype = AST_FRAME_NULL;
00546    p->fr.subclass = 0;
00547    return &p->fr;
00548 }
00549 
00550 static struct ast_frame  *phone_read(struct ast_channel *ast)
00551 {
00552    int res;
00553    struct phone_pvt *p = ast->tech_pvt;
00554    
00555 
00556    /* Some nice norms */
00557    p->fr.datalen = 0;
00558    p->fr.samples = 0;
00559    p->fr.data =  NULL;
00560    p->fr.src = "Phone";
00561    p->fr.offset = 0;
00562    p->fr.mallocd=0;
00563    p->fr.delivery = ast_tv(0,0);
00564 
00565    /* Try to read some data... */
00566    CHECK_BLOCKING(ast);
00567    res = read(p->fd, p->buf, PHONE_MAX_BUF);
00568    ast_clear_flag(ast, AST_FLAG_BLOCKING);
00569    if (res < 0) {
00570 #if 0
00571       if (errno == EAGAIN) {
00572          ast_log(LOG_WARNING, "Null frame received\n");
00573          p->fr.frametype = AST_FRAME_NULL;
00574          p->fr.subclass = 0;
00575          return &p->fr;
00576       }
00577 #endif
00578       ast_log(LOG_WARNING, "Error reading: %s\n", strerror(errno));
00579       return NULL;
00580    }
00581    p->fr.data = p->buf;
00582    if (p->mode != MODE_FXS)
00583    switch(p->buf[0] & 0x3) {
00584    case '0':
00585    case '1':
00586       /* Normal */
00587       break;
00588    case '2':
00589    case '3':
00590       /* VAD/CNG, only send two words */
00591       res = 4;
00592       break;
00593    }
00594    p->fr.samples = 240;
00595    p->fr.datalen = res;
00596    p->fr.frametype = p->lastinput <= AST_FORMAT_MAX_AUDIO ?
00597                           AST_FRAME_VOICE : 
00598            p->lastinput <= AST_FORMAT_PNG ? AST_FRAME_IMAGE 
00599            : AST_FRAME_VIDEO;
00600    p->fr.subclass = p->lastinput;
00601    p->fr.offset = AST_FRIENDLY_OFFSET;
00602    /* Byteswap from little-endian to native-endian */
00603    if (p->fr.subclass == AST_FORMAT_SLINEAR)
00604       ast_frame_byteswap_le(&p->fr);
00605    return &p->fr;
00606 }
00607 
00608 static int phone_write_buf(struct phone_pvt *p, const char *buf, int len, int frlen, int swap)
00609 {
00610    int res;
00611    /* Store as much of the buffer as we can, then write fixed frames */
00612    int space = sizeof(p->obuf) - p->obuflen;
00613    /* Make sure we have enough buffer space to store the frame */
00614    if (space < len)
00615       len = space;
00616    if (swap)
00617       ast_swapcopy_samples(p->obuf+p->obuflen, buf, len/2);
00618    else
00619       memcpy(p->obuf + p->obuflen, buf, len);
00620    p->obuflen += len;
00621    while(p->obuflen > frlen) {
00622       res = write(p->fd, p->obuf, frlen);
00623       if (res != frlen) {
00624          if (res < 1) {
00625 /*
00626  * Card is in non-blocking mode now and it works well now, but there are
00627  * lot of messages like this. So, this message is temporarily disabled.
00628  */
00629             return 0;
00630          } else {
00631             ast_log(LOG_WARNING, "Only wrote %d of %d bytes\n", res, frlen);
00632          }
00633       }
00634       p->obuflen -= frlen;
00635       /* Move memory if necessary */
00636       if (p->obuflen) 
00637          memmove(p->obuf, p->obuf + frlen, p->obuflen);
00638    }
00639    return len;
00640 }
00641 
00642 static int phone_send_text(struct ast_channel *ast, const char *text)
00643 {
00644     int length = strlen(text);
00645     return phone_write_buf(ast->tech_pvt, text, length, length, 0) == 
00646            length ? 0 : -1;
00647 }
00648 
00649 static int phone_write(struct ast_channel *ast, struct ast_frame *frame)
00650 {
00651    struct phone_pvt *p = ast->tech_pvt;
00652    int res;
00653    int maxfr=0;
00654    char *pos;
00655    int sofar;
00656    int expected;
00657    int codecset = 0;
00658    char tmpbuf[4];
00659    /* Write a frame of (presumably voice) data */
00660    if (frame->frametype != AST_FRAME_VOICE && p->mode != MODE_FXS) {
00661       if (frame->frametype != AST_FRAME_IMAGE)
00662          ast_log(LOG_WARNING, "Don't know what to do with  frame type '%d'\n", frame->frametype);
00663       return 0;
00664    }
00665    if (!(frame->subclass &
00666       (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW)) && 
00667        p->mode != MODE_FXS) {
00668       ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
00669       return -1;
00670    }
00671 #if 0
00672    /* If we're not in up mode, go into up mode now */
00673    if (ast->_state != AST_STATE_UP) {
00674       ast_setstate(ast, AST_STATE_UP);
00675       phone_setup(ast);
00676    }
00677 #else
00678    if (ast->_state != AST_STATE_UP) {
00679       /* Don't try tos end audio on-hook */
00680       return 0;
00681    }
00682 #endif   
00683    if (frame->subclass == AST_FORMAT_G723_1) {
00684       if (p->lastformat != AST_FORMAT_G723_1) {
00685          ioctl(p->fd, PHONE_PLAY_STOP);
00686          ioctl(p->fd, PHONE_REC_STOP);
00687          if (ioctl(p->fd, PHONE_PLAY_CODEC, G723_63)) {
00688             ast_log(LOG_WARNING, "Unable to set G723.1 mode\n");
00689             return -1;
00690          }
00691          if (ioctl(p->fd, PHONE_REC_CODEC, G723_63)) {
00692             ast_log(LOG_WARNING, "Unable to set G723.1 mode\n");
00693             return -1;
00694          }
00695          p->lastformat = AST_FORMAT_G723_1;
00696          p->lastinput = AST_FORMAT_G723_1;
00697          /* Reset output buffer */
00698          p->obuflen = 0;
00699          codecset = 1;
00700       }
00701       if (frame->datalen > 24) {
00702          ast_log(LOG_WARNING, "Frame size too large for G.723.1 (%d bytes)\n", frame->datalen);
00703          return -1;
00704       }
00705       maxfr = 24;
00706    } else if (frame->subclass == AST_FORMAT_SLINEAR) {
00707       if (p->lastformat != AST_FORMAT_SLINEAR) {
00708          ioctl(p->fd, PHONE_PLAY_STOP);
00709          ioctl(p->fd, PHONE_REC_STOP);
00710          if (ioctl(p->fd, PHONE_PLAY_CODEC, LINEAR16)) {
00711             ast_log(LOG_WARNING, "Unable to set 16-bit linear mode\n");
00712             return -1;
00713          }
00714          if (ioctl(p->fd, PHONE_REC_CODEC, LINEAR16)) {
00715             ast_log(LOG_WARNING, "Unable to set 16-bit linear mode\n");
00716             return -1;
00717          }
00718          p->lastformat = AST_FORMAT_SLINEAR;
00719          p->lastinput = AST_FORMAT_SLINEAR;
00720          codecset = 1;
00721          /* Reset output buffer */
00722          p->obuflen = 0;
00723       }
00724       maxfr = 480;
00725    } else if (frame->subclass == AST_FORMAT_ULAW) {
00726       if (p->lastformat != AST_FORMAT_ULAW) {
00727          ioctl(p->fd, PHONE_PLAY_STOP);
00728          ioctl(p->fd, PHONE_REC_STOP);
00729          if (ioctl(p->fd, PHONE_PLAY_CODEC, ULAW)) {
00730             ast_log(LOG_WARNING, "Unable to set uLaw mode\n");
00731             return -1;
00732          }
00733          if (ioctl(p->fd, PHONE_REC_CODEC, ULAW)) {
00734             ast_log(LOG_WARNING, "Unable to set uLaw mode\n");
00735             return -1;
00736          }
00737          p->lastformat = AST_FORMAT_ULAW;
00738          p->lastinput = AST_FORMAT_ULAW;
00739          codecset = 1;
00740          /* Reset output buffer */
00741          p->obuflen = 0;
00742       }
00743       maxfr = 240;
00744    } else {
00745       if (p->lastformat != frame->subclass) {
00746          ioctl(p->fd, PHONE_PLAY_STOP);
00747          ioctl(p->fd, PHONE_REC_STOP);
00748          if (ioctl(p->fd, PHONE_PLAY_CODEC, frame->subclass)) {
00749             ast_log(LOG_WARNING, "Unable to set %d mode\n",
00750                frame->subclass);
00751             return -1;
00752          }
00753          if (ioctl(p->fd, PHONE_REC_CODEC, frame->subclass)) {
00754             ast_log(LOG_WARNING, "Unable to set %d mode\n",
00755                frame->subclass);
00756             return -1;
00757          }
00758          p->lastformat = frame->subclass;
00759          p->lastinput = frame->subclass;
00760          codecset = 1;
00761          /* Reset output buffer */
00762          p->obuflen = 0;
00763       }
00764       maxfr = 480;
00765    }
00766    if (codecset) {
00767       ioctl(p->fd, PHONE_REC_DEPTH, 3);
00768       ioctl(p->fd, PHONE_PLAY_DEPTH, 3);
00769       if (ioctl(p->fd, PHONE_PLAY_START)) {
00770          ast_log(LOG_WARNING, "Failed to start playback\n");
00771          return -1;
00772       }
00773       if (ioctl(p->fd, PHONE_REC_START)) {
00774          ast_log(LOG_WARNING, "Failed to start recording\n");
00775          return -1;
00776       }
00777    }
00778    /* If we get here, we have a frame of Appropriate data */
00779    sofar = 0;
00780    pos = frame->data;
00781    while(sofar < frame->datalen) {
00782       /* Write in no more than maxfr sized frames */
00783       expected = frame->datalen - sofar;
00784       if (maxfr < expected)
00785          expected = maxfr;
00786       /* XXX Internet Phone Jack does not handle the 4-byte VAD frame properly! XXX 
00787          we have to pad it to 24 bytes still.  */
00788       if (frame->datalen == 4) {
00789          if (p->silencesupression) {
00790             memset(tmpbuf + 4, 0, sizeof(tmpbuf) - 4);
00791             memcpy(tmpbuf, frame->data, 4);
00792             expected = 24;
00793             res = phone_write_buf(p, tmpbuf, expected, maxfr, 0);
00794          }
00795          res = 4;
00796          expected=4;
00797       } else {
00798          int swap = 0;
00799 #if __BYTE_ORDER == __BIG_ENDIAN
00800          if (frame->subclass == AST_FORMAT_SLINEAR)
00801             swap = 1; /* Swap big-endian samples to little-endian as we copy */
00802 #endif
00803          res = phone_write_buf(p, pos, expected, maxfr, swap);
00804       }
00805       if (res != expected) {
00806          if ((errno != EAGAIN) && (errno != EINTR)) {
00807             if (res < 0) 
00808                ast_log(LOG_WARNING, "Write returned error (%s)\n", strerror(errno));
00809    /*
00810     * Card is in non-blocking mode now and it works well now, but there are
00811     * lot of messages like this. So, this message is temporarily disabled.
00812     */
00813 #if 0
00814             else
00815                ast_log(LOG_WARNING, "Only wrote %d of %d bytes\n", res, frame->datalen);
00816 #endif
00817             return -1;
00818          } else /* Pretend it worked */
00819             res = expected;
00820       }
00821       sofar += res;
00822       pos += res;
00823    }
00824    return 0;
00825 }
00826 
00827 static struct ast_channel *phone_new(struct phone_pvt *i, int state, char *context)
00828 {
00829    struct ast_channel *tmp;
00830    struct phone_codec_data codec;
00831    tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, "", i->ext, i->context, 0, "Phone/%s", i->dev + 5);
00832    if (tmp) {
00833       tmp->tech = cur_tech;
00834       tmp->fds[0] = i->fd;
00835       /* XXX Switching formats silently causes kernel panics XXX */
00836       if (i->mode == MODE_FXS &&
00837           ioctl(i->fd, PHONE_QUERY_CODEC, &codec) == 0) {
00838          if (codec.type == LINEAR16)
00839             tmp->nativeformats =
00840             tmp->rawreadformat =
00841             tmp->rawwriteformat =
00842             AST_FORMAT_SLINEAR;
00843          else {
00844             tmp->nativeformats =
00845             tmp->rawreadformat =
00846             tmp->rawwriteformat =
00847             prefformat & ~AST_FORMAT_SLINEAR;
00848          }
00849       }
00850       else {
00851          tmp->nativeformats = prefformat;
00852          tmp->rawreadformat = prefformat;
00853          tmp->rawwriteformat = prefformat;
00854       }
00855       /* no need to call ast_setstate: the channel_alloc already did its job */
00856       if (state == AST_STATE_RING)
00857          tmp->rings = 1;
00858       tmp->tech_pvt = i;
00859       ast_copy_string(tmp->context, context, sizeof(tmp->context));
00860       if (!ast_strlen_zero(i->ext))
00861          ast_copy_string(tmp->exten, i->ext, sizeof(tmp->exten));
00862       else
00863          strcpy(tmp->exten, "s");
00864       if (!ast_strlen_zero(i->language))
00865          ast_string_field_set(tmp, language, i->language);
00866 
00867       /* Don't use ast_set_callerid() here because it will
00868        * generate a NewCallerID event before the NewChannel event */
00869       tmp->cid.cid_ani = ast_strdup(i->cid_num);
00870 
00871       i->owner = tmp;
00872       ast_module_ref(ast_module_info->self);
00873       if (state != AST_STATE_DOWN) {
00874          if (state == AST_STATE_RING) {
00875             ioctl(tmp->fds[0], PHONE_RINGBACK);
00876             i->cpt = 1;
00877          }
00878          if (ast_pbx_start(tmp)) {
00879             ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
00880             ast_hangup(tmp);
00881          }
00882       }
00883    } else
00884       ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
00885    return tmp;
00886 }
00887 
00888 static void phone_mini_packet(struct phone_pvt *i)
00889 {
00890    int res;
00891    char buf[1024];
00892    /* Ignore stuff we read... */
00893    res = read(i->fd, buf, sizeof(buf));
00894    if (res < 1) {
00895       ast_log(LOG_WARNING, "Read returned %d: %s\n", res, strerror(errno));
00896       return;
00897    }
00898 }
00899 
00900 static void phone_check_exception(struct phone_pvt *i)
00901 {
00902    int offhook=0;
00903    char digit[2] = {0 , 0};
00904    union telephony_exception phonee;
00905    /* XXX Do something XXX */
00906 #if 0
00907    ast_log(LOG_DEBUG, "Exception!\n");
00908 #endif
00909    phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION);
00910    if (phonee.bits.dtmf_ready)  {
00911       digit[0] = ioctl(i->fd, PHONE_GET_DTMF_ASCII);
00912       if (i->mode == MODE_DIALTONE || i->mode == MODE_FXS || i->mode == MODE_SIGMA) {
00913          ioctl(i->fd, PHONE_PLAY_STOP);
00914          ioctl(i->fd, PHONE_REC_STOP);
00915          ioctl(i->fd, PHONE_CPT_STOP);
00916          i->dialtone = 0;
00917          if (strlen(i->ext) < AST_MAX_EXTENSION - 1)
00918             strncat(i->ext, digit, sizeof(i->ext) - strlen(i->ext) - 1);
00919          if ((i->mode != MODE_FXS ||
00920               !(phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION)) ||
00921               !phonee.bits.dtmf_ready) &&
00922              ast_exists_extension(NULL, i->context, i->ext, 1, i->cid_num)) {
00923             /* It's a valid extension in its context, get moving! */
00924             phone_new(i, AST_STATE_RING, i->context);
00925             /* No need to restart monitor, we are the monitor */
00926          } else if (!ast_canmatch_extension(NULL, i->context, i->ext, 1, i->cid_num)) {
00927             /* There is nothing in the specified extension that can match anymore.
00928                Try the default */
00929             if (ast_exists_extension(NULL, "default", i->ext, 1, i->cid_num)) {
00930                /* Check the default, too... */
00931                phone_new(i, AST_STATE_RING, "default");
00932                /* XXX This should probably be justified better XXX */
00933             }  else if (!ast_canmatch_extension(NULL, "default", i->ext, 1, i->cid_num)) {
00934                /* It's not a valid extension, give a busy signal */
00935                if (option_debug)
00936                   ast_log(LOG_DEBUG, "%s can't match anything in %s or default\n", i->ext, i->context);
00937                ioctl(i->fd, PHONE_BUSY);
00938                i->cpt = 1;
00939             }
00940          }
00941 #if 0
00942          ast_verbose("Extension is %s\n", i->ext);
00943 #endif
00944       }
00945    }
00946    if (phonee.bits.hookstate) {
00947       offhook = ioctl(i->fd, PHONE_HOOKSTATE);
00948       if (offhook) {
00949          if (i->mode == MODE_IMMEDIATE) {
00950             phone_new(i, AST_STATE_RING, i->context);
00951          } else if (i->mode == MODE_DIALTONE) {
00952             ast_module_ref(ast_module_info->self);
00953             /* Reset the extension */
00954             i->ext[0] = '\0';
00955             /* Play the dialtone */
00956             i->dialtone++;
00957             ioctl(i->fd, PHONE_PLAY_STOP);
00958             ioctl(i->fd, PHONE_PLAY_CODEC, ULAW);
00959             ioctl(i->fd, PHONE_PLAY_START);
00960             i->lastformat = -1;
00961          } else if (i->mode == MODE_SIGMA) {
00962             ast_module_ref(ast_module_info->self);
00963             /* Reset the extension */
00964             i->ext[0] = '\0';
00965             /* Play the dialtone */
00966             i->dialtone++;
00967             ioctl(i->fd, PHONE_DIALTONE);
00968          }
00969       } else {
00970          if (i->dialtone)
00971             ast_module_unref(ast_module_info->self);
00972          memset(i->ext, 0, sizeof(i->ext));
00973          if (i->cpt)
00974          {
00975             ioctl(i->fd, PHONE_CPT_STOP);
00976             i->cpt = 0;
00977          }
00978          ioctl(i->fd, PHONE_PLAY_STOP);
00979          ioctl(i->fd, PHONE_REC_STOP);
00980          i->dialtone = 0;
00981          i->lastformat = -1;
00982       }
00983    }
00984    if (phonee.bits.pstn_ring) {
00985       ast_verbose("Unit is ringing\n");
00986       phone_new(i, AST_STATE_RING, i->context);
00987    }
00988    if (phonee.bits.caller_id)
00989       ast_verbose("We have caller ID\n");
00990    
00991    
00992 }
00993 
00994 static void *do_monitor(void *data)
00995 {
00996    fd_set rfds, efds;
00997    int n, res;
00998    struct phone_pvt *i;
00999    int tonepos = 0;
01000    /* The tone we're playing this round */
01001    struct timeval tv = {0,0};
01002    int dotone;
01003    /* This thread monitors all the frame relay interfaces which are not yet in use
01004       (and thus do not have a separate thread) indefinitely */
01005    while (monitor) {
01006       /* Don't let anybody kill us right away.  Nobody should lock the interface list
01007          and wait for the monitor list, but the other way around is okay. */
01008       /* Lock the interface list */
01009       if (ast_mutex_lock(&iflock)) {
01010          ast_log(LOG_ERROR, "Unable to grab interface lock\n");
01011          return NULL;
01012       }
01013       /* Build the stuff we're going to select on, that is the socket of every
01014          phone_pvt that does not have an associated owner channel */
01015       n = -1;
01016       FD_ZERO(&rfds);
01017       FD_ZERO(&efds);
01018       i = iflist;
01019       dotone = 0;
01020       while (i) {
01021          if (FD_ISSET(i->fd, &rfds)) 
01022             ast_log(LOG_WARNING, "Descriptor %d appears twice (%s)?\n", i->fd, i->dev);
01023          if (!i->owner) {
01024             /* This needs to be watched, as it lacks an owner */
01025             FD_SET(i->fd, &rfds);
01026             FD_SET(i->fd, &efds);
01027             if (i->fd > n)
01028                n = i->fd;
01029             if (i->dialtone && i->mode != MODE_SIGMA) {
01030                /* Remember we're going to have to come back and play
01031                   more dialtones */
01032                if (ast_tvzero(tv)) {
01033                   /* If we're due for a dialtone, play one */
01034                   if (write(i->fd, DialTone + tonepos, 240) != 240)
01035                      ast_log(LOG_WARNING, "Dial tone write error\n");
01036                }
01037                dotone++;
01038             }
01039          }
01040          
01041          i = i->next;
01042       }
01043       /* Okay, now that we know what to do, release the interface lock */
01044       ast_mutex_unlock(&iflock);
01045 
01046       /* Wait indefinitely for something to happen */
01047       if (dotone && i && i->mode != MODE_SIGMA) {
01048          /* If we're ready to recycle the time, set it to 30 ms */
01049          tonepos += 240;
01050          if (tonepos >= sizeof(DialTone))
01051                tonepos = 0;
01052          if (ast_tvzero(tv)) {
01053             tv = ast_tv(30000, 0);
01054          }
01055          res = ast_select(n + 1, &rfds, NULL, &efds, &tv);
01056       } else {
01057          res = ast_select(n + 1, &rfds, NULL, &efds, NULL);
01058          tv = ast_tv(0,0);
01059          tonepos = 0;
01060       }
01061       /* Okay, select has finished.  Let's see what happened.  */
01062       if (res < 0) {
01063          ast_log(LOG_DEBUG, "select return %d: %s\n", res, strerror(errno));
01064          continue;
01065       }
01066       /* If there are no fd's changed, just continue, it's probably time
01067          to play some more dialtones */
01068       if (!res)
01069          continue;
01070       /* Alright, lock the interface list again, and let's look and see what has
01071          happened */
01072       if (ast_mutex_lock(&iflock)) {
01073          ast_log(LOG_WARNING, "Unable to lock the interface list\n");
01074          continue;
01075       }
01076 
01077       i = iflist;
01078       for(; i; i=i->next) {
01079          if (FD_ISSET(i->fd, &rfds)) {
01080             if (i->owner) {
01081                continue;
01082             }
01083             phone_mini_packet(i);
01084          }
01085          if (FD_ISSET(i->fd, &efds)) {
01086             if (i->owner) {
01087                continue;
01088             }
01089             phone_check_exception(i);
01090          }
01091       }
01092       ast_mutex_unlock(&iflock);
01093    }
01094    return NULL;
01095    
01096 }
01097 
01098 static int restart_monitor()
01099 {
01100    /* If we're supposed to be stopped -- stay stopped */
01101    if (monitor_thread == AST_PTHREADT_STOP)
01102       return 0;
01103    if (ast_mutex_lock(&monlock)) {
01104       ast_log(LOG_WARNING, "Unable to lock monitor\n");
01105       return -1;
01106    }
01107    if (monitor_thread == pthread_self()) {
01108       ast_mutex_unlock(&monlock);
01109       ast_log(LOG_WARNING, "Cannot kill myself\n");
01110       return -1;
01111    }
01112    if (monitor_thread != AST_PTHREADT_NULL) {
01113       if (ast_mutex_lock(&iflock)) {
01114          ast_mutex_unlock(&monlock);
01115          ast_log(LOG_WARNING, "Unable to lock the interface list\n");
01116          return -1;
01117       }
01118       monitor = 0;
01119       while (pthread_kill(monitor_thread, SIGURG) == 0)
01120          sched_yield();
01121       pthread_join(monitor_thread, NULL);
01122       ast_mutex_unlock(&iflock);
01123    }
01124    monitor = 1;
01125    /* Start a new monitor */
01126    if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
01127       ast_mutex_unlock(&monlock);
01128       ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
01129       return -1;
01130    }
01131    ast_mutex_unlock(&monlock);
01132    return 0;
01133 }
01134 
01135 static struct phone_pvt *mkif(char *iface, int mode, int txgain, int rxgain)
01136 {
01137    /* Make a phone_pvt structure for this interface */
01138    struct phone_pvt *tmp;
01139    int flags;  
01140    
01141    tmp = malloc(sizeof(struct phone_pvt));
01142    if (tmp) {
01143       tmp->fd = open(iface, O_RDWR);
01144       if (tmp->fd < 0) {
01145          ast_log(LOG_WARNING, "Unable to open '%s'\n", iface);
01146          free(tmp);
01147          return NULL;
01148       }
01149       if (mode == MODE_FXO) {
01150          if (ioctl(tmp->fd, IXJCTL_PORT, PORT_PSTN)) 
01151             ast_log(LOG_DEBUG, "Unable to set port to PSTN\n");
01152       } else {
01153          if (ioctl(tmp->fd, IXJCTL_PORT, PORT_POTS)) 
01154              if (mode != MODE_FXS)
01155                   ast_log(LOG_DEBUG, "Unable to set port to POTS\n");
01156       }
01157       ioctl(tmp->fd, PHONE_PLAY_STOP);
01158       ioctl(tmp->fd, PHONE_REC_STOP);
01159       ioctl(tmp->fd, PHONE_RING_STOP);
01160       ioctl(tmp->fd, PHONE_CPT_STOP);
01161       if (ioctl(tmp->fd, PHONE_PSTN_SET_STATE, PSTN_ON_HOOK)) 
01162          ast_log(LOG_DEBUG, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n",iface, strerror(errno));
01163       if (echocancel != AEC_OFF)
01164          ioctl(tmp->fd, IXJCTL_AEC_START, echocancel);
01165       if (silencesupression) 
01166          tmp->silencesupression = 1;
01167 #ifdef PHONE_VAD
01168       ioctl(tmp->fd, PHONE_VAD, tmp->silencesupression);
01169 #endif
01170       tmp->mode = mode;
01171       flags = fcntl(tmp->fd, F_GETFL);
01172       fcntl(tmp->fd, F_SETFL, flags | O_NONBLOCK);
01173       tmp->owner = NULL;
01174       tmp->lastformat = -1;
01175       tmp->lastinput = -1;
01176       tmp->ministate = 0;
01177       memset(tmp->ext, 0, sizeof(tmp->ext));
01178       ast_copy_string(tmp->language, language, sizeof(tmp->language));
01179       ast_copy_string(tmp->dev, iface, sizeof(tmp->dev));
01180       ast_copy_string(tmp->context, context, sizeof(tmp->context));
01181       tmp->next = NULL;
01182       tmp->obuflen = 0;
01183       tmp->dialtone = 0;
01184       tmp->cpt = 0;
01185       ast_copy_string(tmp->cid_num, cid_num, sizeof(tmp->cid_num));
01186       ast_copy_string(tmp->cid_name, cid_name, sizeof(tmp->cid_name));
01187       tmp->txgain = txgain;
01188       ioctl(tmp->fd, PHONE_PLAY_VOLUME, tmp->txgain);
01189       tmp->rxgain = rxgain;
01190       ioctl(tmp->fd, PHONE_REC_VOLUME, tmp->rxgain);
01191    }
01192    return tmp;
01193 }
01194 
01195 static struct ast_channel *phone_request(const char *type, int format, void *data, int *cause)
01196 {
01197    int oldformat;
01198    struct phone_pvt *p;
01199    struct ast_channel *tmp = NULL;
01200    char *name = data;
01201 
01202    /* Search for an unowned channel */
01203    if (ast_mutex_lock(&iflock)) {
01204       ast_log(LOG_ERROR, "Unable to lock interface list???\n");
01205       return NULL;
01206    }
01207    p = iflist;
01208    while(p) {
01209       if (p->mode == MODE_FXS ||
01210           format & (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW)) {
01211           size_t length = strlen(p->dev + 5);
01212          if (strncmp(name, p->dev + 5, length) == 0 &&
01213              !isalnum(name[length])) {
01214              if (!p->owner) {
01215                      tmp = phone_new(p, AST_STATE_DOWN, p->context);
01216                      break;
01217                 } else
01218                      *cause = AST_CAUSE_BUSY;
01219             }
01220       }
01221       p = p->next;
01222    }
01223    ast_mutex_unlock(&iflock);
01224    restart_monitor();
01225    if (tmp == NULL) {
01226       oldformat = format;
01227       format &= (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW);
01228       if (!format) {
01229          ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
01230          return NULL;
01231       }
01232    }
01233    return tmp;
01234 }
01235 
01236 /* parse gain value from config file */
01237 static int parse_gain_value(char *gain_type, char *value)
01238 {
01239    float gain;
01240 
01241    /* try to scan number */
01242    if (sscanf(value, "%f", &gain) != 1)
01243    {
01244       ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n",
01245          value, gain_type, config);
01246       return DEFAULT_GAIN;
01247    }
01248 
01249    /* multiplicate gain by 1.0 gain value */ 
01250    gain = gain * (float)DEFAULT_GAIN;
01251 
01252    /* percentage? */
01253    if (value[strlen(value) - 1] == '%')
01254       return (int)(gain / (float)100);
01255 
01256    return (int)gain;
01257 }
01258 
01259 static int __unload_module(void)
01260 {
01261    struct phone_pvt *p, *pl;
01262    /* First, take us out of the channel loop */
01263    if (cur_tech)
01264       ast_channel_unregister(cur_tech);
01265    if (!ast_mutex_lock(&iflock)) {
01266       /* Hangup all interfaces if they have an owner */
01267       p = iflist;
01268       while(p) {
01269          if (p->owner)
01270             ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
01271          p = p->next;
01272       }
01273       iflist = NULL;
01274       ast_mutex_unlock(&iflock);
01275    } else {
01276       ast_log(LOG_WARNING, "Unable to lock the monitor\n");
01277       return -1;
01278    }
01279    if (!ast_mutex_lock(&monlock)) {
01280       if (monitor_thread > AST_PTHREADT_NULL) {
01281          monitor = 0;
01282          while (pthread_kill(monitor_thread, SIGURG) == 0)
01283             sched_yield();
01284          pthread_join(monitor_thread, NULL);
01285       }
01286       monitor_thread = AST_PTHREADT_STOP;
01287       ast_mutex_unlock(&monlock);
01288    } else {
01289       ast_log(LOG_WARNING, "Unable to lock the monitor\n");
01290       return -1;
01291    }
01292 
01293    if (!ast_mutex_lock(&iflock)) {
01294       /* Destroy all the interfaces and free their memory */
01295       p = iflist;
01296       while(p) {
01297          /* Close the socket, assuming it's real */
01298          if (p->fd > -1)
01299             close(p->fd);
01300          pl = p;
01301          p = p->next;
01302          /* Free associated memory */
01303          free(pl);
01304       }
01305       iflist = NULL;
01306       ast_mutex_unlock(&iflock);
01307    } else {
01308       ast_log(LOG_WARNING, "Unable to lock the monitor\n");
01309       return -1;
01310    }
01311       
01312    return 0;
01313 }
01314 
01315 static int unload_module(void)
01316 {
01317    return __unload_module();
01318 }
01319 
01320 static int load_module(void)
01321 {
01322    struct ast_config *cfg;
01323    struct ast_variable *v;
01324    struct phone_pvt *tmp;
01325    int mode = MODE_IMMEDIATE;
01326    int txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN; /* default gain 1.0 */
01327    cfg = ast_config_load(config);
01328 
01329    /* We *must* have a config file otherwise stop immediately */
01330    if (!cfg) {
01331       ast_log(LOG_ERROR, "Unable to load config %s\n", config);
01332       return AST_MODULE_LOAD_DECLINE;
01333    }
01334    if (ast_mutex_lock(&iflock)) {
01335       /* It's a little silly to lock it, but we mind as well just to be sure */
01336       ast_log(LOG_ERROR, "Unable to lock interface list???\n");
01337       return AST_MODULE_LOAD_FAILURE;
01338    }
01339    v = ast_variable_browse(cfg, "interfaces");
01340    while(v) {
01341       /* Create the interface list */
01342       if (!strcasecmp(v->name, "device")) {
01343             tmp = mkif(v->value, mode, txgain, rxgain);
01344             if (tmp) {
01345                tmp->next = iflist;
01346                iflist = tmp;
01347                
01348             } else {
01349                ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
01350                ast_config_destroy(cfg);
01351                ast_mutex_unlock(&iflock);
01352                __unload_module();
01353                return AST_MODULE_LOAD_FAILURE;
01354             }
01355       } else if (!strcasecmp(v->name, "silencesupression")) {
01356          silencesupression = ast_true(v->value);
01357       } else if (!strcasecmp(v->name, "language")) {
01358          ast_copy_string(language, v->value, sizeof(language));
01359       } else if (!strcasecmp(v->name, "callerid")) {
01360          ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
01361       } else if (!strcasecmp(v->name, "mode")) {
01362          if (!strncasecmp(v->value, "di", 2)) 
01363             mode = MODE_DIALTONE;
01364          else if (!strncasecmp(v->value, "sig", 3))
01365             mode = MODE_SIGMA;
01366          else if (!strncasecmp(v->value, "im", 2))
01367             mode = MODE_IMMEDIATE;
01368          else if (!strncasecmp(v->value, "fxs", 3)) {
01369             mode = MODE_FXS;
01370             prefformat = 0x01ff0000; /* All non-voice */
01371          }
01372          else if (!strncasecmp(v->value, "fx", 2))
01373             mode = MODE_FXO;
01374          else
01375             ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
01376       } else if (!strcasecmp(v->name, "context")) {
01377          ast_copy_string(context, v->value, sizeof(context));
01378       } else if (!strcasecmp(v->name, "format")) {
01379          if (!strcasecmp(v->value, "g723.1")) {
01380             prefformat = AST_FORMAT_G723_1;
01381          } else if (!strcasecmp(v->value, "slinear")) {
01382             if (mode == MODE_FXS)
01383                 prefformat |= AST_FORMAT_SLINEAR;
01384             else prefformat = AST_FORMAT_SLINEAR;
01385          } else if (!strcasecmp(v->value, "ulaw")) {
01386             prefformat = AST_FORMAT_ULAW;
01387          } else
01388             ast_log(LOG_WARNING, "Unknown format '%s'\n", v->value);
01389       } else if (!strcasecmp(v->name, "echocancel")) {
01390          if (!strcasecmp(v->value, "off")) {
01391             echocancel = AEC_OFF;
01392          } else if (!strcasecmp(v->value, "low")) {
01393             echocancel = AEC_LOW;
01394          } else if (!strcasecmp(v->value, "medium")) {
01395             echocancel = AEC_MED;
01396          } else if (!strcasecmp(v->value, "high")) {
01397             echocancel = AEC_HIGH;
01398          } else 
01399             ast_log(LOG_WARNING, "Unknown echo cancellation '%s'\n", v->value);
01400       } else if (!strcasecmp(v->name, "txgain")) {
01401          txgain = parse_gain_value(v->name, v->value);
01402       } else if (!strcasecmp(v->name, "rxgain")) {
01403          rxgain = parse_gain_value(v->name, v->value);
01404       }  
01405       v = v->next;
01406    }
01407    ast_mutex_unlock(&iflock);
01408 
01409    if (mode == MODE_FXS) {
01410       phone_tech_fxs.capabilities = prefformat;
01411       cur_tech = &phone_tech_fxs;
01412    } else
01413       cur_tech = (struct ast_channel_tech *) &phone_tech;
01414 
01415    /* Make sure we can register our Adtranphone channel type */
01416 
01417    if (ast_channel_register(cur_tech)) {
01418       ast_log(LOG_ERROR, "Unable to register channel class 'Phone'\n");
01419       ast_config_destroy(cfg);
01420       __unload_module();
01421       return AST_MODULE_LOAD_FAILURE;
01422    }
01423    ast_config_destroy(cfg);
01424    /* And start the monitor for the first time */
01425    restart_monitor();
01426    return AST_MODULE_LOAD_SUCCESS;
01427 }
01428 
01429 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Linux Telephony API Support");

Generated on Mon Mar 31 07:37:59 2008 for Asterisk - the Open Source PBX by  doxygen 1.5.1