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