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