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