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