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