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