389ed883ff8c272ecae3ece7b00603f95be38d8a
[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
15 #include <stdio.h>
16 #include <pthread.h>
17 #include <string.h>
18 #include <asterisk/lock.h>
19 #include <asterisk/channel.h>
20 #include <asterisk/channel_pvt.h>
21 #include <asterisk/config.h>
22 #include <asterisk/logger.h>
23 #include <asterisk/module.h>
24 #include <asterisk/pbx.h>
25 #include <asterisk/options.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <arpa/inet.h>
32 #include <fcntl.h>
33 #include <sys/ioctl.h>
34 #include <ctype.h>
35
36 #include <vpbapi.h>
37
38 #define DEFAULT_GAIN 0
39 #define DEFAULT_ECHO_CANCEL 1
40   
41 #define VPB_SAMPLES 240 
42 #define VPB_MAX_BUF VPB_SAMPLES*4 + AST_FRIENDLY_OFFSET
43
44 #define VPB_NULL_EVENT 200
45
46 #define VPB_WAIT_TIMEOUT 4000
47
48 #define MAX_VPB_GAIN 12.0
49
50 #if defined(__cplusplus) || defined(c_plusplus)
51  extern "C" {
52 #endif
53
54 static char *desc = "VoiceTronix V6PCI/V12PCI/V4PCI  API Support";
55 static char *type = "vpb";
56 static char *tdesc = "Standard VoiceTronix API Driver";
57 static char *config = "vpb.conf";
58
59 /* Default context for dialtone mode */
60 static char context[AST_MAX_EXTENSION] = "default";
61
62 /* Default language */
63 static char language[MAX_LANGUAGE] = "";
64 static int usecnt =0;
65
66 static int gruntdetect_timeout = 3600000; /* Grunt detect timeout is 1hr. */
67
68 static const int prefformat = AST_FORMAT_SLINEAR;
69
70 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
71
72 /* Protect the interface list (of vpb_pvt's) */
73 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
74
75 /* Protect the monitoring thread, so only one process can kill or start it, and not
76    when it's doing something critical. */
77 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
78
79 /* This is the thread for the monitor which checks for input on the channels
80    which are not currently in use.  */
81 static pthread_t monitor_thread;
82
83 static int mthreadactive = -1; /* Flag for monitoring monitorthread.*/
84
85
86 static int restart_monitor(void);
87
88 /* The private structures of the VPB channels are 
89    linked for selecting outgoing channels */
90    
91 #define MODE_DIALTONE   1
92 #define MODE_IMMEDIATE  2
93 #define MODE_FXO        3
94
95 /* Pick a country or add your own! */
96 #define TONES_AU
97 #ifdef TONES_AU
98 static VPB_TONE Dialtone     = {440,    440,    440,    -10,    -10,    -10,    5000,   0   };
99 static VPB_TONE Busytone     = {470,    0,      0,      -10,    -100,   -100,   5000,   0 };
100 static VPB_TONE Ringbacktone = {400,    50,     440,    -10,    -10,    -10,    1400,   800 };
101 #endif
102 /*
103 #define TONES_USA
104 #ifdef TONES_USA
105 static VPB_TONE Dialtone     = {425,   0,   0, -16,  -100, -100, 10000,    0};
106 static VPB_TONE Busytone     = {425,   0,   0, -10,  -100, -100,   500,  500};
107 static VPB_TONE Ringbacktone = {400,   425,   450, -20,  -20, -20,  1000, 1000};
108 #endif
109 */
110
111 /* grunt tone defn's */
112 static VPB_DETECT toned_grunt = { 3, VPB_GRUNT, 1, 2000, 3000, 0, 0, -40, 0, 0, 0, 40, { { VPB_DELAY, 1000, 0, 0 }, { VPB_RISING, 0, 40, 0 }, { 0, 100, 0, 0 } } };
113 static VPB_DETECT toned_ungrunt = { 2, VPB_GRUNT, 1, 2000, 1, 0, 0, -40, 0, 0, 30, 40, { { 0, 0, 0, 0 } } };
114
115 /* Use loop drop detection */
116 static int UseLoopDrop=1;
117
118 #define TIMER_PERIOD_RINGBACK 5200
119 #define TIMER_PERIOD_BUSY 700
120           
121 #define VPB_EVENTS_ALL (VPB_MRING|VPB_MDIGIT|VPB_MDTMF|VPB_MTONEDETECT|VPB_MTIMEREXP|VPB_MPLAY_UNDERFLOW \
122                         |VPB_MRECORD_OVERFLOW|VPB_MSTATION_OFFHOOK|VPB_MSTATION_ONHOOK \
123                         |VPB_MRING_OFF|VPB_MDROP|VPB_MSTATION_FLASH)
124 #define VPB_EVENTS_NODTMF (VPB_MRING|VPB_MDIGIT|VPB_MTONEDETECT|VPB_MTIMEREXP|VPB_MPLAY_UNDERFLOW \
125                         |VPB_MRECORD_OVERFLOW|VPB_MSTATION_OFFHOOK|VPB_MSTATION_ONHOOK \
126                         |VPB_MRING_OFF|VPB_MDROP|VPB_MSTATION_FLASH)
127 #define VPB_EVENTS_STAT (VPB_MRING|VPB_MDIGIT|VPB_MDTMF|VPB_MTONEDETECT|VPB_MTIMEREXP|VPB_MPLAY_UNDERFLOW \
128                         |VPB_MRECORD_OVERFLOW|VPB_MSTATION_OFFHOOK|VPB_MSTATION_ONHOOK \
129                         |VPB_MRING_OFF|VPB_MSTATION_FLASH)
130
131
132 // Dialing parameters for Australia
133 //#define DIAL_WITH_CALL_PROGRESS
134 VPB_TONE_MAP DialToneMap[] = {  { VPB_BUSY_AUST, VPB_CALL_DISCONNECT, 0 },
135                                 { VPB_DIAL, VPB_CALL_DIALTONE, 0 },
136                                 { VPB_RINGBACK_308, VPB_CALL_RINGBACK, 0 },
137                                 { VPB_BUSY_AUST, VPB_CALL_BUSY, 0 },
138                                 { VPB_GRUNT, VPB_CALL_GRUNT, 0 },
139                                 { 0, 0, 1 } };
140 #define VPB_DIALTONE_WAIT 2000 /* Wait up to 2s for a dialtone */
141 #define VPB_RINGWAIT 4000 /* Wait up to 4s for ring tone after dialing */
142 #define VPB_CONNECTED_WAIT 4000 /* If no ring tone detected for 4s then consider call connected */
143 #define TIMER_PERIOD_NOANSWER 120000 /* Let it ring for 120s before deciding theres noone there */
144
145 #define MAX_BRIDGES_V4PCI 2
146 #define MAX_BRIDGES_V12PCI 128
147
148 /* port states */
149 #define VPB_STATE_ONHOOK        0
150 #define VPB_STATE_OFFHOOK       1
151 #define VPB_STATE_DIALLING      2
152 #define VPB_STATE_JOINED        3
153 #define VPB_STATE_GETDTMF       4
154 #define VPB_STATE_PLAYDIAL      5
155 #define VPB_STATE_PLAYBUSY      6
156 #define VPB_STATE_PLAYRING      7
157
158
159 typedef struct  {
160         int inuse;
161         struct ast_channel *c0, *c1, **rc;
162         struct ast_frame **fo;
163         int flags;
164         ast_mutex_t lock;
165         pthread_cond_t cond;
166         int endbridge;
167 } vpb_bridge_t;
168 static vpb_bridge_t * bridges;
169 static int max_bridges = MAX_BRIDGES_V4PCI;
170
171 static ast_mutex_t bridge_lock = AST_MUTEX_INITIALIZER;
172
173 typedef enum {
174         vpb_model_unknown = 0, 
175         vpb_model_v4pci,
176         vpb_model_v12pci
177 } vpb_model_t;
178
179 static struct vpb_pvt {
180
181         ast_mutex_t owner_lock;                 /* Protect blocks that expect ownership to remain the same */
182         struct ast_channel *owner;              /* Channel we belong to, possibly NULL */
183
184         int mode;                               /* fxo/imediate/dialtone*/
185         int handle;                             /* Handle for vpb interface */
186
187         int state;                              /* used to keep port state (internal to driver) */
188
189         int group;                              /* Which group this port belongs to */
190
191         char dev[256];                          /* Device name, eg vpb/1-1 */
192         vpb_model_t vpb_model;                  /* card model */
193
194         struct ast_frame f, fr;                 /* Asterisk frame interface */
195         char buf[VPB_MAX_BUF];                  /* Static buffer for reading frames */
196
197         int dialtone;                           /* NOT USED */
198         float txgain, rxgain;                   /* Hardware gain control */
199         float txswgain, rxswgain;               /* Software gain control */
200
201         int wantdtmf;                           /* Waiting for DTMF. */
202         char context[AST_MAX_EXTENSION];        /* The context for this channel */
203
204         char ext[AST_MAX_EXTENSION];            /* DTMF buffer for the ext[ens] */
205         char language[MAX_LANGUAGE];            /* language being used */
206         char callerid[AST_MAX_EXTENSION];       /* CallerId used for directly connected phone */
207
208         int lastoutput;                         /* Holds the last Audio format output'ed */
209         int lastinput;                          /* Holds the last Audio format input'ed */
210         int last_ignore_dtmf;
211
212         void *busy_timer;                       /* Void pointer for busy vpb_timer */
213         int busy_timer_id;                      /* unique timer ID for busy timer */
214
215         void *ringback_timer;                   /* Void pointer for ringback vpb_timer */
216         int ringback_timer_id;                  /* unique timer ID for ringback timer */
217
218         double lastgrunt;                       /* time stamp (secs since epoc) of last grunt event */
219
220         ast_mutex_t lock;                       /* This one just protects bridge ptr below */
221         vpb_bridge_t *bridge;
222
223         int stopreads;                          /* Stop reading...*/
224
225         pthread_t readthread;                   /* For monitoring read channel. One per owned channel. */
226
227         ast_mutex_t record_lock;                /* This one prevents reentering a record_buf block */
228         ast_mutex_t play_lock;                  /* This one prevents reentering a play_buf block */
229
230         ast_mutex_t play_dtmf_lock;
231         char play_dtmf[16];
232
233         struct vpb_pvt *next;                   /* Next channel in list */
234
235 } *iflist = NULL;
236
237 static struct ast_channel *vpb_new(struct vpb_pvt *i, int state, char *context);
238 static void *do_chanreads(void *pvt);
239
240 // Can't get vpb_bridge() working on v4pci without either a horrible
241 // high pitched feedback noise or bad hiss noise depending on gain settings
242 // Get asterisk to do the bridging
243 #define BAD_V4PCI_BRIDGE
244
245 // This one enables a half duplex bridge which may be required to prevent high pitched
246 // feedback when getting asterisk to do the bridging and when using certain gain settings.
247 //#define HALF_DUPLEX_BRIDGE
248
249 static int vpb_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
250 {
251         struct vpb_pvt *p0 = (struct vpb_pvt *)c0->pvt->pvt;
252         struct vpb_pvt *p1 = (struct vpb_pvt *)c1->pvt->pvt;
253         int i, res;
254
255         #ifdef BAD_V4PCI_BRIDGE
256         if(p0->vpb_model==vpb_model_v4pci)
257                 return -2;
258         #endif
259
260         /* Bridge channels, check if we can.  I believe we always can, so find a slot.*/
261
262         ast_mutex_lock(&bridge_lock); {
263                 for (i = 0; i < max_bridges; i++) 
264                         if (!bridges[i].inuse)
265                                 break;
266                 if (i < max_bridges) {
267                         bridges[i].inuse = 1;
268                         bridges[i].endbridge = 0;
269                         bridges[i].flags = flags;
270                         bridges[i].rc = rc;
271                         bridges[i].fo = fo;
272                         bridges[i].c0 = c0;
273                         bridges[i].c1 = c1;
274                         ast_mutex_init(&bridges[i].lock);
275                         pthread_cond_init(&bridges[i].cond, NULL);
276                 }              
277         } ast_mutex_unlock(&bridge_lock); 
278
279         if (i == max_bridges) {
280                 ast_log(LOG_WARNING, "Failed to bridge %s and %s!\n", c0->name, c1->name);
281                 return -2;
282         } else {
283                 /* Set bridge pointers. You don't want to take these locks while holding bridge lock.*/
284                 ast_mutex_lock(&p0->lock); {
285                         p0->bridge = &bridges[i];
286                 } ast_mutex_unlock(&p0->lock);
287
288                 ast_mutex_lock(&p1->lock); {
289                         p1->bridge = &bridges[i];
290                 } ast_mutex_unlock(&p1->lock);
291
292                 if (option_verbose>1) 
293                         ast_verbose(VERBOSE_PREFIX_2 "Bridging call entered with [%s, %s]\n", c0->name, c1->name);
294         }
295
296         #ifdef HALF_DUPLEX_BRIDGE
297
298         if (option_verbose>1) 
299                 ast_verbose(VERBOSE_PREFIX_2 "Starting half-duplex bridge [%s, %s]\n", c0->name, c1->name);
300
301         int dir = 0;
302
303         memset(p0->buf, 0, sizeof p0->buf);
304         memset(p1->buf, 0, sizeof p1->buf);
305
306         vpb_record_buf_start(p0->handle, VPB_ALAW);
307         vpb_record_buf_start(p1->handle, VPB_ALAW);
308
309         vpb_play_buf_start(p0->handle, VPB_ALAW);
310         vpb_play_buf_start(p1->handle, VPB_ALAW);
311
312         while( !bridges[i].endbridge ) {
313                 struct vpb_pvt *from, *to;
314                 if(++dir%2) {
315                         from = p0;
316                         to = p1;
317                 } else {
318                         from = p1;
319                         to = p0;
320                 }
321                 vpb_record_buf_sync(from->handle, from->buf, VPB_SAMPLES);
322                 vpb_play_buf_sync(to->handle, from->buf, VPB_SAMPLES);
323         }
324
325         vpb_record_buf_finish(p0->handle);
326         vpb_record_buf_finish(p1->handle);
327
328         vpb_play_buf_finish(p0->handle);
329         vpb_play_buf_finish(p1->handle);
330
331         if (option_verbose>1) 
332                 ast_verbose(VERBOSE_PREFIX_2 "Finished half-duplex bridge [%s, %s]\n", c0->name, c1->name);
333
334         res = VPB_OK;
335
336         #else
337
338         res = vpb_bridge(p0->handle, p1->handle, VPB_BRIDGE_ON, i+1 /* resource 1 & 2 only for V4PCI*/ );
339         if (res == VPB_OK) {
340                 //pthread_cond_wait(&bridges[i].cond, &bridges[i].lock); /* Wait for condition signal. */
341                 while( !bridges[i].endbridge ) {};
342                 vpb_bridge(p0->handle, p1->handle, VPB_BRIDGE_OFF, i+1 /* resource 1 & 2 only for V4PCI*/ ); 
343         }
344
345         #endif
346
347         ast_mutex_lock(&bridge_lock); {
348                 bridges[i].inuse = 0;
349                 ast_mutex_destroy(&bridges[i].lock);
350                 pthread_cond_destroy(&bridges[i].cond); 
351         } ast_mutex_unlock(&bridge_lock); 
352
353         ast_mutex_lock(&p0->lock); {
354                 p0->bridge = NULL;
355         } ast_mutex_unlock(&p0->lock);
356
357         ast_mutex_lock(&p1->lock); {
358                 p1->bridge = NULL;
359         } ast_mutex_unlock(&p1->lock);
360
361
362         if (option_verbose>1) 
363                 ast_verbose(VERBOSE_PREFIX_2 "Bridging call done with [%s, %s] => %d\n", c0->name, c1->name, res);
364
365         return (res==VPB_OK)?0:-1;
366 }
367
368 static double get_time_in_ms()
369 {
370         struct timeval tv;
371         gettimeofday(&tv, NULL);
372         return ((double)tv.tv_sec*1000)+((double)tv.tv_usec/1000);
373 }
374
375 // Caller ID can be located in different positions between the rings depending on your Telco
376 // Australian (Telstra) callerid starts 700ms after 1st ring and finishes 1.5s after first ring
377 // Use ANALYSE_CID to record rings and determine location of callerid
378 //#define ANALYSE_CID
379 #define RING_SKIP 600
380 #define CID_MSECS 1700
381
382 static void get_callerid(struct vpb_pvt *p)
383 {
384         short buf[CID_MSECS*8]; // 8kHz sampling rate
385         double cid_record_time;
386         int rc;
387
388         if(strcasecmp(p->callerid, "on")) {
389                 p->owner->callerid = strdup("unknown");
390                 return;
391         }
392
393         if( ast_mutex_trylock(&p->record_lock) == 0 ) {
394
395                 char callerid[AST_MAX_EXTENSION] = ""; 
396
397                 cid_record_time = get_time_in_ms();
398                 if (option_verbose>3) 
399                         ast_verbose(VERBOSE_PREFIX_4 "CID record - start\n");
400
401                 #ifdef ANALYSE_CID
402                 VPB_RECORD record_parms = { "", 8 * 1000 }; // record a couple of rings
403                 vpb_record_set(p->handle,&record_parms);
404                 ast_verbose(VERBOSE_PREFIX_4 "Recording debug CID sample to /tmp/cid.raw\n");
405                 vpb_record_file_sync(p->handle,"/tmp/cid.raw",VPB_LINEAR);
406                 rc = 1; // don't try to decode_cid
407                 #else   
408                 // Skip any trailing ringtone
409                 vpb_sleep(RING_SKIP);
410
411                 if (option_verbose>3) 
412                         ast_verbose(VERBOSE_PREFIX_4 "CID record - skipped %fms trailing ring\n",
413                                  get_time_in_ms() - cid_record_time);
414                 cid_record_time = get_time_in_ms();
415
416                 // Record bit between the rings which contains the callerid
417                 vpb_record_buf_start(p->handle, VPB_LINEAR);
418                 rc = vpb_record_buf_sync(p->handle, (char*)buf, sizeof(buf));
419                 vpb_record_buf_finish(p->handle);
420                 #endif
421
422                 if (option_verbose>3) 
423                         ast_verbose(VERBOSE_PREFIX_4 "CID record - recorded %fms between rings\n", 
424                                 get_time_in_ms() - cid_record_time);
425
426                 ast_mutex_unlock(&p->record_lock);
427
428                 if( rc != VPB_OK ) {
429                         ast_log(LOG_ERROR, "Failed to record caller id sample on %s\n", p->dev );
430                         return;
431                 }
432
433                 // This decodes FSK 1200baud type callerid
434                 if ((rc=vpb_cid_decode(callerid, buf, CID_MSECS*8)) == VPB_OK ) {
435                         if(!*callerid) 
436                                 strcpy(callerid,"undisclosed"); // blocked CID (eg caller used 1831)
437                 } else {
438                         ast_log(LOG_ERROR, "Failed to decode caller id on %s - %s\n", p->dev, vpb_strerror(rc) );
439                         strcpy(callerid,"unknown");
440                 }
441                 p->owner->callerid = strdup(callerid);
442
443         } else 
444                 ast_log(LOG_ERROR, "Failed to set record mode for caller id on %s\n", p->dev );
445 }
446
447 // Terminate any tones we are presently playing
448 static void stoptone( int handle)
449 {
450         int ret;
451         VPB_EVENT je;
452         while(vpb_playtone_state(handle)!=VPB_OK){
453                 vpb_tone_terminate(handle);
454                 ret = vpb_get_event_ch_async(handle,&je);
455                 if ((ret == VPB_OK)&&(je.type != VPB_DIALEND)){
456                         if (option_verbose > 3){
457                                         ast_verbose(VERBOSE_PREFIX_4 "Stop tone collected a wrong event!!\n");
458                         }
459                         vpb_put_event(&je);
460                 }
461                 vpb_sleep(10);
462         }
463 }
464
465 /* Safe vpb_playtone_async */
466 static int playtone( int handle, VPB_TONE *tone)
467 {
468         int ret=VPB_OK;
469         stoptone(handle);
470         if (option_verbose > 3) 
471                 ast_verbose(VERBOSE_PREFIX_4 "[%02d]: Playing tone\n", handle);
472         ret = vpb_playtone_async(handle, tone);
473         return ret;
474 }
475
476 static inline int monitor_handle_owned(struct vpb_pvt *p, VPB_EVENT *e)
477 {
478         struct ast_frame f = {AST_FRAME_CONTROL}; /* default is control, Clear rest. */
479         int endbridge = 0;
480
481         if (option_verbose > 3) 
482                 ast_verbose(VERBOSE_PREFIX_4 "%s: handle_owned got event: [%d=>%d]\n",
483                         p->dev, e->type, e->data);
484
485         f.src = type;
486         switch (e->type) {
487                 case VPB_RING:
488                         if (p->mode == MODE_FXO) {
489                                 f.subclass = AST_CONTROL_RING;
490                         } else
491                                 f.frametype = -1; /* ignore ring on station port. */
492                         break;
493
494                 case VPB_RING_OFF:
495                         f.frametype = -1;
496                         break;
497
498                 case VPB_TIMEREXP:
499                         if (e->data == p->busy_timer_id) {
500                                 playtone(p->handle,&Busytone);
501                                 p->state = VPB_STATE_PLAYBUSY;
502                                 vpb_timer_restart(p->busy_timer);
503                                 f.frametype = -1;
504                         } else if (e->data == p->ringback_timer_id) {
505                                 playtone(p->handle, &Ringbacktone);
506                                 vpb_timer_restart(p->ringback_timer);
507                                 f.frametype = -1;
508                         } else {
509                                 f.frametype = -1; /* Ignore. */
510                         }
511                         break;
512
513                 case VPB_DTMF:
514                         if (p->owner->_state == AST_STATE_UP) {
515                                 f.frametype = AST_FRAME_DTMF;
516                                 f.subclass = e->data;
517                         } else
518                                 f.frametype = -1;
519                         break;
520
521                 case VPB_TONEDETECT:
522                         if (e->data == VPB_BUSY || e->data == VPB_BUSY_308 || e->data == VPB_BUSY_AUST ) {
523                                 f.subclass = AST_CONTROL_HANGUP;
524                                 if (p->owner->_state == AST_STATE_UP) {
525                                         f.subclass = AST_CONTROL_HANGUP;
526                                 }
527                                 else {
528                                         f.subclass = AST_CONTROL_BUSY;
529                                 }
530                         } else if (e->data == VPB_GRUNT) {
531                                 if( ( get_time_in_ms() - p->lastgrunt ) > gruntdetect_timeout ) {
532                                         // Nothing heard on line for a very long time
533                                         // Timeout connection
534                                         if (option_verbose > 2) 
535                                                 ast_verbose(VERBOSE_PREFIX_3 "grunt timeout\n");
536                                         ast_log(LOG_NOTICE,"%s: Line hangup due of lack of conversation\n",p->dev); 
537                                         f.subclass = AST_CONTROL_HANGUP;
538                                 } else {
539                                         p->lastgrunt = get_time_in_ms();
540                                         f.frametype = -1;
541                                 }
542                         } else
543                                 f.frametype = -1;
544                         break;
545
546                 case VPB_CALLEND:
547                         #ifdef DIAL_WITH_CALL_PROGRESS
548                         if (e->data == VPB_CALL_CONNECTED) 
549                                 f.subclass = AST_CONTROL_ANSWER;
550                         else if (e->data == VPB_CALL_NO_DIAL_TONE || e->data == VPB_CALL_NO_RING_BACK)
551                                 f.subclass =  AST_CONTROL_CONGESTION;
552                         else if (e->data == VPB_CALL_NO_ANSWER || e->data == VPB_CALL_BUSY)
553                                 f.subclass = AST_CONTROL_BUSY;
554                         else if (e->data  == VPB_CALL_DISCONNECTED) 
555                                 f.subclass = AST_CONTROL_HANGUP;
556                         #else
557                         ast_log(LOG_NOTICE,"%s: Got call progress callback but blind dialing \n", p->dev); 
558                         f.frametype = -1;
559                         #endif
560                         break;
561
562                 case VPB_STATION_OFFHOOK:
563                         f.subclass = AST_CONTROL_ANSWER;
564                         break;
565
566                 /* not sure why this was commented out */         
567                 case VPB_DROP:
568                         if ((p->mode == MODE_FXO)&&(UseLoopDrop)){ /* ignore loop drop on stations */
569                                 if (p->owner->_state == AST_STATE_UP) 
570                                         f.subclass = AST_CONTROL_HANGUP;
571                                 else
572                                         f.frametype = -1;
573                         }
574                         break;
575                 /* */     
576                 case VPB_STATION_ONHOOK:
577                         f.subclass = AST_CONTROL_HANGUP;
578                         break;
579
580                 case VPB_STATION_FLASH:
581                         f.subclass = AST_CONTROL_FLASH;
582                         break;
583
584                 // Called when dialing has finished and ringing starts
585                 // No indication that call has really been answered when using blind dialing
586                 case VPB_DIALEND:
587                         f.subclass = AST_CONTROL_ANSWER;
588                         if (option_verbose > 1) 
589                                 ast_verbose(VERBOSE_PREFIX_2 "%s: Dialend\n", p->dev);
590                         break;
591
592                 case VPB_PLAY_UNDERFLOW:
593                         f.frametype = -1;
594                         vpb_reset_play_fifo_alarm(p->handle);
595                         break;
596
597                 case VPB_RECORD_OVERFLOW:
598                         f.frametype = -1;
599                         vpb_reset_record_fifo_alarm(p->handle);
600                         break;
601
602                 default:
603                         f.frametype = -1;
604                         break;
605         }
606
607         if (option_verbose > 3) 
608                 ast_verbose(VERBOSE_PREFIX_4 "%s: handle_owned: putting frame: [%d=>%d], bridge=%p\n",
609                         p->dev, f.frametype, f.subclass, (void *)p->bridge);
610
611         ast_mutex_lock(&p->lock); {
612                 if (p->bridge) { /* Check what happened, see if we need to report it. */
613                         switch (f.frametype) {
614                                 case AST_FRAME_DTMF:
615                                         if (!(p->bridge->c0 == p->owner && 
616                                                         (p->bridge->flags & AST_BRIDGE_DTMF_CHANNEL_0) ) &&
617                                                         !(p->bridge->c1 == p->owner && 
618                                                         (p->bridge->flags & AST_BRIDGE_DTMF_CHANNEL_1) )) 
619                                                 /* Kill bridge, this is interesting. */
620                                                 endbridge = 1;
621                                         break;
622
623                                 case AST_FRAME_CONTROL:
624                                         if (!(p->bridge->flags & AST_BRIDGE_IGNORE_SIGS)) 
625                                         #if 0
626                                         if (f.subclass == AST_CONTROL_BUSY ||
627                                         f.subclass == AST_CONTROL_CONGESTION ||
628                                         f.subclass == AST_CONTROL_HANGUP ||
629                                         f.subclass == AST_CONTROL_FLASH)
630                                         #endif
631                                                 endbridge = 1;
632                                         break;
633
634                                 default:
635                                         break;
636                         }
637                         if (endbridge) {
638                                 if (p->bridge->fo)
639                                         *p->bridge->fo = ast_frisolate(&f);
640                                 if (p->bridge->rc)
641                                         *p->bridge->rc = p->owner;
642
643                                 ast_mutex_lock(&p->bridge->lock); {
644                                         p->bridge->endbridge = 1;
645                                         pthread_cond_signal(&p->bridge->cond);
646                                 } ast_mutex_unlock(&p->bridge->lock);                      
647                         }         
648                 }
649         } ast_mutex_unlock(&p->lock);
650
651         if (endbridge) return 0;
652
653         // Trylock used here to avoid deadlock that can occur if we
654         // happen to be in here handling an event when hangup is called
655         // Problem is that hangup holds p->owner->lock
656         if (f.frametype >= 0 && f.frametype != AST_FRAME_NULL) {
657                 if (ast_mutex_trylock(&p->owner->lock)==0)  {
658                         ast_queue_frame(p->owner, &f);
659                         ast_mutex_unlock(&p->owner->lock);
660                 } else {
661                         ast_verbose("%s: Missed event %d/%d \n",
662                                 p->dev,f.frametype, f.subclass);
663                 }
664         }
665
666         return 0;
667 }
668
669 static inline int monitor_handle_notowned(struct vpb_pvt *p, VPB_EVENT *e)
670 {
671         char s[2] = {0};
672
673         if (option_verbose > 3) {
674                 char str[VPB_MAX_STR];
675                 vpb_translate_event(e, str);
676                 ast_verbose(VERBOSE_PREFIX_4 "%s: In not owned, mode=%d, event[%d][%s]=[%d]\n",
677                         p->dev, p->mode, e->type,str, e->data);
678         }
679
680         switch(e->type) {
681                 case VPB_RING:
682                         if (p->mode == MODE_FXO) /* FXO port ring, start * */ {
683                                 vpb_new(p, AST_STATE_RING, p->context);
684                                 get_callerid(p);        /* Australian Caller ID only between 1st and 2nd ring */
685                         }
686                         break;
687
688                 case VPB_RING_OFF:
689                         break;
690
691                 case VPB_STATION_OFFHOOK:
692                         if (p->mode == MODE_IMMEDIATE) 
693                                 vpb_new(p,AST_STATE_RING, p->context);
694                         else {
695                                 ast_verbose(VERBOSE_PREFIX_4 "%s: In not owned, playing dialtone\n",p->dev);
696                                 playtone(p->handle, &Dialtone);
697                                 p->wantdtmf = 1;
698                                 p->ext[0] = 0;  /* Just to be sure & paranoid.*/
699                                 p->state=VPB_STATE_PLAYDIAL;
700                         }
701                         break;
702
703                 case VPB_DIALEND:
704                         if (p->mode == MODE_DIALTONE){
705                                 if (p->state == VPB_STATE_PLAYDIAL) {
706                                         playtone(p->handle, &Dialtone);
707                                         p->wantdtmf = 1;
708                                         p->ext[0] = 0;  // Just to be sure & paranoid.
709                                 }
710                                 /* These are not needed as they have timers to restart them
711                                 else if (p->state == VPB_STATE_PLAYBUSY) {
712                                         playtone(p->handle, &Busytone);
713                                         p->wantdtmf = 1;
714                                         p->ext[0] = 0;  // Just to be sure & paranoid.
715                                 }
716                                 else if (p->state == VPB_STATE_PLAYRING) {
717                                         playtone(p->handle, &Ringbacktone);
718                                         p->wantdtmf = 1;
719                                         p->ext[0] = 0;  // Just to be sure & paranoid.
720                                 }
721                                 */
722                         } else {
723                                 ast_verbose(VERBOSE_PREFIX_4 "%s: Got a DIALEND when not really expected\n",p->dev);
724                         }
725                         break;
726
727                 case VPB_STATION_ONHOOK:        /* clear ext */
728                         stoptone(p->handle);
729                         p->wantdtmf = 1 ;
730                         p->ext[0] = 0;
731                         p->state=VPB_STATE_ONHOOK;
732                         break;
733
734                 case VPB_DTMF:
735                         if (p->state == VPB_STATE_ONHOOK){
736                                 /* DTMF's being passed while on-hook maybe Caller ID */
737                                 break;
738                         }
739                         if (p->wantdtmf == 1) {
740                                 stoptone(p->handle);
741                                 p->wantdtmf = 0;
742                         }
743                         p->state=VPB_STATE_GETDTMF;
744                         s[0] = e->data;
745                         strcat(p->ext, s);
746                         if (ast_exists_extension(NULL, p->context, p->ext, 1, p->callerid)){
747                                 vpb_new(p,AST_STATE_RING, p->context);
748                         } else if (!ast_canmatch_extension(NULL, p->context, p->ext, 1, p->callerid)){
749                                 if (ast_exists_extension(NULL, "default", p->ext, 1, p->callerid)) {
750                                         vpb_new(p,AST_STATE_RING, "default");         
751                                 } else if (!ast_canmatch_extension(NULL, "default", p->ext, 1, p->callerid)) {
752                                         if (option_verbose > 3) {
753                                                 ast_verbose(VERBOSE_PREFIX_4 "%s: can't match anything in %s or default\n",
754                                                          p->dev, p->context);
755                                         }
756                                         playtone(p->handle, &Busytone);
757                                         vpb_timer_restart(p->busy_timer);
758                                         p->state = VPB_STATE_PLAYBUSY;
759                                 }
760                         }
761                         break;
762
763                 default:
764                         /* Ignore.*/
765                         break;
766         }
767
768         if (option_verbose > 3) 
769                 ast_verbose(VERBOSE_PREFIX_4 "%s: Done not owned, mode=%d, [%d=>%d]\n",
770                         p->dev, p->mode, e->type, e->data);
771
772         return 0;
773 }
774
775 static void *do_monitor(void *unused)
776 {
777
778         /* Monitor thread, doesn't die until explicitly killed. */
779
780         if (option_verbose > 1) 
781                 ast_verbose(VERBOSE_PREFIX_2 "Starting vpb monitor thread[%ld]\n",
782         pthread_self());
783
784         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
785
786         for(;;) {
787                 VPB_EVENT e;
788                 VPB_EVENT je;
789                 char str[VPB_MAX_STR];
790                 struct vpb_pvt *p;
791
792                 /*
793                 if (option_verbose > 3)
794                      ast_verbose(VERBOSE_PREFIX_4 "Monitor waiting for event\n");
795                 */
796
797                 int res = vpb_get_event_sync(&e, VPB_WAIT_TIMEOUT);
798                 if( (res==VPB_NO_EVENTS) || (res==VPB_TIME_OUT) ){
799                         /*
800                         if (option_verbose > 3){
801                                 if (res ==  VPB_NO_EVENTS){
802                                         ast_verbose(VERBOSE_PREFIX_4 "No events....\n");
803                                 } else {
804                                         ast_verbose(VERBOSE_PREFIX_4 "No events, timed out....\n");
805                                 }
806                         }
807                         */
808                         continue;
809                 }
810
811                 if (res != VPB_OK) {
812                         ast_log(LOG_ERROR,"Monitor get event error %s\n", vpb_strerror(res) );
813                         ast_verbose("Monitor get event error %s\n", vpb_strerror(res) );
814                         continue;
815                 }
816
817                 str[0] = 0;
818
819                 p = NULL;
820
821                 ast_mutex_lock(&monlock); {
822                         vpb_translate_event(&e, str);
823
824                         if (e.type == VPB_NULL_EVENT) {
825                                 if (option_verbose > 3)
826                                         ast_verbose(VERBOSE_PREFIX_4 "Monitor got null event\n");
827                                 goto done; /* Nothing to do, just a wakeup call.*/
828                         }
829                         if (strlen(str)>1){
830                                 str[(strlen(str)-1)]='\0';
831                         }
832
833                         ast_mutex_lock(&iflock); {
834                                 p = iflist;
835                                 while (p && p->handle != e.handle)
836                                         p = p->next;
837                         } ast_mutex_unlock(&iflock);
838
839                         if (p && (option_verbose > 3))
840                                 ast_verbose(VERBOSE_PREFIX_4 "%s: Event [%d=>%s] \n", 
841                                         p ? p->dev : "null", e.type, str );
842                         done: (void)0;
843
844                 } ast_mutex_unlock(&monlock); 
845
846                 if (!p) {
847                         if (e.type != VPB_NULL_EVENT){
848                                 ast_log(LOG_WARNING, "Got event [%s][%d], no matching iface!\n", str,e.type);    
849                                 if (option_verbose > 3){
850                                         ast_verbose(VERBOSE_PREFIX_4 "vpb/ERR: No interface for Event [%d=>%s] \n",e.type,str );
851                                 }
852                         }
853                         continue;
854                 } 
855
856                 /* flush the event from the channel event Q */
857                 vpb_get_event_ch_async(e.handle,&je);
858                 if (option_verbose > 3){
859                         vpb_translate_event(&je, str);
860                         ast_verbose( VERBOSE_PREFIX_4 "%s: Flushing event [%d]=>%s\n",p->dev,je.type,str);
861                 }
862
863                 /* Two scenarios: Are you owned or not. */
864                 ast_mutex_lock(&p->owner_lock);
865                 if (p->owner) {
866                         monitor_handle_owned(p, &e);
867                         ast_mutex_unlock(&p->owner_lock);
868                 } else {
869                         ast_mutex_unlock(&p->owner_lock);
870                         monitor_handle_notowned(p, &e);
871                 }
872
873         }
874
875         return NULL;
876 }
877
878 static int restart_monitor(void)
879 {
880         int error = 0;
881
882         /* If we're supposed to be stopped -- stay stopped */
883         if (mthreadactive == -2)
884                 return 0;
885
886         if (option_verbose > 3)
887                 ast_verbose(VERBOSE_PREFIX_4 "Restarting monitor\n");
888
889         ast_mutex_lock(&monlock); {
890                 if (monitor_thread == pthread_self()) {
891                         ast_log(LOG_WARNING, "Cannot kill myself\n");
892                         error = -1;
893                         if (option_verbose > 3)
894                                 ast_verbose(VERBOSE_PREFIX_4 "Monitor trying to kill monitor\n");
895                         goto done;
896                 }
897                 if (mthreadactive != -1) {
898                         /* Why do other drivers kill the thread? No need says I, simply awake thread with event. */
899                         VPB_EVENT e;
900                         e.handle = 0;
901                         e.type = VPB_NULL_EVENT;
902                         e.data = 0;
903
904                         if (option_verbose > 3)
905                                 ast_verbose(VERBOSE_PREFIX_4 "Trying to reawake monitor\n");
906
907                         vpb_put_event(&e);
908                 } else {
909                         /* Start a new monitor */
910                         int pid = pthread_create(&monitor_thread, NULL, do_monitor, NULL); 
911                         if (option_verbose > 3)
912                                 ast_verbose(VERBOSE_PREFIX_4 "Created new monitor thread %d\n",pid);
913                         if (pid < 0) {
914                                 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
915                                 error = -1;
916                                 goto done;
917                         } else
918                                 mthreadactive = 0; /* Started the thread!*/
919                 }
920                 done: (void)0;
921         } ast_mutex_unlock(&monlock);
922
923         if (option_verbose > 3)
924                 ast_verbose(VERBOSE_PREFIX_4 "Monitor restarted\n");
925
926         return error;
927 }
928
929 // Per board config that must be called after vpb_open()
930 static void mkbrd(vpb_model_t model, int echo_cancel)
931 {
932         if(!bridges) {
933                 if(model==vpb_model_v4pci) 
934                         max_bridges = MAX_BRIDGES_V4PCI;
935                 bridges = (vpb_bridge_t *)malloc(max_bridges * sizeof(vpb_bridge_t) );
936                 if(!bridges) 
937                         ast_log(LOG_ERROR, "Failed to initialize bridges\n");
938                 else 
939                         memset(bridges,0,max_bridges * sizeof(vpb_bridge_t));
940         }
941         if(!echo_cancel) {
942                 if (model==vpb_model_v4pci) {
943                         vpb_echo_canc_disable();
944                         ast_log(LOG_NOTICE, "Voicetronix echo cancellation OFF\n");
945                 } 
946                 else {
947                 /* need to it port by port for OpenSwitch*/
948                 }
949         } else {
950                 if (model==vpb_model_v4pci) {
951                         vpb_echo_canc_enable();
952                         ast_log(LOG_NOTICE, "Voicetronix echo cancellation ON\n");
953                 }
954                 else {
955                 /* need to it port by port for OpenSwitch*/
956                 }
957         }
958 }
959
960 struct vpb_pvt *mkif(int board, int channel, int mode, float txgain, float rxgain,
961                          float txswgain, float rxswgain, int bal1, int bal2, int bal3,
962                          char * callerid, int echo_cancel, int group )
963 {
964         struct vpb_pvt *tmp;
965         char buf[64];
966
967         tmp = (struct vpb_pvt *)calloc(1, sizeof *tmp);
968
969         if (!tmp)
970                 return NULL;
971
972         tmp->handle = vpb_open(board, channel);
973
974         if (tmp->handle < 0) {    
975                 ast_log(LOG_WARNING, "Unable to create channel vpb/%d-%d: %s\n", 
976                                         board, channel, strerror(errno));
977                 free(tmp);
978                 return NULL;
979         }
980                
981         sprintf(tmp->dev, "vpb/%d-%d", board, channel);
982
983         tmp->mode = mode;
984
985         tmp->group = group;
986
987         strcpy(tmp->language, language);
988         strcpy(tmp->context, context);
989
990         if(callerid) { 
991                 strcpy(tmp->callerid, callerid);
992                 free(callerid);
993         } else {
994                 strcpy(tmp->callerid, "unknown");
995         }
996
997         /* check if codec balances have been set in the config file */
998         if (bal3>=0) {
999                 if ((bal1>=0) && !(bal1 & 32)) bal1 |= 32;
1000                         vpb_set_codec_reg(tmp->handle, 0x42, bal3);
1001         }
1002         if(bal1>=0) vpb_set_codec_reg(tmp->handle, 0x32, bal1);
1003         if(bal2>=0) vpb_set_codec_reg(tmp->handle, 0x3a, bal2);
1004
1005         tmp->txgain = txgain;
1006         vpb_play_set_hw_gain(tmp->handle, (txgain > MAX_VPB_GAIN) ? MAX_VPB_GAIN : txgain);
1007
1008         tmp->rxgain = rxgain;
1009         vpb_record_set_hw_gain(tmp->handle, (rxgain > MAX_VPB_GAIN) ? MAX_VPB_GAIN : rxgain);
1010
1011         tmp->txswgain = txswgain;
1012         vpb_play_set_gain(tmp->handle, (txswgain > MAX_VPB_GAIN) ? MAX_VPB_GAIN : txswgain);
1013
1014         tmp->rxswgain = rxswgain;
1015         vpb_record_set_gain(tmp->handle, (rxswgain > MAX_VPB_GAIN) ? MAX_VPB_GAIN : rxswgain);
1016
1017         tmp->vpb_model = vpb_model_unknown;
1018         if( vpb_get_model(buf) == VPB_OK ) {
1019                 if(strcmp(buf,"V12PCI")==0) 
1020                         tmp->vpb_model = vpb_model_v12pci;
1021                 else if(strcmp(buf,"VPB4")==0) 
1022                         tmp->vpb_model = vpb_model_v4pci;
1023         }
1024
1025         ast_mutex_init(&tmp->lock);
1026         ast_mutex_init(&tmp->record_lock);
1027         ast_mutex_init(&tmp->play_lock);
1028         ast_mutex_init(&tmp->play_dtmf_lock);
1029         ast_mutex_init(&tmp->owner_lock);
1030
1031         tmp->busy_timer_id = vpb_timer_get_unique_timer_id();
1032         vpb_timer_open(&tmp->busy_timer, tmp->handle, tmp->busy_timer_id, TIMER_PERIOD_BUSY);
1033
1034         tmp->ringback_timer_id = vpb_timer_get_unique_timer_id();
1035         vpb_timer_open(&tmp->ringback_timer, tmp->handle, tmp->ringback_timer_id, TIMER_PERIOD_RINGBACK);
1036               
1037         if (mode == MODE_FXO){
1038                 vpb_set_event_mask(tmp->handle, VPB_EVENTS_NODTMF );
1039         }
1040         else {
1041                 vpb_set_event_mask(tmp->handle, VPB_EVENTS_STAT );
1042         }
1043
1044         if ((tmp->vpb_model == vpb_model_v12pci) && (echo_cancel)){
1045                 vpb_hostecho_on(tmp->handle);
1046         }
1047
1048         /* define grunt tone */
1049         vpb_settonedet(tmp->handle,&toned_ungrunt);
1050
1051         ast_log(LOG_NOTICE,"Voicetronix %s channel %s initialized (rxgain=%f txgain=%f) (%f/%f/0x%X/0x%X/0x%X)\n",
1052                 (tmp->vpb_model==vpb_model_v4pci)?"V4PCI":
1053                 (tmp->vpb_model==vpb_model_v12pci)?"V12PCI":"[Unknown model]",
1054                 tmp->dev, tmp->rxswgain, tmp->txswgain, tmp->rxgain, tmp->txgain, bal1, bal2, bal3 );
1055
1056         return tmp;
1057 }
1058
1059 static int vpb_indicate(struct ast_channel *ast, int condition)
1060 {
1061         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
1062         int res = 0;
1063
1064         if (option_verbose > 3)
1065                 ast_verbose(VERBOSE_PREFIX_4 " vpb indicate on %s with %d\n", p->dev, condition);
1066
1067         switch(condition) {
1068                 case AST_CONTROL_BUSY:
1069                 case AST_CONTROL_CONGESTION:
1070                         playtone(p->handle, &Busytone);
1071                         p->state = VPB_STATE_PLAYBUSY;
1072                         vpb_timer_restart(p->busy_timer); 
1073                         break;
1074                 case AST_CONTROL_RINGING:
1075                         playtone(p->handle, &Ringbacktone);
1076                         vpb_timer_restart(p->ringback_timer);
1077                         break;      
1078                 case AST_CONTROL_ANSWER:
1079                 case -1: /* -1 means stop playing? */
1080                         vpb_timer_stop(p->ringback_timer);
1081                         vpb_timer_stop(p->busy_timer);
1082                         stoptone(p->handle);
1083                         break;
1084                 case AST_CONTROL_HANGUP:
1085                         playtone(p->handle, &Busytone);
1086                         p->state = VPB_STATE_PLAYBUSY;
1087                         vpb_timer_restart(p->busy_timer);
1088                         break;
1089
1090                 default:
1091                         res = 0;
1092                         break;
1093         }
1094         return res;
1095 }
1096
1097 static int vpb_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1098 {
1099         struct vpb_pvt *p = (struct vpb_pvt *)newchan->pvt->pvt;
1100
1101         ast_mutex_lock(&p->lock);
1102         ast_log(LOG_DEBUG, 
1103                 "New owner for channel %s is %s\n", p->dev, newchan->name);
1104
1105         if (p->owner == oldchan) {
1106                 p->owner = newchan;
1107         }
1108
1109         if (newchan->_state == AST_STATE_RINGING) 
1110                 vpb_indicate(newchan, AST_CONTROL_RINGING);
1111
1112         ast_mutex_unlock(&p->lock);
1113         return 0;
1114 }
1115
1116 static int vpb_digit(struct ast_channel *ast, char digit)
1117 {
1118         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
1119         char s[2];
1120
1121         s[0] = digit;
1122         s[1] = '\0';
1123
1124         ast_mutex_lock(&p->play_dtmf_lock);
1125         strncat(p->play_dtmf,s,sizeof(*p->play_dtmf));
1126         ast_mutex_unlock(&p->play_dtmf_lock);
1127
1128         return 0;
1129 }
1130
1131 static int vpb_call(struct ast_channel *ast, char *dest, int timeout)
1132 {
1133         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
1134         int res = 0,i;
1135         char *s = strrchr(dest, '/');
1136         char dialstring[254];
1137
1138         if (s)
1139                 s = s + 1;
1140         else
1141                 s = dest;
1142         strcpy(dialstring,s);
1143         for (i=0; dialstring[i] != '\0' ; i++) {
1144                 if ((dialstring[i] == 'w') || (dialstring[i] == 'W'))
1145                         dialstring[i] = ',';
1146                 else if ((dialstring[i] == 'f') || (dialstring[i] == 'F'))
1147                         dialstring[i] = '&';
1148         }       
1149
1150         if (ast->_state != AST_STATE_DOWN && ast->_state != AST_STATE_RESERVED) {
1151                 ast_log(LOG_WARNING, "vpb_call on %s neither down nor reserved!\n", 
1152                 ast->name);
1153                 return -1;
1154         }
1155         if (p->mode != MODE_FXO)  /* Station port, ring it. */
1156                 res = vpb_ring_station_async(p->handle, VPB_RING_STATION_ON,0);       
1157         else {
1158                 VPB_CALL call;
1159
1160                 // Dial must timeout or it can leave channels unuseable
1161                 if( timeout == 0 )
1162                         timeout = TIMER_PERIOD_NOANSWER;
1163                 else 
1164                         timeout = timeout * 1000; //convert from secs to ms.
1165
1166                 // These timeouts are only used with call progress dialing
1167                 call.dialtones = 1; // Number of dialtones to get outside line
1168                 call.dialtone_timeout = VPB_DIALTONE_WAIT; // Wait this long for dialtone (ms)
1169                 call.ringback_timeout = VPB_RINGWAIT; // Wait this long for ringing after dialing (ms)
1170                 call.inter_ringback_timeout = VPB_CONNECTED_WAIT; // If ringing stops for this long consider it connected (ms)
1171                 call.answer_timeout = timeout; // Time to wait for answer after ringing starts (ms)
1172                 memcpy( &call.tone_map,  DialToneMap, sizeof(DialToneMap) );
1173                 vpb_set_call(p->handle, &call);
1174
1175                 if (option_verbose > 1)
1176                         ast_verbose(VERBOSE_PREFIX_2 "Calling %s on %s \n", dialstring, ast->name); 
1177
1178                 if (option_verbose > 2) {
1179                         int j;
1180                         ast_verbose(VERBOSE_PREFIX_2 "Dial parms for %s %d/%dms/%dms/%dms/%dms\n"
1181                                 , ast->name, call.dialtones, call.dialtone_timeout
1182                                 , call.ringback_timeout, call.inter_ringback_timeout
1183                                 , call.answer_timeout );
1184                         for( j=0; !call.tone_map[j].terminate; j++ )
1185                                 ast_verbose(VERBOSE_PREFIX_2 "Dial parms for %s tone %d->%d\n", 
1186                                         ast->name, call.tone_map[j].tone_id, call.tone_map[j].call_id); 
1187                 }
1188
1189                 vpb_sethook_sync(p->handle,VPB_OFFHOOK);
1190                 p->state=VPB_STATE_OFFHOOK;
1191
1192                 #ifndef DIAL_WITH_CALL_PROGRESS
1193                 vpb_sleep(300);
1194                 res = vpb_dial_async(p->handle, dialstring);
1195                 #else
1196                 res = vpb_call_async(p->handle, dialstring);
1197                 #endif
1198
1199                 if (res != VPB_OK) {
1200                         ast_log(LOG_DEBUG, "Call on %s to %s failed: %s\n", ast->name, s, vpb_strerror(res));         
1201                         res = -1;
1202                 } else 
1203                         res = 0;
1204         }
1205
1206         if (option_verbose > 2)
1207                 ast_verbose(VERBOSE_PREFIX_3 " VPB Calling %s [t=%d] on %s returned %d\n", s, timeout, ast->name, res); 
1208         if (res == 0) {
1209                 ast_setstate(ast, AST_STATE_RINGING);
1210                 ast_queue_control(ast,AST_CONTROL_RINGING);             
1211         }
1212
1213         pthread_create(&p->readthread, NULL, do_chanreads, (void *)p);
1214
1215         return res;
1216 }
1217
1218 static int vpb_hangup(struct ast_channel *ast)
1219 {
1220         struct vpb_pvt *p;
1221         VPB_EVENT je;
1222         char str[VPB_MAX_STR];
1223
1224         if (option_verbose > 1) 
1225                 ast_verbose(VERBOSE_PREFIX_2 "%s: Hangup requested\n", ast->name);
1226
1227         if (!ast->pvt || !ast->pvt->pvt) {
1228                 ast_log(LOG_WARNING, "%s: channel not connected?\n", ast->name);
1229                 return 0;
1230         }
1231
1232         if(option_verbose>3) 
1233                 ast_verbose( VERBOSE_PREFIX_4 "%s: Setting state down\n",ast->name);
1234         ast_setstate(ast,AST_STATE_DOWN);
1235
1236         p = (struct vpb_pvt *)ast->pvt->pvt;
1237
1238         /* Stop record */
1239         p->stopreads = 1;
1240         if( p->readthread ){
1241                 pthread_join(p->readthread, NULL); 
1242                 if(option_verbose>3) 
1243                         ast_verbose( VERBOSE_PREFIX_4 "%s: stopped record thread on %s\n",ast->name,p->dev);
1244         }
1245
1246         /* Stop play */
1247         if (p->lastoutput != -1) {
1248                 if(option_verbose>1) 
1249                         ast_verbose( VERBOSE_PREFIX_2 "%s: Ending play mode on %s\n",ast->name,p->dev);
1250                 vpb_play_terminate(p->handle);
1251                 ast_mutex_lock(&p->play_lock); {
1252                         vpb_play_buf_finish(p->handle);
1253                 } ast_mutex_unlock(&p->play_lock);
1254         }
1255
1256         if (p->mode != MODE_FXO) { 
1257                 /* station port. */
1258                 vpb_ring_station_async(p->handle, VPB_RING_STATION_OFF,0);      
1259                 if(p->state!=VPB_STATE_ONHOOK){
1260                         /* This is causing a "dial end" "play tone" loop
1261                         playtone(p->handle, &Busytone); 
1262                         p->state = VPB_STATE_PLAYBUSY;
1263                         if(option_verbose>4) 
1264                                 ast_verbose( VERBOSE_PREFIX_4 "%s: Station offhook[%d], playing busy tone\n",
1265                                                                 ast->name,p->state);
1266                         */
1267                 }
1268                 else {
1269                         stoptone(p->handle);
1270                 }
1271         } else {
1272                 stoptone(p->handle); // Terminates any dialing
1273                 vpb_sethook_sync(p->handle, VPB_ONHOOK);
1274                 p->state=VPB_STATE_ONHOOK;
1275         }
1276         while (VPB_OK==vpb_get_event_ch_async(p->handle,&je)){
1277                 if(option_verbose>3) {
1278                         vpb_translate_event(&je, str);
1279                         ast_verbose( VERBOSE_PREFIX_4 "%s: Flushing event [%d]=>%s\n",ast->name,je.type,str);
1280                 }
1281         }
1282
1283         p->readthread = 0;
1284         p->lastoutput = -1;
1285         p->lastinput = -1;
1286         p->last_ignore_dtmf = 1;
1287         p->ext[0]  = 0;
1288         p->dialtone = 0;
1289
1290         ast_mutex_lock(&p->owner_lock); {
1291                 p->owner = NULL;
1292                 ast->pvt->pvt = NULL;    
1293         } ast_mutex_unlock(&p->owner_lock);
1294
1295         ast_mutex_lock(&usecnt_lock); {
1296                 usecnt--;
1297         } ast_mutex_unlock(&usecnt_lock);
1298         ast_update_use_count();
1299
1300         if (option_verbose > 1)
1301                 ast_verbose(VERBOSE_PREFIX_2 "%s: Hangup complete\n", ast->name);
1302
1303         restart_monitor();
1304         return 0;
1305 }
1306
1307 static int vpb_answer(struct ast_channel *ast)
1308 {
1309         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
1310         VPB_EVENT je;
1311         int ret;
1312
1313         if (ast->_state != AST_STATE_UP) {
1314                 if (p->mode == MODE_FXO){
1315                         vpb_sethook_sync(p->handle, VPB_OFFHOOK);
1316                         p->state=VPB_STATE_OFFHOOK;
1317                         vpb_sleep(500);
1318                         ret = vpb_get_event_ch_async(p->handle,&je);
1319                         if ((ret == VPB_OK)&&(je.type != VPB_DROP)){
1320                                 if (option_verbose > 3){
1321                                                 ast_verbose(VERBOSE_PREFIX_4 "Answer collected a wrong event!!\n");
1322                                 }
1323                                 vpb_put_event(&je);
1324                         }
1325                 }
1326                 ast_setstate(ast, AST_STATE_UP);
1327
1328                 if(option_verbose>1) 
1329                         ast_verbose( VERBOSE_PREFIX_2 "Answered call from %s on %s [%s]\n", 
1330                                         p->owner->callerid, ast->name,(p->mode == MODE_FXO)?"FXO":"FXS");
1331
1332                 ast->rings = 0;
1333                 if( !p->readthread ){
1334                         pthread_create(&p->readthread, NULL, do_chanreads, (void *)p);
1335                 } else {
1336                         if(option_verbose>3) 
1337                                 ast_verbose(VERBOSE_PREFIX_4 "Record thread already running!!\n");
1338                 }
1339         } else {
1340                 if(option_verbose>3) {
1341                         ast_verbose(VERBOSE_PREFIX_4 "Answered state is up\n");
1342                 }
1343         }
1344         return 0;
1345 }
1346
1347 static struct ast_frame  *vpb_read(struct ast_channel *ast)
1348 {
1349         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt; 
1350         static struct ast_frame f = {AST_FRAME_NULL}; 
1351
1352         f.src = type;
1353         ast_log(LOG_NOTICE, "vpb_read should never be called (chan=%s)!\n", p->dev);
1354
1355         return &f;
1356 }
1357
1358 static inline int ast2vpbformat(int ast_format)
1359 {
1360         switch(ast_format) {
1361                 case AST_FORMAT_ALAW:
1362                         return VPB_ALAW;
1363                 case AST_FORMAT_SLINEAR:
1364                         return VPB_LINEAR;
1365                 case AST_FORMAT_ULAW:
1366                         return VPB_MULAW;
1367                 case AST_FORMAT_ADPCM:
1368                         return VPB_OKIADPCM;
1369                 default:
1370                         return -1;
1371         }
1372 }
1373
1374 static inline int astformatbits(int ast_format)
1375 {
1376         switch(ast_format) {
1377                 case AST_FORMAT_ALAW:
1378                 case AST_FORMAT_ULAW:
1379                         return 8;
1380                 case AST_FORMAT_SLINEAR:
1381                         return 16;
1382                 case AST_FORMAT_ADPCM:
1383                         return 4;
1384                 default:
1385                         return 8;
1386         }   
1387 }
1388
1389 int gain_vector(float g, short *v, int n) 
1390 {
1391         int i;
1392         float tmp;
1393         for ( i = 0; i<n; i++) {
1394                 tmp = g*v[i];
1395                 if (tmp > 32767.0)
1396                         tmp = 32767.0;
1397                 if (tmp < -32768.0)
1398                         tmp = -32768.0;
1399                 v[i] = (short)tmp;      
1400         }  
1401         return(i);
1402 }
1403
1404 static int vpb_write(struct ast_channel *ast, struct ast_frame *frame)
1405 {
1406         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt; 
1407         int res = 0, fmt = 0;
1408
1409         if (frame->frametype != AST_FRAME_VOICE) {
1410                 if(option_verbose>3) 
1411                         ast_verbose( VERBOSE_PREFIX_4 "%s: Don't know how to handle from type %d\n", ast->name, frame->frametype);
1412                 return 0;
1413         } else if (ast->_state != AST_STATE_UP) {
1414                 if(option_verbose>3) 
1415                         ast_verbose( VERBOSE_PREFIX_4 "%s: Writing frame type [%d,%d] on chan %s not up\n",ast->name, frame->frametype, frame->subclass, ast->name);
1416                 p->lastoutput = -1;
1417                 return 0;
1418         }
1419
1420         fmt = ast2vpbformat(frame->subclass);
1421         if (fmt < 0) {
1422                 ast_log(LOG_WARNING, "%s: vpb_write Cannot handle frames of %d format!\n",ast->name, frame->subclass);
1423                 return -1;
1424         }
1425
1426         ast_mutex_lock(&p->play_lock);
1427
1428         if (p->lastoutput == -1) {
1429                 vpb_play_buf_start(p->handle, fmt);
1430                 if(option_verbose>1) 
1431                         ast_verbose( VERBOSE_PREFIX_2 "%s: Starting play mode (codec=%d)\n",p->dev,fmt);
1432         } else if (p->lastoutput != fmt) {
1433                 vpb_play_buf_finish(p->handle);
1434                 vpb_play_buf_start(p->handle, fmt);
1435                 if(option_verbose>1) 
1436                         ast_verbose( VERBOSE_PREFIX_2 "%s: Changed play format (%d=>%d)\n",p->dev,p->lastoutput,fmt);
1437         }
1438
1439         p->lastoutput = fmt;
1440
1441         // Apply extra gain !
1442         if( p->txswgain > MAX_VPB_GAIN )
1443                 gain_vector(p->txswgain - MAX_VPB_GAIN , (short*)frame->data, frame->datalen/sizeof(short));
1444
1445         res = vpb_play_buf_sync(p->handle, (char*)frame->data, frame->datalen);
1446         if( (res == VPB_OK) && (option_verbose > 4) ) {
1447                 short * data = (short*)frame->data;
1448                 ast_verbose("%s: Write chan (codec=%d) %d %d\n", p->dev, fmt, data[0],data[1]);
1449         }
1450
1451         ast_mutex_unlock(&p->play_lock);
1452         return 0;
1453 }
1454
1455 /* Read monitor thread function. */
1456 static void *do_chanreads(void *pvt)
1457 {
1458         struct vpb_pvt *p = (struct vpb_pvt *)pvt;
1459         struct ast_frame *fr = &p->fr;
1460         char *readbuf = ((char *)p->buf) + AST_FRIENDLY_OFFSET;
1461         int bridgerec = 0;
1462         int afmt, readlen, res, fmt;
1463         int ignore_dtmf;
1464         char * getdtmf_var = NULL;
1465
1466         fr->frametype = AST_FRAME_VOICE;
1467         fr->src = type;
1468         fr->mallocd = 0;
1469         fr->samples = VPB_SAMPLES;
1470         fr->offset = AST_FRIENDLY_OFFSET;
1471         memset(p->buf, 0, sizeof p->buf);
1472
1473         ast_mutex_lock(&p->record_lock);
1474
1475         p->stopreads = 0; 
1476         while (!p->stopreads && p->owner) {
1477
1478                 ast_mutex_lock(&p->lock); {
1479                         if (p->bridge) {
1480                                 if (p->bridge->c0 == p->owner && (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_0))
1481                                         bridgerec = 1;
1482                                 else if (p->bridge->c1 == p->owner && (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_1))
1483                                         bridgerec = 1;
1484                                 else 
1485                                         bridgerec = 0;
1486                         } else {
1487                                 bridgerec = 1;
1488                         }
1489                 } ast_mutex_unlock(&p->lock);
1490
1491                 if ( (p->owner->_state != AST_STATE_UP) || !bridgerec) {
1492                         vpb_sleep(10);
1493                         continue;
1494                 }
1495
1496                 // Voicetronix DTMF detection can be triggered off ordinary speech
1497                 // This leads to annoying beeps during the conversation
1498                 // Avoid this problem by just setting VPB_GETDTMF when you want to listen for DTMF
1499                 //ignore_dtmf = 1;
1500                 ignore_dtmf = 0; /* set this to 1 to turn this feature on */
1501                 getdtmf_var = pbx_builtin_getvar_helper(p->owner,"VPB_GETDTMF");
1502                 if( getdtmf_var && ( strcasecmp( getdtmf_var, "yes" ) == 0 ) )
1503                         ignore_dtmf = 0;
1504
1505                 if( ignore_dtmf != p->last_ignore_dtmf ) {
1506                         if(option_verbose>1) 
1507                                 ast_verbose( VERBOSE_PREFIX_2 "%s:Now %s DTMF \n",
1508                                         p->dev, ignore_dtmf ? "ignoring" : "listening for");
1509                         vpb_set_event_mask(p->handle, ignore_dtmf ? VPB_EVENTS_NODTMF : VPB_EVENTS_ALL );
1510                 }
1511                 p->last_ignore_dtmf = ignore_dtmf;
1512
1513                 // Play DTMF digits here to avoid problem you get if playing a digit during
1514                 // a record operation
1515                 ast_mutex_lock(&p->play_dtmf_lock);
1516                 if( p->play_dtmf[0] ) {
1517                         // Try to ignore DTMF event we get after playing digit
1518                         // This DTMF is played by asterisk and leads to an annoying trailing beep on CISCO phones
1519                         if( !ignore_dtmf) 
1520                                 vpb_set_event_mask(p->handle, VPB_EVENTS_NODTMF );
1521                         vpb_dial_sync(p->handle,p->play_dtmf);
1522                         if(option_verbose>1) 
1523                                 ast_verbose( VERBOSE_PREFIX_2 "%s: Played DTMF %s\n",p->dev,p->play_dtmf);
1524                         p->play_dtmf[0] = '\0';
1525                         ast_mutex_unlock(&p->play_dtmf_lock);
1526                         vpb_sleep(700); // Long enough to miss echo and DTMF event
1527                         if( !ignore_dtmf) 
1528                                 vpb_set_event_mask(p->handle, VPB_EVENTS_ALL );
1529                         continue;
1530                 }
1531                 ast_mutex_unlock(&p->play_dtmf_lock);
1532
1533                 afmt = (p->owner) ? p->owner->pvt->rawreadformat : AST_FORMAT_SLINEAR;
1534                 fmt = ast2vpbformat(afmt);
1535                 if (fmt < 0) {
1536                         ast_log(LOG_WARNING,"%s: Record failure (unsupported format %d)\n", p->dev, afmt);
1537                         return NULL;
1538                 }
1539                 readlen = VPB_SAMPLES * astformatbits(afmt) / 8;
1540
1541                 if (p->lastinput == -1) {
1542                         vpb_record_buf_start(p->handle, fmt);
1543                         vpb_reset_record_fifo_alarm(p->handle);
1544                         if(option_verbose>1) 
1545                                 ast_verbose( VERBOSE_PREFIX_2 "%s: Starting record mode (codec=%d)\n",p->dev,fmt);
1546                 } else if (p->lastinput != fmt) {
1547                         vpb_record_buf_finish(p->handle);
1548                         vpb_record_buf_start(p->handle, fmt);
1549                         if(option_verbose>1) 
1550                                 ast_verbose( VERBOSE_PREFIX_2 "%s: Changed record format (%d=>%d)\n",p->dev,p->lastinput,fmt);
1551                 }
1552                 p->lastinput = fmt;
1553
1554                 /* Read only if up and not bridged, or a bridge for which we can read. */
1555                 if( (res = vpb_record_buf_sync(p->handle, readbuf, readlen) ) == VPB_OK ) {
1556                         // Apply extra gain !
1557                         if( p->rxswgain > MAX_VPB_GAIN )
1558                                 gain_vector(p->rxswgain - MAX_VPB_GAIN , (short*)readbuf, readlen/sizeof(short));
1559
1560                         fr->subclass = afmt;
1561                         fr->data = readbuf;
1562                         fr->datalen = readlen;
1563
1564                         // Using trylock here to prevent deadlock when channel is hungup
1565                         // (ast_hangup() immediately gets lock)
1566                         if (p->owner && !p->stopreads ) {
1567                                 ast_queue_frame(p->owner, fr);
1568                                 if (option_verbose > 4) {
1569                                         short * data = (short*)readbuf;
1570                                         ast_verbose("%s: Read channel (codec=%d) %d %d\n", p->dev, fmt, data[0], data[1] );     
1571                                 }  
1572                         }
1573                 } else {
1574                         ast_log(LOG_WARNING,"%s: Record failure (%s)\n", p->dev, vpb_strerror(res));
1575                         vpb_record_buf_finish(p->handle);
1576                         vpb_record_buf_start(p->handle, fmt);
1577                 }
1578         }
1579
1580         /* When stopreads seen, go away! */
1581         vpb_record_buf_finish(p->handle);
1582         ast_mutex_unlock(&p->record_lock);
1583
1584         if (option_verbose > 1)
1585                 ast_verbose(VERBOSE_PREFIX_2 "%s: Ending record mode (%d/%s)\n",
1586                          p->dev, p->stopreads, p->owner? "yes" : "no");     
1587         return NULL;
1588 }
1589
1590 static struct ast_channel *vpb_new(struct vpb_pvt *i, int state, char *context)
1591 {
1592         struct ast_channel *tmp; 
1593
1594         if (i->owner) {
1595             ast_log(LOG_WARNING, "Called vpb_new on owned channel (%s) ?!\n", i->dev);
1596             return NULL;
1597         }
1598             
1599         tmp = ast_channel_alloc(1);
1600         if (tmp) {
1601                 strncpy(tmp->name, i->dev, sizeof(tmp->name));
1602                 tmp->type = type;
1603                
1604                 // Linear is the preferred format. Although Voicetronix supports other formats
1605                 // they are all converted to/from linear in the vpb code. Best for us to use
1606                 // linear since we can then adjust volume in this modules.
1607                 tmp->nativeformats = prefformat;
1608                 tmp->pvt->rawreadformat = AST_FORMAT_SLINEAR;
1609                 tmp->pvt->rawwriteformat =  AST_FORMAT_SLINEAR;
1610                 ast_setstate(tmp, state);
1611                 if (state == AST_STATE_RING)
1612                         tmp->rings = 1;
1613                 tmp->pvt->pvt = i;
1614                 /* set Call backs */
1615                 tmp->pvt->send_digit = vpb_digit;
1616                 tmp->pvt->call = vpb_call;
1617                 tmp->pvt->hangup = vpb_hangup;
1618                 tmp->pvt->answer = vpb_answer;
1619                 tmp->pvt->read = vpb_read;
1620                 tmp->pvt->write = vpb_write;
1621                 tmp->pvt->bridge = vpb_bridge;
1622                 tmp->pvt->indicate = vpb_indicate;
1623                 tmp->pvt->fixup = vpb_fixup;
1624                 
1625                 strncpy(tmp->context, context, sizeof(tmp->context)-1);
1626                 if (strlen(i->ext))
1627                         strncpy(tmp->exten, i->ext, sizeof(tmp->exten)-1);
1628                 else
1629                         strncpy(tmp->exten, "s",  sizeof(tmp->exten) - 1);
1630                 if (strlen(i->language))
1631                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1632
1633                 i->owner = tmp;
1634      
1635                 i->bridge = NULL;
1636                 i->lastoutput = -1;
1637                 i->lastinput = -1;
1638                 i->last_ignore_dtmf = 1;
1639                 i->readthread = 0;
1640                 i->play_dtmf[0] = '\0';
1641                 
1642                 i->lastgrunt  = get_time_in_ms(); /* Assume at least one grunt tone seen now. */
1643
1644                 ast_mutex_lock(&usecnt_lock);
1645                 usecnt++;
1646                 ast_mutex_unlock(&usecnt_lock);
1647                 ast_update_use_count();
1648                 if (state != AST_STATE_DOWN) {
1649                         if (ast_pbx_start(tmp)) {
1650                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1651                                 ast_hangup(tmp);
1652                         }
1653                 }
1654         } else {
1655                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1656         }
1657         return tmp;
1658 }
1659
1660 static struct ast_channel *vpb_request(char *type, int format, void *data) 
1661 {
1662         int oldformat;
1663         struct vpb_pvt *p;
1664         struct ast_channel *tmp = NULL;
1665         char *name = strdup(data ? (char *)data : "");
1666         char *s, *sepstr;
1667         int group=-1;
1668
1669         oldformat = format;
1670         format &= prefformat;
1671         if (!format) {
1672                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
1673                 return NULL;
1674         }
1675
1676         sepstr = name;
1677         s = strsep(&sepstr, "/"); /* Handle / issues */
1678         if (!s) 
1679                 s = "";
1680         /* Check if we are looking for a group */
1681         if (toupper(name[0]) == 'G' || toupper(name[0])=='R') {
1682                 group=atoi(name+1);     
1683         }
1684         /* Search for an unowned channel */
1685         ast_mutex_lock(&iflock); {
1686                 p = iflist;
1687                 while(p) {
1688                         if (group == -1){
1689                                 if (strncmp(s, p->dev + 4, sizeof p->dev) == 0) {
1690                                         if (!p->owner) {
1691                                                 tmp = vpb_new(p, AST_STATE_DOWN, p->context);
1692                                                 break;
1693                                         }
1694                                 }
1695                         }
1696                         else {
1697                                 if ((p->group == group) && (!p->owner)) {
1698                                         tmp = vpb_new(p, AST_STATE_DOWN, p->context);
1699                                         break;
1700                                 }
1701                         }
1702                         p = p->next;
1703                 }
1704         } ast_mutex_unlock(&iflock);
1705
1706
1707         if (option_verbose > 1) 
1708                 ast_verbose(VERBOSE_PREFIX_2 " %s requested, got: [%s]\n",
1709                 name, tmp ? tmp->name : "None");
1710
1711         free(name);
1712
1713         restart_monitor();
1714         return tmp;
1715 }
1716
1717 static float parse_gain_value(char *gain_type, char *value)
1718 {
1719         float gain;
1720
1721         /* try to scan number */
1722         if (sscanf(value, "%f", &gain) != 1)
1723         {
1724                 ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n", value, gain_type, config);
1725                 return DEFAULT_GAIN;
1726         }
1727
1728
1729         /* percentage? */
1730         //if (value[strlen(value) - 1] == '%')
1731         //      return gain / (float)100;
1732
1733         return gain;
1734 }
1735
1736 int load_module()
1737 {
1738         struct ast_config *cfg;
1739         struct ast_variable *v;
1740         struct vpb_pvt *tmp;
1741         int board = 0, group = 0;
1742         int mode = MODE_IMMEDIATE;
1743         float txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN; 
1744         float txswgain = 0, rxswgain = 0; 
1745         int first_channel = 1;
1746         int echo_cancel = DEFAULT_ECHO_CANCEL;
1747         int error = 0; /* Error flag */
1748         int bal1 = -1; // Special value - means do not set
1749         int bal2 = -1; 
1750         int bal3 = -1;
1751         char * callerid = NULL;
1752
1753         cfg = ast_load(config);
1754
1755         /* We *must* have a config file otherwise stop immediately */
1756         if (!cfg) {
1757                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
1758                 return -1;
1759         }  
1760
1761         vpb_seterrormode(VPB_ERROR_CODE);
1762
1763         ast_mutex_lock(&iflock); {
1764                 v = ast_variable_browse(cfg, "interfaces");
1765                 while(v) {
1766                         /* Create the interface list */
1767                         if (strcasecmp(v->name, "board") == 0) {
1768                                 board = atoi(v->value);
1769                         } else  if (strcasecmp(v->name, "group") == 0){
1770                                 group = atoi(v->value);
1771                         } else  if (strcasecmp(v->name, "useloopdrop") == 0){
1772                                 UseLoopDrop = atoi(v->value);
1773                         } else if (strcasecmp(v->name, "channel") == 0) {
1774                                 int channel = atoi(v->value);
1775                                 tmp = mkif(board, channel, mode, txgain, rxgain, txswgain, rxswgain, bal1, bal2, bal3, callerid, echo_cancel,group);
1776                                 if (tmp) {
1777                                         if(first_channel) {
1778                                                 mkbrd( tmp->vpb_model, echo_cancel );
1779                                                 first_channel = 0;
1780                                         }
1781                                         tmp->next = iflist;
1782                                         iflist = tmp;
1783                                 } else {
1784                                         ast_log(LOG_ERROR, 
1785                                         "Unable to register channel '%s'\n", v->value);
1786                                         error = -1;
1787                                         goto done;
1788                                 }
1789                                 callerid = NULL;
1790                         } else if (strcasecmp(v->name, "language") == 0) {
1791                                 strncpy(language, v->value, sizeof(language)-1);
1792                         } else if (strcasecmp(v->name, "callerid") == 0) {
1793                                 callerid = strdup(v->value);
1794                         } else if (strcasecmp(v->name, "mode") == 0) {
1795                                 if (strncasecmp(v->value, "di", 2) == 0) 
1796                                         mode = MODE_DIALTONE;
1797                                 else if (strncasecmp(v->value, "im", 2) == 0)
1798                                         mode = MODE_IMMEDIATE;
1799                                 else if (strncasecmp(v->value, "fx", 2) == 0)
1800                                         mode = MODE_FXO;
1801                                 else
1802                                         ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
1803                         } else if (!strcasecmp(v->name, "context")) {
1804                                 strncpy(context, v->value, sizeof(context)-1);
1805                         } else if (!strcasecmp(v->name, "echocancel")) {
1806                                 if (!strcasecmp(v->value, "off")) 
1807                                         echo_cancel = 0;
1808                         } else if (strcasecmp(v->name, "txgain") == 0) {
1809                                 txswgain = parse_gain_value(v->name, v->value);
1810                         } else if (strcasecmp(v->name, "rxgain") == 0) {
1811                                 rxswgain = parse_gain_value(v->name, v->value);
1812                         } else if (strcasecmp(v->name, "txhwgain") == 0) {
1813                                 txgain = parse_gain_value(v->name, v->value);
1814                         } else if (strcasecmp(v->name, "rxhwgain") == 0) {
1815                                 rxgain = parse_gain_value(v->name, v->value);
1816                         } else if (strcasecmp(v->name, "bal1") == 0) {
1817                                 bal1 = strtol(v->value, NULL, 16);
1818                                 if(bal1<0 || bal1>255) {
1819                                         ast_log(LOG_WARNING, "Bad bal1 value: %d\n", bal1);
1820                                         bal1 = -1;
1821                                 }
1822                         } else if (strcasecmp(v->name, "bal2") == 0) {
1823                                 bal2 = strtol(v->value, NULL, 16);
1824                                 if(bal2<0 || bal2>255) {
1825                                         ast_log(LOG_WARNING, "Bad bal2 value: %d\n", bal2);
1826                                         bal2 = -1;
1827                                 }
1828                         } else if (strcasecmp(v->name, "bal3") == 0) {
1829                                 bal3 = strtol(v->value, NULL, 16);
1830                                 if(bal3<0 || bal3>255) {
1831                                         ast_log(LOG_WARNING, "Bad bal3 value: %d\n", bal3);
1832                                         bal3 = -1;
1833                                 }
1834                         } else if (strcasecmp(v->name, "grunttimeout") == 0) {
1835                                 gruntdetect_timeout = 1000*atoi(v->value);
1836                         }
1837                         v = v->next;
1838                 }
1839
1840                 if (gruntdetect_timeout < 1000)
1841                         gruntdetect_timeout = 1000;
1842
1843                 done: (void)0;
1844         } ast_mutex_unlock(&iflock);
1845
1846         ast_destroy(cfg);
1847
1848         if (!error && ast_channel_register(type, tdesc, prefformat, vpb_request) != 0) {
1849                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1850                 error = -1;
1851         }
1852
1853
1854         if (error)
1855                 unload_module();
1856         else 
1857                 restart_monitor(); /* And start the monitor for the first time */
1858
1859         return error;
1860 }
1861
1862
1863 int unload_module()
1864 {
1865         struct vpb_pvt *p;
1866         /* First, take us out of the channel loop */
1867         ast_channel_unregister(type);
1868
1869         ast_mutex_lock(&iflock); {
1870                 /* Hangup all interfaces if they have an owner */
1871                 p = iflist;
1872                 while(p) {
1873                         if (p->owner)
1874                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1875                         p = p->next;
1876                 }
1877                 iflist = NULL;
1878         } ast_mutex_unlock(&iflock);
1879
1880         ast_mutex_lock(&monlock); {
1881                 if (mthreadactive > -1) {
1882                         pthread_cancel(monitor_thread);
1883                         pthread_join(monitor_thread, NULL);
1884                 }
1885                 mthreadactive = -2;
1886         } ast_mutex_unlock(&monlock);
1887
1888         ast_mutex_lock(&iflock); {
1889                 /* Destroy all the interfaces and free their memory */
1890
1891                 while(iflist) {
1892                         p = iflist;                 
1893                         ast_mutex_destroy(&p->lock);
1894                         pthread_cancel(p->readthread);
1895                         ast_mutex_destroy(&p->record_lock);
1896                         ast_mutex_destroy(&p->play_lock);
1897                         ast_mutex_destroy(&p->play_dtmf_lock);
1898                         ast_mutex_destroy(&p->owner_lock);
1899                         p->readthread = 0;
1900
1901                         vpb_close(p->handle);
1902
1903                         iflist = iflist->next;
1904
1905                         free(p);
1906                 }
1907                 iflist = NULL;
1908         } ast_mutex_unlock(&iflock);
1909
1910         ast_mutex_lock(&bridge_lock); {
1911                 memset(bridges, 0, sizeof bridges);          
1912         } ast_mutex_unlock(&bridge_lock);
1913         ast_mutex_destroy(&bridge_lock);
1914         free(bridges);
1915
1916         return 0;
1917 }
1918
1919 int usecount()
1920 {
1921         int res;
1922         ast_mutex_lock(&usecnt_lock);
1923         res = usecnt;
1924         ast_mutex_unlock(&usecnt_lock);
1925         return res;
1926 }
1927
1928 char *description()
1929 {
1930         return desc;
1931 }
1932
1933 char *key()
1934 {
1935         return ASTERISK_GPL_KEY;
1936 }
1937
1938 #if defined(__cplusplus) || defined(c_plusplus)
1939  }
1940 #endif