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