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