/ updated so that it can deal with multiple matching in extensions, with
[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                         }
968                         break;
969
970                 case VPB_RING_OFF:
971                         break;
972
973                 case VPB_STATION_OFFHOOK:
974                         if (p->mode == MODE_IMMEDIATE) 
975                                 vpb_new(p,AST_STATE_RING, p->context);
976                         else {
977                                 ast_verbose(VERBOSE_PREFIX_4 "%s: handle_notowned: playing dialtone\n",p->dev);
978                                 playtone(p->handle, &Dialtone);
979                                 p->state=VPB_STATE_PLAYDIAL;
980                                 p->wantdtmf = 1;
981                                 p->ext[0] = 0;  /* Just to be sure & paranoid.*/
982                         }
983                         break;
984
985                 case VPB_DIALEND:
986                         if (p->mode == MODE_DIALTONE){
987                                 if (p->state == VPB_STATE_PLAYDIAL) {
988                                         playtone(p->handle, &Dialtone);
989                                         p->wantdtmf = 1;
990                                         p->ext[0] = 0;  /* Just to be sure & paranoid. */
991                                 }
992                                 /* These are not needed as they have timers to restart them
993                                 else if (p->state == VPB_STATE_PLAYBUSY) {
994                                         playtone(p->handle, &Busytone);
995                                         p->wantdtmf = 1;
996                                         p->ext[0] = 0;  
997                                 }
998                                 else if (p->state == VPB_STATE_PLAYRING) {
999                                         playtone(p->handle, &Ringbacktone);
1000                                         p->wantdtmf = 1;
1001                                         p->ext[0] = 0;
1002                                 }
1003                                 */
1004                         } else {
1005                                 ast_verbose(VERBOSE_PREFIX_4 "%s: handle_notowned: Got a DIALEND when not really expected\n",p->dev);
1006                         }
1007                         break;
1008
1009                 case VPB_STATION_ONHOOK:        /* clear ext */
1010                         stoptone(p->handle);
1011                         p->wantdtmf = 1 ;
1012                         p->ext[0] = 0;
1013                         p->state=VPB_STATE_ONHOOK;
1014                         break;
1015                 case VPB_TIMEREXP:
1016                         if (e->data == p->dtmfidd_timer_id) {
1017                                 if (ast_exists_extension(NULL, p->context, p->ext, 1, p->callerid)){
1018                                         if (option_verbose > 3)
1019                                                 ast_verbose(VERBOSE_PREFIX_4 "%s: handle_notowned: DTMF IDD timer out, matching on [%s] in [%s]\n", p->dev,p->ext , p->context);
1020                                         vpb_new(p,AST_STATE_RING, p->context);
1021                                 }
1022                         }
1023                         break;
1024
1025                 case VPB_DTMF:
1026                         if (p->state == VPB_STATE_ONHOOK){
1027                                 /* DTMF's being passed while on-hook maybe Caller ID */
1028                                 if ( p->mode == MODE_FXO ) {
1029                                         if ( e->data == DTMF_CID_START ) { /* CallerID Start signal */
1030                                                 p->dtmf_caller_pos = 0; /* Leaves the first digit out */
1031                                                 memset(p->callerid,0,AST_MAX_EXTENSION);
1032                                         }
1033                                         else if ( e->data == DTMF_CID_STOP ) { /* CallerID End signal */
1034                                                 p->callerid[p->dtmf_caller_pos] = '\0';
1035                                                 if (option_verbose > 2)
1036                                                         ast_verbose(VERBOSE_PREFIX_3 " %s: DTMF CallerID %s\n",p->dev,p->callerid);
1037                                                 if (owner){
1038                                                         /*
1039                                                         if (owner->cid.cid_num)
1040                                                                 free(owner->cid.cid_num);
1041                                                         owner->cid.cid_num=NULL;
1042                                                         if (owner->cid.cid_name)
1043                                                                 free(owner->cid.cid_name);
1044                                                         owner->cid.cid_name=NULL;
1045                                                         owner->cid.cid_num = strdup(p->callerid);
1046                                                         */
1047                                                         cid_name[0] = '\0';
1048                                                         cid_num[0] = '\0';
1049                                                         ast_callerid_split(p->callerid, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
1050                                                         ast_set_callerid(owner, cid_num, cid_name, cid_num);
1051
1052                                                 }
1053                                                 else {
1054                                                         if (option_verbose > 2)
1055                                                                 ast_verbose(VERBOSE_PREFIX_3 " %s: DTMF CallerID: no owner to assign CID \n",p->dev);
1056                                                 }
1057                                         } else if ( p->dtmf_caller_pos < AST_MAX_EXTENSION ) {
1058                                                 if ( p->dtmf_caller_pos >= 0 )
1059                                                         p->callerid[p->dtmf_caller_pos] = e->data;
1060                                                 p->dtmf_caller_pos++;
1061                                         }
1062                                 }
1063                                 break;
1064                         }
1065                         if (p->wantdtmf == 1) {
1066                                 stoptone(p->handle);
1067                                 p->wantdtmf = 0;
1068                         }
1069                         p->state=VPB_STATE_GETDTMF;
1070                         s[0] = e->data;
1071                         strncat(p->ext, s, sizeof(p->ext) - strlen(p->ext) - 1);
1072                         if (ast_exists_extension(NULL, p->context, p->ext, 1, p->callerid)){
1073                                 if ( ast_canmatch_extension(NULL, p->context, p->ext, 1, p->callerid)){
1074                                         if (option_verbose > 3)
1075                                                 ast_verbose(VERBOSE_PREFIX_4 "%s: handle_notowned: Multiple matches on [%s] in [%s]\n", p->dev,p->ext , p->context);
1076                                         /* Start DTMF IDD timer */
1077                                         vpb_timer_stop(p->dtmfidd_timer);
1078                                         vpb_timer_start(p->dtmfidd_timer);
1079                                 }
1080                                 else {
1081                                         if (option_verbose > 3)
1082                                                 ast_verbose(VERBOSE_PREFIX_4 "%s: handle_notowned: Matched on [%s] in [%s]\n", p->dev,p->ext , p->context);
1083                                         vpb_new(p,AST_STATE_RING, p->context);
1084                                 }
1085                         } else if (!ast_canmatch_extension(NULL, p->context, p->ext, 1, p->callerid)){
1086                                 if (ast_exists_extension(NULL, "default", p->ext, 1, p->callerid)) {
1087                                         vpb_new(p,AST_STATE_RING, "default");         
1088                                 } else if (!ast_canmatch_extension(NULL, "default", p->ext, 1, p->callerid)) {
1089                                         if (option_verbose > 3) {
1090                                                 ast_verbose(VERBOSE_PREFIX_4 "%s: handle_notowned: can't match anything in %s or default\n", p->dev, p->context);
1091                                         }
1092                                         playtone(p->handle, &Busytone);
1093                                         vpb_timer_stop(p->busy_timer);
1094                                         vpb_timer_start(p->busy_timer);
1095                                         p->state = VPB_STATE_PLAYBUSY;
1096                                 }
1097                         }
1098                         break;
1099
1100                 default:
1101                         /* Ignore.*/
1102                         break;
1103         }
1104
1105         if (option_verbose > 3) 
1106                 ast_verbose(VERBOSE_PREFIX_4 "%s: handle_notowned: mode=%d, [%d=>%d]\n",
1107                         p->dev, p->mode, e->type, e->data);
1108
1109         return 0;
1110 }
1111
1112 static void *do_monitor(void *unused)
1113 {
1114
1115         /* Monitor thread, doesn't die until explicitly killed. */
1116
1117         if (option_verbose > 1) 
1118                 ast_verbose(VERBOSE_PREFIX_2 "Starting vpb monitor thread[%ld]\n",
1119         pthread_self());
1120
1121         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
1122
1123         for(;;) {
1124                 VPB_EVENT e;
1125                 VPB_EVENT je;
1126                 char str[VPB_MAX_STR];
1127                 struct vpb_pvt *p;
1128
1129                 /*
1130                 if (option_verbose > 3)
1131                      ast_verbose(VERBOSE_PREFIX_4 "Monitor waiting for event\n");
1132                 */
1133
1134                 int res = vpb_get_event_sync(&e, VPB_WAIT_TIMEOUT);
1135                 if( (res==VPB_NO_EVENTS) || (res==VPB_TIME_OUT) ){
1136                         /*
1137                         if (option_verbose > 3){
1138                                 if (res ==  VPB_NO_EVENTS){
1139                                         ast_verbose(VERBOSE_PREFIX_4 "No events....\n");
1140                                 } else {
1141                                         ast_verbose(VERBOSE_PREFIX_4 "No events, timed out....\n");
1142                                 }
1143                         }
1144                         */
1145                         continue;
1146                 }
1147
1148                 if (res != VPB_OK) {
1149                         ast_log(LOG_ERROR,"Monitor get event error %s\n", vpb_strerror(res) );
1150                         ast_verbose("Monitor get event error %s\n", vpb_strerror(res) );
1151                         continue;
1152                 }
1153
1154                 str[0] = 0;
1155
1156                 p = NULL;
1157
1158                 ast_mutex_lock(&monlock); {
1159
1160                         if (e.type == VPB_NULL_EVENT) {
1161                                 if (option_verbose > 3)
1162                                         ast_verbose(VERBOSE_PREFIX_4 "Monitor got null event\n");
1163                         }
1164                         else {
1165                                 vpb_translate_event(&e, str);
1166                                 if (strlen(str)>1){
1167                                         str[(strlen(str)-1)]='\0';
1168                                 }
1169
1170                                 ast_mutex_lock(&iflock); {
1171                                         p = iflist;
1172                                         while (p && p->handle != e.handle)
1173                                                 p = p->next;
1174                                 } ast_mutex_unlock(&iflock);
1175
1176                                 if (p && (option_verbose > 3))
1177                                         ast_verbose(VERBOSE_PREFIX_4 "%s: Event [%d=>%s] \n", 
1178                                                 p ? p->dev : "null", e.type, str );
1179                         }
1180
1181                 } ast_mutex_unlock(&monlock); 
1182
1183                 if (!p) {
1184                         if (e.type != VPB_NULL_EVENT){
1185                                 ast_log(LOG_WARNING, "Got event [%s][%d], no matching iface!\n", str,e.type);    
1186                                 if (option_verbose > 3){
1187                                         ast_verbose(VERBOSE_PREFIX_4 "vpb/ERR: No interface for Event [%d=>%s] \n",e.type,str );
1188                                 }
1189                         }
1190                         continue;
1191                 } 
1192
1193                 /* flush the event from the channel event Q */
1194                 vpb_get_event_ch_async(e.handle,&je);
1195                 if (option_verbose > 4){
1196                         vpb_translate_event(&je, str);
1197                         ast_verbose("%s: Flushing event [%d]=>%s\n",p->dev,je.type,str);
1198                 }
1199
1200                 /* Check for ownership and locks */
1201                 if ((p->owner)&&(!p->golock)){
1202                         /* Need to get owner lock */
1203                         /* Safely grab both p->lock and p->owner->lock so that there
1204                         cannot be a race with something from the other side */
1205                         /*
1206                         ast_mutex_lock(&p->lock);
1207                         while(ast_mutex_trylock(&p->owner->lock)) {
1208                                 ast_mutex_unlock(&p->lock);
1209                                 usleep(1);
1210                                 ast_mutex_lock(&p->lock);
1211                                 if (!p->owner)
1212                                         break;
1213                         }
1214                         if (p->owner)
1215                                 p->golock=1;
1216                         */
1217                 }
1218                 /* Two scenarios: Are you owned or not. */
1219                 if (p->owner) {
1220                         monitor_handle_owned(p, &e);
1221                 } else {
1222                         monitor_handle_notowned(p, &e);
1223                 }
1224                 /* if ((!p->owner)&&(p->golock)){
1225                         ast_mutex_unlock(&p->owner->lock);
1226                         ast_mutex_unlock(&p->lock);
1227                 }
1228                 */
1229
1230         }
1231
1232         return NULL;
1233 }
1234
1235 static int restart_monitor(void)
1236 {
1237         int error = 0;
1238
1239         /* If we're supposed to be stopped -- stay stopped */
1240         if (mthreadactive == -2)
1241                 return 0;
1242
1243         if (option_verbose > 3)
1244                 ast_verbose(VERBOSE_PREFIX_4 "Restarting monitor\n");
1245
1246         ast_mutex_lock(&monlock); {
1247                 if (monitor_thread == pthread_self()) {
1248                         ast_log(LOG_WARNING, "Cannot kill myself\n");
1249                         error = -1;
1250                         if (option_verbose > 3)
1251                                 ast_verbose(VERBOSE_PREFIX_4 "Monitor trying to kill monitor\n");
1252                 }
1253                 else {
1254                         if (mthreadactive != -1) {
1255                                 /* Why do other drivers kill the thread? No need says I, simply awake thread with event. */
1256                                 VPB_EVENT e;
1257                                 e.handle = 0;
1258                                 e.type = VPB_NULL_EVENT;
1259                                 e.data = 0;
1260
1261                                 if (option_verbose > 3)
1262                                         ast_verbose(VERBOSE_PREFIX_4 "Trying to reawake monitor\n");
1263
1264                                 vpb_put_event(&e);
1265                         } else {
1266                                 /* Start a new monitor */
1267                                 int pid = ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL); 
1268                                 if (option_verbose > 3)
1269                                         ast_verbose(VERBOSE_PREFIX_4 "Created new monitor thread %d\n",pid);
1270                                 if (pid < 0) {
1271                                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1272                                         error = -1;
1273                                 } else
1274                                         mthreadactive = 0; /* Started the thread!*/
1275                         }
1276                 }
1277         } ast_mutex_unlock(&monlock);
1278
1279         if (option_verbose > 3)
1280                 ast_verbose(VERBOSE_PREFIX_4 "Monitor restarted\n");
1281
1282         return error;
1283 }
1284
1285 /* Per board config that must be called after vpb_open() */
1286 static void mkbrd(vpb_model_t model, int echo_cancel)
1287 {
1288         if(!bridges) {
1289                 if(model==vpb_model_v4pci) 
1290                         max_bridges = MAX_BRIDGES_V4PCI;
1291                 bridges = (vpb_bridge_t *)malloc(max_bridges * sizeof(vpb_bridge_t) );
1292                 if(!bridges) 
1293                         ast_log(LOG_ERROR, "Failed to initialize bridges\n");
1294                 else {
1295                         memset(bridges,0,max_bridges * sizeof(vpb_bridge_t));
1296                         for(int i = 0; i < max_bridges; i++ ) {
1297                                 ast_mutex_init(&bridges[i].lock);
1298                                 pthread_cond_init(&bridges[i].cond, NULL);
1299                         }
1300                 }
1301         }
1302         if(!echo_cancel) {
1303                 if (model==vpb_model_v4pci) {
1304                         vpb_echo_canc_disable();
1305                         ast_log(LOG_NOTICE, "Voicetronix echo cancellation OFF\n");
1306                 } 
1307                 else {
1308                 /* need to it port by port for OpenSwitch*/
1309                 }
1310         } else {
1311                 if (model==vpb_model_v4pci) {
1312                         vpb_echo_canc_enable();
1313                         ast_log(LOG_NOTICE, "Voicetronix echo cancellation ON\n");
1314                         if (ec_supp_threshold > -1){
1315                                 vpb_echo_canc_set_sup_thresh((short *)&ec_supp_threshold);
1316                                 ast_log(LOG_NOTICE, "Voicetronix EC Sup Thres set\n");
1317                         }
1318                 }
1319                 else {
1320                 /* need to it port by port for OpenSwitch*/
1321                 }
1322         }
1323 }
1324
1325 static struct vpb_pvt *mkif(int board, int channel, int mode, float txgain, float rxgain,
1326                          float txswgain, float rxswgain, int bal1, int bal2, int bal3,
1327                          char * callerid, int echo_cancel, int group )
1328 {
1329         struct vpb_pvt *tmp;
1330         char buf[64];
1331
1332         tmp = (struct vpb_pvt *)calloc(1, sizeof *tmp);
1333
1334         if (!tmp)
1335                 return NULL;
1336
1337         tmp->handle = vpb_open(board, channel);
1338
1339         if (tmp->handle < 0) {    
1340                 ast_log(LOG_WARNING, "Unable to create channel vpb/%d-%d: %s\n", 
1341                                         board, channel, strerror(errno));
1342                 free(tmp);
1343                 return NULL;
1344         }
1345                
1346         snprintf(tmp->dev, sizeof(tmp->dev), "vpb/%d-%d", board, channel);
1347
1348         tmp->mode = mode;
1349
1350         tmp->group = group;
1351
1352         /* Initilize dtmf caller ID position variable */
1353         tmp->dtmf_caller_pos=0;
1354
1355         strncpy(tmp->language, language, sizeof(tmp->language) - 1);
1356         strncpy(tmp->context, context, sizeof(tmp->context) - 1);
1357
1358         tmp->callerid_type=0;
1359         if(callerid) { 
1360                 if (strcasecmp(callerid,"on")==0){
1361                         tmp->callerid_type =1;
1362                         strncpy(tmp->callerid, "unknown", sizeof(tmp->callerid) - 1);
1363                 }
1364                 else if (strcasecmp(callerid,"v23")==0){
1365                         tmp->callerid_type =2;
1366                         strncpy(tmp->callerid, "unknown", sizeof(tmp->callerid) - 1);
1367                 }
1368                 else if (strcasecmp(callerid,"bell")==0){
1369                         tmp->callerid_type =3;
1370                         strncpy(tmp->callerid, "unknown", sizeof(tmp->callerid) - 1);
1371                 }
1372                 else {
1373                         strncpy(tmp->callerid, callerid, sizeof(tmp->callerid) - 1);
1374                 }
1375         } else {
1376                 strncpy(tmp->callerid, "unknown", sizeof(tmp->callerid) - 1);
1377         }
1378
1379         /* check if codec balances have been set in the config file */
1380         if (bal3>=0) {
1381                 if ((bal1>=0) && !(bal1 & 32)) bal1 |= 32;
1382                         vpb_set_codec_reg(tmp->handle, 0x42, bal3);
1383         }
1384         if(bal1>=0) vpb_set_codec_reg(tmp->handle, 0x32, bal1);
1385         if(bal2>=0) vpb_set_codec_reg(tmp->handle, 0x3a, bal2);
1386
1387         tmp->txgain = txgain;
1388         vpb_play_set_hw_gain(tmp->handle, (txgain > MAX_VPB_GAIN) ? MAX_VPB_GAIN : txgain);
1389
1390         tmp->rxgain = rxgain;
1391         vpb_record_set_hw_gain(tmp->handle, (rxgain > MAX_VPB_GAIN) ? MAX_VPB_GAIN : rxgain);
1392
1393         tmp->txswgain = txswgain;
1394         vpb_play_set_gain(tmp->handle, (txswgain > MAX_VPB_GAIN) ? MAX_VPB_GAIN : txswgain);
1395
1396         tmp->rxswgain = rxswgain;
1397         vpb_record_set_gain(tmp->handle, (rxswgain > MAX_VPB_GAIN) ? MAX_VPB_GAIN : rxswgain);
1398
1399         tmp->vpb_model = vpb_model_unknown;
1400         if( vpb_get_model(buf) == VPB_OK ) {
1401                 if(strcmp(buf,"V12PCI")==0) 
1402                         tmp->vpb_model = vpb_model_v12pci;
1403                 else if(strcmp(buf,"VPB4")==0) 
1404                         tmp->vpb_model = vpb_model_v4pci;
1405         }
1406
1407         ast_mutex_init(&tmp->owner_lock);
1408         ast_mutex_init(&tmp->lock);
1409         ast_mutex_init(&tmp->record_lock);
1410         ast_mutex_init(&tmp->play_lock);
1411         ast_mutex_init(&tmp->play_dtmf_lock);
1412
1413         /* set default read state */
1414         tmp->read_state = 0;
1415         
1416         tmp->golock=0;
1417
1418         tmp->busy_timer_id = vpb_timer_get_unique_timer_id();
1419         vpb_timer_open(&tmp->busy_timer, tmp->handle, tmp->busy_timer_id, TIMER_PERIOD_BUSY);
1420
1421         tmp->ringback_timer_id = vpb_timer_get_unique_timer_id();
1422         vpb_timer_open(&tmp->ringback_timer, tmp->handle, tmp->ringback_timer_id, TIMER_PERIOD_RINGBACK);
1423
1424         tmp->ring_timer_id = vpb_timer_get_unique_timer_id();
1425         vpb_timer_open(&tmp->ring_timer, tmp->handle, tmp->ring_timer_id, TIMER_PERIOD_RING);
1426               
1427         tmp->dtmfidd_timer_id = vpb_timer_get_unique_timer_id();
1428         vpb_timer_open(&tmp->dtmfidd_timer, tmp->handle, tmp->dtmfidd_timer_id, dtmf_idd);
1429               
1430         if (mode == MODE_FXO){
1431                 vpb_set_event_mask(tmp->handle, VPB_EVENTS_ALL );
1432         }
1433         else {
1434                 vpb_set_event_mask(tmp->handle, VPB_EVENTS_STAT );
1435         }
1436
1437         if ((tmp->vpb_model == vpb_model_v12pci) && (echo_cancel)){
1438                 vpb_hostecho_on(tmp->handle);
1439         }
1440
1441         /* define grunt tone */
1442         vpb_settonedet(tmp->handle,&toned_ungrunt);
1443
1444         ast_log(LOG_NOTICE,"Voicetronix %s channel %s initialized (rxgain=%f txgain=%f) (%f/%f/0x%X/0x%X/0x%X)\n",
1445                 (tmp->vpb_model==vpb_model_v4pci)?"V4PCI":
1446                 (tmp->vpb_model==vpb_model_v12pci)?"V12PCI":"[Unknown model]",
1447                 tmp->dev, tmp->rxswgain, tmp->txswgain, tmp->rxgain, tmp->txgain, bal1, bal2, bal3 );
1448
1449         return tmp;
1450 }
1451
1452 static int vpb_indicate(struct ast_channel *ast, int condition)
1453 {
1454         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
1455         int res = 0;
1456         int tmp = 0;
1457
1458         if (option_verbose > 3)
1459                 ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_indicate [%d] state[%d]\n", p->dev, condition,ast->_state);
1460 /*
1461         if (ast->_state != AST_STATE_UP) {
1462                 ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_indicate Not in AST_STATE_UP\n", p->dev, condition,ast->_state);
1463                 return res;
1464         }
1465 */
1466
1467 /*
1468         if (option_verbose > 3) ast_verbose("%s: LOCKING in indicate \n", p->dev);
1469         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1470 */
1471         ast_mutex_lock(&p->lock);
1472         switch(condition) {
1473                 case AST_CONTROL_BUSY:
1474                 case AST_CONTROL_CONGESTION:
1475                         if (ast->_state == AST_STATE_UP) {
1476                                 playtone(p->handle, &Busytone);
1477                                 p->state = VPB_STATE_PLAYBUSY;
1478                                 vpb_timer_stop(p->busy_timer); 
1479                                 vpb_timer_start(p->busy_timer); 
1480                         }
1481                         break;
1482                 case AST_CONTROL_RINGING:
1483                         if (ast->_state == AST_STATE_UP) {
1484                                 playtone(p->handle, &Ringbacktone);
1485                                 p->state = VPB_STATE_PLAYRING;
1486                                 if (option_verbose > 3)
1487                                         ast_verbose(VERBOSE_PREFIX_4 "%s: vpb indicate: setting ringback timer [%d]\n", p->dev,p->ringback_timer_id);
1488                                 
1489                                 vpb_timer_stop(p->ringback_timer);
1490                                 vpb_timer_start(p->ringback_timer);
1491                         }
1492                         break;      
1493                 case AST_CONTROL_ANSWER:
1494                 case -1: /* -1 means stop playing? */
1495                         vpb_timer_stop(p->ringback_timer);
1496                         vpb_timer_stop(p->busy_timer);
1497                         stoptone(p->handle);
1498                         break;
1499                 case AST_CONTROL_HANGUP:
1500                         if (ast->_state == AST_STATE_UP) {
1501                                 playtone(p->handle, &Busytone);
1502                                 p->state = VPB_STATE_PLAYBUSY;
1503                                 vpb_timer_stop(p->busy_timer);
1504                                 vpb_timer_start(p->busy_timer);
1505                         }
1506                         break;
1507
1508                 default:
1509                         res = 0;
1510                         break;
1511         }
1512         tmp = ast_mutex_unlock(&p->lock);
1513 /*
1514         if (option_verbose > 3) ast_verbose("%s: unLOCKING in indicate [%d]\n", p->dev,tmp);
1515 */
1516         return res;
1517 }
1518
1519 static int vpb_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1520 {
1521         struct vpb_pvt *p = (struct vpb_pvt *)newchan->pvt->pvt;
1522         int res = 0;
1523
1524 /*
1525         if (option_verbose > 3) ast_verbose("%s: LOCKING in fixup \n", p->dev);
1526         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1527 */
1528         ast_mutex_lock(&p->lock);
1529         ast_log(LOG_DEBUG, "New owner for channel %s is %s\n", p->dev, newchan->name);
1530
1531         if (p->owner == oldchan) {
1532                 p->owner = newchan;
1533         }
1534
1535         if (newchan->_state == AST_STATE_RINGING){
1536                 if (use_ast_ind == 1)
1537                         ast_indicate(newchan, AST_CONTROL_RINGING);
1538                 else
1539                         vpb_indicate(newchan, AST_CONTROL_RINGING);
1540         }
1541
1542         res= ast_mutex_unlock(&p->lock);
1543 /*
1544         if (option_verbose > 3) ast_verbose("%s: unLOCKING in fixup [%d]\n", p->dev,res);
1545 */
1546         return 0;
1547 }
1548
1549 static int vpb_digit(struct ast_channel *ast, char digit)
1550 {
1551         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
1552         char s[2];
1553         int res = 0;
1554
1555 /*
1556         if (option_verbose > 3) ast_verbose("%s: LOCKING in digit \n", p->dev);
1557         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1558 */
1559         ast_mutex_lock(&p->lock);
1560
1561
1562         s[0] = digit;
1563         s[1] = '\0';
1564
1565         if (option_verbose > 3)
1566                 ast_verbose(VERBOSE_PREFIX_4 "%s: play digit[%s]\n", p->dev, s);
1567
1568         ast_mutex_lock(&p->play_dtmf_lock);
1569         strncat(p->play_dtmf,s,sizeof(*p->play_dtmf));
1570         ast_mutex_unlock(&p->play_dtmf_lock);
1571
1572         res = ast_mutex_unlock(&p->lock);
1573 /*
1574         if (option_verbose > 3) ast_verbose("%s: unLOCKING in digit [%d]\n", p->dev,res);
1575 */
1576         return 0;
1577 }
1578
1579 /* Places a call out of a VPB channel */
1580 static int vpb_call(struct ast_channel *ast, char *dest, int timeout)
1581 {
1582         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
1583         int res = 0,i;
1584         char *s = strrchr(dest, '/');
1585         char dialstring[254] = "";
1586         int tmp = 0;
1587
1588 /*
1589         if (option_verbose > 3) ast_verbose("%s: LOCKING in call \n", p->dev);
1590         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1591 */
1592         ast_mutex_lock(&p->lock);
1593
1594         if (s)
1595                 s = s + 1;
1596         else
1597                 s = dest;
1598         strncpy(dialstring, s, sizeof(dialstring) - 1);
1599         for (i=0; dialstring[i] != '\0' ; i++) {
1600                 if ((dialstring[i] == 'w') || (dialstring[i] == 'W'))
1601                         dialstring[i] = ',';
1602                 else if ((dialstring[i] == 'f') || (dialstring[i] == 'F'))
1603                         dialstring[i] = '&';
1604         }       
1605         if (option_verbose > 3)
1606                 ast_verbose(VERBOSE_PREFIX_4 "%s: starting call\n", p->dev);
1607
1608         if (ast->_state != AST_STATE_DOWN && ast->_state != AST_STATE_RESERVED) {
1609                 ast_log(LOG_WARNING, "vpb_call on %s neither down nor reserved!\n", ast->name);
1610                 tmp = ast_mutex_unlock(&p->lock);
1611 /*
1612                 if (option_verbose > 3) ast_verbose("%s: unLOCKING in call [%d]\n", p->dev,tmp);
1613 */
1614                 return -1;
1615         }
1616         if (p->mode != MODE_FXO)  /* Station port, ring it. */
1617                 res = vpb_ring_station_async(p->handle, VPB_RING_STATION_ON,0);       
1618         else {
1619                 VPB_CALL call;
1620
1621                 /* Dial must timeout or it can leave channels unuseable */
1622                 if( timeout == 0 )
1623                         timeout = TIMER_PERIOD_NOANSWER;
1624                 else 
1625                         timeout = timeout * 1000; /* convert from secs to ms. */
1626
1627                 /* These timeouts are only used with call progress dialing */
1628                 call.dialtones = 1; /* Number of dialtones to get outside line */
1629                 call.dialtone_timeout = VPB_DIALTONE_WAIT; /* Wait this long for dialtone (ms) */
1630                 call.ringback_timeout = VPB_RINGWAIT; /* Wait this long for ringing after dialing (ms) */
1631                 call.inter_ringback_timeout = VPB_CONNECTED_WAIT; /* If ringing stops for this long consider it connected (ms) */
1632                 call.answer_timeout = timeout; /* Time to wait for answer after ringing starts (ms) */
1633                 memcpy( &call.tone_map,  DialToneMap, sizeof(DialToneMap) );
1634                 vpb_set_call(p->handle, &call);
1635
1636                 if (option_verbose > 1)
1637                         ast_verbose(VERBOSE_PREFIX_2 "%s: Calling %s on %s \n",p->dev, dialstring, ast->name); 
1638
1639                 if (option_verbose > 2) {
1640                         int j;
1641                         ast_verbose(VERBOSE_PREFIX_2 "%s: Dial parms for %s %d/%dms/%dms/%dms/%dms\n", p->dev
1642                                 , ast->name, call.dialtones, call.dialtone_timeout
1643                                 , call.ringback_timeout, call.inter_ringback_timeout
1644                                 , call.answer_timeout );
1645                         for( j=0; !call.tone_map[j].terminate; j++ )
1646                                 ast_verbose(VERBOSE_PREFIX_2 "%s: Dial parms for %s tone %d->%d\n", p->dev,
1647                                         ast->name, call.tone_map[j].tone_id, call.tone_map[j].call_id); 
1648                 }
1649
1650                 if (option_verbose > 4)
1651                                 ast_verbose("%s: Disabling Loop Drop detection\n",p->dev);
1652                 vpb_disable_event(p->handle, VPB_MDROP);
1653                 vpb_sethook_sync(p->handle,VPB_OFFHOOK);
1654                 p->state=VPB_STATE_OFFHOOK;
1655
1656                 #ifndef DIAL_WITH_CALL_PROGRESS
1657                 vpb_sleep(300);
1658                 if (option_verbose > 4)
1659                                 ast_verbose("%s: Disabling Loop Drop detection\n",p->dev);
1660                 vpb_enable_event(p->handle, VPB_MDROP);
1661                 res = vpb_dial_async(p->handle, dialstring);
1662                 #else
1663                 if (option_verbose > 4)
1664                                 ast_verbose("%s: Disabling Loop Drop detection\n",p->dev);
1665                 vpb_enable_event(p->handle, VPB_MDROP);
1666                 res = vpb_call_async(p->handle, dialstring);
1667                 #endif
1668
1669                 if (res != VPB_OK) {
1670                         ast_log(LOG_DEBUG, "Call on %s to %s failed: %s\n", ast->name, s, vpb_strerror(res));         
1671                         res = -1;
1672                 } else 
1673                         res = 0;
1674         }
1675
1676         if (option_verbose > 2)
1677                 ast_verbose(VERBOSE_PREFIX_3 "%s: VPB Calling %s [t=%d] on %s returned %d\n",p->dev , s, timeout, ast->name, res); 
1678         if (res == 0) {
1679                 ast_setstate(ast, AST_STATE_RINGING);
1680                 ast_queue_control(ast,AST_CONTROL_RINGING);             
1681         }
1682
1683         if (!p->readthread){
1684                 ast_pthread_create(&p->readthread, NULL, do_chanreads, (void *)p);
1685         }
1686
1687         tmp = ast_mutex_unlock(&p->lock);
1688 /*
1689         if (option_verbose > 3) ast_verbose("%s: unLOCKING in call [%d]\n", p->dev,tmp);
1690 */
1691         return res;
1692 }
1693
1694 static int vpb_hangup(struct ast_channel *ast)
1695 {
1696         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
1697         VPB_EVENT je;
1698         char str[VPB_MAX_STR];
1699         int res =0 ;
1700
1701 /*
1702         if (option_verbose > 3) ast_verbose("%s: LOCKING in hangup \n", p->dev);
1703         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);
1704         if (option_verbose > 3) ast_verbose("%s: LOCKING pthread_self(%d)\n", p->dev,pthread_self());
1705         ast_mutex_lock(&p->lock);
1706 */
1707         if (option_verbose > 1) 
1708                 ast_verbose(VERBOSE_PREFIX_2 "%s: Hangup requested\n", ast->name);
1709
1710         if (!ast->pvt || !ast->pvt->pvt) {
1711                 ast_log(LOG_WARNING, "%s: channel not connected?\n", ast->name);
1712                 res = ast_mutex_unlock(&p->lock);
1713 /*
1714                 if (option_verbose > 3) ast_verbose("%s: unLOCKING in hangup [%d]\n", p->dev,res);
1715 */
1716                 return 0;
1717         }
1718
1719
1720
1721         /* Stop record */
1722         p->stopreads = 1;
1723         if( p->readthread ){
1724                 pthread_join(p->readthread, NULL); 
1725                 if(option_verbose>3) 
1726                         ast_verbose( VERBOSE_PREFIX_4 "%s: stopped record thread on %s\n",ast->name,p->dev);
1727         }
1728
1729         /* Stop play */
1730         if (p->lastoutput != -1) {
1731                 if(option_verbose>1) 
1732                         ast_verbose( VERBOSE_PREFIX_2 "%s: Ending play mode on %s\n",ast->name,p->dev);
1733                 vpb_play_terminate(p->handle);
1734                 ast_mutex_lock(&p->play_lock); {
1735                         vpb_play_buf_finish(p->handle);
1736                 } ast_mutex_unlock(&p->play_lock);
1737         }
1738
1739         if(option_verbose>3) 
1740                 ast_verbose( VERBOSE_PREFIX_4 "%s: Setting state down\n",ast->name);
1741         ast_setstate(ast,AST_STATE_DOWN);
1742
1743
1744 /*
1745         if (option_verbose > 3) ast_verbose("%s: LOCKING in hangup \n", p->dev);
1746         if (option_verbose > 3) ast_verbose("%s: LOCKING in hangup count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1747         if (option_verbose > 3) ast_verbose("%s: LOCKING pthread_self(%d)\n", p->dev,pthread_self());
1748 */
1749         ast_mutex_lock(&p->lock);
1750
1751         if (p->mode != MODE_FXO) { 
1752                 /* station port. */
1753                 vpb_ring_station_async(p->handle, VPB_RING_STATION_OFF,0);      
1754                 if(p->state!=VPB_STATE_ONHOOK){
1755                         /* This is causing a "dial end" "play tone" loop
1756                         playtone(p->handle, &Busytone); 
1757                         p->state = VPB_STATE_PLAYBUSY;
1758                         if(option_verbose>4) 
1759                                 ast_verbose( VERBOSE_PREFIX_4 "%s: Station offhook[%d], playing busy tone\n",
1760                                                                 ast->name,p->state);
1761                         */
1762                 }
1763                 else {
1764                         stoptone(p->handle);
1765                 }
1766         } else {
1767                 stoptone(p->handle); /* Terminates any dialing */
1768                 vpb_sethook_sync(p->handle, VPB_ONHOOK);
1769                 p->state=VPB_STATE_ONHOOK;
1770         }
1771         while (VPB_OK==vpb_get_event_ch_async(p->handle,&je)){
1772                 if(option_verbose>3) {
1773                         vpb_translate_event(&je, str);
1774                         ast_verbose( VERBOSE_PREFIX_4 "%s: Flushing event [%d]=>%s\n",ast->name,je.type,str);
1775                 }
1776         }
1777
1778         p->readthread = 0;
1779         p->lastoutput = -1;
1780         p->lastinput = -1;
1781         p->last_ignore_dtmf = 1;
1782         p->ext[0]  = 0;
1783         p->dialtone = 0;
1784
1785         p->owner = NULL;
1786         ast->pvt->pvt=NULL;
1787
1788         ast_mutex_lock(&usecnt_lock); {
1789                 usecnt--;
1790         } ast_mutex_unlock(&usecnt_lock);
1791         ast_update_use_count();
1792
1793         if (option_verbose > 1)
1794                 ast_verbose(VERBOSE_PREFIX_2 "%s: Hangup complete\n", ast->name);
1795
1796         restart_monitor();
1797 /*
1798         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);
1799 */
1800         res = ast_mutex_unlock(&p->lock);
1801 /*
1802         if (option_verbose > 3) ast_verbose("%s: unLOCKING in hangup [%d]\n", p->dev,res);
1803         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);
1804 */
1805         return 0;
1806 }
1807
1808 static int vpb_answer(struct ast_channel *ast)
1809 {
1810         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt;
1811         VPB_EVENT je;
1812         int ret;
1813         int res = 0;
1814 /*
1815         if (option_verbose > 3) ast_verbose("%s: LOCKING in answer \n", p->dev);
1816         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1817 */
1818         ast_mutex_lock(&p->lock);
1819
1820         if (option_verbose > 3)
1821                         ast_verbose(VERBOSE_PREFIX_4 "%s: Answering channel\n",p->dev);
1822
1823         if (p->mode == MODE_FXO){
1824                 if (option_verbose > 3)
1825                                 ast_verbose("%s: Disabling Loop Drop detection\n",p->dev);
1826                 vpb_disable_event(p->handle, VPB_MDROP);
1827         }
1828
1829         if (ast->_state != AST_STATE_UP) {
1830                 if (p->mode == MODE_FXO){
1831                         vpb_sethook_sync(p->handle, VPB_OFFHOOK);
1832                         p->state=VPB_STATE_OFFHOOK;
1833 /*                      vpb_sleep(500);
1834                         ret = vpb_get_event_ch_async(p->handle,&je);
1835                         if ((ret == VPB_OK)&&((je.type != VPB_DROP)&&(je.type != VPB_RING))){
1836                                 if (option_verbose > 3){
1837                                                 ast_verbose(VERBOSE_PREFIX_4 "%s: Answer collected a wrong event!!\n",p->dev);
1838                                 }
1839                                 vpb_put_event(&je);
1840                         }
1841 */
1842                 }
1843                 ast_setstate(ast, AST_STATE_UP);
1844
1845                 if(option_verbose>1) 
1846 /*
1847                         ast_verbose( VERBOSE_PREFIX_2 "%s: Answered call from %s on %s [%s]\n", p->dev, 
1848                                         p->owner->callerid, ast->name,(p->mode == MODE_FXO)?"FXO":"FXS"); 
1849 */
1850                         ast_verbose( VERBOSE_PREFIX_2 "%s: Answered call on %s [%s]\n", p->dev,
1851                                          ast->name,(p->mode == MODE_FXO)?"FXO":"FXS");
1852
1853                 ast->rings = 0;
1854                 if( !p->readthread ){
1855         /*              res = ast_mutex_unlock(&p->lock); */
1856         /*              ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res); */
1857                         ast_pthread_create(&p->readthread, NULL, do_chanreads, (void *)p);
1858                 } else {
1859                         if(option_verbose>3) 
1860                                 ast_verbose(VERBOSE_PREFIX_4 "%s: Record thread already running!!\n",p->dev);
1861                 }
1862         } else {
1863                 if(option_verbose>3) {
1864                         ast_verbose(VERBOSE_PREFIX_4 "%s: Answered state is up\n",p->dev);
1865                 }
1866         /*      res = ast_mutex_unlock(&p->lock); */
1867         /*      ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res); */
1868         }
1869         vpb_sleep(500);
1870         if (p->mode == MODE_FXO){
1871                 if (option_verbose > 3)
1872                                 ast_verbose("%s: Re-enabling Loop Drop detection\n",p->dev);
1873                 vpb_enable_event(p->handle,VPB_MDROP);
1874         }
1875         res = ast_mutex_unlock(&p->lock);
1876 /*
1877         if(option_verbose>3) ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res);
1878 */
1879         return 0;
1880 }
1881
1882 static struct ast_frame  *vpb_read(struct ast_channel *ast)
1883 {
1884         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt; 
1885         static struct ast_frame f = {AST_FRAME_NULL}; 
1886
1887         f.src = type;
1888         ast_log(LOG_NOTICE, "%s: vpb_read: should never be called!\n", p->dev);
1889         ast_verbose("%s: vpb_read: should never be called!\n", p->dev);
1890
1891         return &f;
1892 }
1893
1894 static inline int ast2vpbformat(int ast_format)
1895 {
1896         switch(ast_format) {
1897                 case AST_FORMAT_ALAW:
1898                         return VPB_ALAW;
1899                 case AST_FORMAT_SLINEAR:
1900                         return VPB_LINEAR;
1901                 case AST_FORMAT_ULAW:
1902                         return VPB_MULAW;
1903                 case AST_FORMAT_ADPCM:
1904                         return VPB_OKIADPCM;
1905                 default:
1906                         return -1;
1907         }
1908 }
1909
1910 static inline char * ast2vpbformatname(int ast_format)
1911 {
1912         switch(ast_format) {
1913                 case AST_FORMAT_ALAW:
1914                         return "AST_FORMAT_ALAW:VPB_ALAW";
1915                 case AST_FORMAT_SLINEAR:
1916                         return "AST_FORMAT_SLINEAR:VPB_LINEAR";
1917                 case AST_FORMAT_ULAW:
1918                         return "AST_FORMAT_ULAW:VPB_MULAW";
1919                 case AST_FORMAT_ADPCM:
1920                         return "AST_FORMAT_ADPCM:VPB_OKIADPCM";
1921                 default:
1922                         return "UNKN:UNKN";
1923         }
1924 }
1925
1926 static inline int astformatbits(int ast_format)
1927 {
1928         switch(ast_format) {
1929                 case AST_FORMAT_ALAW:
1930                 case AST_FORMAT_ULAW:
1931                         return 8;
1932                 case AST_FORMAT_SLINEAR:
1933                         return 16;
1934                 case AST_FORMAT_ADPCM:
1935                         return 4;
1936                 default:
1937                         return 8;
1938         }   
1939 }
1940
1941 int a_gain_vector(float g, short *v, int n) 
1942 {
1943         int i;
1944         float tmp;
1945         for ( i = 0; i<n; i++) {
1946                 tmp = g*v[i];
1947                 if (tmp > 32767.0)
1948                         tmp = 32767.0;
1949                 if (tmp < -32768.0)
1950                         tmp = -32768.0;
1951                 v[i] = (short)tmp;      
1952         }  
1953         return(i);
1954 }
1955
1956 /* Writes a frame of voice data to a VPB channel */
1957 static int vpb_write(struct ast_channel *ast, struct ast_frame *frame)
1958 {
1959         struct vpb_pvt *p = (struct vpb_pvt *)ast->pvt->pvt; 
1960         int res = 0, fmt = 0;
1961         struct timeval play_buf_time_start,play_buf_time_finish;
1962 /*      ast_mutex_lock(&p->lock); */
1963         if(option_verbose>5) 
1964                 ast_verbose("%s: vpb_write: Writing to channel\n", p->dev);
1965
1966         if (frame->frametype != AST_FRAME_VOICE) {
1967                 if(option_verbose>3) 
1968                         ast_verbose("%s: vpb_write: Don't know how to handle from type %d\n", ast->name, frame->frametype);
1969 /*              ast_mutex_unlock(&p->lock); */
1970                 return 0;
1971         } else if (ast->_state != AST_STATE_UP) {
1972                 if(option_verbose>3) 
1973                         ast_verbose("%s: vpb_write: Attempt to Write frame type[%d]subclass[%d] on not up chan\n",ast->name, frame->frametype, frame->subclass);
1974                 p->lastoutput = -1;
1975 /*              ast_mutex_unlock(&p->lock); */
1976                 return 0;
1977         }
1978 /*      ast_log(LOG_DEBUG, "%s: vpb_write: Checked frame type..\n", p->dev); */
1979
1980         fmt = ast2vpbformat(frame->subclass);
1981         if (fmt < 0) {
1982                 ast_log(LOG_WARNING, "%s: vpb_write: Cannot handle frames of %d format!\n",ast->name, frame->subclass);
1983                 return -1;
1984         }
1985 /*      ast_log(LOG_DEBUG, "%s: vpb_write: Checked frame format..\n", p->dev); */
1986
1987         ast_mutex_lock(&p->play_lock);
1988
1989 /*      ast_log(LOG_DEBUG, "%s: vpb_write: Got play lock..\n", p->dev); */
1990
1991         /* Check if we have set up the play_buf */
1992         if (p->lastoutput == -1) {
1993                 vpb_play_buf_start(p->handle, fmt);
1994                 if(option_verbose>1) {
1995                         ast_verbose("%s: vpb_write: Starting play mode (codec=%d)[%s]\n",p->dev,fmt,ast2vpbformatname(frame->subclass));
1996                 }
1997         } else if (p->lastoutput != fmt) {
1998                 vpb_play_buf_finish(p->handle);
1999                 vpb_play_buf_start(p->handle, fmt);
2000                 if(option_verbose>1) 
2001                         ast_verbose("%s: vpb_write: Changed play format (%d=>%d)\n",p->dev,p->lastoutput,fmt);
2002         }
2003         p->lastoutput = fmt;
2004
2005
2006
2007         /* Apply extra gain ! */
2008         if( p->txswgain > MAX_VPB_GAIN )
2009                 a_gain_vector(p->txswgain - MAX_VPB_GAIN , (short*)frame->data, frame->datalen/sizeof(short));
2010
2011 /*      ast_log(LOG_DEBUG, "%s: vpb_write: Applied gain..\n", p->dev); */
2012
2013 /*      gettimeofday(&tv, NULL); */
2014 /*      return ((double)tv.tv_sec*1000)+((double)tv.tv_usec/1000); */
2015
2016         if ((p->read_state == 1)&&(p->play_buf_time<5)){
2017         gettimeofday(&play_buf_time_start,NULL);
2018         res = vpb_play_buf_sync(p->handle, (char*)frame->data, frame->datalen);
2019         if( (res == VPB_OK) && (option_verbose > 5) ) {
2020                 short * data = (short*)frame->data;
2021                 ast_verbose("%s: vpb_write: Wrote chan (codec=%d) %d %d\n", p->dev, fmt, data[0],data[1]);
2022         }
2023         gettimeofday(&play_buf_time_finish,NULL);
2024         if (play_buf_time_finish.tv_sec == play_buf_time_start.tv_sec){
2025                 p->play_buf_time=(int)((play_buf_time_finish.tv_usec-play_buf_time_start.tv_usec)/1000);
2026 /*              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); */
2027         }
2028         else {
2029                 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);
2030         }
2031 /*      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); */
2032         }
2033         else {
2034                 p->chuck_count++;
2035                 ast_log(LOG_DEBUG, "%s: vpb_write: Tossed data away, tooooo much data!![%d]\n", p->dev,p->chuck_count);
2036                 p->play_buf_time=0;
2037         }
2038
2039         ast_mutex_unlock(&p->play_lock);
2040 /*      ast_mutex_unlock(&p->lock); */
2041         if(option_verbose>5) 
2042                 ast_verbose("%s: vpb_write: Done Writing to channel\n", p->dev);
2043         return 0;
2044 }
2045
2046 /* Read monitor thread function. */
2047 static void *do_chanreads(void *pvt)
2048 {
2049         struct vpb_pvt *p = (struct vpb_pvt *)pvt;
2050         struct ast_frame *fr = &p->fr;
2051         char *readbuf = ((char *)p->buf) + AST_FRIENDLY_OFFSET;
2052         int bridgerec = 0;
2053         int afmt, readlen, res, fmt, trycnt=0;
2054         int ignore_dtmf;
2055         char * getdtmf_var = NULL;
2056
2057         fr->frametype = AST_FRAME_VOICE;
2058         fr->src = type;
2059         fr->mallocd = 0;
2060         fr->delivery.tv_sec = 0;
2061         fr->delivery.tv_usec = 0;
2062         fr->samples = VPB_SAMPLES;
2063         fr->offset = AST_FRIENDLY_OFFSET;
2064         memset(p->buf, 0, sizeof p->buf);
2065
2066         if (option_verbose > 2) {
2067                 ast_verbose("%s: chanreads: starting thread\n", p->dev);
2068         }  
2069         ast_mutex_lock(&p->record_lock);
2070
2071         p->stopreads = 0; 
2072         p->read_state = 1;
2073         while (!p->stopreads && p->owner) {
2074
2075                 if (option_verbose > 4)
2076                         ast_verbose("%s: chanreads: Starting cycle ...\n", p->dev);
2077                 if (option_verbose > 4)
2078                         ast_verbose("%s: chanreads: Checking bridge \n", p->dev);
2079                 if (p->bridge) {
2080                         if (p->bridge->c0 == p->owner && (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_0))
2081                                 bridgerec = 1;
2082                         else if (p->bridge->c1 == p->owner && (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_1))
2083                                 bridgerec = 1;
2084                         else 
2085                                 bridgerec = 0;
2086                 } else {
2087                         if (option_verbose > 4)
2088                                 ast_verbose("%s: chanreads: No native bridge.\n", p->dev);
2089                         if (p->owner->_bridge){
2090                                 if (option_verbose > 4){
2091                                         ast_verbose("%s: chanreads: Got Asterisk bridge with [%s].\n", p->dev,p->owner->_bridge->name);
2092                                 }
2093                                 bridgerec = 1;
2094                         }
2095                         else {
2096                                 bridgerec = 0;
2097                         }
2098                 }
2099
2100 /*              if ( (p->owner->_state != AST_STATE_UP) || !bridgerec) { */
2101                 if ( (p->owner->_state != AST_STATE_UP) ) {
2102                         if (option_verbose > 4) {
2103                                 if (p->owner->_state != AST_STATE_UP)
2104                                         ast_verbose("%s: chanreads: Im not up[%d]\n", p->dev,p->owner->_state);
2105                                 else
2106                                         ast_verbose("%s: chanreads: No bridgerec[%d]\n", p->dev,bridgerec);
2107                         }  
2108                         vpb_sleep(10);
2109                         continue;
2110                 }
2111
2112                 /* Voicetronix DTMF detection can be triggered off ordinary speech
2113                  * This leads to annoying beeps during the conversation
2114                  * Avoid this problem by just setting VPB_GETDTMF when you want to listen for DTMF
2115                  */
2116                 /* ignore_dtmf = 1; */
2117                 ignore_dtmf = 0; /* set this to 1 to turn this feature on */
2118                 getdtmf_var = pbx_builtin_getvar_helper(p->owner,"VPB_GETDTMF");
2119                 if( getdtmf_var && ( strcasecmp( getdtmf_var, "yes" ) == 0 ) )
2120                         ignore_dtmf = 0;
2121
2122                 if( ignore_dtmf != p->last_ignore_dtmf ) {
2123                         if(option_verbose>1) 
2124                                 ast_verbose( VERBOSE_PREFIX_2 "%s:Now %s DTMF \n",
2125                                         p->dev, ignore_dtmf ? "ignoring" : "listening for");
2126                         vpb_set_event_mask(p->handle, ignore_dtmf ? VPB_EVENTS_NODTMF : VPB_EVENTS_ALL );
2127                 }
2128                 p->last_ignore_dtmf = ignore_dtmf;
2129
2130                 /* Play DTMF digits here to avoid problem you get if playing a digit during 
2131                  * a record operation
2132                  */
2133                 if (option_verbose > 5) {
2134                         ast_verbose("%s: chanreads: Checking dtmf's \n", p->dev);
2135                 }  
2136                 ast_mutex_lock(&p->play_dtmf_lock);
2137                 if( p->play_dtmf[0] ) {
2138                         /* Try to ignore DTMF event we get after playing digit */
2139                         /* This DTMF is played by asterisk and leads to an annoying trailing beep on CISCO phones */
2140                         if( !ignore_dtmf) 
2141                                 vpb_set_event_mask(p->handle, VPB_EVENTS_NODTMF );
2142 /*                      if (strcmp(p->owner->type,"vpb")==0){ */
2143                         if (p->bridge == NULL){
2144                                 vpb_dial_sync(p->handle,p->play_dtmf);
2145                                 if(option_verbose>1) 
2146                                         ast_verbose( VERBOSE_PREFIX_2 "%s: chanreads: Played DTMF %s\n",p->dev,p->play_dtmf);
2147                         }
2148                         else {
2149                                 if (option_verbose > 1) 
2150                                         ast_verbose(VERBOSE_PREFIX_2 "%s: chanreads: Not playing DTMF frame on native bridge\n", p->dev);
2151                         }
2152                         p->play_dtmf[0] = '\0';
2153                         ast_mutex_unlock(&p->play_dtmf_lock);
2154                         vpb_sleep(700); /* Long enough to miss echo and DTMF event */
2155                         if( !ignore_dtmf) 
2156                                 vpb_set_event_mask(p->handle, VPB_EVENTS_ALL );
2157                         continue;
2158                 }
2159                 ast_mutex_unlock(&p->play_dtmf_lock);
2160
2161 /*              afmt = (p->owner) ? p->owner->pvt->rawreadformat : AST_FORMAT_SLINEAR; */
2162                 if (p->owner){
2163                         afmt = p->owner->pvt->rawreadformat;
2164 /*                      ast_log(LOG_DEBUG,"%s: Record using owner format [%s]\n", p->dev, ast2vpbformatname(afmt)); */
2165                 }
2166                 else {
2167                         afmt = AST_FORMAT_SLINEAR;
2168 /*                      ast_log(LOG_DEBUG,"%s: Record using default format [%s]\n", p->dev, ast2vpbformatname(afmt)); */
2169                 }
2170                 fmt = ast2vpbformat(afmt);
2171                 if (fmt < 0) {
2172                         ast_log(LOG_WARNING,"%s: Record failure (unsupported format %d)\n", p->dev, afmt);
2173                         return NULL;
2174                 }
2175                 readlen = VPB_SAMPLES * astformatbits(afmt) / 8;
2176
2177                 if (p->lastinput == -1) {
2178                         vpb_record_buf_start(p->handle, fmt);
2179                         vpb_reset_record_fifo_alarm(p->handle);
2180                         if(option_verbose>1) 
2181                                 ast_verbose( VERBOSE_PREFIX_2 "%s: Starting record mode (codec=%d)[%s]\n",p->dev,fmt,ast2vpbformatname(afmt));
2182                 } else if (p->lastinput != fmt) {
2183                         vpb_record_buf_finish(p->handle);
2184                         vpb_record_buf_start(p->handle, fmt);
2185                         if(option_verbose>1) 
2186                                 ast_verbose( VERBOSE_PREFIX_2 "%s: Changed record format (%d=>%d)\n",p->dev,p->lastinput,fmt);
2187                 }
2188                 p->lastinput = fmt;
2189
2190                 /* Read only if up and not bridged, or a bridge for which we can read. */
2191                 if (option_verbose > 5) {
2192                         ast_verbose("%s: chanreads: getting buffer!\n", p->dev);
2193                 }  
2194                 if( (res = vpb_record_buf_sync(p->handle, readbuf, readlen) ) == VPB_OK ) {
2195                         if (option_verbose > 5) {
2196                                 ast_verbose("%s: chanreads: got buffer!\n", p->dev);
2197                         }  
2198                         /* Apply extra gain ! */
2199                         if( p->rxswgain > MAX_VPB_GAIN )
2200                                 a_gain_vector(p->rxswgain - MAX_VPB_GAIN , (short*)readbuf, readlen/sizeof(short));
2201                         if (option_verbose > 5) {
2202                                 ast_verbose("%s: chanreads: applied gain\n", p->dev);
2203                         }  
2204
2205                         fr->subclass = afmt;
2206                         fr->data = readbuf;
2207                         fr->datalen = readlen;
2208
2209                         /* Using trylock here to prevent deadlock when channel is hungup
2210                          * (ast_hangup() immediately gets lock)
2211                          */
2212                         if (p->owner && !p->stopreads ) {
2213                                 if (option_verbose > 5) {
2214                                         ast_verbose("%s: chanreads: queueing buffer on read frame q (state[%d])\n", p->dev,p->owner->_state);
2215                                 }  
2216                                 do {
2217                                         res = ast_mutex_trylock(&p->owner->lock);
2218                                         trycnt++;
2219                                 } while((res !=0)&&(trycnt<300));
2220                                 if (res==0)  {
2221                                         ast_queue_frame(p->owner, fr);
2222                                         ast_mutex_unlock(&p->owner->lock);
2223                                 } else {
2224                                         if (option_verbose > 4) 
2225                                                 ast_verbose("%s: chanreads: Couldnt get lock after %d tries!\n", p->dev,trycnt);
2226                                 }
2227                                 trycnt=0;
2228                                 
2229 /*
2230                                 res = ast_mutex_trylock(&p->owner->lock);
2231                                 if (res==0)  {
2232                                         ast_queue_frame(p->owner, fr);
2233                                         ast_mutex_unlock(&p->owner->lock);
2234                                 } else {
2235                                         if (res == EINVAL )
2236                                                 if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EINVAL[%d]\n", p->dev,res);
2237                                         else if (res == EBUSY )
2238                                                 if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EBUSY[%d]\n", p->dev,res);
2239                                         while(res !=0){
2240                                         res = ast_mutex_trylock(&p->owner->lock);
2241                                         }
2242                                         if (res==0)  {
2243                                                 ast_queue_frame(p->owner, fr);
2244                                                 ast_mutex_unlock(&p->owner->lock);
2245                                         }
2246                                         else {
2247                                                 if (res == EINVAL )
2248                                                         if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EINVAL[%d]\n", p->dev,res);
2249                                                 else if (res == EBUSY )
2250                                                         if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EBUSY[%d]\n", p->dev,res);
2251                                                 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);
2252                                         }
2253                                 }
2254 */
2255                                 if (option_verbose > 6) {
2256                                         short * data = (short*)readbuf;
2257                                         ast_verbose("%s: Read channel (codec=%d) %d %d\n", p->dev, fmt, data[0], data[1] );
2258                                 }  
2259                         }
2260                         else {
2261                                 if (option_verbose > 4) {
2262                                         ast_verbose("%s: p->stopreads[%d] p->owner[%p]\n", p->dev, p->stopreads,(void *)p->owner);
2263                                 }  
2264                         }
2265                 } else {
2266                         ast_log(LOG_WARNING,"%s: Record failure (%s)\n", p->dev, vpb_strerror(res));
2267                         vpb_record_buf_finish(p->handle);
2268                         vpb_record_buf_start(p->handle, fmt);
2269                 }
2270                 if (option_verbose > 4)
2271                         ast_verbose("%s: chanreads: Finished cycle...\n", p->dev);
2272         }
2273         p->read_state=0;
2274
2275         /* When stopreads seen, go away! */
2276         vpb_record_buf_finish(p->handle);
2277         p->read_state=0;
2278         ast_mutex_unlock(&p->record_lock);
2279
2280         if (option_verbose > 1)
2281                 ast_verbose(VERBOSE_PREFIX_2 "%s: Ending record mode (%d/%s)\n",
2282                          p->dev, p->stopreads, p->owner? "yes" : "no");     
2283         return NULL;
2284 }
2285
2286 static struct ast_channel *vpb_new(struct vpb_pvt *me, int state, char *context)
2287 {
2288         struct ast_channel *tmp; 
2289         char cid_num[256];
2290         char cid_name[256];
2291
2292         if (me->owner) {
2293             ast_log(LOG_WARNING, "Called vpb_new on owned channel (%s) ?!\n", me->dev);
2294             return NULL;
2295         }
2296         if (option_verbose > 3)
2297                 ast_verbose("%s: New call for context [%s]\n",me->dev,context);
2298             
2299         tmp = ast_channel_alloc(1);
2300         if (tmp) {
2301                 strncpy(tmp->name, me->dev, sizeof(tmp->name) - 1);
2302                 tmp->type = type;
2303                
2304                 /* Linear is the preferred format. Although Voicetronix supports other formats
2305                  * they are all converted to/from linear in the vpb code. Best for us to use
2306                  * linear since we can then adjust volume in this modules.
2307                  */
2308                 tmp->nativeformats = prefformat;
2309                 tmp->pvt->rawreadformat = AST_FORMAT_SLINEAR;
2310                 tmp->pvt->rawwriteformat =  AST_FORMAT_SLINEAR;
2311                 ast_setstate(tmp, state);
2312                 if (state == AST_STATE_RING) {
2313                         tmp->rings = 1;
2314                         cid_name[0] = '\0';
2315                         cid_num[0] = '\0';
2316                         ast_callerid_split(me->callerid, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
2317                         ast_set_callerid(tmp, cid_num, cid_name, cid_num);
2318                 }
2319                 tmp->pvt->pvt = me;
2320                 /* set call backs */
2321                 tmp->pvt->send_digit = vpb_digit;
2322                 tmp->pvt->call = vpb_call;
2323                 tmp->pvt->hangup = vpb_hangup;
2324                 tmp->pvt->answer = vpb_answer;
2325                 tmp->pvt->read = vpb_read;
2326                 tmp->pvt->write = vpb_write;
2327                 tmp->pvt->bridge = vpb_bridge;
2328                 if (use_ast_ind == 0)
2329                         tmp->pvt->indicate = vpb_indicate;
2330                 tmp->pvt->fixup = vpb_fixup;
2331                 
2332                 strncpy(tmp->context, context, sizeof(tmp->context)-1);
2333                 if (strlen(me->ext))
2334                         strncpy(tmp->exten, me->ext, sizeof(tmp->exten)-1);
2335                 else
2336                         strncpy(tmp->exten, "s",  sizeof(tmp->exten) - 1);
2337                 if (strlen(me->language))
2338                         strncpy(tmp->language, me->language, sizeof(tmp->language)-1);
2339
2340                 me->owner = tmp;
2341      
2342                 me->bridge = NULL;
2343                 me->lastoutput = -1;
2344                 me->lastinput = -1;
2345                 me->last_ignore_dtmf = 1;
2346                 me->readthread = 0;
2347                 me->play_dtmf[0] = '\0';
2348                 
2349                 me->lastgrunt  = get_time_in_ms(); /* Assume at least one grunt tone seen now. */
2350
2351                 ast_mutex_lock(&usecnt_lock);
2352                 usecnt++;
2353                 ast_mutex_unlock(&usecnt_lock);
2354                 ast_update_use_count();
2355                 if (state != AST_STATE_DOWN) {
2356                         if (ast_pbx_start(tmp)) {
2357                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2358                                 ast_hangup(tmp);
2359                         }
2360                 }
2361         } else {
2362                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2363         }
2364         return tmp;
2365 }
2366
2367 static struct ast_channel *vpb_request(const char *type, int format, void *data, int *cause) 
2368 {
2369         int oldformat;
2370         struct vpb_pvt *p;
2371         struct ast_channel *tmp = NULL;
2372         char *name = strdup(data ? (char *)data : "");
2373         char *s, *sepstr;
2374         int group=-1;
2375
2376         oldformat = format;
2377         format &= prefformat;
2378         if (!format) {
2379                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
2380                 return NULL;
2381         }
2382
2383         sepstr = name;
2384         s = strsep(&sepstr, "/"); /* Handle / issues */
2385         if (!s) 
2386                 s = "";
2387         /* Check if we are looking for a group */
2388         if (toupper(name[0]) == 'G' || toupper(name[0])=='R') {
2389                 group=atoi(name+1);     
2390         }
2391         /* Search for an unowned channel */
2392         ast_mutex_lock(&iflock); {
2393                 p = iflist;
2394                 while(p) {
2395                         if (group == -1){
2396                                 if (strncmp(s, p->dev + 4, sizeof p->dev) == 0) {
2397                                         if (!p->owner) {
2398                                                 tmp = vpb_new(p, AST_STATE_DOWN, p->context);
2399                                                 break;
2400                                         }
2401                                 }
2402                         }
2403                         else {
2404                                 if ((p->group == group) && (!p->owner)) {
2405                                         tmp = vpb_new(p, AST_STATE_DOWN, p->context);
2406                                         break;
2407                                 }
2408                         }
2409                         p = p->next;
2410                 }
2411         } ast_mutex_unlock(&iflock);
2412
2413
2414         if (option_verbose > 1) 
2415                 ast_verbose(VERBOSE_PREFIX_2 " %s requested, got: [%s]\n",
2416                 name, tmp ? tmp->name : "None");
2417
2418         free(name);
2419
2420         restart_monitor();
2421         return tmp;
2422 }
2423
2424 static float parse_gain_value(char *gain_type, char *value)
2425 {
2426         float gain;
2427
2428         /* try to scan number */
2429         if (sscanf(value, "%f", &gain) != 1)
2430         {
2431                 ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n", value, gain_type, config);
2432                 return DEFAULT_GAIN;
2433         }
2434
2435
2436         /* percentage? */
2437         /*if (value[strlen(value) - 1] == '%') */
2438         /*      return gain / (float)100; */
2439
2440         return gain;
2441 }
2442
2443 int load_module()
2444 {
2445         struct ast_config *cfg;
2446         struct ast_variable *v;
2447         struct vpb_pvt *tmp;
2448         int board = 0, group = 0;
2449         int mode = MODE_IMMEDIATE;
2450         float txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN; 
2451         float txswgain = 0, rxswgain = 0; 
2452         int first_channel = 1;
2453         int echo_cancel = DEFAULT_ECHO_CANCEL;
2454         int error = 0; /* Error flag */
2455         int bal1 = -1; /* Special value - means do not set */
2456         int bal2 = -1; 
2457         int bal3 = -1;
2458         char * callerid = NULL;
2459
2460         cfg = ast_config_load(config);
2461
2462         /* We *must* have a config file otherwise stop immediately */
2463         if (!cfg) {
2464                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
2465                 return -1;
2466         }  
2467
2468         vpb_seterrormode(VPB_ERROR_CODE);
2469
2470         ast_mutex_lock(&iflock); {
2471                 v = ast_variable_browse(cfg, "general");
2472                 while (v){
2473                         if (strcasecmp(v->name, "cards") == 0) {
2474                                 ast_log(LOG_NOTICE,"VPB Driver configured to use [%d] cards\n",atoi(v->value));
2475                         }
2476                         else if (strcasecmp(v->name, "indication") == 0) {
2477                                 use_ast_ind = 1;
2478                                 ast_log(LOG_NOTICE,"VPB driver using Asterisk Indication functions!\n");
2479                         }
2480                         else if (strcasecmp(v->name, "ecsuppthres") ==0) {
2481                                 ec_supp_threshold = atoi(v->value);
2482                         }
2483                         else if (strcasecmp(v->name, "dtmfidd") ==0) {
2484                                 dtmf_idd = atoi(v->value);
2485                                 ast_log(LOG_NOTICE,"VPB Driver setting DTMF IDD to [%d]ms\n",dtmf_idd);
2486                         }
2487                         v = v->next;
2488                 }
2489         
2490                 v = ast_variable_browse(cfg, "interfaces");
2491                 while(v) {
2492                         /* Create the interface list */
2493                         if (strcasecmp(v->name, "board") == 0) {
2494                                 board = atoi(v->value);
2495                         } else  if (strcasecmp(v->name, "group") == 0){
2496                                 group = atoi(v->value);
2497                         } else  if (strcasecmp(v->name, "useloopdrop") == 0){
2498                                 UseLoopDrop = atoi(v->value);
2499                         } else  if (strcasecmp(v->name, "usenativebridge") == 0){
2500                                 UseNativeBridge = atoi(v->value);
2501                         } else if (strcasecmp(v->name, "channel") == 0) {
2502                                 int channel = atoi(v->value);
2503                                 tmp = mkif(board, channel, mode, txgain, rxgain, txswgain, rxswgain, bal1, bal2, bal3, callerid, echo_cancel,group);
2504                                 if (tmp) {
2505                                         if(first_channel) {
2506                                                 mkbrd( tmp->vpb_model, echo_cancel );
2507                                                 first_channel = 0;
2508                                         }
2509                                         tmp->next = iflist;
2510                                         iflist = tmp;
2511                                 } else {
2512                                         ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
2513                                         error = -1;
2514                                         goto done;
2515                                 }
2516                         } else if (strcasecmp(v->name, "language") == 0) {
2517                                 strncpy(language, v->value, sizeof(language)-1);
2518                         } else if (strcasecmp(v->name, "callerid") == 0) {
2519                                 callerid = strdup(v->value);
2520                         } else if (strcasecmp(v->name, "mode") == 0) {
2521                                 if (strncasecmp(v->value, "di", 2) == 0) 
2522                                         mode = MODE_DIALTONE;
2523                                 else if (strncasecmp(v->value, "im", 2) == 0)
2524                                         mode = MODE_IMMEDIATE;
2525                                 else if (strncasecmp(v->value, "fx", 2) == 0)
2526                                         mode = MODE_FXO;
2527                                 else
2528                                         ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
2529                         } else if (!strcasecmp(v->name, "context")) {
2530                                 strncpy(context, v->value, sizeof(context)-1);
2531                         } else if (!strcasecmp(v->name, "echocancel")) {
2532                                 if (!strcasecmp(v->value, "off")) 
2533                                         echo_cancel = 0;
2534                         } else if (strcasecmp(v->name, "txgain") == 0) {
2535                                 txswgain = parse_gain_value(v->name, v->value);
2536                         } else if (strcasecmp(v->name, "rxgain") == 0) {
2537                                 rxswgain = parse_gain_value(v->name, v->value);
2538                         } else if (strcasecmp(v->name, "txhwgain") == 0) {
2539                                 txgain = parse_gain_value(v->name, v->value);
2540                         } else if (strcasecmp(v->name, "rxhwgain") == 0) {
2541                                 rxgain = parse_gain_value(v->name, v->value);
2542                         } else if (strcasecmp(v->name, "bal1") == 0) {
2543                                 bal1 = strtol(v->value, NULL, 16);
2544                                 if(bal1<0 || bal1>255) {
2545                                         ast_log(LOG_WARNING, "Bad bal1 value: %d\n", bal1);
2546                                         bal1 = -1;
2547                                 }
2548                         } else if (strcasecmp(v->name, "bal2") == 0) {
2549                                 bal2 = strtol(v->value, NULL, 16);
2550                                 if(bal2<0 || bal2>255) {
2551                                         ast_log(LOG_WARNING, "Bad bal2 value: %d\n", bal2);
2552                                         bal2 = -1;
2553                                 }
2554                         } else if (strcasecmp(v->name, "bal3") == 0) {
2555                                 bal3 = strtol(v->value, NULL, 16);
2556                                 if(bal3<0 || bal3>255) {
2557                                         ast_log(LOG_WARNING, "Bad bal3 value: %d\n", bal3);
2558                                         bal3 = -1;
2559                                 }
2560                         } else if (strcasecmp(v->name, "grunttimeout") == 0) {
2561                                 gruntdetect_timeout = 1000*atoi(v->value);
2562                         }
2563                         v = v->next;
2564                 }
2565
2566                 if (gruntdetect_timeout < 1000)
2567                         gruntdetect_timeout = 1000;
2568
2569                 done: (void)0;
2570         } ast_mutex_unlock(&iflock);
2571
2572         ast_config_destroy(cfg);
2573
2574         if (!error && ast_channel_register(type, tdesc, prefformat, vpb_request) != 0) {
2575                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
2576                 error = -1;
2577         }
2578
2579
2580         if (error)
2581                 unload_module();
2582         else 
2583                 restart_monitor(); /* And start the monitor for the first time */
2584
2585         return error;
2586 }
2587
2588
2589 int unload_module()
2590 {
2591         struct vpb_pvt *p;
2592         /* First, take us out of the channel loop */
2593         ast_channel_unregister(type);
2594
2595         ast_mutex_lock(&iflock); {
2596                 /* Hangup all interfaces if they have an owner */
2597                 p = iflist;
2598                 while(p) {
2599                         if (p->owner)
2600                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2601                         p = p->next;
2602                 }
2603                 iflist = NULL;
2604         } ast_mutex_unlock(&iflock);
2605
2606         ast_mutex_lock(&monlock); {
2607                 if (mthreadactive > -1) {
2608                         pthread_cancel(monitor_thread);
2609                         pthread_join(monitor_thread, NULL);
2610                 }
2611                 mthreadactive = -2;
2612         } ast_mutex_unlock(&monlock);
2613
2614         ast_mutex_lock(&iflock); {
2615                 /* Destroy all the interfaces and free their memory */
2616
2617                 while(iflist) {
2618                         p = iflist;                 
2619                         ast_mutex_destroy(&p->lock);
2620                         pthread_cancel(p->readthread);
2621                         ast_mutex_destroy(&p->owner_lock);
2622                         ast_mutex_destroy(&p->record_lock);
2623                         ast_mutex_destroy(&p->play_lock);
2624                         ast_mutex_destroy(&p->play_dtmf_lock);
2625                         p->readthread = 0;
2626
2627                         vpb_close(p->handle);
2628
2629                         iflist = iflist->next;
2630
2631                         free(p);
2632                 }
2633                 iflist = NULL;
2634         } ast_mutex_unlock(&iflock);
2635
2636         ast_mutex_lock(&bridge_lock); {
2637                 memset(bridges, 0, sizeof bridges);          
2638         } ast_mutex_unlock(&bridge_lock);
2639         ast_mutex_destroy(&bridge_lock);
2640         for(int i = 0; i < max_bridges; i++ ) {
2641                 ast_mutex_destroy(&bridges[i].lock);
2642                 pthread_cond_destroy(&bridges[i].cond);
2643         }
2644         free(bridges);
2645
2646         return 0;
2647 }
2648
2649 int usecount()
2650 {
2651         int res;
2652         ast_mutex_lock(&usecnt_lock);
2653         res = usecnt;
2654         ast_mutex_unlock(&usecnt_lock);
2655         return res;
2656 }
2657
2658 char *description()
2659 {
2660         return desc;
2661 }
2662
2663 char *key()
2664 {
2665         return ASTERISK_GPL_KEY;
2666 }
2667
2668 /**/
2669 #if defined(__cplusplus) || defined(c_plusplus)
2670  }
2671 #endif
2672 /**/