Make chan_vpb.c detect austel busy (bug 545)
[asterisk/asterisk.git] / channels / chan_vpb.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * VoiceTronix Interface driver
5  * 
6  * Copyright (C) 2003, Paul Bagyenda
7  *
8  * Paul Bagyenda <bagyenda@dsmagic.com>
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/lock.h>
18 #include <asterisk/channel.h>
19 #include <asterisk/channel_pvt.h>
20 #include <asterisk/config.h>
21 #include <asterisk/logger.h>
22 #include <asterisk/module.h>
23 #include <asterisk/pbx.h>
24 #include <asterisk/options.h>
25 #include <sys/socket.h>
26 #include <sys/time.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <arpa/inet.h>
31 #include <fcntl.h>
32 #include <sys/ioctl.h>
33
34 #include <vpbapi.h>
35
36
37 #define DEFAULT_GAIN 1.0
38 #define VPB_SAMPLES 240 
39 #define VPB_MAX_BUF VPB_SAMPLES*4 + AST_FRIENDLY_OFFSET
40
41 #define VPB_NULL_EVENT 200
42
43 #define VPB_DIALTONE_WAIT 2000
44 #define VPB_RINGWAIT 2000
45 #define VPB_WAIT_TIMEOUT 40
46
47 #if defined(__cplusplus) || defined(c_plusplus)
48  extern "C" {
49 #endif
50
51 static char *desc = "VoiceTronix V6PCI/V12PCI  API Support";
52 static char *type = "vpb";
53 static char *tdesc = "Standard VoiceTronix API Driver";
54 static char *config = "vpb.conf";
55
56 /* Default context for dialtone mode */
57 static char context[AST_MAX_EXTENSION] = "default";
58
59 /* Default language */
60 static char language[MAX_LANGUAGE] = "";
61 static int usecnt =0;
62
63 static int echocancel = 1; 
64 static int setrxgain = 0, settxgain = 0;
65
66 static int tcounter  = 0;
67
68 static int gruntdetect_timeout = 5000; /* Grunt detect timeout is 5 seconds. */
69
70 static int silencesupression = 0;
71
72 static const int prefformat = AST_FORMAT_ALAW | AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ADPCM;
73
74 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
75
76 /* Protect the interface list (of vpb_pvt's) */
77 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
78
79 /* Protect the monitoring thread, so only one process can kill or start it, and not
80    when it's doing something critical. */
81 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
82
83 /* This is the thread for the monitor which checks for input on the channels
84    which are not currently in use.  */
85 static pthread_t monitor_thread;
86
87 static int mthreadactive = -1; /* Flag for monitoring monitorthread.*/
88
89
90 static int restart_monitor(void);
91
92 /* The private structures of the VPB channels are linked for
93    selecting outgoing channels */
94    
95 #define MODE_DIALTONE   1
96 #define MODE_IMMEDIATE  2
97 #define MODE_FXO        3
98
99
100 static VPB_TONE Dialtone     = {440, 440, 440, 0,  0, 0, 5000, 0   };
101 static VPB_TONE Busytone     = {440,   0,   0, 0,  -100, -100,   500, 500};
102 static VPB_TONE Ringbacktone = {440,   0,   0, 0,  -100, -100,  100, 100};
103
104
105 #define VPB_MAX_BRIDGES 128 
106 static struct vpb_bridge_t {
107      int inuse;
108      struct ast_channel *c0, *c1, **rc;
109      struct ast_frame **fo;
110      int flags;
111      
112      ast_mutex_t lock;
113      pthread_cond_t cond;
114 } bridges[VPB_MAX_BRIDGES]; /* Bridges...*/
115
116 static ast_mutex_t bridge_lock = AST_MUTEX_INITIALIZER;
117
118 static struct vpb_pvt {
119
120      struct ast_channel *owner;         /* Channel we belong to, possibly NULL */
121      int mode;                                          /* Is this in the  */
122      int handle;  /* Handle for vpb interface */
123
124      char dev[256];
125
126      struct ast_frame f, fr;
127      char buf[VPB_MAX_BUF];                     /* Static buffer for reading frames */
128      char obuf[VPB_MAX_BUF];
129      
130      int dialtone;
131      float txgain, rxgain;             /* gain control for playing, recording  */
132      
133      int wantdtmf; /* Waiting for DTMF. */
134      int silencesupression;
135      char context[AST_MAX_EXTENSION];
136
137      char ext[AST_MAX_EXTENSION];
138      char language[MAX_LANGUAGE];
139      char callerid[AST_MAX_EXTENSION];
140
141      int lastinput;
142      int lastoutput;
143
144      struct vpb_bridge_t *bridge;
145      void *timer; /* For call timeout. */
146      int calling;
147     
148      int lastgrunt;
149
150      ast_mutex_t lock;
151
152     int stopreads; /* Stop reading...*/
153      pthread_t readthread;    /* For monitoring read channel. One per owned channel. */
154
155      struct vpb_pvt *next;                      /* Next channel in list */
156 } *iflist = NULL;
157
158 static char callerid[AST_MAX_EXTENSION];
159
160 static int vpb_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
161 {
162      struct vpb_pvt *p0 = (struct vpb_pvt *)c0->pvt->pvt;
163      struct vpb_pvt *p1 = (struct vpb_pvt *)c1->pvt->pvt;
164      int i, len = sizeof bridges/sizeof bridges[0], res;
165      
166      /* Bridge channels, check if we can.  I believe we always can, so find a slot.*/
167      
168      ast_mutex_lock(&bridge_lock); {
169           for (i = 0; i < len; i++) 
170                if (!bridges[i].inuse)
171                     break;
172           if (i < len) {
173                bridges[i].inuse = 1;
174                bridges[i].flags = flags;
175                bridges[i].rc = rc;
176                bridges[i].fo = fo;
177                bridges[i].c0 = c0;
178                bridges[i].c1 = c1;
179                ast_mutex_init(&bridges[i].lock);
180                pthread_cond_init(&bridges[i].cond, NULL);
181           }            
182      } ast_mutex_unlock(&bridge_lock); 
183
184      if (i == len) {
185           ast_log(LOG_WARNING, "Failed to bridge %s and %s!\n", c0->name, c1->name);
186           return -2;
187      } else {
188
189           /* Set bridge pointers. You don't want to take these locks while holding bridge lock.*/
190           ast_mutex_lock(&p0->lock); {
191                p0->bridge = &bridges[i];
192           } ast_mutex_unlock(&p0->lock);
193
194           ast_mutex_lock(&p1->lock); {
195                p1->bridge = &bridges[i];
196           } ast_mutex_unlock(&p1->lock);
197
198           if (option_verbose > 4) 
199                ast_verbose(VERBOSE_PREFIX_3 
200                            " Bridging call entered with [%s, %s]\n", c0->name, c1->name);
201      }
202      res = vpb_bridge(p0->handle, p1->handle, VPB_BRIDGE_ON, 0);
203
204      if (res != VPB_OK) 
205           goto done;
206
207      res = pthread_cond_wait(&bridges[i].cond, &bridges[i].lock); /* Wait for condition signal. */
208      
209      
210  done: /* Out of wait. */
211
212      vpb_bridge(p0->handle, p1->handle, VPB_BRIDGE_OFF, 0); 
213
214      
215      ast_mutex_lock(&bridge_lock); {
216           bridges[i].inuse = 0;
217           ast_mutex_destroy(&bridges[i].lock);
218           pthread_cond_destroy(&bridges[i].cond);       
219      } ast_mutex_unlock(&bridge_lock); 
220      
221      ast_mutex_lock(&p0->lock); {
222           p0->bridge = NULL;
223      } ast_mutex_unlock(&p0->lock);
224      
225      ast_mutex_lock(&p1->lock); {
226           p1->bridge = NULL;
227      } ast_mutex_unlock(&p1->lock);
228
229      
230      if (option_verbose > 4) 
231           ast_verbose(VERBOSE_PREFIX_3 
232                       " Bridging call done with [%s, %s] => %d\n", c0->name, c1->name, res);
233     
234      if (res != 0 && res != VPB_OK) /* Don't assume VPB_OK is zero! */
235           return -1;
236      else 
237           return 0;
238 }
239
240 static inline int monitor_handle_owned(struct vpb_pvt *p, VPB_EVENT *e)
241 {
242      struct ast_frame f = {AST_FRAME_CONTROL}; /* default is control, Clear rest. */
243      int endbridge = 0;
244
245      if (option_verbose > 4) 
246           ast_verbose(VERBOSE_PREFIX_3 " %s handle_owned got event: [%d=>%d]\n",
247                       p->dev, e->type, e->data);
248      
249      f.src = type;
250      switch (e->type) {
251      case VPB_RING:
252           if (p->mode == MODE_FXO) 
253                f.subclass = AST_CONTROL_RING;
254           else
255                f.frametype = -1; /* ignore ring on station port. */
256           break;
257      case VPB_TIMEREXP:
258           if (p->calling) { /* This means time to stop calling. */
259                f.subclass = AST_CONTROL_BUSY;
260                vpb_timer_close(p->timer);
261           } else
262                f.frametype = -1; /* Ignore. */
263           break;
264      case VPB_DTMF:
265           if (p->owner->_state == AST_STATE_UP) {
266                f.frametype = AST_FRAME_DTMF;
267                f.subclass = e->data;
268           } else
269                f.frametype = -1;
270           break;
271
272      case VPB_TONEDETECT:
273           if (e->data == VPB_BUSY || e->data == VPB_BUSY_308 || e->data == VPB_BUSY_AUST)
274                f.subclass = AST_CONTROL_BUSY;
275           else if (e->data == VPB_GRUNT) {
276                p->lastgrunt = tcounter;
277                f.frametype = -1;
278           } else
279                f.frametype = -1;
280           break;
281
282      case VPB_CALLEND:
283           if (e->data == VPB_CALL_CONNECTED)
284                f.subclass = AST_CONTROL_ANSWER;
285           else if (e->data == VPB_CALL_NO_DIAL_TONE ||
286                    e->data == VPB_CALL_NO_RING_BACK)
287                f.subclass =  AST_CONTROL_CONGESTION;
288           else if (e->data == VPB_CALL_NO_ANSWER ||
289                    e->data == VPB_CALL_BUSY)
290                f.subclass = AST_CONTROL_BUSY;
291           else if (e->data  == VPB_CALL_DISCONNECTED) 
292                f.subclass = AST_CONTROL_HANGUP;
293           break;
294
295      case VPB_STATION_OFFHOOK:
296            f.subclass = AST_CONTROL_ANSWER;
297           break;
298           
299      case VPB_STATION_ONHOOK:
300           f.subclass = AST_CONTROL_HANGUP;
301           break;
302           
303      case VPB_STATION_FLASH:
304           f.subclass = AST_CONTROL_FLASH;
305           break;
306         
307      case VPB_DIALEND:
308           f.subclass = AST_CONTROL_ANSWER;
309           break;
310           
311      default:
312           f.frametype = -1;
313           break;
314      }
315
316      if (option_verbose > 4) 
317           ast_verbose(VERBOSE_PREFIX_3 " handle_owned: putting frame: [%d=>%d], bridge=%p\n",
318                       f.frametype, f.subclass, (void *)p->bridge);
319
320      ast_mutex_lock(&p->lock); {
321           if (p->bridge) { /* Check what happened, see if we need to report it. */
322                switch (f.frametype) { 
323                case AST_FRAME_DTMF:
324                     if (!(p->bridge->c0 == p->owner && 
325                           (p->bridge->flags & AST_BRIDGE_DTMF_CHANNEL_0) ) &&
326                         !(p->bridge->c1 == p->owner && 
327                           (p->bridge->flags & AST_BRIDGE_DTMF_CHANNEL_1) )) 
328                          /* Kill bridge, this is interesting. */
329                          endbridge = 1;
330                     break;
331                     
332                case AST_FRAME_CONTROL:
333                     if (!(p->bridge->flags & AST_BRIDGE_IGNORE_SIGS)) 
334 #if 0
335                          if (f.subclass == AST_CONTROL_BUSY ||
336                              f.subclass == AST_CONTROL_CONGESTION ||
337                              f.subclass == AST_CONTROL_HANGUP ||
338                              f.subclass == AST_CONTROL_FLASH)
339 #endif
340                               endbridge = 1;
341                     break;
342                default:
343                     
344                     break;
345                }
346                if (endbridge) {
347                     if (p->bridge->fo)
348                          *p->bridge->fo = ast_frisolate(&f);
349                     if (p->bridge->rc)
350                          *p->bridge->rc = p->owner;
351                     
352                     ast_mutex_lock(&p->bridge->lock); {
353                          pthread_cond_signal(&p->bridge->cond);
354                     } ast_mutex_unlock(&p->bridge->lock);                          
355                }          
356           }
357      } ast_mutex_unlock(&p->lock);
358      
359      if (endbridge) return 0;
360      
361      if (f.frametype >= 0 && f.frametype != AST_FRAME_NULL) 
362           ast_queue_frame(p->owner, &f, 0);
363      return 0;
364 }
365
366 static struct ast_channel *vpb_new(struct vpb_pvt *i, int state, char *context);
367
368 static inline int monitor_handle_notowned(struct vpb_pvt *p, VPB_EVENT *e)
369 {
370      char s[2] = {0};
371
372      if (option_verbose > 4) 
373           ast_verbose(VERBOSE_PREFIX_3 " %s: In not owned, mode=%d, [%d=>%d]\n",
374                       p->dev, p->mode, e->type, e->data);
375           
376      switch(e->type) {
377      case VPB_RING:
378           if (p->mode == MODE_FXO) /* FXO port ring, start * */
379                vpb_new(p, AST_STATE_RING, p->context);
380           break;
381      case VPB_STATION_OFFHOOK:
382           if (p->mode == MODE_IMMEDIATE) 
383                vpb_new(p,AST_STATE_RING, p->context);
384           else {
385                vpb_playtone_async(p->handle, &Dialtone);
386                p->wantdtmf = 1;
387                p->ext[0] = 0; /* Just to be sure & paranoid.*/
388           }
389           break;
390
391      case VPB_STATION_ONHOOK: /*, clear ext */
392            while (vpb_playtone_state(p->handle) != 0){
393                  vpb_tone_terminate(p->handle);
394                  vpb_sleep(10);
395              }
396           p->wantdtmf = 1;
397           p->ext[0] = 0;
398           break;
399
400      case VPB_DTMF:
401           if (p->wantdtmf == 1) {
402            while (vpb_playtone_state(p->handle) != 0){
403                  vpb_tone_terminate(p->handle);
404                  vpb_sleep(10);
405              }
406
407                p->wantdtmf = 0;
408           }
409           s[0] = e->data;
410           strcat(p->ext, s);
411           
412           if (ast_exists_extension(NULL, p->context, p->ext, 1, p->callerid)) 
413                vpb_new(p,AST_STATE_RING, p->context);
414           else if (!ast_canmatch_extension(NULL, p->context, p->ext, 1, p->callerid)) 
415                if (ast_exists_extension(NULL, "default", p->ext, 1, p->callerid)) 
416                     vpb_new(p,AST_STATE_RING, "default");             
417                else if (!ast_canmatch_extension(NULL, "default", p->ext, 1, p->callerid)) {
418                     if (option_debug)
419                          ast_log(LOG_DEBUG, 
420                                  "%s can't match anything in %s or default\n", 
421                                  p->ext, p->context);
422                     vpb_playtone_async(p->handle, &Busytone);
423                }
424           
425           break;
426           
427      default:
428           /* Ignore.*/
429           break;
430      }
431      
432      if (option_verbose > 4) 
433          ast_verbose(VERBOSE_PREFIX_3 " %s: Done not owned, mode=%d, [%d=>%d]\n",
434                       p->dev, p->mode, e->type, e->data);
435      
436      return 0;
437  }
438
439 static void *do_monitor(void *unused)
440 {
441     
442      /* Monitor thread, doesn't die until explicitly killed. */
443      
444      if (option_verbose > 4) 
445           ast_verbose(VERBOSE_PREFIX_3 "Starting vpb monitor thread[%ld]\n",
446                       pthread_self());
447      pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
448      
449      do {
450           VPB_EVENT e;
451           char str[VPB_MAX_STR];
452           
453           int res = vpb_get_event_sync(&e, VPB_WAIT_TIMEOUT);
454
455           if (res != VPB_OK)
456                goto end_loop;
457           
458           str[0] = 0;
459           ast_mutex_lock(&monlock),
460                ast_mutex_lock(&iflock); {
461                struct vpb_pvt *p = iflist; /* Find the pvt structure */       
462                 
463                vpb_translate_event(&e, str);
464                
465                if (e.type == VPB_NULL_EVENT) 
466                     goto done; /* Nothing to do, just a wakeup call.*/
467                while (p && p->handle != e.handle)
468                     p = p->next;
469                
470                if (option_verbose > 2)
471                     ast_verbose(VERBOSE_PREFIX_3 " Event [%d=>%s] on %s\n", 
472                                 e.type, str, p ? p->dev : "null");
473                
474                if (!p) {
475                            ast_log(LOG_WARNING, 
476                                    "Got event %s, no matching iface!\n", str);    
477                            goto done;
478                } 
479                
480                
481                /* Two scenarios: Are you owned or not. */
482                
483                if (p->owner) 
484                         monitor_handle_owned(p, &e);
485                else 
486                     monitor_handle_notowned(p, &e);
487                
488                done: (void)0;
489           } ast_mutex_unlock(&iflock);
490           ast_mutex_unlock(&monlock);
491           
492      end_loop:
493           tcounter += VPB_WAIT_TIMEOUT; /* Ok, not quite but will suffice. */
494           
495      } while(1);
496      
497      
498      return NULL;
499 }
500
501 static int restart_monitor(void)
502 {
503      int error = 0;
504      
505      /* If we're supposed to be stopped -- stay stopped */
506      if (mthreadactive == -2)
507           return 0;
508      ast_mutex_lock(&monlock); {
509           if (monitor_thread == pthread_self()) {
510                ast_log(LOG_WARNING, "Cannot kill myself\n");
511                error = -1;
512                goto done;
513           }
514           if (mthreadactive != -1) {
515                /* Why do other drivers kill the thread? No need says I, simply awake thread with event. */
516                VPB_EVENT e;
517                e.handle = 0;
518                e.type = VPB_NULL_EVENT;
519                e.data = 0;
520                
521                vpb_put_event(&e);
522           } else {
523                /* Start a new monitor */
524                int pid = pthread_create(&monitor_thread, NULL, do_monitor, NULL); 
525                if (pid < 0) {
526                     ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
527                     error = -1;
528                     goto done;
529                } else
530                     mthreadactive = 0; /* Started the thread!*/
531
532 #if 0          
533                if (option_verbose > 4) 
534                     ast_verbose(VERBOSE_PREFIX_3 
535                                 "Starting vpb restast: thread[%d]\n",
536                                 pid);
537 #endif
538           }
539      done: (void)0;
540      } ast_mutex_unlock(&monlock);
541      
542      return error;
543 }
544
545 struct vpb_pvt *mkif(int board, int channel, int mode, float txgain, float rxgain)
546 {
547      struct vpb_pvt *tmp;
548
549
550      tmp = (struct vpb_pvt *)calloc(1, sizeof *tmp);
551
552      if (!tmp)
553           return NULL;
554
555      tmp->handle = vpb_open(board, channel);
556      
557      if (tmp->handle < 0) {       
558           ast_log(LOG_WARNING, "Unable to create channel vpb/%d-%d: %s\n",
559                   board, channel, strerror(errno));
560           free(tmp);
561           return NULL;
562      }
563           
564      if (echocancel) {
565           if (option_verbose > 4)
566                ast_verbose(VERBOSE_PREFIX_3 " vpb turned on echo cancel.\n");
567           vpb_echo_canc_enable();
568           vpb_echo_canc_force_adapt_on();
569           echocancel = 0; /* So we do not initialise twice! */
570      }
571      
572      if (option_verbose > 4) 
573           ast_verbose(VERBOSE_PREFIX_3 " vpb created channel: [%d:%d]\n",
574                       board, channel);
575
576      sprintf(tmp->dev, "vpb/%d-%d", board, channel);
577
578      tmp->mode = mode;
579
580      strcpy(tmp->language, language);
581      strcpy(tmp->context, context);
582      
583      strcpy(tmp->callerid, callerid);
584      tmp->txgain = txgain;
585
586      tmp->rxgain = rxgain;
587
588      tmp->lastinput = -1;
589      tmp->lastoutput = -1;
590
591      tmp->bridge = NULL;
592
593      tmp->readthread = 0;
594
595      ast_mutex_init(&tmp->lock);
596
597      if (setrxgain)      
598           vpb_record_set_gain(tmp->handle, rxgain);
599      if (settxgain)  
600           vpb_play_set_gain(tmp->handle, txgain);
601      
602      return tmp;
603 }
604
605
606 static int vpb_indicate(struct ast_channel *ast, int condition)
607 {
608     struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
609     int res = 0;
610
611     if (option_verbose > 4)
612         ast_verbose(VERBOSE_PREFIX_3 " vpb indicate on %s with %d\n",
613                     p->dev, condition);
614
615     switch(condition) {
616         case AST_CONTROL_BUSY:
617         case AST_CONTROL_CONGESTION:
618           while (vpb_playtone_state(p->handle) != 0){
619                 res = vpb_tone_terminate(p->handle);
620                 vpb_sleep(10);
621             }
622             res = vpb_playtone_async(p->handle, &Busytone);
623             break;
624         case AST_CONTROL_RINGING:
625           while (vpb_playtone_state(p->handle) != 0){
626                 res = vpb_tone_terminate(p->handle);
627                 vpb_sleep(10);
628             }
629             res = vpb_playtone_async(p->handle, &Ringbacktone);
630             break;          
631         case AST_CONTROL_ANSWER:
632         case -1: /* -1 means stop playing? */
633            while (vpb_playtone_state(p->handle) != 0){
634                  res = vpb_tone_terminate(p->handle);
635                  vpb_sleep(10);
636            }
637
638             break;
639         case AST_CONTROL_HANGUP:
640           while (vpb_playtone_state(p->handle) != 0){
641                 res = vpb_tone_terminate(p->handle);
642                 vpb_sleep(10);
643             }
644             res = vpb_playtone_async(p->handle, &Busytone);
645             break;
646             
647         default:
648             res = 0;
649             break;
650     }
651     return res;
652 }
653
654 static int vpb_fixup(struct ast_channel *oldchan, struct ast_channel *newchan, int needlock)
655 {
656         struct vpb_pvt *p = (struct vpb_pvt *)newchan->pvt->pvt;
657
658         ast_log(LOG_DEBUG, 
659                 "New owner for channel %s is %s\n", p->dev, newchan->name);
660         if (p->owner == oldchan)
661                 p->owner = newchan;
662
663         if (newchan->_state == AST_STATE_RINGING) 
664                 vpb_indicate(newchan, AST_CONTROL_RINGING);
665
666         return 0;
667 }
668
669 static int vpb_digit(struct ast_channel *ast, char digit)
670 {
671     char s[2];
672
673     s[0] = digit;
674     s[1] = '\0';
675    
676     return vpb_dial_sync(((struct vpb_pvt *)ast->pvt->pvt)->handle, s);
677 }
678
679
680 static int vpb_call(struct ast_channel *ast, char *dest, int timeout)
681 {
682     struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
683     int res = 0;
684     char *s = strrchr(dest, '/');
685
686     if (s)
687          s = s + 1;
688     else
689          s = dest;
690
691     if (ast->_state != AST_STATE_DOWN && ast->_state != AST_STATE_RESERVED) {
692         ast_log(LOG_WARNING, "vpb_call on %s neither down nor reserved!\n", 
693                 ast->name);
694         return -1;
695     }
696     if (p->mode != MODE_FXO)  /* Station port, ring it. */
697         res = vpb_ring_station_async(p->handle, VPB_RING_STATION_ON,'1');       
698      else {
699           VPB_CALL call;
700
701           vpb_get_call(p->handle, &call);
702           
703           call.dialtone_timeout = VPB_DIALTONE_WAIT;
704           call.answer_timeout = timeout;
705           call.ringback_timeout = VPB_RINGWAIT;
706
707           vpb_set_call(p->handle, &call);
708
709           if (option_verbose > 2)
710                ast_verbose(VERBOSE_PREFIX_3 " Calling %s on %s \n", 
711                            dest, ast->name); 
712
713           vpb_sethook_sync(p->handle,VPB_OFFHOOK);
714           
715           res = vpb_dial_async(p->handle, s);
716
717           if (res != VPB_OK) {
718             ast_log(LOG_DEBUG, "Call on %s to %s failed: %s\n", 
719                     ast->name, dest, vpb_strerror(res));              
720             res = -1;
721           } else 
722             res = 0;
723     }
724
725     if (option_verbose > 2)
726         ast_verbose(VERBOSE_PREFIX_3 
727                     " VPB Calling %s [t=%d] on %s returned %d\n", 
728                     dest, timeout, ast->name, res); 
729
730     if (res == 0) {
731          if (timeout) {
732               vpb_timer_open(&p->timer, p->handle, 0, 100*timeout);
733               vpb_timer_start(p->timer);
734          }
735          p->calling = 1;
736         ast_setstate(ast, AST_STATE_RINGING);
737         ast_queue_control(ast,AST_CONTROL_RINGING, 0);          
738     }
739
740     return res;
741 }
742
743 static int vpb_hangup(struct ast_channel *ast)
744 {
745     struct vpb_pvt *p;
746
747     if (option_verbose > 2) 
748         ast_verbose(VERBOSE_PREFIX_3 " hangup on vpb (%s)\n", ast->name);
749     
750     if (!ast->pvt || !ast->pvt->pvt) {
751         ast_log(LOG_WARNING, "channel (%s) not connected?\n", ast->name);
752         return 0;
753     }
754
755     p = (struct vpb_pvt *)ast->pvt->pvt;
756
757     vpb_play_terminate(p->handle);
758     vpb_record_terminate(p->handle);
759     
760     if (p->mode != MODE_FXO) { /* station port. */
761         vpb_ring_station_async(p->handle, VPB_RING_STATION_OFF,'1');    
762         vpb_playtone_async(p->handle, &Busytone);
763
764     } else
765         vpb_sethook_sync(p->handle, VPB_ONHOOK);
766
767     ast_setstate(ast,AST_STATE_DOWN);
768     
769     ast_mutex_lock(&p->lock); {    
770          p->lastinput = p->lastoutput  = -1;
771          p->ext[0]  = 0;
772          p->owner = NULL;
773          p->dialtone = 0;
774          p->calling = 0;
775          ast->pvt->pvt = NULL;   
776     } ast_mutex_unlock(&p->lock);
777          
778     ast_mutex_lock(&usecnt_lock); {
779         usecnt--;
780     } ast_mutex_unlock(&usecnt_lock);
781     ast_update_use_count();
782
783     /* Stop thread doing reads. */
784     p->stopreads = 1;
785     pthread_join(p->readthread, NULL); 
786
787     if (option_verbose > 2)
788         ast_verbose(VERBOSE_PREFIX_3 " Hungup on %s complete\n", ast->name);
789     
790     restart_monitor();
791     return 0;
792 }
793
794 static int vpb_answer(struct ast_channel *ast)
795 {
796     struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
797
798     if (p->mode == MODE_FXO)
799         vpb_sethook_sync(p->handle, VPB_OFFHOOK);
800     
801     if (option_debug)
802         ast_log(LOG_DEBUG, "vpb answer on %s\n", ast->name);
803     ast->rings = 0;
804     ast_setstate(ast, AST_STATE_UP);
805     
806     return 0;
807 }
808
809 static struct ast_frame  *vpb_read(struct ast_channel *ast)
810 {
811     struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt; 
812     static struct ast_frame f = {AST_FRAME_NULL}; 
813     
814     f.src = type;
815     ast_log(LOG_NOTICE, "vpb_read should never be called (chan=%s)!\n", p->dev);
816         
817     return &f;
818 }
819
820 static inline int ast2vpbformat(int ast_format)
821 {
822
823     switch(ast_format) {
824         case AST_FORMAT_ALAW:
825             return VPB_ALAW;
826         case AST_FORMAT_SLINEAR:
827             return VPB_LINEAR;
828         case AST_FORMAT_ULAW:
829             return VPB_MULAW;
830         case AST_FORMAT_ADPCM:
831
832             return VPB_OKIADPCM;
833         default:
834             return -1;
835     }
836 }
837
838 static inline int astformatbits(int ast_format)
839 {
840
841     switch(ast_format) {
842         case AST_FORMAT_ALAW:
843         case AST_FORMAT_ULAW:
844             return 8;
845         case AST_FORMAT_SLINEAR:
846             return 16;
847         case AST_FORMAT_ADPCM:
848             return 4;
849         default:
850             return 8;
851     }   
852 }
853
854 static int vpb_write(struct ast_channel *ast, struct ast_frame *frame)
855 {
856     struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt; 
857     int res = 0, fmt = 0;
858
859     if (frame->frametype != AST_FRAME_VOICE) {
860         ast_log(LOG_WARNING, "Don't know how to handle from type %d\n",
861                 frame->frametype);
862         return 0;
863     } else if (ast->_state != AST_STATE_UP) {
864         if (option_verbose  > 4)
865             ast_log(LOG_WARNING, "Writing frame type [%d,%d] on chan %s not up\n",
866                     frame->frametype, frame->subclass, ast->name);
867         return 0;
868         
869     }
870     
871
872     fmt = ast2vpbformat(frame->subclass);
873
874     if (option_verbose > 4)
875         ast_verbose(VERBOSE_PREFIX_3 
876                     " Write chan %s: got frame type = %d\n",
877                     p->dev, frame->subclass);
878        
879     if (fmt < 0) {
880         ast_log(LOG_WARNING, "vpb_write Cannot handle frames of %d format!\n", 
881                 frame->subclass);
882         return -1;
883     }
884     
885
886     if (p->lastoutput != fmt) {
887          vpb_play_buf_start(p->handle, fmt);
888          p->lastoutput = fmt;
889     }
890     
891     memcpy(p->obuf, frame->data, 
892            (frame->datalen > (int)sizeof p->obuf) ? sizeof p->obuf : frame->datalen);
893     res = vpb_play_buf_sync(p->handle, p->obuf, frame->datalen);
894     if (res != VPB_OK)
895          return -1;
896     else 
897          return 0;
898 }
899
900 /* Read monitor thread function. */
901 static void *do_chanreads(void *pvt)
902 {
903      struct vpb_pvt *p = (struct vpb_pvt *)pvt;
904      struct ast_frame *fr = &p->fr;
905      char *readbuf = ((char *)p->buf) + AST_FRIENDLY_OFFSET;
906      int bridgerec = 0;
907  
908      fr->frametype = AST_FRAME_VOICE;
909      fr->src = type;
910      fr->mallocd = 0;
911      
912      memset(p->buf, 0, sizeof p->buf);
913
914      while (!p->stopreads && p->owner) {         
915          int res = -1, fmt;
916          struct ast_channel *owner = p->owner;
917          int afmt = (owner) ? owner->pvt->rawreadformat : AST_FORMAT_ALAW;
918          int state = (owner) ? owner->_state : AST_STATE_DOWN;
919          int readlen;   
920          
921          fmt = ast2vpbformat(afmt);
922          
923          if (fmt < 0) {
924              p->stopreads = 1;
925              goto done;
926          }
927
928          readlen = VPB_SAMPLES * astformatbits(afmt) / 8;
929
930          if (p->lastinput != fmt) {
931              if (option_verbose > 2) 
932                  ast_verbose(" Read_channel ##  %s: Setting record mode, bridge = %d\n", 
933                              p->dev, p->bridge ? 1 : 0);             
934              vpb_record_buf_start(p->handle, fmt);
935              p->lastinput = fmt;
936          } 
937
938          ast_mutex_lock(&p->lock); {
939               if (p->bridge) 
940                    if (p->bridge->c0 == p->owner && 
941                        (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_0))
942                         bridgerec = 1;
943                    else if (p->bridge->c1 == p->owner && 
944                        (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_1))
945                         bridgerec = 1;
946                    else 
947                         bridgerec = 0;
948               else
949                    bridgerec = 1;
950          } ast_mutex_unlock(&p->lock);
951          
952          if (state == AST_STATE_UP && bridgerec) {  
953              /* Read only if up and not bridged, or a bridge for which we can read. */
954               res = vpb_record_buf_sync(p->handle, readbuf, readlen);         
955         }  else {
956               res = 0;
957               vpb_sleep(10);
958          }
959          if (res == VPB_OK) {
960               fr->subclass = afmt;
961               fr->samples = VPB_SAMPLES;
962               fr->data = readbuf;
963               fr->datalen = readlen;
964               fr->offset = AST_FRIENDLY_OFFSET;
965
966               ast_mutex_lock(&p->lock); {    
967                    if (p->owner) ast_queue_frame(p->owner, fr, 0);
968               } ast_mutex_unlock(&p->lock);
969          } else 
970               p->stopreads = 1;
971                  
972      done: (void)0;
973          if (option_verbose > 4)
974              ast_verbose(" Read_channel  %s (state=%d), res=%d, bridge=%d\n", 
975                          p->dev, state, res, bridgerec);     
976      }
977      
978      /* When stopreads seen, go away! */
979      vpb_record_buf_finish(p->handle);
980
981      if (option_verbose > 4)
982          ast_verbose(" Read_channel  %s terminating, stopreads=%d, owner=%s\n", 
983                              p->dev, p->stopreads, p->owner? "yes" : "no");     
984
985      return NULL;
986 }
987
988 static struct ast_channel *vpb_new(struct vpb_pvt *i, int state, char *context)
989 {
990         struct ast_channel *tmp; 
991
992         if (i->owner) {
993             ast_log(LOG_WARNING, "Called vpb_new on owned channel (%s) ?!\n", i->dev);
994             return NULL;
995         }
996             
997         tmp = ast_channel_alloc(1);
998         if (tmp) {
999                 strncpy(tmp->name, i->dev, sizeof(tmp->name));
1000                 tmp->type = type;
1001                
1002                 tmp->nativeformats = prefformat;
1003                 tmp->pvt->rawreadformat = AST_FORMAT_ALAW;
1004                 tmp->pvt->rawwriteformat =  AST_FORMAT_ALAW;
1005                 ast_setstate(tmp, state);
1006                 if (state == AST_STATE_RING)
1007                         tmp->rings = 1;
1008                 tmp->pvt->pvt = i;
1009                 tmp->pvt->send_digit = vpb_digit;
1010                 tmp->pvt->call = vpb_call;
1011                 tmp->pvt->hangup = vpb_hangup;
1012                 tmp->pvt->answer = vpb_answer;
1013                 tmp->pvt->read = vpb_read;
1014                 tmp->pvt->write = vpb_write;
1015                 tmp->pvt->bridge = vpb_bridge;
1016                 tmp->pvt->indicate = vpb_indicate;
1017                 tmp->pvt->fixup = vpb_fixup;
1018                 
1019                 strncpy(tmp->context, context, sizeof(tmp->context)-1);
1020                 if (strlen(i->ext))
1021                         strncpy(tmp->exten, i->ext, sizeof(tmp->exten)-1);
1022                 else
1023                         strncpy(tmp->exten, "s",  sizeof(tmp->exten) - 1);
1024                 if (strlen(i->language))
1025                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1026                 if (strlen(i->callerid))
1027                         tmp->callerid = strdup(i->callerid);
1028                 i->owner = tmp;
1029
1030                 
1031                 i->lastinput = i->lastoutput = -1;
1032                 i->lastgrunt  = tcounter; /* Assume at least one grunt tone seen now. */
1033
1034                 ast_mutex_lock(&usecnt_lock);
1035                 usecnt++;
1036                 ast_mutex_unlock(&usecnt_lock);
1037                 ast_update_use_count();
1038                 if (state != AST_STATE_DOWN) 
1039                      if (ast_pbx_start(tmp)) {
1040                           ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1041                           ast_hangup(tmp);
1042                      }
1043
1044                 i->stopreads = 0; /* So read thread runs. */    
1045                 /* Finally start read monitoring thread. */
1046                 pthread_create(&i->readthread, NULL, do_chanreads, (void *)i);
1047         } else
1048                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1049         return tmp;
1050 }
1051
1052 static struct ast_channel *vpb_request(char *type, int format, void *data) 
1053 {
1054      int oldformat;
1055      struct vpb_pvt *p;
1056      struct ast_channel *tmp = NULL;
1057      char *name = strdup(data ? (char *)data : "");
1058      char *s, *sepstr;
1059      
1060      oldformat = format;
1061      format &= prefformat;
1062      if (!format) {
1063           ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
1064           return NULL;
1065      }
1066      
1067      sepstr = name;
1068      s = strsep(&sepstr, "/"); /* Handle / issues */
1069      if (!s) 
1070           s = "";
1071      /* Search for an unowned channel */
1072      ast_mutex_lock(&iflock); {
1073           p = iflist;
1074           while(p) {
1075                if (strncmp(s, p->dev + 4, sizeof p->dev) == 0) 
1076                     if (!p->owner) {
1077                          tmp = vpb_new(p, AST_STATE_DOWN, p->context);
1078                          break;
1079                     }
1080                p = p->next;
1081           }
1082      } ast_mutex_unlock(&iflock);
1083
1084
1085      if (option_verbose > 2) 
1086           ast_verbose(VERBOSE_PREFIX_3 " %s requested, got: [%s]\n",
1087                       name, tmp ? tmp->name : "None");
1088
1089      free(name);
1090      
1091      restart_monitor();
1092      return tmp;
1093 }
1094
1095 static float parse_gain_value(char *gain_type, char *value)
1096 {
1097         float gain;
1098
1099         /* try to scan number */
1100         if (sscanf(value, "%f", &gain) != 1)
1101         {
1102                 ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n",
1103                         value, gain_type, config);
1104                 return DEFAULT_GAIN;
1105         }
1106
1107
1108         /* percentage? */
1109         if (value[strlen(value) - 1] == '%')
1110                 return gain / (float)100;
1111
1112         return gain;
1113 }
1114
1115 static int __unload_module(void)
1116 {
1117      struct vpb_pvt *p;
1118         /* First, take us out of the channel loop */
1119         ast_channel_unregister(type);
1120
1121         ast_mutex_lock(&iflock); {
1122              /* Hangup all interfaces if they have an owner */
1123              p = iflist;
1124              while(p) {
1125                   if (p->owner)
1126                        ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1127                   p = p->next;
1128              }
1129              iflist = NULL;
1130         } ast_mutex_unlock(&iflock);
1131
1132         ast_mutex_lock(&monlock); {
1133              if (mthreadactive > -1) {
1134                   pthread_cancel(monitor_thread);
1135                   pthread_join(monitor_thread, NULL);
1136              }
1137              mthreadactive = -2;
1138         } ast_mutex_unlock(&monlock);
1139
1140         ast_mutex_lock(&iflock); {
1141                 /* Destroy all the interfaces and free their memory */
1142
1143                 while(iflist) {
1144                      p = iflist;                    
1145                      ast_mutex_destroy(&p->lock);
1146                      pthread_cancel(p->readthread);
1147                      p->readthread = 0;
1148                      
1149                      iflist = iflist->next;
1150                      
1151                      free(p);
1152                 }
1153                 iflist = NULL;
1154         } ast_mutex_unlock(&iflock);
1155         
1156         ast_mutex_lock(&bridge_lock); {
1157              memset(bridges, 0, sizeof bridges);             
1158         } ast_mutex_unlock(&bridge_lock);
1159         ast_mutex_destroy(&bridge_lock);
1160
1161         tcounter = 0;
1162         
1163         return 0;
1164 }
1165
1166 int unload_module(void)
1167 {
1168         return __unload_module();
1169 }
1170
1171 int load_module()
1172 {
1173         struct ast_config *cfg;
1174         struct ast_variable *v;
1175         struct vpb_pvt *tmp;
1176         int board = 0, group = 0;
1177         int mode = MODE_IMMEDIATE;
1178         float txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN; 
1179         
1180         int error = 0; /* Error flag */
1181
1182
1183         setrxgain = settxgain = 0;
1184
1185         cfg = ast_load(config);
1186         
1187         /* We *must* have a config file otherwise stop immediately */
1188         if (!cfg) {
1189              ast_log(LOG_ERROR, "Unable to load config %s\n", config);
1190              return -1;
1191         }  
1192         
1193         vpb_seterrormode(VPB_DEVELOPMENT);
1194         
1195         ast_mutex_lock(&iflock); {
1196              v = ast_variable_browse(cfg, "interfaces");
1197              while(v) {
1198                   /* Create the interface list */
1199                   if (strcasecmp(v->name, "board") == 0) 
1200                        board = atoi(v->value);
1201                   else  if (strcasecmp(v->name, "group") == 0)
1202                        group = atoi(v->value);
1203                   else if (strcasecmp(v->name, "channel") == 0) {
1204                        int channel = atoi(v->value);
1205                        tmp = mkif(board, channel, mode, txgain, rxgain);
1206                        if (tmp) {
1207                             tmp->next = iflist;
1208                             iflist = tmp;
1209                             
1210                        } else {
1211                             ast_log(LOG_ERROR, 
1212                                     "Unable to register channel '%s'\n", v->value);
1213                             error = -1;
1214                             goto done;
1215                             
1216                        }
1217                   } else if (strcasecmp(v->name, "silencesupression") == 0) 
1218                        silencesupression = ast_true(v->value);
1219                   else if (strcasecmp(v->name, "language") == 0) 
1220                        strncpy(language, v->value, sizeof(language)-1);
1221                   else if (strcasecmp(v->name, "callerid") == 0) 
1222                        strncpy(callerid, v->value, sizeof(callerid)-1);
1223                   else if (strcasecmp(v->name, "mode") == 0) {
1224                        if (strncasecmp(v->value, "di", 2) == 0) 
1225                             mode = MODE_DIALTONE;
1226                        else if (strncasecmp(v->value, "im", 2) == 0)
1227                             mode = MODE_IMMEDIATE;
1228                        else if (strncasecmp(v->value, "fx", 2) == 0)
1229                             mode = MODE_FXO;
1230                        else
1231                             ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
1232                   } else if (!strcasecmp(v->name, "context")) 
1233                        strncpy(context, v->value, sizeof(context)-1);
1234                   else if (!strcasecmp(v->name, "echocancel")) {
1235                        if (!strcasecmp(v->value, "off")) 
1236                             echocancel = 0;
1237                        else 
1238                             echocancel = 1;
1239                   } else if (strcasecmp(v->name, "txgain") == 0) {
1240                        settxgain = 1;
1241                        txgain = parse_gain_value(v->name, v->value);
1242                   } else if (strcasecmp(v->name, "rxgain") == 0) {
1243                        setrxgain = 1;
1244                        rxgain = parse_gain_value(v->name, v->value);
1245                   } 
1246 #if 0
1247                   else if (strcasecmp(v->name, "grunttimeout") == 0) 
1248                        gruntdetect_timeout = 1000*atoi(v->value);
1249 #endif    
1250                   v = v->next;
1251              }
1252              
1253              if (gruntdetect_timeout < 1000)
1254                   gruntdetect_timeout = 1000;
1255
1256         done: (void)0;
1257         } ast_mutex_unlock(&iflock);
1258
1259         
1260         ast_destroy(cfg);
1261         
1262         if (!error && 
1263             ast_channel_register(type, tdesc, 
1264                                 prefformat, vpb_request) != 0) {
1265              ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1266              
1267              error = -1;
1268         }
1269
1270
1271         if (error)
1272              __unload_module();
1273         else         
1274              restart_monitor(); /* And start the monitor for the first time */
1275         
1276         return error;
1277 }
1278
1279 int usecount()
1280 {
1281         int res;
1282         ast_mutex_lock(&usecnt_lock);
1283         res = usecnt;
1284         ast_mutex_unlock(&usecnt_lock);
1285         return res;
1286 }
1287
1288 char *description()
1289 {
1290         return desc;
1291 }
1292
1293 char *key()
1294 {
1295         return ASTERISK_GPL_KEY;
1296 }
1297
1298 #if defined(__cplusplus) || defined(c_plusplus)
1299  }
1300 #endif