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