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