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