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