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