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