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