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