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