update doxygen docs to specify authors
[asterisk/asterisk.git] / channels / chan_phone.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Generic Linux Telephony Interface driver
22  *
23  * \author Mark Spencer <markster@digium.com>
24  * 
25  * \ingroup channel_drivers
26  */
27
28 #include <stdio.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <sys/socket.h>
32 #include <sys/time.h>
33 #include <errno.h>
34 #include <unistd.h>
35 #include <stdlib.h>
36 #include <arpa/inet.h>
37 #include <fcntl.h>
38 #include <sys/ioctl.h>
39 #include <linux/telephony.h>
40 /* Still use some IXJ specific stuff */
41 #include <linux/version.h>
42 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
43 # include <linux/compiler.h>
44 #endif
45 #include <linux/ixjuser.h>
46
47 #include "asterisk.h"
48
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
50
51 #include "asterisk/lock.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/config.h"
54 #include "asterisk/logger.h"
55 #include "asterisk/module.h"
56 #include "asterisk/pbx.h"
57 #include "asterisk/options.h"
58 #include "asterisk/utils.h"
59 #include "asterisk/callerid.h"
60 #include "asterisk/causes.h"
61 #include "DialTone.h"
62
63 #ifdef QTI_PHONEJACK_TJ_PCI     /* check for the newer quicknet driver v.3.1.0 which has this symbol */
64 #define QNDRV_VER 310
65 #else
66 #define QNDRV_VER 100
67 #endif
68
69 #if QNDRV_VER > 100
70 #ifdef __linux__
71 #define IXJ_PHONE_RING_START(x) ioctl(p->fd, PHONE_RING_START, &x);
72 #else /* FreeBSD and others */
73 #define IXJ_PHONE_RING_START(x) ioctl(p->fd, PHONE_RING_START, x);
74 #endif /* __linux__ */
75 #else   /* older driver */
76 #define IXJ_PHONE_RING_START(x) ioctl(p->fd, PHONE_RING_START, &x);
77 #endif
78
79 #define DEFAULT_CALLER_ID "Unknown"
80 #define PHONE_MAX_BUF 480
81 #define DEFAULT_GAIN 0x100
82
83 static const char desc[] = "Linux Telephony API Support";
84 static const char type[] = "Phone";
85 static const char tdesc[] = "Standard Linux Telephony API Driver";
86 static const char config[] = "phone.conf";
87
88 /* Default context for dialtone mode */
89 static char context[AST_MAX_EXTENSION] = "default";
90
91 /* Default language */
92 static char language[MAX_LANGUAGE] = "";
93 static int usecnt =0;
94
95 static int echocancel = AEC_OFF;
96
97 static int silencesupression = 0;
98
99 static int prefformat = AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW;
100
101 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
102
103 /* Protect the interface list (of phone_pvt's) */
104 AST_MUTEX_DEFINE_STATIC(iflock);
105
106 /* Protect the monitoring thread, so only one process can kill or start it, and not
107    when it's doing something critical. */
108 AST_MUTEX_DEFINE_STATIC(monlock);
109    
110 /* This is the thread for the monitor which checks for input on the channels
111    which are not currently in use.  */
112 static pthread_t monitor_thread = AST_PTHREADT_NULL;
113
114 static int restart_monitor(void);
115
116 /* The private structures of the Phone Jack channels are linked for
117    selecting outgoing channels */
118    
119 #define MODE_DIALTONE   1
120 #define MODE_IMMEDIATE  2
121 #define MODE_FXO                3
122 #define MODE_FXS        4
123
124 static struct phone_pvt {
125         int fd;                                                 /* Raw file descriptor for this device */
126         struct ast_channel *owner;              /* Channel we belong to, possibly NULL */
127         int mode;                                               /* Is this in the  */
128         int lastformat;                                 /* Last output format */
129         int lastinput;                                  /* Last input format */
130         int ministate;                                  /* Miniature state, for dialtone mode */
131         char dev[256];                                  /* Device name */
132         struct phone_pvt *next;                 /* Next channel in list */
133         struct ast_frame fr;                    /* Frame */
134         char offset[AST_FRIENDLY_OFFSET];
135         char buf[PHONE_MAX_BUF];                                        /* Static buffer for reading frames */
136         int obuflen;
137         int dialtone;
138         int txgain, rxgain;             /* gain control for playing, recording  */
139                                                                         /* 0x100 - 1.0, 0x200 - 2.0, 0x80 - 0.5 */
140         int cpt;                                                /* Call Progress Tone playing? */
141         int silencesupression;
142         char context[AST_MAX_EXTENSION];
143         char obuf[PHONE_MAX_BUF * 2];
144         char ext[AST_MAX_EXTENSION];
145         char language[MAX_LANGUAGE];
146         char cid_num[AST_MAX_EXTENSION];
147         char cid_name[AST_MAX_EXTENSION];
148 } *iflist = NULL;
149
150 static char cid_num[AST_MAX_EXTENSION];
151 static char cid_name[AST_MAX_EXTENSION];
152
153 static struct ast_channel *phone_request(const char *type, int format, void *data, int *cause);
154 static int phone_digit(struct ast_channel *ast, char digit);
155 static int phone_call(struct ast_channel *ast, char *dest, int timeout);
156 static int phone_hangup(struct ast_channel *ast);
157 static int phone_answer(struct ast_channel *ast);
158 static struct ast_frame *phone_read(struct ast_channel *ast);
159 static int phone_write(struct ast_channel *ast, struct ast_frame *frame);
160 static struct ast_frame *phone_exception(struct ast_channel *ast);
161 static int phone_send_text(struct ast_channel *ast, const char *text);
162 static int phone_fixup(struct ast_channel *old, struct ast_channel *new);
163
164 static const struct ast_channel_tech phone_tech = {
165         .type = type,
166         .description = tdesc,
167         .capabilities = AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW,
168         .requester = phone_request,
169         .send_digit = phone_digit,
170         .call = phone_call,
171         .hangup = phone_hangup,
172         .answer = phone_answer,
173         .read = phone_read,
174         .write = phone_write,
175         .exception = phone_exception,
176         .fixup = phone_fixup
177 };
178
179 static struct ast_channel_tech phone_tech_fxs = {
180         .type = type,
181         .description = tdesc,
182         .requester = phone_request,
183         .send_digit = phone_digit,
184         .call = phone_call,
185         .hangup = phone_hangup,
186         .answer = phone_answer,
187         .read = phone_read,
188         .write = phone_write,
189         .exception = phone_exception,
190         .write_video = phone_write,
191         .send_text = phone_send_text,
192         .fixup = phone_fixup
193 };
194
195 static struct ast_channel_tech *cur_tech;
196
197 static int phone_fixup(struct ast_channel *old, struct ast_channel *new)
198 {
199         struct phone_pvt *pvt = old->tech_pvt;
200         if (pvt && pvt->owner == old)
201                 pvt->owner = new;
202         return 0;
203 }
204
205 static int phone_digit(struct ast_channel *ast, char digit)
206 {
207         struct phone_pvt *p;
208         int outdigit;
209         p = ast->tech_pvt;
210         ast_log(LOG_NOTICE, "Dialed %c\n", digit);
211         switch(digit) {
212         case '0':
213         case '1':
214         case '2':
215         case '3':
216         case '4':
217         case '5':
218         case '6':
219         case '7':
220         case '8':
221         case '9':
222                 outdigit = digit - '0';
223                 break;
224         case '*':
225                 outdigit = 11;
226                 break;
227         case '#':
228                 outdigit = 12;
229                 break;
230         case 'f':       /*flash*/
231         case 'F':
232                 ioctl(p->fd, IXJCTL_PSTN_SET_STATE, PSTN_ON_HOOK);
233                 usleep(320000);
234                 ioctl(p->fd, IXJCTL_PSTN_SET_STATE, PSTN_OFF_HOOK);
235                 p->lastformat = -1;
236                 return 0;
237         default:
238                 ast_log(LOG_WARNING, "Unknown digit '%c'\n", digit);
239                 return -1;
240         }
241         ast_log(LOG_NOTICE, "Dialed %d\n", outdigit);
242         ioctl(p->fd, PHONE_PLAY_TONE, outdigit);
243         p->lastformat = -1;
244         return 0;
245 }
246
247 static int phone_call(struct ast_channel *ast, char *dest, int timeout)
248 {
249         struct phone_pvt *p;
250
251         PHONE_CID cid;
252         time_t UtcTime;
253         struct tm tm;
254         int start;
255
256         time(&UtcTime);
257         localtime_r(&UtcTime,&tm);
258
259         memset(&cid, 0, sizeof(PHONE_CID));
260         if(&tm != NULL) {
261                 snprintf(cid.month, sizeof(cid.month), "%02d",(tm.tm_mon + 1));
262                 snprintf(cid.day, sizeof(cid.day),     "%02d", tm.tm_mday);
263                 snprintf(cid.hour, sizeof(cid.hour),   "%02d", tm.tm_hour);
264                 snprintf(cid.min, sizeof(cid.min),     "%02d", tm.tm_min);
265         }
266         /* the standard format of ast->callerid is:  "name" <number>, but not always complete */
267         if (ast_strlen_zero(ast->cid.cid_name))
268                 strncpy(cid.name, DEFAULT_CALLER_ID, sizeof(cid.name) - 1);
269         else
270                 strncpy(cid.name, ast->cid.cid_name, sizeof(cid.name) - 1);
271
272         if (ast->cid.cid_num) 
273                 strncpy(cid.number, ast->cid.cid_num, sizeof(cid.number) - 1);
274
275         p = ast->tech_pvt;
276
277         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
278                 ast_log(LOG_WARNING, "phone_call called on %s, neither down nor reserved\n", ast->name);
279                 return -1;
280         }
281         if (option_debug)
282                 ast_log(LOG_DEBUG, "Ringing %s on %s (%d)\n", dest, ast->name, ast->fds[0]);
283
284         start = IXJ_PHONE_RING_START(cid);
285         if (start == -1)
286                 return -1;
287         
288         if (p->mode == MODE_FXS) {
289                 char *digit = strchr(dest, '/');
290                 if (digit)
291                 {
292                   digit++;
293                   while (*digit)
294                     phone_digit(ast, *digit++);
295                 }
296         }
297  
298         ast_setstate(ast, AST_STATE_RINGING);
299         ast_queue_control(ast, AST_CONTROL_RINGING);
300         return 0;
301 }
302
303 static int phone_hangup(struct ast_channel *ast)
304 {
305         struct phone_pvt *p;
306         p = ast->tech_pvt;
307         if (option_debug)
308                 ast_log(LOG_DEBUG, "phone_hangup(%s)\n", ast->name);
309         if (!ast->tech_pvt) {
310                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
311                 return 0;
312         }
313         /* XXX Is there anything we can do to really hang up except stop recording? */
314         ast_setstate(ast, AST_STATE_DOWN);
315         if (ioctl(p->fd, PHONE_REC_STOP))
316                 ast_log(LOG_WARNING, "Failed to stop recording\n");
317         if (ioctl(p->fd, PHONE_PLAY_STOP))
318                 ast_log(LOG_WARNING, "Failed to stop playing\n");
319         if (ioctl(p->fd, PHONE_RING_STOP))
320                 ast_log(LOG_WARNING, "Failed to stop ringing\n");
321         if (ioctl(p->fd, PHONE_CPT_STOP))
322                 ast_log(LOG_WARNING, "Failed to stop sounds\n");
323
324         /* If it's an FXO, hang them up */
325         if (p->mode == MODE_FXO) {
326                 if (ioctl(p->fd, PHONE_PSTN_SET_STATE, PSTN_ON_HOOK)) 
327                         ast_log(LOG_DEBUG, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n",ast->name, strerror(errno));
328         }
329
330         /* If they're off hook, give a busy signal */
331         if (ioctl(p->fd, PHONE_HOOKSTATE)) {
332                 if (option_debug)
333                         ast_log(LOG_DEBUG, "Got hunghup, giving busy signal\n");
334                 ioctl(p->fd, PHONE_BUSY);
335                 p->cpt = 1;
336         }
337         p->lastformat = -1;
338         p->lastinput = -1;
339         p->ministate = 0;
340         p->obuflen = 0;
341         p->dialtone = 0;
342         memset(p->ext, 0, sizeof(p->ext));
343         ((struct phone_pvt *)(ast->tech_pvt))->owner = NULL;
344         ast_mutex_lock(&usecnt_lock);
345         usecnt--;
346         if (usecnt < 0) 
347                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
348         ast_mutex_unlock(&usecnt_lock);
349         ast_update_use_count();
350         if (option_verbose > 2) 
351                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
352         ast->tech_pvt = NULL;
353         ast_setstate(ast, AST_STATE_DOWN);
354         restart_monitor();
355         return 0;
356 }
357
358 static int phone_setup(struct ast_channel *ast)
359 {
360         struct phone_pvt *p;
361         p = ast->tech_pvt;
362         ioctl(p->fd, PHONE_CPT_STOP);
363         /* Nothing to answering really, just start recording */
364         if (ast->rawreadformat == AST_FORMAT_G723_1) {
365                 /* Prefer g723 */
366                 ioctl(p->fd, PHONE_REC_STOP);
367                 if (p->lastinput != AST_FORMAT_G723_1) {
368                         p->lastinput = AST_FORMAT_G723_1;
369                         if (ioctl(p->fd, PHONE_REC_CODEC, G723_63)) {
370                                 ast_log(LOG_WARNING, "Failed to set codec to g723.1\n");
371                                 return -1;
372                         }
373                 }
374         } else if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
375                 ioctl(p->fd, PHONE_REC_STOP);
376                 if (p->lastinput != AST_FORMAT_SLINEAR) {
377                         p->lastinput = AST_FORMAT_SLINEAR;
378                         if (ioctl(p->fd, PHONE_REC_CODEC, LINEAR16)) {
379                                 ast_log(LOG_WARNING, "Failed to set codec to signed linear 16\n");
380                                 return -1;
381                         }
382                 }
383         } else if (ast->rawreadformat == AST_FORMAT_ULAW) {
384                 ioctl(p->fd, PHONE_REC_STOP);
385                 if (p->lastinput != AST_FORMAT_ULAW) {
386                         p->lastinput = AST_FORMAT_ULAW;
387                         if (ioctl(p->fd, PHONE_REC_CODEC, ULAW)) {
388                                 ast_log(LOG_WARNING, "Failed to set codec to uLaw\n");
389                                 return -1;
390                         }
391                 }
392         } else if (p->mode == MODE_FXS) {
393                 ioctl(p->fd, PHONE_REC_STOP);
394                 if (p->lastinput != ast->rawreadformat) {
395                         p->lastinput = ast->rawreadformat;
396                         if (ioctl(p->fd, PHONE_REC_CODEC, ast->rawreadformat)) {
397                                 ast_log(LOG_WARNING, "Failed to set codec to %d\n", 
398                                         ast->rawreadformat);
399                                 return -1;
400                         }
401                 }
402         } else {
403                 ast_log(LOG_WARNING, "Can't do format %s\n", ast_getformatname(ast->rawreadformat));
404                 return -1;
405         }
406         if (ioctl(p->fd, PHONE_REC_START)) {
407                 ast_log(LOG_WARNING, "Failed to start recording\n");
408                 return -1;
409         }
410         /* set the DTMF times (the default is too short) */
411         ioctl(p->fd, PHONE_SET_TONE_ON_TIME, 300);
412         ioctl(p->fd, PHONE_SET_TONE_OFF_TIME, 200);
413         return 0;
414 }
415
416 static int phone_answer(struct ast_channel *ast)
417 {
418         struct phone_pvt *p;
419         p = ast->tech_pvt;
420         /* In case it's a LineJack, take it off hook */
421         if (p->mode == MODE_FXO) {
422                 if (ioctl(p->fd, PHONE_PSTN_SET_STATE, PSTN_OFF_HOOK)) 
423                         ast_log(LOG_DEBUG, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n", ast->name, strerror(errno));
424                 else
425                         ast_log(LOG_DEBUG, "Took linejack off hook\n");
426         }
427         phone_setup(ast);
428         if (option_debug)
429                 ast_log(LOG_DEBUG, "phone_answer(%s)\n", ast->name);
430         ast->rings = 0;
431         ast_setstate(ast, AST_STATE_UP);
432         return 0;
433 }
434
435 #if 0
436 static char phone_2digit(char c)
437 {
438         if (c == 12)
439                 return '#';
440         else if (c == 11)
441                 return '*';
442         else if ((c < 10) && (c >= 0))
443                 return '0' + c - 1;
444         else
445                 return '?';
446 }
447 #endif
448
449 static struct ast_frame  *phone_exception(struct ast_channel *ast)
450 {
451         int res;
452         union telephony_exception phonee;
453         struct phone_pvt *p = ast->tech_pvt;
454         char digit;
455
456         /* Some nice norms */
457         p->fr.datalen = 0;
458         p->fr.samples = 0;
459         p->fr.data =  NULL;
460         p->fr.src = type;
461         p->fr.offset = 0;
462         p->fr.mallocd=0;
463         p->fr.delivery = ast_tv(0,0);
464         
465         phonee.bytes = ioctl(p->fd, PHONE_EXCEPTION);
466         if (phonee.bits.dtmf_ready)  {
467                 if (option_debug)
468                         ast_log(LOG_DEBUG, "phone_exception(): DTMF\n");
469         
470                 /* We've got a digit -- Just handle this nicely and easily */
471                 digit =  ioctl(p->fd, PHONE_GET_DTMF_ASCII);
472                 p->fr.subclass = digit;
473                 p->fr.frametype = AST_FRAME_DTMF;
474                 return &p->fr;
475         }
476         if (phonee.bits.hookstate) {
477                 if (option_debug)
478                         ast_log(LOG_DEBUG, "Hookstate changed\n");
479                 res = ioctl(p->fd, PHONE_HOOKSTATE);
480                 /* See if we've gone on hook, if so, notify by returning NULL */
481                 if (option_debug)
482                         ast_log(LOG_DEBUG, "New hookstate: %d\n", res);
483                 if (!res && (p->mode != MODE_FXO))
484                         return NULL;
485                 else {
486                         if (ast->_state == AST_STATE_RINGING) {
487                                 /* They've picked up the phone */
488                                 p->fr.frametype = AST_FRAME_CONTROL;
489                                 p->fr.subclass = AST_CONTROL_ANSWER;
490                                 phone_setup(ast);
491                                 ast_setstate(ast, AST_STATE_UP);
492                                 return &p->fr;
493                         }  else 
494                                 ast_log(LOG_WARNING, "Got off hook in weird state %d\n", ast->_state);
495                 }
496         }
497 #if 1
498         if (phonee.bits.pstn_ring)
499                 ast_verbose("Unit is ringing\n");
500         if (phonee.bits.caller_id) {
501                 ast_verbose("We have caller ID\n");
502         }
503         if (phonee.bits.pstn_wink)
504                 ast_verbose("Detected Wink\n");
505 #endif
506         /* Strange -- nothing there.. */
507         p->fr.frametype = AST_FRAME_NULL;
508         p->fr.subclass = 0;
509         return &p->fr;
510 }
511
512 static struct ast_frame  *phone_read(struct ast_channel *ast)
513 {
514         int res;
515         struct phone_pvt *p = ast->tech_pvt;
516         
517
518         /* Some nice norms */
519         p->fr.datalen = 0;
520         p->fr.samples = 0;
521         p->fr.data =  NULL;
522         p->fr.src = type;
523         p->fr.offset = 0;
524         p->fr.mallocd=0;
525         p->fr.delivery = ast_tv(0,0);
526
527         /* Try to read some data... */
528         CHECK_BLOCKING(ast);
529         res = read(p->fd, p->buf, PHONE_MAX_BUF);
530         ast_clear_flag(ast, AST_FLAG_BLOCKING);
531         if (res < 0) {
532 #if 0
533                 if (errno == EAGAIN) {
534                         ast_log(LOG_WARNING, "Null frame received\n");
535                         p->fr.frametype = AST_FRAME_NULL;
536                         p->fr.subclass = 0;
537                         return &p->fr;
538                 }
539 #endif
540                 ast_log(LOG_WARNING, "Error reading: %s\n", strerror(errno));
541                 return NULL;
542         }
543         p->fr.data = p->buf;
544         if (p->mode != MODE_FXS)
545         switch(p->buf[0] & 0x3) {
546         case '0':
547         case '1':
548                 /* Normal */
549                 break;
550         case '2':
551         case '3':
552                 /* VAD/CNG, only send two words */
553                 res = 4;
554                 break;
555         }
556         p->fr.samples = 240;
557         p->fr.datalen = res;
558         p->fr.frametype = p->lastinput <= AST_FORMAT_MAX_AUDIO ?
559                           AST_FRAME_VOICE : 
560                           p->lastinput <= AST_FORMAT_PNG ? AST_FRAME_IMAGE 
561                           : AST_FRAME_VIDEO;
562         p->fr.subclass = p->lastinput;
563         p->fr.offset = AST_FRIENDLY_OFFSET;
564         /* Byteswap from little-endian to native-endian */
565         if (p->fr.subclass == AST_FORMAT_SLINEAR)
566                 ast_frame_byteswap_le(&p->fr);
567         return &p->fr;
568 }
569
570 static int phone_write_buf(struct phone_pvt *p, const char *buf, int len, int frlen, int swap)
571 {
572         int res;
573         /* Store as much of the buffer as we can, then write fixed frames */
574         int space = sizeof(p->obuf) - p->obuflen;
575         /* Make sure we have enough buffer space to store the frame */
576         if (space < len)
577                 len = space;
578         if (swap)
579                 ast_swapcopy_samples(p->obuf+p->obuflen, buf, len/2);
580         else
581                 memcpy(p->obuf + p->obuflen, buf, len);
582         p->obuflen += len;
583         while(p->obuflen > frlen) {
584                 res = write(p->fd, p->obuf, frlen);
585                 if (res != frlen) {
586                         if (res < 1) {
587 /*
588  * Card is in non-blocking mode now and it works well now, but there are
589  * lot of messages like this. So, this message is temporarily disabled.
590  */
591                                 return 0;
592                         } else {
593                                 ast_log(LOG_WARNING, "Only wrote %d of %d bytes\n", res, frlen);
594                         }
595                 }
596                 p->obuflen -= frlen;
597                 /* Move memory if necessary */
598                 if (p->obuflen) 
599                         memmove(p->obuf, p->obuf + frlen, p->obuflen);
600         }
601         return len;
602 }
603
604 static int phone_send_text(struct ast_channel *ast, const char *text)
605 {
606     int length = strlen(text);
607     return phone_write_buf(ast->tech_pvt, text, length, length, 0) == 
608            length ? 0 : -1;
609 }
610
611 static int phone_write(struct ast_channel *ast, struct ast_frame *frame)
612 {
613         struct phone_pvt *p = ast->tech_pvt;
614         int res;
615         int maxfr=0;
616         char *pos;
617         int sofar;
618         int expected;
619         int codecset = 0;
620         char tmpbuf[4];
621         /* Write a frame of (presumably voice) data */
622         if (frame->frametype != AST_FRAME_VOICE && p->mode != MODE_FXS) {
623                 if (frame->frametype != AST_FRAME_IMAGE)
624                         ast_log(LOG_WARNING, "Don't know what to do with  frame type '%d'\n", frame->frametype);
625                 return 0;
626         }
627         if (!(frame->subclass &
628                 (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW)) && 
629             p->mode != MODE_FXS) {
630                 ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
631                 return -1;
632         }
633 #if 0
634         /* If we're not in up mode, go into up mode now */
635         if (ast->_state != AST_STATE_UP) {
636                 ast_setstate(ast, AST_STATE_UP);
637                 phone_setup(ast);
638         }
639 #else
640         if (ast->_state != AST_STATE_UP) {
641                 /* Don't try tos end audio on-hook */
642                 return 0;
643         }
644 #endif  
645         if (frame->subclass == AST_FORMAT_G723_1) {
646                 if (p->lastformat != AST_FORMAT_G723_1) {
647                         ioctl(p->fd, PHONE_PLAY_STOP);
648                         ioctl(p->fd, PHONE_REC_STOP);
649                         if (ioctl(p->fd, PHONE_PLAY_CODEC, G723_63)) {
650                                 ast_log(LOG_WARNING, "Unable to set G723.1 mode\n");
651                                 return -1;
652                         }
653                         if (ioctl(p->fd, PHONE_REC_CODEC, G723_63)) {
654                                 ast_log(LOG_WARNING, "Unable to set G723.1 mode\n");
655                                 return -1;
656                         }
657                         p->lastformat = AST_FORMAT_G723_1;
658                         p->lastinput = AST_FORMAT_G723_1;
659                         /* Reset output buffer */
660                         p->obuflen = 0;
661                         codecset = 1;
662                 }
663                 if (frame->datalen > 24) {
664                         ast_log(LOG_WARNING, "Frame size too large for G.723.1 (%d bytes)\n", frame->datalen);
665                         return -1;
666                 }
667                 maxfr = 24;
668         } else if (frame->subclass == AST_FORMAT_SLINEAR) {
669                 if (p->lastformat != AST_FORMAT_SLINEAR) {
670                         ioctl(p->fd, PHONE_PLAY_STOP);
671                         ioctl(p->fd, PHONE_REC_STOP);
672                         if (ioctl(p->fd, PHONE_PLAY_CODEC, LINEAR16)) {
673                                 ast_log(LOG_WARNING, "Unable to set 16-bit linear mode\n");
674                                 return -1;
675                         }
676                         if (ioctl(p->fd, PHONE_REC_CODEC, LINEAR16)) {
677                                 ast_log(LOG_WARNING, "Unable to set 16-bit linear mode\n");
678                                 return -1;
679                         }
680                         p->lastformat = AST_FORMAT_SLINEAR;
681                         p->lastinput = AST_FORMAT_SLINEAR;
682                         codecset = 1;
683                         /* Reset output buffer */
684                         p->obuflen = 0;
685                 }
686                 maxfr = 480;
687         } else if (frame->subclass == AST_FORMAT_ULAW) {
688                 if (p->lastformat != AST_FORMAT_ULAW) {
689                         ioctl(p->fd, PHONE_PLAY_STOP);
690                         ioctl(p->fd, PHONE_REC_STOP);
691                         if (ioctl(p->fd, PHONE_PLAY_CODEC, ULAW)) {
692                                 ast_log(LOG_WARNING, "Unable to set uLaw mode\n");
693                                 return -1;
694                         }
695                         if (ioctl(p->fd, PHONE_REC_CODEC, ULAW)) {
696                                 ast_log(LOG_WARNING, "Unable to set uLaw mode\n");
697                                 return -1;
698                         }
699                         p->lastformat = AST_FORMAT_ULAW;
700                         p->lastinput = AST_FORMAT_ULAW;
701                         codecset = 1;
702                         /* Reset output buffer */
703                         p->obuflen = 0;
704                 }
705                 maxfr = 240;
706         } else {
707                 if (p->lastformat != frame->subclass) {
708                         ioctl(p->fd, PHONE_PLAY_STOP);
709                         ioctl(p->fd, PHONE_REC_STOP);
710                         if (ioctl(p->fd, PHONE_PLAY_CODEC, frame->subclass)) {
711                                 ast_log(LOG_WARNING, "Unable to set %d mode\n",
712                                         frame->subclass);
713                                 return -1;
714                         }
715                         if (ioctl(p->fd, PHONE_REC_CODEC, frame->subclass)) {
716                                 ast_log(LOG_WARNING, "Unable to set %d mode\n",
717                                         frame->subclass);
718                                 return -1;
719                         }
720                         p->lastformat = frame->subclass;
721                         p->lastinput = frame->subclass;
722                         codecset = 1;
723                         /* Reset output buffer */
724                         p->obuflen = 0;
725                 }
726                 maxfr = 480;
727         }
728         if (codecset) {
729                 ioctl(p->fd, PHONE_REC_DEPTH, 3);
730                 ioctl(p->fd, PHONE_PLAY_DEPTH, 3);
731                 if (ioctl(p->fd, PHONE_PLAY_START)) {
732                         ast_log(LOG_WARNING, "Failed to start playback\n");
733                         return -1;
734                 }
735                 if (ioctl(p->fd, PHONE_REC_START)) {
736                         ast_log(LOG_WARNING, "Failed to start recording\n");
737                         return -1;
738                 }
739         }
740         /* If we get here, we have a frame of Appropriate data */
741         sofar = 0;
742         pos = frame->data;
743         while(sofar < frame->datalen) {
744                 /* Write in no more than maxfr sized frames */
745                 expected = frame->datalen - sofar;
746                 if (maxfr < expected)
747                         expected = maxfr;
748                 /* XXX Internet Phone Jack does not handle the 4-byte VAD frame properly! XXX 
749                    we have to pad it to 24 bytes still.  */
750                 if (frame->datalen == 4) {
751                         if (p->silencesupression) {
752                                 memset(tmpbuf + 4, 0, sizeof(tmpbuf) - 4);
753                                 memcpy(tmpbuf, frame->data, 4);
754                                 expected = 24;
755                                 res = phone_write_buf(p, tmpbuf, expected, maxfr, 0);
756                         }
757                         res = 4;
758                         expected=4;
759                 } else {
760                         int swap = 0;
761 #if __BYTE_ORDER == __BIG_ENDIAN
762                         if (frame->subclass == AST_FORMAT_SLINEAR)
763                                 swap = 1; /* Swap big-endian samples to little-endian as we copy */
764 #endif
765                         res = phone_write_buf(p, pos, expected, maxfr, swap);
766                 }
767                 if (res != expected) {
768                         if ((errno != EAGAIN) && (errno != EINTR)) {
769                                 if (res < 0) 
770                                         ast_log(LOG_WARNING, "Write returned error (%s)\n", strerror(errno));
771         /*
772          * Card is in non-blocking mode now and it works well now, but there are
773          * lot of messages like this. So, this message is temporarily disabled.
774          */
775 #if 0
776                                 else
777                                         ast_log(LOG_WARNING, "Only wrote %d of %d bytes\n", res, frame->datalen);
778 #endif
779                                 return -1;
780                         } else /* Pretend it worked */
781                                 res = expected;
782                 }
783                 sofar += res;
784                 pos += res;
785         }
786         return 0;
787 }
788
789 static struct ast_channel *phone_new(struct phone_pvt *i, int state, char *context)
790 {
791         struct ast_channel *tmp;
792         struct phone_codec_data codec;
793         tmp = ast_channel_alloc(1);
794         if (tmp) {
795                 tmp->tech = cur_tech;
796                 snprintf(tmp->name, sizeof(tmp->name), "Phone/%s", i->dev + 5);
797                 tmp->type = type;
798                 tmp->fds[0] = i->fd;
799                 /* XXX Switching formats silently causes kernel panics XXX */
800                 if (i->mode == MODE_FXS &&
801                     ioctl(i->fd, PHONE_QUERY_CODEC, &codec) == 0) {
802                         if (codec.type == LINEAR16)
803                                 tmp->nativeformats =
804                                 tmp->rawreadformat =
805                                 tmp->rawwriteformat =
806                                 AST_FORMAT_SLINEAR;
807                         else {
808                                 tmp->nativeformats =
809                                 tmp->rawreadformat =
810                                 tmp->rawwriteformat =
811                                 prefformat & ~AST_FORMAT_SLINEAR;
812                         }
813                 }
814                 else {
815                         tmp->nativeformats = prefformat;
816                         tmp->rawreadformat = prefformat;
817                         tmp->rawwriteformat = prefformat;
818                 }
819                 ast_setstate(tmp, state);
820                 if (state == AST_STATE_RING)
821                         tmp->rings = 1;
822                 tmp->tech_pvt = i;
823                 strncpy(tmp->context, context, sizeof(tmp->context)-1);
824                 if (!ast_strlen_zero(i->ext))
825                         strncpy(tmp->exten, i->ext, sizeof(tmp->exten)-1);
826                 else
827                         strncpy(tmp->exten, "s",  sizeof(tmp->exten) - 1);
828                 if (!ast_strlen_zero(i->language))
829                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
830                 if (!ast_strlen_zero(i->cid_num))
831                         tmp->cid.cid_num = strdup(i->cid_num);
832                 if (!ast_strlen_zero(i->cid_name))
833                         tmp->cid.cid_name = strdup(i->cid_name);
834                 i->owner = tmp;
835                 ast_mutex_lock(&usecnt_lock);
836                 usecnt++;
837                 ast_mutex_unlock(&usecnt_lock);
838                 ast_update_use_count();
839                 if (state != AST_STATE_DOWN) {
840                         if (state == AST_STATE_RING) {
841                                 ioctl(tmp->fds[0], PHONE_RINGBACK);
842                                 i->cpt = 1;
843                         }
844                         if (ast_pbx_start(tmp)) {
845                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
846                                 ast_hangup(tmp);
847                         }
848                 }
849         } else
850                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
851         return tmp;
852 }
853
854 static void phone_mini_packet(struct phone_pvt *i)
855 {
856         int res;
857         char buf[1024];
858         /* Ignore stuff we read... */
859         res = read(i->fd, buf, sizeof(buf));
860         if (res < 1) {
861                 ast_log(LOG_WARNING, "Read returned %d: %s\n", res, strerror(errno));
862                 return;
863         }
864 }
865
866 static void phone_check_exception(struct phone_pvt *i)
867 {
868         int offhook=0;
869         char digit[2] = {0 , 0};
870         union telephony_exception phonee;
871         /* XXX Do something XXX */
872 #if 0
873         ast_log(LOG_DEBUG, "Exception!\n");
874 #endif
875         phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION);
876         if (phonee.bits.dtmf_ready)  {
877                 digit[0] = ioctl(i->fd, PHONE_GET_DTMF_ASCII);
878                 if (i->mode == MODE_DIALTONE || i->mode == MODE_FXS) {
879                         ioctl(i->fd, PHONE_PLAY_STOP);
880                         ioctl(i->fd, PHONE_REC_STOP);
881                         ioctl(i->fd, PHONE_CPT_STOP);
882                         i->dialtone = 0;
883                         if (strlen(i->ext) < AST_MAX_EXTENSION - 1)
884                                 strncat(i->ext, digit, sizeof(i->ext) - strlen(i->ext) - 1);
885                         if ((i->mode != MODE_FXS ||
886                              !(phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION)) ||
887                              !phonee.bits.dtmf_ready) &&
888                             ast_exists_extension(NULL, i->context, i->ext, 1, i->cid_num)) {
889                                 /* It's a valid extension in its context, get moving! */
890                                 phone_new(i, AST_STATE_RING, i->context);
891                                 /* No need to restart monitor, we are the monitor */
892                         } else if (!ast_canmatch_extension(NULL, i->context, i->ext, 1, i->cid_num)) {
893                                 /* There is nothing in the specified extension that can match anymore.
894                                    Try the default */
895                                 if (ast_exists_extension(NULL, "default", i->ext, 1, i->cid_num)) {
896                                         /* Check the default, too... */
897                                         phone_new(i, AST_STATE_RING, "default");
898                                         /* XXX This should probably be justified better XXX */
899                                 }  else if (!ast_canmatch_extension(NULL, "default", i->ext, 1, i->cid_num)) {
900                                         /* It's not a valid extension, give a busy signal */
901                                         if (option_debug)
902                                                 ast_log(LOG_DEBUG, "%s can't match anything in %s or default\n", i->ext, i->context);
903                                         ioctl(i->fd, PHONE_BUSY);
904                                         i->cpt = 1;
905                                 }
906                         }
907 #if 0
908                         ast_verbose("Extension is %s\n", i->ext);
909 #endif
910                 }
911         }
912         if (phonee.bits.hookstate) {
913                 offhook = ioctl(i->fd, PHONE_HOOKSTATE);
914                 if (offhook) {
915                         if (i->mode == MODE_IMMEDIATE) {
916                                 phone_new(i, AST_STATE_RING, i->context);
917                         } else if (i->mode == MODE_DIALTONE) {
918                                 ast_mutex_lock(&usecnt_lock);
919                                 usecnt++;
920                                 ast_mutex_unlock(&usecnt_lock);
921                                 ast_update_use_count();
922                                 /* Reset the extension */
923                                 i->ext[0] = '\0';
924                                 /* Play the dialtone */
925                                 i->dialtone++;
926                                 ioctl(i->fd, PHONE_PLAY_STOP);
927                                 ioctl(i->fd, PHONE_PLAY_CODEC, ULAW);
928                                 ioctl(i->fd, PHONE_PLAY_START);
929                                 i->lastformat = -1;
930                         }
931                 } else {
932                         if (i->dialtone) {
933                                 ast_mutex_lock(&usecnt_lock);
934                                 usecnt--;
935                                 ast_mutex_unlock(&usecnt_lock);
936                                 ast_update_use_count();
937                         }
938                         memset(i->ext, 0, sizeof(i->ext));
939                         if (i->cpt)
940                         {
941                                 ioctl(i->fd, PHONE_CPT_STOP);
942                                 i->cpt = 0;
943                         }
944                         ioctl(i->fd, PHONE_PLAY_STOP);
945                         ioctl(i->fd, PHONE_REC_STOP);
946                         i->dialtone = 0;
947                         i->lastformat = -1;
948                 }
949         }
950         if (phonee.bits.pstn_ring) {
951                 ast_verbose("Unit is ringing\n");
952                 phone_new(i, AST_STATE_RING, i->context);
953         }
954         if (phonee.bits.caller_id)
955                 ast_verbose("We have caller ID\n");
956         
957         
958 }
959
960 static void *do_monitor(void *data)
961 {
962         fd_set rfds, efds;
963         int n, res;
964         struct phone_pvt *i;
965         int tonepos = 0;
966         /* The tone we're playing this round */
967         struct timeval tv = {0,0};
968         int dotone;
969         /* This thread monitors all the frame relay interfaces which are not yet in use
970            (and thus do not have a separate thread) indefinitely */
971         /* From here on out, we die whenever asked */
972         if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
973                 ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
974                 return NULL;
975         }
976         for(;;) {
977                 /* Don't let anybody kill us right away.  Nobody should lock the interface list
978                    and wait for the monitor list, but the other way around is okay. */
979                 if (ast_mutex_lock(&monlock)) {
980                         ast_log(LOG_ERROR, "Unable to grab monitor lock\n");
981                         return NULL;
982                 }
983                 /* Lock the interface list */
984                 if (ast_mutex_lock(&iflock)) {
985                         ast_log(LOG_ERROR, "Unable to grab interface lock\n");
986                         ast_mutex_unlock(&monlock);
987                         return NULL;
988                 }
989                 /* Build the stuff we're going to select on, that is the socket of every
990                    phone_pvt that does not have an associated owner channel */
991                 n = -1;
992                 FD_ZERO(&rfds);
993                 FD_ZERO(&efds);
994                 i = iflist;
995                 dotone = 0;
996                 while(i) {
997                         if (FD_ISSET(i->fd, &rfds)) 
998                                 ast_log(LOG_WARNING, "Descriptor %d appears twice (%s)?\n", i->fd, i->dev);
999                         if (!i->owner) {
1000                                 /* This needs to be watched, as it lacks an owner */
1001                                 FD_SET(i->fd, &rfds);
1002                                 FD_SET(i->fd, &efds);
1003                                 if (i->fd > n)
1004                                         n = i->fd;
1005                                 if (i->dialtone) {
1006                                         /* Remember we're going to have to come back and play
1007                                            more dialtones */
1008                                         if (ast_tvzero(tv)) {
1009                                                 /* If we're due for a dialtone, play one */
1010                                                 if (write(i->fd, DialTone + tonepos, 240) != 240)
1011                                                         ast_log(LOG_WARNING, "Dial tone write error\n");
1012                                         }
1013                                         dotone++;
1014                                 }
1015                         }
1016                         
1017                         i = i->next;
1018                 }
1019                 /* Okay, now that we know what to do, release the interface lock */
1020                 ast_mutex_unlock(&iflock);
1021
1022                 /* And from now on, we're okay to be killed, so release the monitor lock as well */
1023                 ast_mutex_unlock(&monlock);
1024
1025                 /* Wait indefinitely for something to happen */
1026                 if (dotone) {
1027                         /* If we're ready to recycle the time, set it to 30 ms */
1028                         tonepos += 240;
1029                         if (tonepos >= sizeof(DialTone))
1030                                         tonepos = 0;
1031                         if (ast_tvzero(tv)) {
1032                                 tv = ast_tv(30000, 0);
1033                         }
1034                         res = ast_select(n + 1, &rfds, NULL, &efds, &tv);
1035                 } else {
1036                         res = ast_select(n + 1, &rfds, NULL, &efds, NULL);
1037                         tv = ast_tv(0,0);
1038                         tonepos = 0;
1039                 }
1040                 /* Okay, select has finished.  Let's see what happened.  */
1041                 if (res < 0) {
1042                         ast_log(LOG_WARNING, "select return %d: %s\n", res, strerror(errno));
1043                         continue;
1044                 }
1045                 /* If there are no fd's changed, just continue, it's probably time
1046                    to play some more dialtones */
1047                 if (!res)
1048                         continue;
1049                 /* Alright, lock the interface list again, and let's look and see what has
1050                    happened */
1051                 if (ast_mutex_lock(&iflock)) {
1052                         ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1053                         continue;
1054                 }
1055
1056                 i = iflist;
1057                 for(; i; i=i->next) {
1058                         if (FD_ISSET(i->fd, &rfds)) {
1059                                 if (i->owner) {
1060                                         continue;
1061                                 }
1062                                 phone_mini_packet(i);
1063                         }
1064                         if (FD_ISSET(i->fd, &efds)) {
1065                                 if (i->owner) {
1066                                         continue;
1067                                 }
1068                                 phone_check_exception(i);
1069                         }
1070                 }
1071                 ast_mutex_unlock(&iflock);
1072         }
1073         /* Never reached */
1074         return NULL;
1075         
1076 }
1077
1078 static int restart_monitor()
1079 {
1080         /* If we're supposed to be stopped -- stay stopped */
1081         if (monitor_thread == AST_PTHREADT_STOP)
1082                 return 0;
1083         if (ast_mutex_lock(&monlock)) {
1084                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1085                 return -1;
1086         }
1087         if (monitor_thread == pthread_self()) {
1088                 ast_mutex_unlock(&monlock);
1089                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1090                 return -1;
1091         }
1092         if (monitor_thread != AST_PTHREADT_NULL) {
1093                 if (ast_mutex_lock(&iflock)) {
1094                   ast_mutex_unlock(&monlock);
1095                   ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1096                   return -1;
1097                 }
1098                 pthread_cancel(monitor_thread);
1099 #if 0
1100                 pthread_join(monitor_thread, NULL);
1101 #endif
1102                 ast_mutex_unlock(&iflock);
1103         }
1104         /* Start a new monitor */
1105         if (ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1106                 ast_mutex_unlock(&monlock);
1107                 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1108                 return -1;
1109         }
1110         ast_mutex_unlock(&monlock);
1111         return 0;
1112 }
1113
1114 static struct phone_pvt *mkif(char *iface, int mode, int txgain, int rxgain)
1115 {
1116         /* Make a phone_pvt structure for this interface */
1117         struct phone_pvt *tmp;
1118         int flags;      
1119         
1120         tmp = malloc(sizeof(struct phone_pvt));
1121         if (tmp) {
1122                 tmp->fd = open(iface, O_RDWR);
1123                 if (tmp->fd < 0) {
1124                         ast_log(LOG_WARNING, "Unable to open '%s'\n", iface);
1125                         free(tmp);
1126                         return NULL;
1127                 }
1128                 if (mode == MODE_FXO) {
1129                         if (ioctl(tmp->fd, IXJCTL_PORT, PORT_PSTN)) 
1130                                 ast_log(LOG_DEBUG, "Unable to set port to PSTN\n");
1131                 } else {
1132                         if (ioctl(tmp->fd, IXJCTL_PORT, PORT_POTS)) 
1133                                  if (mode != MODE_FXS)
1134                                       ast_log(LOG_DEBUG, "Unable to set port to POTS\n");
1135                 }
1136                 ioctl(tmp->fd, PHONE_PLAY_STOP);
1137                 ioctl(tmp->fd, PHONE_REC_STOP);
1138                 ioctl(tmp->fd, PHONE_RING_STOP);
1139                 ioctl(tmp->fd, PHONE_CPT_STOP);
1140                 if (ioctl(tmp->fd, PHONE_PSTN_SET_STATE, PSTN_ON_HOOK)) 
1141                         ast_log(LOG_DEBUG, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n",iface, strerror(errno));
1142                 if (echocancel != AEC_OFF)
1143                         ioctl(tmp->fd, IXJCTL_AEC_START, echocancel);
1144                 if (silencesupression) 
1145                         tmp->silencesupression = 1;
1146 #ifdef PHONE_VAD
1147                 ioctl(tmp->fd, PHONE_VAD, tmp->silencesupression);
1148 #endif
1149                 tmp->mode = mode;
1150                 flags = fcntl(tmp->fd, F_GETFL);
1151                 fcntl(tmp->fd, F_SETFL, flags | O_NONBLOCK);
1152                 tmp->owner = NULL;
1153                 tmp->lastformat = -1;
1154                 tmp->lastinput = -1;
1155                 tmp->ministate = 0;
1156                 memset(tmp->ext, 0, sizeof(tmp->ext));
1157                 strncpy(tmp->language, language, sizeof(tmp->language)-1);
1158                 strncpy(tmp->dev, iface, sizeof(tmp->dev)-1);
1159                 strncpy(tmp->context, context, sizeof(tmp->context)-1);
1160                 tmp->next = NULL;
1161                 tmp->obuflen = 0;
1162                 tmp->dialtone = 0;
1163                 tmp->cpt = 0;
1164                 strncpy(tmp->cid_num, cid_num, sizeof(tmp->cid_num)-1);
1165                 strncpy(tmp->cid_name, cid_name, sizeof(tmp->cid_name)-1);
1166                 tmp->txgain = txgain;
1167                 ioctl(tmp->fd, PHONE_PLAY_VOLUME, tmp->txgain);
1168                 tmp->rxgain = rxgain;
1169                 ioctl(tmp->fd, PHONE_REC_VOLUME, tmp->rxgain);
1170         }
1171         return tmp;
1172 }
1173
1174 static struct ast_channel *phone_request(const char *type, int format, void *data, int *cause)
1175 {
1176         int oldformat;
1177         struct phone_pvt *p;
1178         struct ast_channel *tmp = NULL;
1179         char *name = data;
1180
1181         /* Search for an unowned channel */
1182         if (ast_mutex_lock(&iflock)) {
1183                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
1184                 return NULL;
1185         }
1186         p = iflist;
1187         while(p) {
1188                 if (p->mode == MODE_FXS ||
1189                     format & (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW)) {
1190                     size_t length = strlen(p->dev + 5);
1191                 if (strncmp(name, p->dev + 5, length) == 0 &&
1192                     !isalnum(name[length])) {
1193                     if (!p->owner) {
1194                      tmp = phone_new(p, AST_STATE_DOWN, p->context);
1195                      break;
1196                 } else
1197                      *cause = AST_CAUSE_BUSY;
1198             }
1199                 }
1200                 p = p->next;
1201         }
1202         ast_mutex_unlock(&iflock);
1203         restart_monitor();
1204         if (tmp == NULL) {
1205                 oldformat = format;
1206                 format &= (AST_FORMAT_G723_1 | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW);
1207                 if (!format) {
1208                         ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
1209                         return NULL;
1210                 }
1211         }
1212         return tmp;
1213 }
1214
1215 /* parse gain value from config file */
1216 static int parse_gain_value(char *gain_type, char *value)
1217 {
1218         float gain;
1219
1220         /* try to scan number */
1221         if (sscanf(value, "%f", &gain) != 1)
1222         {
1223                 ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n",
1224                         value, gain_type, config);
1225                 return DEFAULT_GAIN;
1226         }
1227
1228         /* multiplicate gain by 1.0 gain value */ 
1229         gain = gain * (float)DEFAULT_GAIN;
1230
1231         /* percentage? */
1232         if (value[strlen(value) - 1] == '%')
1233                 return (int)(gain / (float)100);
1234
1235         return (int)gain;
1236 }
1237
1238 static int __unload_module(void)
1239 {
1240         struct phone_pvt *p, *pl;
1241         /* First, take us out of the channel loop */
1242         ast_channel_unregister(cur_tech);
1243         if (!ast_mutex_lock(&iflock)) {
1244                 /* Hangup all interfaces if they have an owner */
1245                 p = iflist;
1246                 while(p) {
1247                         if (p->owner)
1248                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1249                         p = p->next;
1250                 }
1251                 iflist = NULL;
1252                 ast_mutex_unlock(&iflock);
1253         } else {
1254                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1255                 return -1;
1256         }
1257         if (!ast_mutex_lock(&monlock)) {
1258                 if (monitor_thread > AST_PTHREADT_NULL) {
1259                         pthread_cancel(monitor_thread);
1260                         pthread_join(monitor_thread, NULL);
1261                 }
1262                 monitor_thread = AST_PTHREADT_STOP;
1263                 ast_mutex_unlock(&monlock);
1264         } else {
1265                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1266                 return -1;
1267         }
1268
1269         if (!ast_mutex_lock(&iflock)) {
1270                 /* Destroy all the interfaces and free their memory */
1271                 p = iflist;
1272                 while(p) {
1273                         /* Close the socket, assuming it's real */
1274                         if (p->fd > -1)
1275                                 close(p->fd);
1276                         pl = p;
1277                         p = p->next;
1278                         /* Free associated memory */
1279                         free(pl);
1280                 }
1281                 iflist = NULL;
1282                 ast_mutex_unlock(&iflock);
1283         } else {
1284                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1285                 return -1;
1286         }
1287                 
1288         return 0;
1289 }
1290
1291 int unload_module(void)
1292 {
1293         return __unload_module();
1294 }
1295
1296 int load_module()
1297 {
1298         struct ast_config *cfg;
1299         struct ast_variable *v;
1300         struct phone_pvt *tmp;
1301         int mode = MODE_IMMEDIATE;
1302         int txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN; /* default gain 1.0 */
1303         cfg = ast_config_load(config);
1304
1305         /* We *must* have a config file otherwise stop immediately */
1306         if (!cfg) {
1307                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
1308                 return -1;
1309         }
1310         if (ast_mutex_lock(&iflock)) {
1311                 /* It's a little silly to lock it, but we mind as well just to be sure */
1312                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
1313                 return -1;
1314         }
1315         v = ast_variable_browse(cfg, "interfaces");
1316         while(v) {
1317                 /* Create the interface list */
1318                 if (!strcasecmp(v->name, "device")) {
1319                                 tmp = mkif(v->value, mode, txgain, rxgain);
1320                                 if (tmp) {
1321                                         tmp->next = iflist;
1322                                         iflist = tmp;
1323                                         
1324                                 } else {
1325                                         ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
1326                                         ast_config_destroy(cfg);
1327                                         ast_mutex_unlock(&iflock);
1328                                         __unload_module();
1329                                         return -1;
1330                                 }
1331                 } else if (!strcasecmp(v->name, "silencesupression")) {
1332                         silencesupression = ast_true(v->value);
1333                 } else if (!strcasecmp(v->name, "language")) {
1334                         strncpy(language, v->value, sizeof(language)-1);
1335                 } else if (!strcasecmp(v->name, "callerid")) {
1336                         ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
1337                 } else if (!strcasecmp(v->name, "mode")) {
1338                         if (!strncasecmp(v->value, "di", 2)) 
1339                                 mode = MODE_DIALTONE;
1340                         else if (!strncasecmp(v->value, "im", 2))
1341                                 mode = MODE_IMMEDIATE;
1342                         else if (!strncasecmp(v->value, "fxs", 3)) {
1343                                 mode = MODE_FXS;
1344                                 prefformat = 0x01ff0000; /* All non-voice */
1345                         }
1346                         else if (!strncasecmp(v->value, "fx", 2))
1347                                 mode = MODE_FXO;
1348                         else
1349                                 ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
1350                 } else if (!strcasecmp(v->name, "context")) {
1351                         strncpy(context, v->value, sizeof(context)-1);
1352                 } else if (!strcasecmp(v->name, "format")) {
1353                         if (!strcasecmp(v->value, "g723.1")) {
1354                                 prefformat = AST_FORMAT_G723_1;
1355                         } else if (!strcasecmp(v->value, "slinear")) {
1356                                 if (mode == MODE_FXS)
1357                                     prefformat |= AST_FORMAT_SLINEAR;
1358                                 else prefformat = AST_FORMAT_SLINEAR;
1359                         } else if (!strcasecmp(v->value, "ulaw")) {
1360                                 prefformat = AST_FORMAT_ULAW;
1361                         } else
1362                                 ast_log(LOG_WARNING, "Unknown format '%s'\n", v->value);
1363                 } else if (!strcasecmp(v->name, "echocancel")) {
1364                         if (!strcasecmp(v->value, "off")) {
1365                                 echocancel = AEC_OFF;
1366                         } else if (!strcasecmp(v->value, "low")) {
1367                                 echocancel = AEC_LOW;
1368                         } else if (!strcasecmp(v->value, "medium")) {
1369                                 echocancel = AEC_MED;
1370                         } else if (!strcasecmp(v->value, "high")) {
1371                                 echocancel = AEC_HIGH;
1372                         } else 
1373                                 ast_log(LOG_WARNING, "Unknown echo cancellation '%s'\n", v->value);
1374                 } else if (!strcasecmp(v->name, "txgain")) {
1375                         txgain = parse_gain_value(v->name, v->value);
1376                 } else if (!strcasecmp(v->name, "rxgain")) {
1377                         rxgain = parse_gain_value(v->name, v->value);
1378                 }       
1379                 v = v->next;
1380         }
1381         ast_mutex_unlock(&iflock);
1382
1383         if (mode == MODE_FXS) {
1384                 phone_tech_fxs.capabilities = prefformat;
1385                 cur_tech = &phone_tech_fxs;
1386         } else
1387                 cur_tech = (struct ast_channel_tech *) &phone_tech;
1388
1389         /* Make sure we can register our Adtranphone channel type */
1390
1391         if (ast_channel_register(cur_tech)) {
1392                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1393                 ast_config_destroy(cfg);
1394                 __unload_module();
1395                 return -1;
1396         }
1397         ast_config_destroy(cfg);
1398         /* And start the monitor for the first time */
1399         restart_monitor();
1400         return 0;
1401 }
1402
1403 int usecount()
1404 {
1405         return usecnt;
1406 }
1407
1408 char *description()
1409 {
1410         return (char *) desc;
1411 }
1412
1413 char *key()
1414 {
1415         return ASTERISK_GPL_KEY;
1416 }