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