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