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