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