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