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