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