Merged revisions 55954 via svnmerge from
[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);
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_log(LOG_DEBUG, "%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_log(LOG_DEBUG, "%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                                 free(owner->cid.cid_num);
683                         owner->cid.cid_num=NULL;
684                         if (owner->cid.cid_name)
685                                 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 = strdup(cli_struct->cldn);
692                                 owner->cid.cid_name = 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                 free(owner->cid.cid_num);
795                 owner->cid.cid_num = NULL;
796         }
797         if (owner->cid.cid_name) {
798                 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_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
934                                 } else
935                                         ast_log(LOG_DEBUG, "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                                                                 free(owner->cid.cid_num);
1243                                                         owner->cid.cid_num=NULL;
1244                                                         if (owner->cid.cid_name)
1245                                                                 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 = (vpb_bridge_t *)malloc(max_bridges * sizeof(vpb_bridge_t) );
1503                 if(!bridges) 
1504                         ast_log(LOG_ERROR, "Failed to initialize bridges\n");
1505                 else {
1506                         memset(bridges,0,max_bridges * sizeof(vpb_bridge_t));
1507                         for(int i = 0; i < max_bridges; i++ ) {
1508                                 ast_mutex_init(&bridges[i].lock);
1509                                 ast_cond_init(&bridges[i].cond, NULL);
1510                         }
1511                 }
1512         }
1513         if(!echo_cancel) {
1514                 if (model==vpb_model_v4pci) {
1515                         vpb_echo_canc_disable();
1516                         ast_log(LOG_NOTICE, "Voicetronix echo cancellation OFF\n");
1517                 } 
1518                 else {
1519                 /* need to it port by port for OpenSwitch*/
1520                 }
1521         } else {
1522                 if (model==vpb_model_v4pci) {
1523                         vpb_echo_canc_enable();
1524                         ast_log(LOG_NOTICE, "Voicetronix echo cancellation ON\n");
1525                         if (ec_supp_threshold > -1){
1526                                 #ifdef VPB_PRI
1527                                 vpb_echo_canc_set_sup_thresh(0,(short *)&ec_supp_threshold);
1528                                 #else
1529                                 vpb_echo_canc_set_sup_thresh((short *)&ec_supp_threshold);
1530                                 #endif
1531                                 ast_log(LOG_NOTICE, "Voicetronix EC Sup Thres set\n");
1532                         }
1533                 }
1534                 else {
1535                 /* need to it port by port for OpenSwitch*/
1536                 }
1537         }
1538 }
1539
1540 static struct vpb_pvt *mkif(int board, int channel, int mode, int gains, float txgain, float rxgain,
1541                          float txswgain, float rxswgain, int bal1, int bal2, int bal3,
1542                          char * callerid, int echo_cancel, int group, ast_group_t callgroup, ast_group_t pickupgroup )
1543 {
1544         struct vpb_pvt *tmp;
1545         char buf[64];
1546
1547         tmp = (struct vpb_pvt *)calloc(1, sizeof *tmp);
1548
1549         if (!tmp)
1550                 return NULL;
1551
1552         tmp->handle = vpb_open(board, channel);
1553
1554         if (tmp->handle < 0) {    
1555                 ast_log(LOG_WARNING, "Unable to create channel vpb/%d-%d: %s\n", 
1556                                         board, channel, strerror(errno));
1557                 free(tmp);
1558                 return NULL;
1559         }
1560                
1561         snprintf(tmp->dev, sizeof(tmp->dev), "vpb/%d-%d", board, channel);
1562
1563         tmp->mode = mode;
1564
1565         tmp->group = group;
1566         tmp->callgroup = callgroup;
1567         tmp->pickupgroup = pickupgroup;
1568
1569         /* Initilize dtmf caller ID position variable */
1570         tmp->dtmf_caller_pos=0;
1571
1572         strncpy(tmp->language, language, sizeof(tmp->language) - 1);
1573         strncpy(tmp->context, context, sizeof(tmp->context) - 1);
1574
1575         tmp->callerid_type=0;
1576         if(callerid) { 
1577                 if (strcasecmp(callerid,"on")==0){
1578                         tmp->callerid_type =1;
1579                         strncpy(tmp->callerid, "unknown", sizeof(tmp->callerid) - 1);
1580                 }
1581                 else if (strcasecmp(callerid,"v23")==0){
1582                         tmp->callerid_type =2;
1583                         strncpy(tmp->callerid, "unknown", sizeof(tmp->callerid) - 1);
1584                 }
1585                 else if (strcasecmp(callerid,"bell")==0){
1586                         tmp->callerid_type =3;
1587                         strncpy(tmp->callerid, "unknown", sizeof(tmp->callerid) - 1);
1588                 }
1589                 else {
1590                         strncpy(tmp->callerid, callerid, sizeof(tmp->callerid) - 1);
1591                 }
1592         } else {
1593                 strncpy(tmp->callerid, "unknown", sizeof(tmp->callerid) - 1);
1594         }
1595
1596         /* check if codec balances have been set in the config file */
1597         if (bal3>=0) {
1598                 if ((bal1>=0) && !(bal1 & 32)) bal1 |= 32;
1599                         vpb_set_codec_reg(tmp->handle, 0x42, bal3);
1600         }
1601         if(bal1>=0) vpb_set_codec_reg(tmp->handle, 0x32, bal1);
1602         if(bal2>=0) vpb_set_codec_reg(tmp->handle, 0x3a, bal2);
1603
1604         if (gains & VPB_GOT_TXHWG){
1605                 if (txgain > MAX_VPB_GAIN){
1606                         tmp->txgain = MAX_VPB_GAIN;
1607                 }
1608                 else if (txgain < MIN_VPB_GAIN){
1609                         tmp->txgain = MIN_VPB_GAIN;
1610                 }
1611                 else {
1612                         tmp->txgain = txgain;
1613                 }
1614                 
1615                 ast_log(LOG_NOTICE,"VPB setting Tx Hw gain to [%f]\n",tmp->txgain);
1616                 vpb_play_set_hw_gain(tmp->handle, tmp->txgain);
1617         }
1618
1619         if (gains & VPB_GOT_RXHWG){
1620                 if (rxgain > MAX_VPB_GAIN){
1621                         tmp->rxgain = MAX_VPB_GAIN;
1622                 }
1623                 else if (rxgain < MIN_VPB_GAIN){
1624                         tmp->rxgain = MIN_VPB_GAIN;
1625                 }
1626                 else {
1627                         tmp->rxgain = rxgain;
1628                 }
1629                 ast_log(LOG_NOTICE,"VPB setting Rx Hw gain to [%f]\n",tmp->rxgain);
1630                 vpb_record_set_hw_gain(tmp->handle,tmp->rxgain);
1631         }
1632
1633         if (gains & VPB_GOT_TXSWG){
1634                 tmp->txswgain = txswgain;
1635                 ast_log(LOG_NOTICE,"VPB setting Tx Sw gain to [%f]\n",tmp->txswgain);
1636                 vpb_play_set_gain(tmp->handle, tmp->txswgain);
1637         }
1638
1639         if (gains & VPB_GOT_RXSWG){
1640                 tmp->rxswgain = rxswgain;
1641                 ast_log(LOG_NOTICE,"VPB setting Rx Sw gain to [%f]\n",tmp->rxswgain);
1642                 vpb_record_set_gain(tmp->handle, tmp->rxswgain);
1643         }
1644
1645         tmp->vpb_model = vpb_model_unknown;
1646         if( vpb_get_model(buf) == VPB_OK ) {
1647                 if(strcmp(buf,"V12PCI")==0) 
1648                         tmp->vpb_model = vpb_model_v12pci;
1649                 else if(strcmp(buf,"VPB4")==0) 
1650                         tmp->vpb_model = vpb_model_v4pci;
1651         }
1652
1653         ast_mutex_init(&tmp->owner_lock);
1654         ast_mutex_init(&tmp->lock);
1655         ast_mutex_init(&tmp->record_lock);
1656         ast_mutex_init(&tmp->play_lock);
1657         ast_mutex_init(&tmp->play_dtmf_lock);
1658
1659         /* set default read state */
1660         tmp->read_state = 0;
1661         
1662         tmp->golock=0;
1663
1664         tmp->busy_timer_id = vpb_timer_get_unique_timer_id();
1665         vpb_timer_open(&tmp->busy_timer, tmp->handle, tmp->busy_timer_id, TIMER_PERIOD_BUSY);
1666
1667         tmp->ringback_timer_id = vpb_timer_get_unique_timer_id();
1668         vpb_timer_open(&tmp->ringback_timer, tmp->handle, tmp->ringback_timer_id, TIMER_PERIOD_RINGBACK);
1669
1670         tmp->ring_timer_id = vpb_timer_get_unique_timer_id();
1671         vpb_timer_open(&tmp->ring_timer, tmp->handle, tmp->ring_timer_id, timer_period_ring);
1672               
1673         tmp->dtmfidd_timer_id = vpb_timer_get_unique_timer_id();
1674         vpb_timer_open(&tmp->dtmfidd_timer, tmp->handle, tmp->dtmfidd_timer_id, dtmf_idd);
1675               
1676         if (mode == MODE_FXO){
1677                 if (use_ast_dtmfdet)
1678                         vpb_set_event_mask(tmp->handle, VPB_EVENTS_NODTMF );
1679                 else
1680                         vpb_set_event_mask(tmp->handle, VPB_EVENTS_ALL );
1681         }
1682         else {
1683 /*
1684                 if (use_ast_dtmfdet)
1685                         vpb_set_event_mask(tmp->handle, VPB_EVENTS_NODTMF );
1686                 else
1687 */
1688                         vpb_set_event_mask(tmp->handle, VPB_EVENTS_STAT );
1689         }
1690
1691         if ((tmp->vpb_model == vpb_model_v12pci) && (echo_cancel)){
1692                 vpb_hostecho_on(tmp->handle);
1693         }
1694         if (use_ast_dtmfdet) {
1695                 tmp->vad = ast_dsp_new();
1696                 ast_dsp_set_features(tmp->vad, DSP_FEATURE_DTMF_DETECT);
1697                 ast_dsp_digitmode(tmp->vad, DSP_DIGITMODE_DTMF);
1698                 if (relaxdtmf)
1699                         ast_dsp_digitmode(tmp->vad, DSP_DIGITMODE_DTMF|DSP_DIGITMODE_RELAXDTMF);
1700         }
1701         else {
1702                 tmp->vad = NULL;
1703         }
1704
1705         /* define grunt tone */
1706         vpb_settonedet(tmp->handle,&toned_ungrunt);
1707
1708         ast_log(LOG_NOTICE,"Voicetronix %s channel %s initialized (rxsg=%f/txsg=%f/rxhg=%f/txhg=%f)(0x%x/0x%x/0x%x)\n",
1709                 (tmp->vpb_model==vpb_model_v4pci)?"V4PCI": (tmp->vpb_model==vpb_model_v12pci)?"V12PCI":"[Unknown model]",
1710                 tmp->dev, tmp->rxswgain, tmp->txswgain, tmp->rxgain, tmp->txgain, bal1, bal2, bal3 );
1711
1712         return tmp;
1713 }
1714
1715 static int vpb_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1716 {
1717         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1718         int res = 0;
1719         int tmp = 0;
1720
1721         if (use_ast_ind == 1) {
1722                 if (option_verbose > 3)
1723                         ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_indicate called when using Ast Indications !?!\n", p->dev);
1724                 return 0;
1725         }
1726
1727         if (option_verbose > 3)
1728                 ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_indicate [%d] state[%d]\n", p->dev, condition,ast->_state);
1729 /*
1730         if (ast->_state != AST_STATE_UP) {
1731                 ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_indicate Not in AST_STATE_UP\n", p->dev, condition,ast->_state);
1732                 return res;
1733         }
1734 */
1735
1736 /*
1737         if (option_verbose > 3) ast_verbose("%s: LOCKING in indicate \n", p->dev);
1738         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1739 */
1740         ast_mutex_lock(&p->lock);
1741         switch(condition) {
1742                 case AST_CONTROL_BUSY:
1743                 case AST_CONTROL_CONGESTION:
1744                         if (ast->_state == AST_STATE_UP) {
1745                                 playtone(p->handle, &Busytone);
1746                                 p->state = VPB_STATE_PLAYBUSY;
1747                                 vpb_timer_stop(p->busy_timer); 
1748                                 vpb_timer_start(p->busy_timer); 
1749                         }
1750                         break;
1751                 case AST_CONTROL_RINGING:
1752                         if (ast->_state == AST_STATE_UP) {
1753                                 playtone(p->handle, &Ringbacktone);
1754                                 p->state = VPB_STATE_PLAYRING;
1755                                 if (option_verbose > 3)
1756                                         ast_verbose(VERBOSE_PREFIX_4 "%s: vpb indicate: setting ringback timer [%d]\n", p->dev,p->ringback_timer_id);
1757                                 
1758                                 vpb_timer_stop(p->ringback_timer);
1759                                 vpb_timer_start(p->ringback_timer);
1760                         }
1761                         break;      
1762                 case AST_CONTROL_ANSWER:
1763                 case -1: /* -1 means stop playing? */
1764                         vpb_timer_stop(p->ringback_timer);
1765                         vpb_timer_stop(p->busy_timer);
1766                         stoptone(p->handle);
1767                         break;
1768                 case AST_CONTROL_HANGUP:
1769                         if (ast->_state == AST_STATE_UP) {
1770                                 playtone(p->handle, &Busytone);
1771                                 p->state = VPB_STATE_PLAYBUSY;
1772                                 vpb_timer_stop(p->busy_timer);
1773                                 vpb_timer_start(p->busy_timer);
1774                         }
1775                         break;
1776                 case AST_CONTROL_HOLD:
1777                         ast_moh_start(ast, (const char *) data, NULL);
1778                         break;
1779                 case AST_CONTROL_UNHOLD:
1780                         ast_moh_stop(ast);
1781                         break;
1782                 default:
1783                         res = 0;
1784                         break;
1785         }
1786         tmp = ast_mutex_unlock(&p->lock);
1787 /*
1788         if (option_verbose > 3) ast_verbose("%s: unLOCKING in indicate [%d]\n", p->dev,tmp);
1789 */
1790         return res;
1791 }
1792
1793 static int vpb_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1794 {
1795         struct vpb_pvt *p = (struct vpb_pvt *)newchan->tech_pvt;
1796         int res = 0;
1797
1798 /*
1799         if (option_verbose > 3) ast_verbose("%s: LOCKING in fixup \n", p->dev);
1800         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1801 */
1802         ast_mutex_lock(&p->lock);
1803         ast_log(LOG_DEBUG, "New owner for channel %s is %s\n", p->dev, newchan->name);
1804
1805         if (p->owner == oldchan) {
1806                 p->owner = newchan;
1807         }
1808
1809         if (newchan->_state == AST_STATE_RINGING){
1810                 if (use_ast_ind == 1) {
1811                         if (option_verbose > 3)
1812                                 ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_fixup Calling ast_indicate\n", p->dev);
1813                         ast_indicate(newchan, AST_CONTROL_RINGING);
1814                 }
1815                 else {
1816                         if (option_verbose > 3)
1817                                 ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_fixup Calling vpb_indicate\n", p->dev);
1818                         vpb_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
1819                 }
1820         }
1821
1822         res= ast_mutex_unlock(&p->lock);
1823 /*
1824         if (option_verbose > 3) ast_verbose("%s: unLOCKING in fixup [%d]\n", p->dev,res);
1825 */
1826         return 0;
1827 }
1828
1829 static int vpb_digit_begin(struct ast_channel *ast, char digit)
1830 {
1831         /* XXX Modify this callback to let Asterisk control the length of DTMF */
1832         return 0;
1833 }
1834 static int vpb_digit_end(struct ast_channel *ast, char digit)
1835 {
1836         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1837         char s[2];
1838         int res = 0;
1839
1840         if (use_ast_dtmf){
1841                 if (option_verbose > 3)
1842                         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);
1843                 return 0;
1844         }
1845
1846 /*
1847         if (option_verbose > 3) ast_verbose("%s: LOCKING in digit \n", p->dev);
1848         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1849 */
1850         ast_mutex_lock(&p->lock);
1851
1852
1853         s[0] = digit;
1854         s[1] = '\0';
1855
1856         if (option_verbose > 3)
1857                 ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_digit: asked to play digit[%s]\n", p->dev, s);
1858
1859         ast_mutex_lock(&p->play_dtmf_lock);
1860         strncat(p->play_dtmf,s,sizeof(*p->play_dtmf));
1861         ast_mutex_unlock(&p->play_dtmf_lock);
1862
1863         res = ast_mutex_unlock(&p->lock);
1864 /*
1865         if (option_verbose > 3) ast_verbose("%s: unLOCKING in digit [%d]\n", p->dev,res);
1866 */
1867         return 0;
1868 }
1869
1870 /* Places a call out of a VPB channel */
1871 static int vpb_call(struct ast_channel *ast, char *dest, int timeout)
1872 {
1873         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1874         int res = 0,i;
1875         char *s = strrchr(dest, '/');
1876         char dialstring[254] = "";
1877         int tmp = 0;
1878
1879 /*
1880         if (option_verbose > 3) ast_verbose("%s: LOCKING in call \n", p->dev);
1881         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1882 */
1883         ast_mutex_lock(&p->lock);
1884         if (option_verbose > 3)
1885                 ast_verbose(VERBOSE_PREFIX_4 "%s: starting call to [%s]\n", p->dev,dest);
1886
1887         if (s)
1888                 s = s + 1;
1889         else
1890                 s = dest;
1891         strncpy(dialstring, s, sizeof(dialstring) - 1);
1892         for (i=0; dialstring[i] != '\0' ; i++) {
1893                 if ((dialstring[i] == 'w') || (dialstring[i] == 'W'))
1894                         dialstring[i] = ',';
1895                 else if ((dialstring[i] == 'f') || (dialstring[i] == 'F'))
1896                         dialstring[i] = '&';
1897         }       
1898
1899         if (ast->_state != AST_STATE_DOWN && ast->_state != AST_STATE_RESERVED) {
1900                 ast_log(LOG_WARNING, "vpb_call on %s neither down nor reserved!\n", ast->name);
1901                 tmp = ast_mutex_unlock(&p->lock);
1902 /*
1903                 if (option_verbose > 3) ast_verbose("%s: unLOCKING in call [%d]\n", p->dev,tmp);
1904 */
1905                 return -1;
1906         }
1907         if (p->mode != MODE_FXO)  /* Station port, ring it. */
1908                 res = vpb_ring_station_async(p->handle, VPB_RING_STATION_ON,0);       
1909         else {
1910                 VPB_CALL call;
1911
1912                 /* Dial must timeout or it can leave channels unuseable */
1913                 if( timeout == 0 )
1914                         timeout = TIMER_PERIOD_NOANSWER;
1915                 else 
1916                         timeout = timeout * 1000; /* convert from secs to ms. */
1917
1918                 /* These timeouts are only used with call progress dialing */
1919                 call.dialtones = 1; /* Number of dialtones to get outside line */
1920                 call.dialtone_timeout = VPB_DIALTONE_WAIT; /* Wait this long for dialtone (ms) */
1921                 call.ringback_timeout = VPB_RINGWAIT; /* Wait this long for ringing after dialing (ms) */
1922                 call.inter_ringback_timeout = VPB_CONNECTED_WAIT; /* If ringing stops for this long consider it connected (ms) */
1923                 call.answer_timeout = timeout; /* Time to wait for answer after ringing starts (ms) */
1924                 memcpy( &call.tone_map,  DialToneMap, sizeof(DialToneMap) );
1925                 vpb_set_call(p->handle, &call);
1926
1927                 if (option_verbose > 1)
1928                         ast_verbose(VERBOSE_PREFIX_2 "%s: Calling %s on %s \n",p->dev, dialstring, ast->name); 
1929
1930                 if (option_verbose > 2) {
1931                         int j;
1932                         ast_verbose(VERBOSE_PREFIX_2 "%s: Dial parms for %s %d/%dms/%dms/%dms/%dms\n", p->dev
1933                                 , ast->name, call.dialtones, call.dialtone_timeout
1934                                 , call.ringback_timeout, call.inter_ringback_timeout
1935                                 , call.answer_timeout );
1936                         for( j=0; !call.tone_map[j].terminate; j++ )
1937                                 ast_verbose(VERBOSE_PREFIX_2 "%s: Dial parms for %s tone %d->%d\n", p->dev,
1938                                         ast->name, call.tone_map[j].tone_id, call.tone_map[j].call_id); 
1939                 }
1940
1941                 if (option_verbose > 3)
1942                                 ast_verbose("%s: Disabling Loop Drop detection\n",p->dev);
1943                 vpb_disable_event(p->handle, VPB_MDROP);
1944                 vpb_sethook_sync(p->handle,VPB_OFFHOOK);
1945                 p->state=VPB_STATE_OFFHOOK;
1946
1947                 #ifndef DIAL_WITH_CALL_PROGRESS
1948                 vpb_sleep(300);
1949                 if (option_verbose > 3)
1950                                 ast_verbose("%s: Enabling Loop Drop detection\n",p->dev);
1951                 vpb_enable_event(p->handle, VPB_MDROP);
1952                 res = vpb_dial_async(p->handle, dialstring);
1953                 #else
1954                 if (option_verbose > 3)
1955                                 ast_verbose("%s: Enabling Loop Drop detection\n",p->dev);
1956                 vpb_enable_event(p->handle, VPB_MDROP);
1957                 res = vpb_call_async(p->handle, dialstring);
1958                 #endif
1959
1960                 if (res != VPB_OK) {
1961                         ast_log(LOG_DEBUG, "Call on %s to %s failed: %s\n", ast->name, s, vpb_strerror(res));         
1962                         res = -1;
1963                 } else 
1964                         res = 0;
1965         }
1966
1967         if (option_verbose > 2)
1968                 ast_verbose(VERBOSE_PREFIX_3 "%s: VPB Calling %s [t=%d] on %s returned %d\n",p->dev , s, timeout, ast->name, res); 
1969         if (res == 0) {
1970                 ast_setstate(ast, AST_STATE_RINGING);
1971                 ast_queue_control(ast,AST_CONTROL_RINGING);             
1972         }
1973
1974         if (!p->readthread){
1975                 ast_pthread_create(&p->readthread, NULL, do_chanreads, (void *)p);
1976         }
1977
1978         tmp = ast_mutex_unlock(&p->lock);
1979 /*
1980         if (option_verbose > 3) ast_verbose("%s: unLOCKING in call [%d]\n", p->dev,tmp);
1981 */
1982         return res;
1983 }
1984
1985 static int vpb_hangup(struct ast_channel *ast)
1986 {
1987         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1988         VPB_EVENT je;
1989         char str[VPB_MAX_STR];
1990         int res =0 ;
1991
1992 /*
1993         if (option_verbose > 3) ast_verbose("%s: LOCKING in hangup \n", p->dev);
1994         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);
1995         if (option_verbose > 3) ast_verbose("%s: LOCKING pthread_self(%d)\n", p->dev,pthread_self());
1996         ast_mutex_lock(&p->lock);
1997 */
1998         if (option_verbose > 1) 
1999                 ast_verbose(VERBOSE_PREFIX_2 "%s: Hangup requested\n", ast->name);
2000
2001         if (!ast->tech || !ast->tech_pvt) {
2002                 ast_log(LOG_WARNING, "%s: channel not connected?\n", ast->name);
2003                 res = ast_mutex_unlock(&p->lock);
2004 /*
2005                 if (option_verbose > 3) ast_verbose("%s: unLOCKING in hangup [%d]\n", p->dev,res);
2006 */
2007                 /* Free up ast dsp if we have one */
2008                 if ((use_ast_dtmfdet)&&(p->vad)) {
2009                         ast_dsp_free(p->vad);
2010                         p->vad = NULL;
2011                 }
2012                 return 0;
2013         }
2014
2015
2016
2017         /* Stop record */
2018         p->stopreads = 1;
2019         if( p->readthread ){
2020                 pthread_join(p->readthread, NULL); 
2021                 if(option_verbose>3) 
2022                         ast_verbose( VERBOSE_PREFIX_4 "%s: stopped record thread \n",ast->name);
2023         }
2024
2025         /* Stop play */
2026         if (p->lastoutput != -1) {
2027                 if(option_verbose>1) 
2028                         ast_verbose( VERBOSE_PREFIX_2 "%s: Ending play mode \n",ast->name);
2029                 vpb_play_terminate(p->handle);
2030                 ast_mutex_lock(&p->play_lock); {
2031                         vpb_play_buf_finish(p->handle);
2032                 } ast_mutex_unlock(&p->play_lock);
2033         }
2034
2035         if(option_verbose>3) 
2036                 ast_verbose( VERBOSE_PREFIX_4 "%s: Setting state down\n",ast->name);
2037         ast_setstate(ast,AST_STATE_DOWN);
2038
2039
2040 /*
2041         if (option_verbose > 3) ast_verbose("%s: LOCKING in hangup \n", p->dev);
2042         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);
2043         if (option_verbose > 3) ast_verbose("%s: LOCKING pthread_self(%d)\n", p->dev,pthread_self());
2044 */
2045         ast_mutex_lock(&p->lock);
2046
2047         if (p->mode != MODE_FXO) {
2048                 /* station port. */
2049                 vpb_ring_station_async(p->handle, VPB_RING_STATION_OFF,0);      
2050                 if(p->state!=VPB_STATE_ONHOOK){
2051                         /* This is causing a "dial end" "play tone" loop
2052                         playtone(p->handle, &Busytone); 
2053                         p->state = VPB_STATE_PLAYBUSY;
2054                         if(option_verbose>4) 
2055                                 ast_verbose( VERBOSE_PREFIX_4 "%s: Station offhook[%d], playing busy tone\n",
2056                                                                 ast->name,p->state);
2057                         */
2058                 }
2059                 else {
2060                         stoptone(p->handle);
2061                 }
2062                 #ifdef VPB_PRI
2063                 vpb_setloop_async(p->handle, VPB_OFFHOOK);
2064                 vpb_sleep(100);
2065                 vpb_setloop_async(p->handle, VPB_ONHOOK);
2066                 #endif
2067         } else {
2068                 stoptone(p->handle); /* Terminates any dialing */
2069                 vpb_sethook_sync(p->handle, VPB_ONHOOK);
2070                 p->state=VPB_STATE_ONHOOK;
2071         }
2072         while (VPB_OK==vpb_get_event_ch_async(p->handle,&je)){
2073                 if(option_verbose>3) {
2074                         vpb_translate_event(&je, str);
2075                         ast_verbose( VERBOSE_PREFIX_4 "%s: Flushing event [%d]=>%s\n",ast->name,je.type,str);
2076                 }
2077         }
2078
2079         p->readthread = 0;
2080         p->lastoutput = -1;
2081         p->lastinput = -1;
2082         p->last_ignore_dtmf = 1;
2083         p->ext[0]  = 0;
2084         p->dialtone = 0;
2085
2086         p->owner = NULL;
2087         ast->tech_pvt=NULL;
2088
2089         /* Free up ast dsp if we have one */
2090         if ((use_ast_dtmfdet)&&(p->vad)) {
2091                 ast_dsp_free(p->vad);
2092                 p->vad = NULL;
2093         }
2094
2095         if (option_verbose > 1)
2096                 ast_verbose(VERBOSE_PREFIX_2 "%s: Hangup complete\n", ast->name);
2097
2098         restart_monitor();
2099 /*
2100         if (option_verbose > 3) ast_verbose("%s: LOCKING in hangup count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
2101 */
2102         res = ast_mutex_unlock(&p->lock);
2103 /*
2104         if (option_verbose > 3) ast_verbose("%s: unLOCKING in hangup [%d]\n", p->dev,res);
2105         if (option_verbose > 3) ast_verbose("%s: LOCKING in hangup count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
2106 */
2107         return 0;
2108 }
2109
2110 static int vpb_answer(struct ast_channel *ast)
2111 {
2112         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
2113         int res = 0;
2114 /*
2115         VPB_EVENT je;
2116         int ret;
2117         if (option_verbose > 3) ast_verbose("%s: LOCKING in answer \n", p->dev);
2118         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
2119 */
2120         ast_mutex_lock(&p->lock);
2121
2122         if (option_verbose > 3)
2123                         ast_verbose(VERBOSE_PREFIX_4 "%s: Answering channel\n",p->dev);
2124
2125         if (p->mode == MODE_FXO){
2126                 if (option_verbose > 3)
2127                                 ast_verbose("%s: Disabling Loop Drop detection\n",p->dev);
2128                 vpb_disable_event(p->handle, VPB_MDROP);
2129         }
2130
2131         if (ast->_state != AST_STATE_UP) {
2132                 if (p->mode == MODE_FXO){
2133                         vpb_sethook_sync(p->handle, VPB_OFFHOOK);
2134                         p->state=VPB_STATE_OFFHOOK;
2135 /*                      vpb_sleep(500);
2136                         ret = vpb_get_event_ch_async(p->handle,&je);
2137                         if ((ret == VPB_OK)&&((je.type != VPB_DROP)&&(je.type != VPB_RING))){
2138                                 if (option_verbose > 3){
2139                                                 ast_verbose(VERBOSE_PREFIX_4 "%s: Answer collected a wrong event!!\n",p->dev);
2140                                 }
2141                                 vpb_put_event(&je);
2142                         }
2143 */
2144                 }
2145                 ast_setstate(ast, AST_STATE_UP);
2146
2147                 if(option_verbose>1) 
2148 /*
2149                         ast_verbose( VERBOSE_PREFIX_2 "%s: Answered call from %s on %s [%s]\n", p->dev, 
2150                                         p->owner->callerid, ast->name,(p->mode == MODE_FXO)?"FXO":"FXS"); 
2151 */
2152                         ast_verbose( VERBOSE_PREFIX_2 "%s: Answered call on %s [%s]\n", p->dev,
2153                                          ast->name,(p->mode == MODE_FXO)?"FXO":"FXS");
2154
2155                 ast->rings = 0;
2156                 if( !p->readthread ){
2157         /*              res = ast_mutex_unlock(&p->lock); */
2158         /*              ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res); */
2159                         ast_pthread_create(&p->readthread, NULL, do_chanreads, (void *)p);
2160                 } else {
2161                         if(option_verbose>3) 
2162                                 ast_verbose(VERBOSE_PREFIX_4 "%s: Record thread already running!!\n",p->dev);
2163                 }
2164         } else {
2165                 if(option_verbose>3) {
2166                         ast_verbose(VERBOSE_PREFIX_4 "%s: Answered state is up\n",p->dev);
2167                 }
2168         /*      res = ast_mutex_unlock(&p->lock); */
2169         /*      ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res); */
2170         }
2171         vpb_sleep(500);
2172         if (p->mode == MODE_FXO){
2173                 if (option_verbose > 3)
2174                                 ast_verbose("%s: Re-enabling Loop Drop detection\n",p->dev);
2175                 vpb_enable_event(p->handle,VPB_MDROP);
2176         }
2177         res = ast_mutex_unlock(&p->lock);
2178 /*
2179         if(option_verbose>3) ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res);
2180 */
2181         return 0;
2182 }
2183
2184 static struct ast_frame  *vpb_read(struct ast_channel *ast)
2185 {
2186         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt; 
2187         static struct ast_frame f = {AST_FRAME_NULL}; 
2188
2189         f.src = "vpb";
2190         ast_log(LOG_NOTICE, "%s: vpb_read: should never be called!\n", p->dev);
2191         ast_verbose("%s: vpb_read: should never be called!\n", p->dev);
2192
2193         return &f;
2194 }
2195
2196 static inline int ast2vpbformat(int ast_format)
2197 {
2198         switch(ast_format) {
2199                 case AST_FORMAT_ALAW:
2200                         return VPB_ALAW;
2201                 case AST_FORMAT_SLINEAR:
2202                         return VPB_LINEAR;
2203                 case AST_FORMAT_ULAW:
2204                         return VPB_MULAW;
2205                 case AST_FORMAT_ADPCM:
2206                         return VPB_OKIADPCM;
2207                 default:
2208                         return -1;
2209         }
2210 }
2211
2212 static inline char * ast2vpbformatname(int ast_format)
2213 {
2214         switch(ast_format) {
2215                 case AST_FORMAT_ALAW:
2216                         return "AST_FORMAT_ALAW:VPB_ALAW";
2217                 case AST_FORMAT_SLINEAR:
2218                         return "AST_FORMAT_SLINEAR:VPB_LINEAR";
2219                 case AST_FORMAT_ULAW:
2220                         return "AST_FORMAT_ULAW:VPB_MULAW";
2221                 case AST_FORMAT_ADPCM:
2222                         return "AST_FORMAT_ADPCM:VPB_OKIADPCM";
2223                 default:
2224                         return "UNKN:UNKN";
2225         }
2226 }
2227
2228 static inline int astformatbits(int ast_format)
2229 {
2230         switch(ast_format) {
2231                 case AST_FORMAT_ALAW:
2232                 case AST_FORMAT_ULAW:
2233                         return 8;
2234                 case AST_FORMAT_SLINEAR:
2235                         return 16;
2236                 case AST_FORMAT_ADPCM:
2237                         return 4;
2238                 default:
2239                         return 8;
2240         }   
2241 }
2242
2243 int a_gain_vector(float g, short *v, int n) 
2244 {
2245         int i;
2246         float tmp;
2247         for ( i = 0; i<n; i++) {
2248                 tmp = g*v[i];
2249                 if (tmp > 32767.0)
2250                         tmp = 32767.0;
2251                 if (tmp < -32768.0)
2252                         tmp = -32768.0;
2253                 v[i] = (short)tmp;      
2254         }  
2255         return(i);
2256 }
2257
2258 /* Writes a frame of voice data to a VPB channel */
2259 static int vpb_write(struct ast_channel *ast, struct ast_frame *frame)
2260 {
2261         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt; 
2262         int res = 0, fmt = 0;
2263         struct timeval play_buf_time_start;
2264         int tdiff;
2265
2266 /*      ast_mutex_lock(&p->lock); */
2267         if(option_verbose>5) 
2268                 ast_verbose("%s: vpb_write: Writing to channel\n", p->dev);
2269
2270         if (frame->frametype != AST_FRAME_VOICE) {
2271                 if(option_verbose>3) 
2272                         ast_verbose("%s: vpb_write: Don't know how to handle from type %d\n", ast->name, frame->frametype);
2273 /*              ast_mutex_unlock(&p->lock); */
2274                 return 0;
2275         } else if (ast->_state != AST_STATE_UP) {
2276                 if(option_verbose>3) 
2277                         ast_verbose("%s: vpb_write: Attempt to Write frame type[%d]subclass[%d] on not up chan(state[%d])\n",ast->name, frame->frametype, frame->subclass,ast->_state);
2278                 p->lastoutput = -1;
2279 /*              ast_mutex_unlock(&p->lock); */
2280                 return 0;
2281         }
2282 /*      ast_log(LOG_DEBUG, "%s: vpb_write: Checked frame type..\n", p->dev); */
2283
2284
2285         fmt = ast2vpbformat(frame->subclass);
2286         if (fmt < 0) {
2287                 ast_log(LOG_WARNING, "%s: vpb_write: Cannot handle frames of %d format!\n",ast->name, frame->subclass);
2288                 return -1;
2289         }
2290
2291         tdiff = ast_tvdiff_ms(ast_tvnow(), p->lastplay);
2292         ast_log(LOG_DEBUG, "%s: vpb_write: time since last play(%d) \n", p->dev, tdiff); 
2293         if (tdiff < (VPB_SAMPLES/8 - 1)){
2294                 ast_log(LOG_DEBUG, "%s: vpb_write: Asked to play too often (%d) (%d)\n", p->dev, tdiff,frame->datalen); 
2295 //              return 0;
2296         }
2297         p->lastplay = ast_tvnow();
2298 /*
2299         ast_log(LOG_DEBUG, "%s: vpb_write: Checked frame format..\n", p->dev); 
2300 */
2301
2302         ast_mutex_lock(&p->play_lock);
2303
2304 /*
2305         ast_log(LOG_DEBUG, "%s: vpb_write: Got play lock..\n", p->dev); 
2306 */
2307
2308         /* Check if we have set up the play_buf */
2309         if (p->lastoutput == -1) {
2310                 vpb_play_buf_start(p->handle, fmt);
2311                 if(option_verbose>1) {
2312                         ast_verbose("%s: vpb_write: Starting play mode (codec=%d)[%s]\n",p->dev,fmt,ast2vpbformatname(frame->subclass));
2313                 }
2314                 p->lastoutput = fmt;
2315                 ast_mutex_unlock(&p->play_lock);
2316                 return 0;
2317         } else if (p->lastoutput != fmt) {
2318                 vpb_play_buf_finish(p->handle);
2319                 vpb_play_buf_start(p->handle, fmt);
2320                 if(option_verbose>1) 
2321                         ast_verbose("%s: vpb_write: Changed play format (%d=>%d)\n",p->dev,p->lastoutput,fmt);
2322                 ast_mutex_unlock(&p->play_lock);
2323                 return 0;
2324         }
2325         p->lastoutput = fmt;
2326
2327
2328
2329         /* Apply extra gain ! */
2330         if( p->txswgain > MAX_VPB_GAIN )
2331                 a_gain_vector(p->txswgain - MAX_VPB_GAIN , (short*)frame->data, frame->datalen/sizeof(short));
2332
2333 /*      ast_log(LOG_DEBUG, "%s: vpb_write: Applied gain..\n", p->dev); */
2334 /*      ast_log(LOG_DEBUG, "%s: vpb_write: play_buf_time %d\n", p->dev, p->play_buf_time); */
2335
2336         if ((p->read_state == 1)&&(p->play_buf_time<5)){
2337                 play_buf_time_start = ast_tvnow();
2338 /*              res = vpb_play_buf_sync(p->handle, (char*)frame->data, tdiff*8*2); */
2339                 res = vpb_play_buf_sync(p->handle, (char*)frame->data, frame->datalen);
2340                 if( res == VPB_OK && option_verbose > 5 ) {
2341                         short * data = (short*)frame->data;
2342                         ast_verbose("%s: vpb_write: Wrote chan (codec=%d) %d %d\n", p->dev, fmt, data[0],data[1]);
2343                 }
2344                 p->play_buf_time = ast_tvdiff_ms(ast_tvnow(), play_buf_time_start);
2345         }
2346         else {
2347                 p->chuck_count++;
2348                 ast_log(LOG_DEBUG, "%s: vpb_write: Tossed data away, tooooo much data!![%d]\n", p->dev,p->chuck_count);
2349                 p->play_buf_time=0;
2350         }
2351
2352         ast_mutex_unlock(&p->play_lock);
2353 /*      ast_mutex_unlock(&p->lock); */
2354         if(option_verbose>5) 
2355                 ast_verbose("%s: vpb_write: Done Writing to channel\n", p->dev);
2356         return 0;
2357 }
2358
2359 /* Read monitor thread function. */
2360 static void *do_chanreads(void *pvt)
2361 {
2362         struct vpb_pvt *p = (struct vpb_pvt *)pvt;
2363         struct ast_frame *fr = &p->fr;
2364         char *readbuf = ((char *)p->buf) + AST_FRIENDLY_OFFSET;
2365         int bridgerec = 0;
2366         int afmt, readlen, res, fmt, trycnt=0;
2367         int ignore_dtmf;
2368         const char * getdtmf_var = NULL;
2369
2370         fr->frametype = AST_FRAME_VOICE;
2371         fr->src = "vpb";
2372         fr->mallocd = 0;
2373         fr->delivery.tv_sec = 0;
2374         fr->delivery.tv_usec = 0;
2375         fr->samples = VPB_SAMPLES;
2376         fr->offset = AST_FRIENDLY_OFFSET;
2377         memset(p->buf, 0, sizeof p->buf);
2378
2379         if (option_verbose > 2) {
2380                 ast_verbose("%s: chanreads: starting thread\n", p->dev);
2381         }  
2382         ast_mutex_lock(&p->record_lock);
2383
2384         p->stopreads = 0; 
2385         p->read_state = 1;
2386         while (!p->stopreads && p->owner) {
2387
2388                 if (option_verbose > 4)
2389                         ast_verbose("%s: chanreads: Starting cycle ...\n", p->dev);
2390                 if (option_verbose > 4)
2391                         ast_verbose("%s: chanreads: Checking bridge \n", p->dev);
2392                 if (p->bridge) {
2393                         if (p->bridge->c0 == p->owner && (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_0))
2394                                 bridgerec = 1;
2395                         else if (p->bridge->c1 == p->owner && (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_1))
2396                                 bridgerec = 1;
2397                         else 
2398                                 bridgerec = 0;
2399                 } else {
2400                         if (option_verbose > 4)
2401                                 ast_verbose("%s: chanreads: No native bridge.\n", p->dev);
2402                         if (p->owner->_bridge){
2403                                 if (option_verbose > 4){
2404                                         ast_verbose("%s: chanreads: Got Asterisk bridge with [%s].\n", p->dev,p->owner->_bridge->name);
2405                                 }
2406                                 bridgerec = 1;
2407                         }
2408                         else {
2409                                 bridgerec = 0;
2410                         }
2411                 }
2412
2413 /*              if ( (p->owner->_state != AST_STATE_UP) || !bridgerec) */
2414                 if ( (p->owner->_state != AST_STATE_UP) ) 
2415                 {
2416                         if (option_verbose > 4) {
2417                                 if (p->owner->_state != AST_STATE_UP)
2418                                         ast_verbose("%s: chanreads: Im not up[%d]\n", p->dev,p->owner->_state);
2419                                 else
2420                                         ast_verbose("%s: chanreads: No bridgerec[%d]\n", p->dev,bridgerec);
2421                         }  
2422                         vpb_sleep(10);
2423                         continue;
2424                 }
2425
2426                 /* Voicetronix DTMF detection can be triggered off ordinary speech
2427                  * This leads to annoying beeps during the conversation
2428                  * Avoid this problem by just setting VPB_GETDTMF when you want to listen for DTMF
2429                  */
2430                 /* ignore_dtmf = 1; */
2431                 ignore_dtmf = 0; /* set this to 1 to turn this feature on */
2432                 getdtmf_var = pbx_builtin_getvar_helper(p->owner,"VPB_GETDTMF");
2433                 if( getdtmf_var && ( strcasecmp( getdtmf_var, "yes" ) == 0 ) )
2434                         ignore_dtmf = 0;
2435
2436                 if(( ignore_dtmf != p->last_ignore_dtmf ) &&(!use_ast_dtmfdet)){
2437                         if(option_verbose>1) 
2438                                 ast_verbose( VERBOSE_PREFIX_2 "%s:Now %s DTMF \n",
2439                                         p->dev, ignore_dtmf ? "ignoring" : "listening for");
2440                         vpb_set_event_mask(p->handle, ignore_dtmf ? VPB_EVENTS_NODTMF : VPB_EVENTS_ALL );
2441                 }
2442                 p->last_ignore_dtmf = ignore_dtmf;
2443
2444                 /* Play DTMF digits here to avoid problem you get if playing a digit during 
2445                  * a record operation
2446                  */
2447                 if (option_verbose > 5) {
2448                         ast_verbose("%s: chanreads: Checking dtmf's \n", p->dev);
2449                 }  
2450                 ast_mutex_lock(&p->play_dtmf_lock);
2451                 if( p->play_dtmf[0] ) {
2452                         /* Try to ignore DTMF event we get after playing digit */
2453                         /* This DTMF is played by asterisk and leads to an annoying trailing beep on CISCO phones */
2454                         if( !ignore_dtmf) 
2455                                 vpb_set_event_mask(p->handle, VPB_EVENTS_NODTMF );
2456                         if (p->bridge == NULL){
2457                                 vpb_dial_sync(p->handle,p->play_dtmf);
2458                                 if(option_verbose>1) 
2459                                         ast_verbose( VERBOSE_PREFIX_2 "%s: chanreads: Played DTMF %s\n",p->dev,p->play_dtmf);
2460                         }
2461                         else {
2462                                 if (option_verbose > 1) 
2463                                         ast_verbose(VERBOSE_PREFIX_2 "%s: chanreads: Not playing DTMF frame on native bridge\n", p->dev);
2464                         }
2465                         p->play_dtmf[0] = '\0';
2466                         ast_mutex_unlock(&p->play_dtmf_lock);
2467                         vpb_sleep(700); /* Long enough to miss echo and DTMF event */
2468                         if( !ignore_dtmf) 
2469                                 vpb_set_event_mask(p->handle, VPB_EVENTS_ALL );
2470                         continue;
2471                 }
2472                 ast_mutex_unlock(&p->play_dtmf_lock);
2473
2474 /*              afmt = (p->owner) ? p->owner->rawreadformat : AST_FORMAT_SLINEAR; */
2475                 if (p->owner){
2476                         afmt = p->owner->rawreadformat;
2477 /*                      ast_log(LOG_DEBUG,"%s: Record using owner format [%s]\n", p->dev, ast2vpbformatname(afmt)); */
2478                 }
2479                 else {
2480                         afmt = AST_FORMAT_SLINEAR;
2481 /*                      ast_log(LOG_DEBUG,"%s: Record using default format [%s]\n", p->dev, ast2vpbformatname(afmt)); */
2482                 }
2483                 fmt = ast2vpbformat(afmt);
2484                 if (fmt < 0) {
2485                         ast_log(LOG_WARNING,"%s: Record failure (unsupported format %d)\n", p->dev, afmt);
2486                         return NULL;
2487                 }
2488                 readlen = VPB_SAMPLES * astformatbits(afmt) / 8;
2489
2490                 if (p->lastinput == -1) {
2491                         vpb_record_buf_start(p->handle, fmt);
2492                         vpb_reset_record_fifo_alarm(p->handle);
2493                         p->lastinput = fmt;
2494                         if(option_verbose>1) 
2495                                 ast_verbose( VERBOSE_PREFIX_2 "%s: Starting record mode (codec=%d)[%s]\n",p->dev,fmt,ast2vpbformatname(afmt));
2496                         continue;
2497                 } else if (p->lastinput != fmt) {
2498                         vpb_record_buf_finish(p->handle);
2499                         vpb_record_buf_start(p->handle, fmt);
2500                         p->lastinput = fmt;
2501                         if(option_verbose>1) 
2502                                 ast_verbose( VERBOSE_PREFIX_2 "%s: Changed record format (%d=>%d)\n",p->dev,p->lastinput,fmt);
2503                         continue;
2504                 }
2505
2506                 /* Read only if up and not bridged, or a bridge for which we can read. */
2507                 if (option_verbose > 5) {
2508                         ast_verbose("%s: chanreads: getting buffer!\n", p->dev);
2509                 }  
2510                 if( (res = vpb_record_buf_sync(p->handle, readbuf, readlen) ) == VPB_OK ) {
2511                         if (option_verbose > 5) {
2512                                 ast_verbose("%s: chanreads: got buffer!\n", p->dev);
2513                         }  
2514                         /* Apply extra gain ! */
2515                         if( p->rxswgain > MAX_VPB_GAIN )
2516                                 a_gain_vector(p->rxswgain - MAX_VPB_GAIN , (short*)readbuf, readlen/sizeof(short));
2517                         if (option_verbose > 5) {
2518                                 ast_verbose("%s: chanreads: applied gain\n", p->dev);
2519                         }  
2520
2521                         fr->subclass = afmt;
2522                         fr->data = readbuf;
2523                         fr->datalen = readlen;
2524                         fr->frametype = AST_FRAME_VOICE;
2525
2526                         if ((use_ast_dtmfdet)&&(p->vad)){
2527                                 fr = ast_dsp_process(p->owner,p->vad,fr);
2528                                 if (fr && (fr->frametype == AST_FRAME_DTMF))
2529                                         ast_log(LOG_DEBUG, "%s: chanreads: Detected DTMF '%c'\n",p->dev, fr->subclass);
2530                                 if (fr->subclass == 'm'){
2531                                         /* conf mute request */
2532                                         fr->frametype = AST_FRAME_NULL;
2533                                         fr->subclass = 0;
2534                                 }
2535                                 else if (fr->subclass == 'u'){
2536                                         /* Unmute */
2537                                         fr->frametype = AST_FRAME_NULL;
2538                                         fr->subclass = 0;
2539                                 }
2540                                 else if (fr->subclass == 'f'){
2541                                 }
2542                         }
2543                         /* Using trylock here to prevent deadlock when channel is hungup
2544                          * (ast_hangup() immediately gets lock)
2545                          */
2546                         if (p->owner && !p->stopreads ) {
2547                                 if (option_verbose > 5) {
2548                                         ast_verbose("%s: chanreads: queueing buffer on read frame q (state[%d])\n", p->dev,p->owner->_state);
2549                                 }  
2550                                 do {
2551                                         res = ast_mutex_trylock(&p->owner->lock);
2552                                         trycnt++;
2553                                 } while((res !=0)&&(trycnt<300));
2554                                 if (res==0)  {
2555                                         ast_queue_frame(p->owner, fr);
2556                                         ast_mutex_unlock(&p->owner->lock);
2557                                 } else {
2558                                         if (option_verbose > 4) 
2559                                                 ast_verbose("%s: chanreads: Couldnt get lock after %d tries!\n", p->dev,trycnt);
2560                                 }
2561                                 trycnt=0;
2562                                 
2563 /*
2564                                 res = ast_mutex_trylock(&p->owner->lock);
2565                                 if (res==0)  {
2566                                         ast_queue_frame(p->owner, fr);
2567                                         ast_mutex_unlock(&p->owner->lock);
2568                                 } else {
2569                                         if (res == EINVAL )
2570                                                 if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EINVAL[%d]\n", p->dev,res);
2571                                         else if (res == EBUSY )
2572                                                 if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EBUSY[%d]\n", p->dev,res);
2573                                         while(res !=0){
2574                                         res = ast_mutex_trylock(&p->owner->lock);
2575                                         }
2576                                         if (res==0)  {
2577                                                 ast_queue_frame(p->owner, fr);
2578                                                 ast_mutex_unlock(&p->owner->lock);
2579                                         }
2580                                         else {
2581                                                 if (res == EINVAL )
2582                                                         if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EINVAL[%d]\n", p->dev,res);
2583                                                 else if (res == EBUSY )
2584                                                         if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EBUSY[%d]\n", p->dev,res);
2585                                                 if (option_verbose > 4) ast_verbose("%s: chanreads: Couldnt get lock on owner[%s][%d][%d] channel to send frame!\n", p->dev,p->owner->name,(int)p->owner->lock.__m_owner,(int)p->owner->lock.__m_count);
2586                                         }
2587                                 }
2588 */
2589                                 if (option_verbose > 6) {
2590                                         short * data = (short*)readbuf;
2591                                         ast_verbose("%s: Read channel (codec=%d) %d %d\n", p->dev, fmt, data[0], data[1] );
2592                                 }  
2593                         }
2594                         else {
2595                                 if (option_verbose > 4) {
2596                                         ast_verbose("%s: p->stopreads[%d] p->owner[%p]\n", p->dev, p->stopreads,(void *)p->owner);
2597                                 }  
2598                         }
2599                 }
2600                 if (option_verbose > 4)
2601                         ast_verbose("%s: chanreads: Finished cycle...\n", p->dev);
2602         }
2603         p->read_state=0;
2604
2605         /* When stopreads seen, go away! */
2606         vpb_record_buf_finish(p->handle);
2607         p->read_state=0;
2608         ast_mutex_unlock(&p->record_lock);
2609
2610         if (option_verbose > 1)
2611                 ast_verbose(VERBOSE_PREFIX_2 "%s: Ending record mode (%d/%s)\n",
2612                          p->dev, p->stopreads, p->owner? "yes" : "no");     
2613         return NULL;
2614 }
2615
2616 static struct ast_channel *vpb_new(struct vpb_pvt *me, enum ast_channel_state state, char *context)
2617 {
2618         struct ast_channel *tmp; 
2619         char cid_num[256];
2620         char cid_name[256];
2621
2622         if (me->owner) {
2623             ast_log(LOG_WARNING, "Called vpb_new on owned channel (%s) ?!\n", me->dev);
2624             return NULL;
2625         }
2626         if (option_verbose > 3)
2627                 ast_verbose("%s: New call for context [%s]\n",me->dev,context);
2628             
2629         tmp = ast_channel_alloc(1, state, 0, 0, me->dev);
2630         if (tmp) {
2631                 if (use_ast_ind == 1){
2632                         tmp->tech = &vpb_tech_indicate;
2633                 }
2634                 else {
2635                         tmp->tech = &vpb_tech;
2636                 }
2637
2638                 tmp->callgroup = me->callgroup;
2639                 tmp->pickupgroup = me->pickupgroup;
2640                
2641                 /* Linear is the preferred format. Although Voicetronix supports other formats
2642                  * they are all converted to/from linear in the vpb code. Best for us to use
2643                  * linear since we can then adjust volume in this modules.
2644                  */
2645                 tmp->nativeformats = prefformat;
2646                 tmp->rawreadformat = AST_FORMAT_SLINEAR;
2647                 tmp->rawwriteformat =  AST_FORMAT_SLINEAR;
2648                 if (state == AST_STATE_RING) {
2649                         tmp->rings = 1;
2650                         cid_name[0] = '\0';
2651                         cid_num[0] = '\0';
2652                         ast_callerid_split(me->callerid, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
2653                         ast_set_callerid(tmp, cid_num, cid_name, cid_num);
2654                 }
2655                 tmp->tech_pvt = me;
2656                 
2657                 strncpy(tmp->context, context, sizeof(tmp->context)-1);
2658                 if (strlen(me->ext))
2659                         strncpy(tmp->exten, me->ext, sizeof(tmp->exten)-1);
2660                 else
2661                         strncpy(tmp->exten, "s",  sizeof(tmp->exten) - 1);
2662                 if (strlen(me->language))
2663                         ast_string_field_set(tmp, language, me->language);
2664
2665                 me->owner = tmp;
2666      
2667                 me->bridge = NULL;
2668                 me->lastoutput = -1;
2669                 me->lastinput = -1;
2670                 me->last_ignore_dtmf = 1;
2671                 me->readthread = 0;
2672                 me->play_dtmf[0] = '\0';
2673                 me->faxhandled =0;
2674                 
2675                 me->lastgrunt  = ast_tvnow(); /* Assume at least one grunt tone seen now. */
2676                 me->lastplay  = ast_tvnow(); /* Assume at least one grunt tone seen now. */
2677
2678                 if (state != AST_STATE_DOWN) {
2679                         if ((me->mode != MODE_FXO)&&(state != AST_STATE_UP)){
2680                                 vpb_answer(tmp);
2681                         }
2682                         if (ast_pbx_start(tmp)) {
2683                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2684                                 ast_hangup(tmp);
2685                         }
2686                 }
2687         } else {
2688                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2689         }
2690         return tmp;
2691 }
2692
2693 static struct ast_channel *vpb_request(const char *type, int format, void *data, int *cause) 
2694 {
2695         int oldformat;
2696         struct vpb_pvt *p;
2697         struct ast_channel *tmp = NULL;
2698         char *name = strdup(data ? (char *)data : "");
2699         char *s, *sepstr;
2700         int group=-1;
2701
2702         oldformat = format;
2703         format &= prefformat;
2704         if (!format) {
2705                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
2706                 return NULL;
2707         }
2708
2709         sepstr = name;
2710         s = strsep(&sepstr, "/"); /* Handle / issues */
2711         if (!s) 
2712                 s = "";
2713         /* Check if we are looking for a group */
2714         if (toupper(name[0]) == 'G' || toupper(name[0])=='R') {
2715                 group=atoi(name+1);     
2716         }
2717         /* Search for an unowned channel */
2718         ast_mutex_lock(&iflock); {
2719                 p = iflist;
2720                 while(p) {
2721                         if (group == -1){
2722                                 if (strncmp(s, p->dev + 4, sizeof p->dev) == 0) {
2723                                         if (!p->owner) {
2724                                                 tmp = vpb_new(p, AST_STATE_DOWN, p->context);
2725                                                 break;
2726                                         }
2727                                 }
2728                         }
2729                         else {
2730                                 if ((p->group == group) && (!p->owner)) {
2731                                         tmp = vpb_new(p, AST_STATE_DOWN, p->context);
2732                                         break;
2733                                 }
2734                         }
2735                         p = p->next;
2736                 }
2737         } ast_mutex_unlock(&iflock);
2738
2739
2740         if (option_verbose > 1) 
2741                 ast_verbose(VERBOSE_PREFIX_2 " %s requested, got: [%s]\n",
2742                 name, tmp ? tmp->name : "None");
2743
2744         free(name);
2745
2746         restart_monitor();
2747         return tmp;
2748 }
2749
2750 static float parse_gain_value(char *gain_type, char *value)
2751 {
2752         float gain;
2753
2754         /* try to scan number */
2755         if (sscanf(value, "%f", &gain) != 1)
2756         {
2757                 ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n", value, gain_type, config);
2758                 return DEFAULT_GAIN;
2759         }
2760
2761
2762         /* percentage? */
2763         /*if (value[strlen(value) - 1] == '%') */
2764         /*      return gain / (float)100; */
2765
2766         return gain;
2767 }
2768
2769
2770 int unload_module()
2771 {
2772         struct vpb_pvt *p;
2773         /* First, take us out of the channel loop */
2774         if (use_ast_ind == 1){
2775                 ast_channel_unregister(&vpb_tech_indicate);
2776         }
2777         else {
2778                 ast_channel_unregister(&vpb_tech);
2779         }
2780
2781         ast_mutex_lock(&iflock); {
2782                 /* Hangup all interfaces if they have an owner */
2783                 p = iflist;
2784                 while(p) {
2785                         if (p->owner)
2786                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2787                         p = p->next;
2788                 }
2789                 iflist = NULL;
2790         } ast_mutex_unlock(&iflock);
2791
2792         ast_mutex_lock(&monlock); {
2793                 if (mthreadactive > -1) {
2794                         pthread_cancel(monitor_thread);
2795                         pthread_join(monitor_thread, NULL);
2796                 }
2797                 mthreadactive = -2;
2798         } ast_mutex_unlock(&monlock);
2799
2800         ast_mutex_lock(&iflock); {
2801                 /* Destroy all the interfaces and free their memory */
2802
2803                 while(iflist) {
2804                         p = iflist;                 
2805                         ast_mutex_destroy(&p->lock);
2806                         pthread_cancel(p->readthread);
2807                         ast_mutex_destroy(&p->owner_lock);
2808                         ast_mutex_destroy(&p->record_lock);
2809                         ast_mutex_destroy(&p->play_lock);
2810                         ast_mutex_destroy(&p->play_dtmf_lock);
2811                         p->readthread = 0;
2812
2813                         vpb_close(p->handle);
2814
2815                         iflist = iflist->next;
2816
2817                         free(p);
2818                 }
2819                 iflist = NULL;
2820         } ast_mutex_unlock(&iflock);
2821
2822         ast_mutex_lock(&bridge_lock); {
2823                 memset(bridges, 0, sizeof bridges);          
2824         } ast_mutex_unlock(&bridge_lock);
2825         ast_mutex_destroy(&bridge_lock);
2826         for(int i = 0; i < max_bridges; i++ ) {
2827                 ast_mutex_destroy(&bridges[i].lock);
2828                 ast_cond_destroy(&bridges[i].cond);
2829         }
2830         free(bridges);
2831
2832         return 0;
2833 }
2834
2835 int load_module()
2836 {
2837         struct ast_config *cfg;
2838         struct ast_variable *v;
2839         struct vpb_pvt *tmp;
2840         int board = 0, group = 0;
2841         ast_group_t     callgroup = 0;
2842         ast_group_t     pickupgroup = 0;
2843         int mode = MODE_IMMEDIATE;
2844         float txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN; 
2845         float txswgain = 0, rxswgain = 0; 
2846         int got_gain=0;
2847         int first_channel = 1;
2848         int echo_cancel = DEFAULT_ECHO_CANCEL;
2849         int error = 0; /* Error flag */
2850         int bal1 = -1; /* Special value - means do not set */
2851         int bal2 = -1; 
2852         int bal3 = -1;
2853         char * callerid = NULL;
2854
2855         cfg = ast_config_load(config);
2856
2857         /* We *must* have a config file otherwise stop immediately */
2858         if (!cfg) {
2859                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
2860                 return AST_MODULE_LOAD_DECLINE;
2861         }  
2862
2863         vpb_seterrormode(VPB_ERROR_CODE);
2864
2865         ast_mutex_lock(&iflock); {
2866                 v = ast_variable_browse(cfg, "general");
2867                 while (v){
2868                         if (strcasecmp(v->name, "cards") == 0) {
2869                                 ast_log(LOG_NOTICE,"VPB Driver configured to use [%d] cards\n",atoi(v->value));
2870                         }
2871                         else if (strcasecmp(v->name, "indication") == 0) {
2872                                 use_ast_ind = 1;
2873                                 ast_log(LOG_NOTICE,"VPB driver using Asterisk Indication functions!\n");
2874                         }
2875                         else if (strcasecmp(v->name, "break-for-dtmf") == 0) {
2876                                 if (ast_true(v->value)){
2877                                         break_for_dtmf = 1;
2878                                 }
2879                                 else {
2880                                         break_for_dtmf = 0;
2881                                         ast_log(LOG_NOTICE,"VPB driver not stopping for DTMF's in native bridge\n");
2882                                 }
2883                         }
2884                         else if (strcasecmp(v->name, "ast-dtmf") == 0) {
2885                                 use_ast_dtmf = 1;
2886                                 ast_log(LOG_NOTICE,"VPB driver using Asterisk DTMF play functions!\n");
2887                         }
2888                         else if (strcasecmp(v->name, "ast-dtmf-det") == 0) {
2889                                 use_ast_dtmfdet = 1;
2890                                 ast_log(LOG_NOTICE,"VPB driver using Asterisk DTMF detection functions!\n");
2891                         }
2892                         else if (strcasecmp(v->name, "relaxdtmf") == 0) {
2893                                 relaxdtmf = 1;
2894                                 ast_log(LOG_NOTICE,"VPB driver using Relaxed DTMF with Asterisk DTMF detections functions!\n");
2895                         }
2896                         else if (strcasecmp(v->name, "timer_period_ring") ==0) {
2897                                 timer_period_ring = atoi(v->value);
2898                         }
2899                         else if (strcasecmp(v->name, "ecsuppthres") ==0) {
2900                                 ec_supp_threshold = atoi(v->value);
2901