updates to compile against current trunk
[asterisk/asterisk.git] / channels / chan_vpb.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2003, Paul Bagyenda
5  * Paul Bagyenda <bagyenda@dsmagic.com>
6  * Copyright (C) 2004 - 2005, Ben Kramer
7  * Ben Kramer <ben@voicetronix.com.au>
8  *
9  * Daniel Bichara <daniel@bichara.com.br> - Brazilian CallerID detection (c)2004 
10  *
11  * Welber Silveira - welberms@magiclink.com.br - (c)2004
12  * Copying CLID string to propper structure after detection
13  *
14  * See http://www.asterisk.org for more information about
15  * the Asterisk project. Please do not directly contact
16  * any of the maintainers of this project for assistance;
17  * the project provides a web site, mailing lists and IRC
18  * channels for your use.
19  *
20  * This program is free software, distributed under the terms of
21  * the GNU General Public License Version 2. See the LICENSE file
22  * at the top of the source tree.
23  */
24
25 /*! \file
26  *
27  * \brief VoiceTronix Interface driver
28  * 
29  * \ingroup channel_drivers
30  */
31
32
33 extern "C" {
34
35 #include <stdio.h>
36 #include <string.h>
37
38 #include "asterisk.h"
39
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41
42 #include "asterisk/lock.h"
43 #include "asterisk/utils.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/config.h"
46 #include "asterisk/logger.h"
47 #include "asterisk/module.h"
48 #include "asterisk/pbx.h"
49 #include "asterisk/options.h"
50 #include "asterisk/callerid.h"
51 #include "asterisk/dsp.h"
52 #include "asterisk/features.h"
53 }
54
55 #include <sys/socket.h>
56 #include <sys/time.h>
57 #include <errno.h>
58 #include <unistd.h>
59 #include <stdlib.h>
60 #include <arpa/inet.h>
61 #include <fcntl.h>
62 #include <sys/ioctl.h>
63 #include <ctype.h>
64
65 #include <vpbapi.h>
66 #include <assert.h>
67
68 #ifdef pthread_create
69 #undef pthread_create
70 #endif
71
72 #define DEFAULT_GAIN 0
73 #define DEFAULT_ECHO_CANCEL 1
74   
75 #define VPB_SAMPLES 160 
76 #define VPB_MAX_BUF VPB_SAMPLES*4 + AST_FRIENDLY_OFFSET
77
78 #define VPB_NULL_EVENT 200
79
80 #define VPB_WAIT_TIMEOUT 4000
81
82 #define MAX_VPB_GAIN 12.0
83 #define MIN_VPB_GAIN -12.0
84
85 #define DTMF_CALLERID  
86 #define DTMF_CID_START 'D'
87 #define DTMF_CID_STOP 'C'
88
89 /**/
90 #if defined(__cplusplus) || defined(c_plusplus)
91  extern "C" {
92 #endif
93 /**/
94
95 static const char desc[] = "VoiceTronix V6PCI/V12PCI/V4PCI  API Support";
96 static const char tdesc[] = "Standard VoiceTronix API Driver";
97 static const char config[] = "vpb.conf";
98
99 /* Default context for dialtone mode */
100 static char context[AST_MAX_EXTENSION] = "default";
101
102 /* Default language */
103 static char language[MAX_LANGUAGE] = "";
104 static int usecnt =0;
105
106 static int gruntdetect_timeout = 3600000; /* Grunt detect timeout is 1hr. */
107
108 static const int prefformat = AST_FORMAT_SLINEAR;
109
110 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
111
112 /* Protect the interface list (of vpb_pvt's) */
113 AST_MUTEX_DEFINE_STATIC(iflock);
114
115 /* Protect the monitoring thread, so only one process can kill or start it, and not
116    when it's doing something critical. */
117 AST_MUTEX_DEFINE_STATIC(monlock);
118
119 /* This is the thread for the monitor which checks for input on the channels
120    which are not currently in use.  */
121 static pthread_t monitor_thread;
122
123 static int mthreadactive = -1; /* Flag for monitoring monitorthread.*/
124
125
126 static int restart_monitor(void);
127
128 /* The private structures of the VPB channels are 
129    linked for selecting outgoing channels */
130    
131 #define MODE_DIALTONE   1
132 #define MODE_IMMEDIATE  2
133 #define MODE_FXO        3
134
135 /* Pick a country or add your own! */
136 /* These are the tones that are played to the user */
137 #define TONES_AU
138 /* #define TONES_USA */
139
140 #ifdef TONES_AU
141 static VPB_TONE Dialtone     = {440,    440,    440,    -10,    -10,    -10,    5000,   0   };
142 static VPB_TONE Busytone     = {470,    0,      0,      -10,    -100,   -100,   5000,   0 };
143 static VPB_TONE Ringbacktone = {400,    50,     440,    -10,    -10,    -10,    1400,   800 };
144 #endif
145 #ifdef TONES_USA
146 static VPB_TONE Dialtone     = {350, 440,   0, -16,   -16, -100, 10000,    0};
147 static VPB_TONE Busytone     = {480, 620,   0, -10,   -10, -100,   500,  500};
148 static VPB_TONE Ringbacktone = {440, 480,   0, -20,   -20, -100,  2000, 4000};
149 #endif
150
151 /* grunt tone defn's */
152 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 } } };
153 static VPB_DETECT toned_ungrunt = { 2, VPB_GRUNT, 1, 2000, 1, 0, 0, -40, 0, 0, 30, 40, { { 0, 0, 0, 0 } } };
154
155 /* Use loop polarity detection for CID */
156 static int UsePolarityCID=0;
157
158 /* Use loop drop detection */
159 static int UseLoopDrop=1;
160
161 /* To use or not to use Native bridging */
162 static int UseNativeBridge=1;
163
164 /* Use Asterisk Indication or VPB */
165 static int use_ast_ind=0;
166
167 /* Use Asterisk DTMF detection or VPB */
168 static int use_ast_dtmfdet=0;
169
170 static int relaxdtmf=0;
171
172 /* Use Asterisk DTMF play back or VPB */
173 static int use_ast_dtmf=0;
174
175 /* Break for DTMF on native bridge ? */
176 static int break_for_dtmf=1;
177
178 /* Set EC suppression threshold */
179 static int ec_supp_threshold=-1;
180
181 /* Inter Digit Delay for collecting DTMF's */
182 static int dtmf_idd = 3000;
183
184 #define TIMER_PERIOD_RINGBACK 2000
185 #define TIMER_PERIOD_BUSY 700
186 #define TIMER_PERIOD_RING 4000
187 static int timer_period_ring = TIMER_PERIOD_RING;
188           
189 #define VPB_EVENTS_ALL (VPB_MRING|VPB_MDIGIT|VPB_MDTMF|VPB_MTONEDETECT|VPB_MTIMEREXP|VPB_MPLAY_UNDERFLOW \
190                         |VPB_MRECORD_OVERFLOW|VPB_MSTATION_OFFHOOK|VPB_MSTATION_ONHOOK \
191                         |VPB_MRING_OFF|VPB_MDROP|VPB_MSTATION_FLASH)
192 #define VPB_EVENTS_NODROP (VPB_MRING|VPB_MDIGIT|VPB_MDTMF|VPB_MTONEDETECT|VPB_MTIMEREXP|VPB_MPLAY_UNDERFLOW \
193                         |VPB_MRECORD_OVERFLOW|VPB_MSTATION_OFFHOOK|VPB_MSTATION_ONHOOK \
194                         |VPB_MRING_OFF|VPB_MSTATION_FLASH)
195 #define VPB_EVENTS_NODTMF (VPB_MRING|VPB_MDIGIT|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_STAT (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
202
203 /* Dialing parameters for Australia */
204 /* #define DIAL_WITH_CALL_PROGRESS */
205 VPB_TONE_MAP DialToneMap[] = {  { VPB_BUSY_AUST, VPB_CALL_DISCONNECT, 0 },
206                                 { VPB_DIAL, VPB_CALL_DIALTONE, 0 },
207                                 { VPB_RINGBACK_308, VPB_CALL_RINGBACK, 0 },
208                                 { VPB_BUSY_AUST, VPB_CALL_BUSY, 0 },
209                                 { VPB_GRUNT, VPB_CALL_GRUNT, 0 },
210                                 { 0, 0, 1 } };
211 #define VPB_DIALTONE_WAIT 2000 /* Wait up to 2s for a dialtone */
212 #define VPB_RINGWAIT 4000 /* Wait up to 4s for ring tone after dialing */
213 #define VPB_CONNECTED_WAIT 4000 /* If no ring tone detected for 4s then consider call connected */
214 #define TIMER_PERIOD_NOANSWER 120000 /* Let it ring for 120s before deciding theres noone there */
215
216 #define MAX_BRIDGES_V4PCI 2
217 #define MAX_BRIDGES_V12PCI 128
218
219 /* port states */
220 #define VPB_STATE_ONHOOK        0
221 #define VPB_STATE_OFFHOOK       1
222 #define VPB_STATE_DIALLING      2
223 #define VPB_STATE_JOINED        3
224 #define VPB_STATE_GETDTMF       4
225 #define VPB_STATE_PLAYDIAL      5
226 #define VPB_STATE_PLAYBUSY      6
227 #define VPB_STATE_PLAYRING      7
228
229 #define VPB_GOT_RXHWG           1
230 #define VPB_GOT_TXHWG           2
231 #define VPB_GOT_RXSWG           4
232 #define VPB_GOT_TXSWG           8
233
234 typedef struct  {
235         int inuse;
236         struct ast_channel *c0, *c1, **rc;
237         struct ast_frame **fo;
238         int flags;
239         ast_mutex_t lock;
240         ast_cond_t cond;
241         int endbridge;
242 } vpb_bridge_t;
243
244 static vpb_bridge_t * bridges;
245 static int max_bridges = MAX_BRIDGES_V4PCI;
246
247 AST_MUTEX_DEFINE_STATIC(bridge_lock);
248
249 typedef enum {
250         vpb_model_unknown = 0, 
251         vpb_model_v4pci,
252         vpb_model_v12pci
253 } vpb_model_t;
254
255 static struct vpb_pvt {
256
257         ast_mutex_t owner_lock;                 /* Protect blocks that expect ownership to remain the same */
258         struct ast_channel *owner;              /* Channel who owns us, possibly NULL */
259
260         int golock;                             /* Got owner lock ? */
261
262         int mode;                               /* fxo/imediate/dialtone*/
263         int handle;                             /* Handle for vpb interface */
264
265         int state;                              /* used to keep port state (internal to driver) */
266
267         int group;                              /* Which group this port belongs to */
268         ast_group_t callgroup;                  /* Call group */
269         ast_group_t pickupgroup;                /* Pickup group */
270
271
272         char dev[256];                          /* Device name, eg vpb/1-1 */
273         vpb_model_t vpb_model;                  /* card model */
274
275         struct ast_frame f, fr;                 /* Asterisk frame interface */
276         char buf[VPB_MAX_BUF];                  /* Static buffer for reading frames */
277
278         int dialtone;                           /* NOT USED */
279         float txgain, rxgain;                   /* Hardware gain control */
280         float txswgain, rxswgain;               /* Software gain control */
281
282         int wantdtmf;                           /* Waiting for DTMF. */
283         char context[AST_MAX_EXTENSION];        /* The context for this channel */
284
285         char ext[AST_MAX_EXTENSION];            /* DTMF buffer for the ext[ens] */
286         char language[MAX_LANGUAGE];            /* language being used */
287         char callerid[AST_MAX_EXTENSION];       /* CallerId used for directly connected phone */
288         int  callerid_type;                     /* Caller ID type: 0=>none 1=>vpb 2=>AstV23 3=>AstBell */
289         char cid_num[AST_MAX_EXTENSION];
290         char cid_name[AST_MAX_EXTENSION];
291
292         int dtmf_caller_pos;                    /* DTMF CallerID detection (Brazil)*/
293
294         int lastoutput;                         /* Holds the last Audio format output'ed */
295         int lastinput;                          /* Holds the last Audio format input'ed */
296         int last_ignore_dtmf;
297
298         void *busy_timer;                       /* Void pointer for busy vpb_timer */
299         int busy_timer_id;                      /* unique timer ID for busy timer */
300
301         void *ringback_timer;                   /* Void pointer for ringback vpb_timer */
302         int ringback_timer_id;                  /* unique timer ID for ringback timer */
303
304         void *ring_timer;                       /* Void pointer for ring vpb_timer */
305         int ring_timer_id;                      /* unique timer ID for ring timer */
306
307         void *dtmfidd_timer;                    /* Void pointer for DTMF IDD vpb_timer */
308         int dtmfidd_timer_id;                   /* unique timer ID for DTMF IDD timer */
309
310         struct ast_dsp *vad;                    /* AST  Voice Activation Detection dsp */
311
312         struct timeval lastgrunt;                       /* time stamp of last grunt event */
313
314         ast_mutex_t lock;                       /* This one just protects bridge ptr below */
315         vpb_bridge_t *bridge;
316
317         int stopreads;                          /* Stop reading...*/
318         int read_state;                         /* Read state */
319         int chuck_count;                        /* a count of packets weve chucked away!*/
320         pthread_t readthread;                   /* For monitoring read channel. One per owned channel. */
321
322         ast_mutex_t record_lock;                /* This one prevents reentering a record_buf block */
323         ast_mutex_t play_lock;                  /* This one prevents reentering a play_buf block */
324         int  play_buf_time;                     /* How long the last play_buf took */
325         struct timeval lastplay;                /* Last play time */
326
327         ast_mutex_t play_dtmf_lock;
328         char play_dtmf[16];
329
330         int faxhandled;                         /* has a fax tone been handled ? */
331
332         struct vpb_pvt *next;                   /* Next channel in list */
333
334 } *iflist = NULL;
335
336 static struct ast_channel *vpb_new(struct vpb_pvt *i, int state, char *context);
337 static void *do_chanreads(void *pvt);
338
339 static struct ast_channel *vpb_request(const char *type, int format, void *data, int *cause);
340 static int vpb_digit(struct ast_channel *ast, char digit);
341 static int vpb_call(struct ast_channel *ast, char *dest, int timeout);
342 static int vpb_hangup(struct ast_channel *ast);
343 static int vpb_answer(struct ast_channel *ast);
344 static struct ast_frame *vpb_read(struct ast_channel *ast);
345 static int vpb_write(struct ast_channel *ast, struct ast_frame *frame);
346 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);
347 static int vpb_indicate(struct ast_channel *ast, int condition);
348 static int vpb_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
349
350 static struct ast_channel_tech vpb_tech = {
351         type: "vpb",
352         description: tdesc,
353         capabilities: AST_FORMAT_SLINEAR,
354         properties: 0,
355         requester: vpb_request,
356         devicestate: NULL,
357         send_digit: vpb_digit,
358         send_digit_begin: NULL,
359         send_digit_end: NULL,
360         call: vpb_call,
361         hangup: vpb_hangup,
362         answer: vpb_answer,
363         read: vpb_read,
364         write: vpb_write,
365         send_text: NULL,
366         send_image: NULL,
367         send_html: NULL,
368         exception: NULL,
369         bridge: ast_vpb_bridge,
370         indicate: vpb_indicate,
371         fixup: vpb_fixup,
372         setoption: NULL,
373         queryoption: NULL,
374         transfer: NULL,
375         write_video: NULL,
376         bridged_channel: NULL
377 };
378
379 static struct ast_channel_tech vpb_tech_indicate = {
380         type: "vpb",
381         description: tdesc,
382         capabilities: AST_FORMAT_SLINEAR,
383         properties: 0,
384         requester: vpb_request,
385         devicestate: NULL,
386         send_digit: vpb_digit,
387         send_digit_begin: NULL,
388         send_digit_end: NULL,
389         call: vpb_call,
390         hangup: vpb_hangup,
391         answer: vpb_answer,
392         read: vpb_read,
393         write: vpb_write,
394         send_text: NULL,
395         send_image: NULL,
396         send_html: NULL,
397         exception: NULL,
398         bridge: ast_vpb_bridge,
399         indicate: NULL,
400         fixup: vpb_fixup,
401         setoption: NULL,
402         queryoption: NULL,
403         transfer: NULL,
404         write_video: NULL,
405         bridged_channel: NULL
406 };
407
408 /* Can't get ast_vpb_bridge() working on v4pci without either a horrible 
409 *  high pitched feedback noise or bad hiss noise depending on gain settings
410 *  Get asterisk to do the bridging
411 */
412 #define BAD_V4PCI_BRIDGE
413
414 /* This one enables a half duplex bridge which may be required to prevent high pitched
415  * feedback when getting asterisk to do the bridging and when using certain gain settings.
416  */
417 /* #define HALF_DUPLEX_BRIDGE */
418
419 /* This is the Native bridge code, which Asterisk will try before using its own bridging code */
420 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)
421 {
422         struct vpb_pvt *p0 = (struct vpb_pvt *)c0->tech_pvt;
423         struct vpb_pvt *p1 = (struct vpb_pvt *)c1->tech_pvt;
424         int i;
425         int res;
426         struct ast_channel *cs[3];
427         struct ast_channel *who;
428         struct ast_frame *f;
429
430         cs[0] = c0;
431         cs[1] = c1;
432
433         #ifdef BAD_V4PCI_BRIDGE
434         if(p0->vpb_model==vpb_model_v4pci)
435                 return AST_BRIDGE_FAILED_NOWARN;
436         #endif
437         if ( UseNativeBridge != 1){
438                 return AST_BRIDGE_FAILED_NOWARN;
439         }
440
441 /*
442         ast_mutex_lock(&p0->lock);
443         ast_mutex_lock(&p1->lock);
444 */
445
446         /* Bridge channels, check if we can.  I believe we always can, so find a slot.*/
447
448         ast_mutex_lock(&bridge_lock); {
449                 for (i = 0; i < max_bridges; i++) 
450                         if (!bridges[i].inuse)
451                                 break;
452                 if (i < max_bridges) {
453                         bridges[i].inuse = 1;
454                         bridges[i].endbridge = 0;
455                         bridges[i].flags = flags;
456                         bridges[i].rc = rc;
457                         bridges[i].fo = fo;
458                         bridges[i].c0 = c0;
459                         bridges[i].c1 = c1;
460                 }              
461         } ast_mutex_unlock(&bridge_lock); 
462
463         if (i == max_bridges) {
464                 ast_log(LOG_WARNING, "%s: vpb_bridge: Failed to bridge %s and %s!\n", p0->dev, c0->name, c1->name);
465                 ast_mutex_unlock(&p0->lock);
466                 ast_mutex_unlock(&p1->lock);
467                 return AST_BRIDGE_FAILED_NOWARN;
468         } else {
469                 /* Set bridge pointers. You don't want to take these locks while holding bridge lock.*/
470                 ast_mutex_lock(&p0->lock); {
471                         p0->bridge = &bridges[i];
472                 } ast_mutex_unlock(&p0->lock);
473
474                 ast_mutex_lock(&p1->lock); {
475                         p1->bridge = &bridges[i];
476                 } ast_mutex_unlock(&p1->lock);
477
478                 if (option_verbose>1) 
479                         ast_verbose(VERBOSE_PREFIX_2 "%s: vpb_bridge: Bridging call entered with [%s, %s]\n",p0->dev, c0->name, c1->name);
480         }
481
482         if (option_verbose > 2) 
483                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
484
485         #ifdef HALF_DUPLEX_BRIDGE
486
487         if (option_verbose>1) 
488                 ast_verbose(VERBOSE_PREFIX_2 "%s: vpb_bridge: Starting half-duplex bridge [%s, %s]\n",p0->dev, c0->name, c1->name);
489
490         int dir = 0;
491
492         memset(p0->buf, 0, sizeof p0->buf);
493         memset(p1->buf, 0, sizeof p1->buf);
494
495         vpb_record_buf_start(p0->handle, VPB_ALAW);
496         vpb_record_buf_start(p1->handle, VPB_ALAW);
497
498         vpb_play_buf_start(p0->handle, VPB_ALAW);
499         vpb_play_buf_start(p1->handle, VPB_ALAW);
500
501         while( !bridges[i].endbridge ) {
502                 struct vpb_pvt *from, *to;
503                 if(++dir%2) {
504                         from = p0;
505                         to = p1;
506                 } else {
507                         from = p1;
508                         to = p0;
509                 }
510                 vpb_record_buf_sync(from->handle, from->buf, VPB_SAMPLES);
511                 vpb_play_buf_sync(to->handle, from->buf, VPB_SAMPLES);
512         }
513
514         vpb_record_buf_finish(p0->handle);
515         vpb_record_buf_finish(p1->handle);
516
517         vpb_play_buf_finish(p0->handle);
518         vpb_play_buf_finish(p1->handle);
519
520         if (option_verbose>1) 
521                 ast_verbose(VERBOSE_PREFIX_2 "%s: vpb_bridge: Finished half-duplex bridge [%s, %s]\n",p0->dev, c0->name, c1->name);
522
523         res = VPB_OK;
524
525         #else
526
527         res = vpb_bridge(p0->handle, p1->handle, VPB_BRIDGE_ON, i+1 /* resource 1 & 2 only for V4PCI*/ );
528         if (res == VPB_OK) {
529                 /* pthread_cond_wait(&bridges[i].cond, &bridges[i].lock);*/ /* Wait for condition signal. */
530                 while( !bridges[i].endbridge ) {
531                         /* Are we really ment to be doing nothing ?!?! */
532                         who = ast_waitfor_n(cs, 2, &timeoutms);
533                         if (!who) {
534                                 if (!timeoutms) {
535                                         res = AST_BRIDGE_RETRY;
536                                         break;
537                                 }
538                                 ast_log(LOG_DEBUG, "%s: vpb_bridge: Empty frame read...\n",p0->dev);
539                                 /* check for hangup / whentohangup */
540                                 if (ast_check_hangup(c0) || ast_check_hangup(c1))
541                                         break;
542                                 continue;
543                         }
544                         f = ast_read(who);
545                         if (!f || ((f->frametype == AST_FRAME_DTMF) &&
546                                            (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
547                                        ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
548                                 *fo = f;
549                                 *rc = who;
550                                 ast_log(LOG_DEBUG, "%s: vpb_bridge: Got a [%s]\n",p0->dev, f ? "digit" : "hangup");
551 /*
552                                 if ((c0->tech_pvt == pvt0) && (!c0->_softhangup)) {
553                                         if (pr0->set_rtp_peer(c0, NULL, NULL, 0)) 
554                                                 ast_log(LOG_WARNING, "Channel '%s' failed to revert\n", c0->name);
555                                 }
556                                 if ((c1->tech_pvt == pvt1) && (!c1->_softhangup)) {
557                                         if (pr1->set_rtp_peer(c1, NULL, NULL, 0)) 
558                                                 ast_log(LOG_WARNING, "Channel '%s' failed to revert back\n", c1->name);
559                                 }
560 */
561                                 /* That's all we needed */
562                                 /*return 0; */
563                                 /* Check if we need to break */
564                                 if (break_for_dtmf){
565                                         break;
566                                 }
567                                 else if ((f->frametype == AST_FRAME_DTMF) && ((f->subclass == '#')||(f->subclass == '*'))){
568                                         break;
569                                 }
570                         } else {
571                                 if ((f->frametype == AST_FRAME_DTMF) || 
572                                         (f->frametype == AST_FRAME_VOICE) || 
573                                         (f->frametype == AST_FRAME_VIDEO)) 
574                                         {
575                                         /* Forward voice or DTMF frames if they happen upon us */
576                                         /* Actually I dont think we want to forward on any frames!
577                                         if (who == c0) {
578                                                 ast_write(c1, f);
579                                         } else if (who == c1) {
580                                                 ast_write(c0, f);
581                                         }
582                                         */
583                                 }
584                                 ast_frfree(f);
585                         }
586                         /* Swap priority not that it's a big deal at this point */
587                         cs[2] = cs[0];
588                         cs[0] = cs[1];
589                         cs[1] = cs[2];
590                 };
591                 vpb_bridge(p0->handle, p1->handle, VPB_BRIDGE_OFF, i+1 /* resource 1 & 2 only for V4PCI*/ ); 
592         }
593
594         #endif
595
596         ast_mutex_lock(&bridge_lock); {
597                 bridges[i].inuse = 0;
598         } ast_mutex_unlock(&bridge_lock); 
599
600         p0->bridge = NULL;
601         p1->bridge = NULL;
602
603
604         if (option_verbose>1) 
605                 ast_verbose(VERBOSE_PREFIX_2 "Bridging call done with [%s, %s] => %d\n", c0->name, c1->name, res);
606
607 /*
608         ast_mutex_unlock(&p0->lock);
609         ast_mutex_unlock(&p1->lock);
610 */
611         return (res==VPB_OK) ? AST_BRIDGE_COMPLETE : AST_BRIDGE_FAILED;
612 }
613
614 /* Caller ID can be located in different positions between the rings depending on your Telco
615  * Australian (Telstra) callerid starts 700ms after 1st ring and finishes 1.5s after first ring
616  * Use ANALYSE_CID to record rings and determine location of callerid
617  */
618 /* #define ANALYSE_CID */
619 #define RING_SKIP 300
620 #define CID_MSECS 2000
621
622 static void get_callerid(struct vpb_pvt *p)
623 {
624         short buf[CID_MSECS*8]; /* 8kHz sampling rate */
625         struct timeval cid_record_time;
626         int rc;
627         struct ast_channel *owner = p->owner;
628 /*
629         char callerid[AST_MAX_EXTENSION] = ""; 
630 */
631 #ifdef ANALYSE_CID
632         void * ws;
633         char * file="cidsams.wav";
634 #endif
635
636
637         if( ast_mutex_trylock(&p->record_lock) == 0 ) {
638
639                 cid_record_time = ast_tvnow();
640                 if (option_verbose>3) 
641                         ast_verbose(VERBOSE_PREFIX_4 "CID record - start\n");
642
643                 /* Skip any trailing ringtone */
644                 if (UsePolarityCID != 1){
645                         vpb_sleep(RING_SKIP);
646                 }
647
648                 if (option_verbose>3) 
649                         ast_verbose(VERBOSE_PREFIX_4 "CID record - skipped %dms trailing ring\n",
650                                  ast_tvdiff_ms(ast_tvnow(), cid_record_time));
651                 cid_record_time = ast_tvnow();
652
653                 /* Record bit between the rings which contains the callerid */
654                 vpb_record_buf_start(p->handle, VPB_LINEAR);
655                 rc = vpb_record_buf_sync(p->handle, (char*)buf, sizeof(buf));
656                 vpb_record_buf_finish(p->handle);
657 #ifdef ANALYSE_CID
658                 vpb_wave_open_write(&ws, file, VPB_LINEAR);
659                 vpb_wave_write(ws,(char*)buf,sizeof(buf));
660                 vpb_wave_close_write(ws);
661 #endif
662
663                 if (option_verbose>3) 
664                         ast_verbose(VERBOSE_PREFIX_4 "CID record - recorded %dms between rings\n", 
665                                  ast_tvdiff_ms(ast_tvnow(), cid_record_time));
666
667                 ast_mutex_unlock(&p->record_lock);
668
669                 if( rc != VPB_OK ) {
670                         ast_log(LOG_ERROR, "Failed to record caller id sample on %s\n", p->dev );
671                         return;
672                 }
673
674                 VPB_CID *cli_struct = new VPB_CID;
675                 cli_struct->ra_cldn[0]=0;
676                 cli_struct->ra_cn[0]=0;
677                 /* This decodes FSK 1200baud type callerid */
678                 if ((rc=vpb_cid_decode2(cli_struct, buf, CID_MSECS*8)) == VPB_OK ) {
679                         /*
680                         if (owner->cid.cid_num)
681                                 free(owner->cid.cid_num);
682                         owner->cid.cid_num=NULL;
683                         if (owner->cid.cid_name)
684                                 free(owner->cid.cid_name);
685                         owner->cid.cid_name=NULL;
686                         */
687                         
688                         if (cli_struct->ra_cldn[0]=='\0'){
689                                 /*
690                                 owner->cid.cid_num = strdup(cli_struct->cldn);
691                                 owner->cid.cid_name = strdup(cli_struct->cn);
692                                 */
693                                 if (owner){
694                                         ast_set_callerid(owner, cli_struct->cldn, cli_struct->cn, cli_struct->cldn);
695                                 } else {
696                                         strcpy(p->cid_num, cli_struct->cldn);
697                                         strcpy(p->cid_name, cli_struct->cn);
698
699                                 }
700                                 if (option_verbose>3) 
701                                         ast_verbose(VERBOSE_PREFIX_4 "CID record - got [%s] [%s]\n",owner->cid.cid_num,owner->cid.cid_name );
702                                 snprintf(p->callerid,sizeof(p->callerid)-1,"%s %s",cli_struct->cldn,cli_struct->cn);
703                         }
704                         else {
705                                 ast_log(LOG_ERROR,"CID record - No caller id avalable on %s \n", p->dev);
706                         }
707
708                 } else {
709                         ast_log(LOG_ERROR, "CID record - Failed to decode caller id on %s - %s\n", p->dev, vpb_strerror(rc) );
710                         strncpy(p->callerid,"unknown", sizeof(p->callerid) - 1);
711                 }
712                 delete cli_struct;
713
714         } else 
715                 ast_log(LOG_ERROR, "CID record - Failed to set record mode for caller id on %s\n", p->dev );
716 }
717
718 static void get_callerid_ast(struct vpb_pvt *p)
719 {
720         struct callerid_state *cs;
721         char buf[1024];
722         char *name=NULL, *number=NULL;
723         int flags;
724         int rc=0,vrc;
725         int sam_count=0;
726         struct ast_channel *owner = p->owner;
727         int which_cid;
728 /*
729         float old_gain;
730 */
731 #ifdef ANALYSE_CID
732         void * ws;
733         char * file="cidsams.wav";
734 #endif
735
736         if(p->callerid_type == 1) {
737         if (option_verbose>3) ast_verbose(VERBOSE_PREFIX_4 "Collected caller ID already\n");
738                 return;
739         }
740         else if(p->callerid_type == 2 ) {
741                 which_cid=CID_SIG_V23;
742         if (option_verbose>3) ast_verbose(VERBOSE_PREFIX_4 "Collecting Caller ID v23...\n");
743         }
744         else if(p->callerid_type == 3) {
745                 which_cid=CID_SIG_BELL;
746         if (option_verbose>3) ast_verbose(VERBOSE_PREFIX_4 "Collecting Caller ID bell...\n");
747         }
748         else {
749                 if (option_verbose>3) 
750                         ast_verbose(VERBOSE_PREFIX_4 "Caller ID disabled\n");
751                 return;
752         }
753 /*      vpb_sleep(RING_SKIP); */
754 /*      vpb_record_get_gain(p->handle, &old_gain); */
755         cs = callerid_new(which_cid);
756         if (cs){
757 #ifdef ANALYSE_CID
758                 vpb_wave_open_write(&ws, file, VPB_MULAW); 
759                 vpb_record_set_gain(p->handle, 3.0); 
760                 vpb_record_set_hw_gain(p->handle,12.0); 
761 #endif
762                 vpb_record_buf_start(p->handle, VPB_MULAW);
763                 while((rc == 0)&&(sam_count<8000*3)){
764                         vrc = vpb_record_buf_sync(p->handle, (char*)buf, sizeof(buf));
765                         if (vrc != VPB_OK)
766                                 ast_log(LOG_ERROR, "%s: Caller ID couldnt read audio buffer!\n",p->dev);
767                         rc = callerid_feed(cs,(unsigned char *)buf,sizeof(buf),AST_FORMAT_ULAW);
768 #ifdef ANALYSE_CID
769                         vpb_wave_write(ws,(char*)buf,sizeof(buf)); 
770 #endif
771                         sam_count+=sizeof(buf);
772                         if (option_verbose>3) ast_verbose(VERBOSE_PREFIX_4 "Collecting Caller ID samples [%d][%d]...\n",sam_count,rc);
773                 }
774                 vpb_record_buf_finish(p->handle);
775 #ifdef ANALYSE_CID
776                 vpb_wave_close_write(ws); 
777 #endif
778                 if (rc == 1){
779                         callerid_get(cs, &name, &number, &flags);
780                         if (option_verbose>0) 
781                                 ast_verbose(VERBOSE_PREFIX_1 "%s: Caller ID name [%s] number [%s] flags [%d]\n",p->dev,name, number,flags);
782                 }
783                 else {
784                         ast_log(LOG_ERROR, "%s: Failed to decode Caller ID \n", p->dev );
785                 }
786 /*              vpb_record_set_gain(p->handle, old_gain); */
787 /*              vpb_record_set_hw_gain(p->handle,6.0); */
788         }
789         else {
790                 ast_log(LOG_ERROR, "%s: Failed to create Caller ID struct\n", p->dev );
791         }
792         if (owner->cid.cid_num) {
793                 free(owner->cid.cid_num);
794                 owner->cid.cid_num = NULL;
795         }
796         if (owner->cid.cid_name) {
797                 free(owner->cid.cid_name);
798                 owner->cid.cid_name = NULL;
799         }
800         if (number)
801                 ast_shrink_phone_number(number);
802         if (!ast_strlen_zero(number)) {
803                 owner->cid.cid_num = strdup(number);
804                 owner->cid.cid_ani = strdup(number);
805                 if (!ast_strlen_zero(name)){
806                         owner->cid.cid_name = strdup(name);
807                         snprintf(p->callerid,(sizeof(p->callerid)-1),"%s %s",number,name);
808                 }
809                 else {
810                         snprintf(p->callerid,(sizeof(p->callerid)-1),"%s",number);
811                 }
812         }
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 = -1; /* ignore ring on station port. */
865                         break;
866
867                 case VPB_RING_OFF:
868                         f.frametype = -1;
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 = -1;
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 = -1;
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 = -1;
892                                 }
893                                 
894                         } else {
895                                 f.frametype = -1; /* Ignore. */
896                         }
897                         break;
898
899                 case VPB_DTMF_DOWN:
900                 case VPB_DTMF:
901                         if (use_ast_dtmfdet){
902                                 f.frametype = -1;
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 = -1;
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 = ast_strlen_zero(p->owner->macrocontext) ? p->owner->context : p->owner->macrocontext;
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 = -1;
952                                 }
953                         } 
954                         else {
955                                 f.frametype = -1;
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 = -1;
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 = -1;
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 = -1;
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 = -1;
1011                         }
1012                         break;
1013
1014                 case VPB_PLAY_UNDERFLOW:
1015                         f.frametype = -1;
1016                         vpb_reset_play_fifo_alarm(p->handle);
1017                         break;
1018
1019                 case VPB_RECORD_OVERFLOW:
1020                         f.frametype = -1;
1021                         vpb_reset_record_fifo_alarm(p->handle);
1022                         break;
1023
1024                 default:
1025                         f.frametype = -1;
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)
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
1780                 default:
1781                         res = 0;
1782                         break;
1783         }
1784         tmp = ast_mutex_unlock(&p->lock);
1785 /*
1786         if (option_verbose > 3) ast_verbose("%s: unLOCKING in indicate [%d]\n", p->dev,tmp);
1787 */
1788         return res;
1789 }
1790
1791 static int vpb_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1792 {
1793         struct vpb_pvt *p = (struct vpb_pvt *)newchan->tech_pvt;
1794         int res = 0;
1795
1796 /*
1797         if (option_verbose > 3) ast_verbose("%s: LOCKING in fixup \n", p->dev);
1798         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1799 */
1800         ast_mutex_lock(&p->lock);
1801         ast_log(LOG_DEBUG, "New owner for channel %s is %s\n", p->dev, newchan->name);
1802
1803         if (p->owner == oldchan) {
1804                 p->owner = newchan;
1805         }
1806
1807         if (newchan->_state == AST_STATE_RINGING){
1808                 if (use_ast_ind == 1) {
1809                         if (option_verbose > 3)
1810                                 ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_fixup Calling ast_indicate\n", p->dev);
1811                         ast_indicate(newchan, AST_CONTROL_RINGING);
1812                 }
1813                 else {
1814                         if (option_verbose > 3)
1815                                 ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_fixup Calling vpb_indicate\n", p->dev);
1816                         vpb_indicate(newchan, AST_CONTROL_RINGING);
1817                 }
1818         }
1819
1820         res= ast_mutex_unlock(&p->lock);
1821 /*
1822         if (option_verbose > 3) ast_verbose("%s: unLOCKING in fixup [%d]\n", p->dev,res);
1823 */
1824         return 0;
1825 }
1826
1827 static int vpb_digit(struct ast_channel *ast, char digit)
1828 {
1829         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1830         char s[2];
1831         int res = 0;
1832
1833         if (use_ast_dtmf){
1834                 if (option_verbose > 3)
1835                         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);
1836                 return 0;
1837         }
1838
1839 /*
1840         if (option_verbose > 3) ast_verbose("%s: LOCKING in digit \n", p->dev);
1841         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1842 */
1843         ast_mutex_lock(&p->lock);
1844
1845
1846         s[0] = digit;
1847         s[1] = '\0';
1848
1849         if (option_verbose > 3)
1850                 ast_verbose(VERBOSE_PREFIX_4 "%s: vpb_digit: asked to play digit[%s]\n", p->dev, s);
1851
1852         ast_mutex_lock(&p->play_dtmf_lock);
1853         strncat(p->play_dtmf,s,sizeof(*p->play_dtmf));
1854         ast_mutex_unlock(&p->play_dtmf_lock);
1855
1856         res = ast_mutex_unlock(&p->lock);
1857 /*
1858         if (option_verbose > 3) ast_verbose("%s: unLOCKING in digit [%d]\n", p->dev,res);
1859 */
1860         return 0;
1861 }
1862
1863 /* Places a call out of a VPB channel */
1864 static int vpb_call(struct ast_channel *ast, char *dest, int timeout)
1865 {
1866         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1867         int res = 0,i;
1868         char *s = strrchr(dest, '/');
1869         char dialstring[254] = "";
1870         int tmp = 0;
1871
1872 /*
1873         if (option_verbose > 3) ast_verbose("%s: LOCKING in call \n", p->dev);
1874         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1875 */
1876         ast_mutex_lock(&p->lock);
1877         if (option_verbose > 3)
1878                 ast_verbose(VERBOSE_PREFIX_4 "%s: starting call to [%s]\n", p->dev,dest);
1879
1880         if (s)
1881                 s = s + 1;
1882         else
1883                 s = dest;
1884         strncpy(dialstring, s, sizeof(dialstring) - 1);
1885         for (i=0; dialstring[i] != '\0' ; i++) {
1886                 if ((dialstring[i] == 'w') || (dialstring[i] == 'W'))
1887                         dialstring[i] = ',';
1888                 else if ((dialstring[i] == 'f') || (dialstring[i] == 'F'))
1889                         dialstring[i] = '&';
1890         }       
1891
1892         if (ast->_state != AST_STATE_DOWN && ast->_state != AST_STATE_RESERVED) {
1893                 ast_log(LOG_WARNING, "vpb_call on %s neither down nor reserved!\n", ast->name);
1894                 tmp = ast_mutex_unlock(&p->lock);
1895 /*
1896                 if (option_verbose > 3) ast_verbose("%s: unLOCKING in call [%d]\n", p->dev,tmp);
1897 */
1898                 return -1;
1899         }
1900         if (p->mode != MODE_FXO)  /* Station port, ring it. */
1901                 res = vpb_ring_station_async(p->handle, VPB_RING_STATION_ON,0);       
1902         else {
1903                 VPB_CALL call;
1904
1905                 /* Dial must timeout or it can leave channels unuseable */
1906                 if( timeout == 0 )
1907                         timeout = TIMER_PERIOD_NOANSWER;
1908                 else 
1909                         timeout = timeout * 1000; /* convert from secs to ms. */
1910
1911                 /* These timeouts are only used with call progress dialing */
1912                 call.dialtones = 1; /* Number of dialtones to get outside line */
1913                 call.dialtone_timeout = VPB_DIALTONE_WAIT; /* Wait this long for dialtone (ms) */
1914                 call.ringback_timeout = VPB_RINGWAIT; /* Wait this long for ringing after dialing (ms) */
1915                 call.inter_ringback_timeout = VPB_CONNECTED_WAIT; /* If ringing stops for this long consider it connected (ms) */
1916                 call.answer_timeout = timeout; /* Time to wait for answer after ringing starts (ms) */
1917                 memcpy( &call.tone_map,  DialToneMap, sizeof(DialToneMap) );
1918                 vpb_set_call(p->handle, &call);
1919
1920                 if (option_verbose > 1)
1921                         ast_verbose(VERBOSE_PREFIX_2 "%s: Calling %s on %s \n",p->dev, dialstring, ast->name); 
1922
1923                 if (option_verbose > 2) {
1924                         int j;
1925                         ast_verbose(VERBOSE_PREFIX_2 "%s: Dial parms for %s %d/%dms/%dms/%dms/%dms\n", p->dev
1926                                 , ast->name, call.dialtones, call.dialtone_timeout
1927                                 , call.ringback_timeout, call.inter_ringback_timeout
1928                                 , call.answer_timeout );
1929                         for( j=0; !call.tone_map[j].terminate; j++ )
1930                                 ast_verbose(VERBOSE_PREFIX_2 "%s: Dial parms for %s tone %d->%d\n", p->dev,
1931                                         ast->name, call.tone_map[j].tone_id, call.tone_map[j].call_id); 
1932                 }
1933
1934                 if (option_verbose > 3)
1935                                 ast_verbose("%s: Disabling Loop Drop detection\n",p->dev);
1936                 vpb_disable_event(p->handle, VPB_MDROP);
1937                 vpb_sethook_sync(p->handle,VPB_OFFHOOK);
1938                 p->state=VPB_STATE_OFFHOOK;
1939
1940                 #ifndef DIAL_WITH_CALL_PROGRESS
1941                 vpb_sleep(300);
1942                 if (option_verbose > 3)
1943                                 ast_verbose("%s: Enabling Loop Drop detection\n",p->dev);
1944                 vpb_enable_event(p->handle, VPB_MDROP);
1945                 res = vpb_dial_async(p->handle, dialstring);
1946                 #else
1947                 if (option_verbose > 3)
1948                                 ast_verbose("%s: Enabling Loop Drop detection\n",p->dev);
1949                 vpb_enable_event(p->handle, VPB_MDROP);
1950                 res = vpb_call_async(p->handle, dialstring);
1951                 #endif
1952
1953                 if (res != VPB_OK) {
1954                         ast_log(LOG_DEBUG, "Call on %s to %s failed: %s\n", ast->name, s, vpb_strerror(res));         
1955                         res = -1;
1956                 } else 
1957                         res = 0;
1958         }
1959
1960         if (option_verbose > 2)
1961                 ast_verbose(VERBOSE_PREFIX_3 "%s: VPB Calling %s [t=%d] on %s returned %d\n",p->dev , s, timeout, ast->name, res); 
1962         if (res == 0) {
1963                 ast_setstate(ast, AST_STATE_RINGING);
1964                 ast_queue_control(ast,AST_CONTROL_RINGING);             
1965         }
1966
1967         if (!p->readthread){
1968                 ast_pthread_create(&p->readthread, NULL, do_chanreads, (void *)p);
1969         }
1970
1971         tmp = ast_mutex_unlock(&p->lock);
1972 /*
1973         if (option_verbose > 3) ast_verbose("%s: unLOCKING in call [%d]\n", p->dev,tmp);
1974 */
1975         return res;
1976 }
1977
1978 static int vpb_hangup(struct ast_channel *ast)
1979 {
1980         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1981         VPB_EVENT je;
1982         char str[VPB_MAX_STR];
1983         int res =0 ;
1984
1985 /*
1986         if (option_verbose > 3) ast_verbose("%s: LOCKING in hangup \n", p->dev);
1987         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);
1988         if (option_verbose > 3) ast_verbose("%s: LOCKING pthread_self(%d)\n", p->dev,pthread_self());
1989         ast_mutex_lock(&p->lock);
1990 */
1991         if (option_verbose > 1) 
1992                 ast_verbose(VERBOSE_PREFIX_2 "%s: Hangup requested\n", ast->name);
1993
1994         if (!ast->tech || !ast->tech_pvt) {
1995                 ast_log(LOG_WARNING, "%s: channel not connected?\n", ast->name);
1996                 res = ast_mutex_unlock(&p->lock);
1997 /*
1998                 if (option_verbose > 3) ast_verbose("%s: unLOCKING in hangup [%d]\n", p->dev,res);
1999 */
2000                 /* Free up ast dsp if we have one */
2001                 if ((use_ast_dtmfdet)&&(p->vad)) {
2002                         ast_dsp_free(p->vad);
2003                         p->vad = NULL;
2004                 }
2005                 return 0;
2006         }
2007
2008
2009
2010         /* Stop record */
2011         p->stopreads = 1;
2012         if( p->readthread ){
2013                 pthread_join(p->readthread, NULL); 
2014                 if(option_verbose>3) 
2015                         ast_verbose( VERBOSE_PREFIX_4 "%s: stopped record thread \n",ast->name);
2016         }
2017
2018         /* Stop play */
2019         if (p->lastoutput != -1) {
2020                 if(option_verbose>1) 
2021                         ast_verbose( VERBOSE_PREFIX_2 "%s: Ending play mode \n",ast->name);
2022                 vpb_play_terminate(p->handle);
2023                 ast_mutex_lock(&p->play_lock); {
2024                         vpb_play_buf_finish(p->handle);
2025                 } ast_mutex_unlock(&p->play_lock);
2026         }
2027
2028         if(option_verbose>3) 
2029                 ast_verbose( VERBOSE_PREFIX_4 "%s: Setting state down\n",ast->name);
2030         ast_setstate(ast,AST_STATE_DOWN);
2031
2032
2033 /*
2034         if (option_verbose > 3) ast_verbose("%s: LOCKING in hangup \n", p->dev);
2035         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);
2036         if (option_verbose > 3) ast_verbose("%s: LOCKING pthread_self(%d)\n", p->dev,pthread_self());
2037 */
2038         ast_mutex_lock(&p->lock);
2039
2040         if (p->mode != MODE_FXO) {
2041                 /* station port. */
2042                 vpb_ring_station_async(p->handle, VPB_RING_STATION_OFF,0);      
2043                 if(p->state!=VPB_STATE_ONHOOK){
2044                         /* This is causing a "dial end" "play tone" loop
2045                         playtone(p->handle, &Busytone); 
2046                         p->state = VPB_STATE_PLAYBUSY;
2047                         if(option_verbose>4) 
2048                                 ast_verbose( VERBOSE_PREFIX_4 "%s: Station offhook[%d], playing busy tone\n",
2049                                                                 ast->name,p->state);
2050                         */
2051                 }
2052                 else {
2053                         stoptone(p->handle);
2054                 }
2055                 #ifdef VPB_PRI
2056                 vpb_setloop_async(p->handle, VPB_OFFHOOK);
2057                 vpb_sleep(100);
2058                 vpb_setloop_async(p->handle, VPB_ONHOOK);
2059                 #endif
2060         } else {
2061                 stoptone(p->handle); /* Terminates any dialing */
2062                 vpb_sethook_sync(p->handle, VPB_ONHOOK);
2063                 p->state=VPB_STATE_ONHOOK;
2064         }
2065         while (VPB_OK==vpb_get_event_ch_async(p->handle,&je)){
2066                 if(option_verbose>3) {
2067                         vpb_translate_event(&je, str);
2068                         ast_verbose( VERBOSE_PREFIX_4 "%s: Flushing event [%d]=>%s\n",ast->name,je.type,str);
2069                 }
2070         }
2071
2072         p->readthread = 0;
2073         p->lastoutput = -1;
2074         p->lastinput = -1;
2075         p->last_ignore_dtmf = 1;
2076         p->ext[0]  = 0;
2077         p->dialtone = 0;
2078
2079         p->owner = NULL;
2080         ast->tech_pvt=NULL;
2081
2082         /* Free up ast dsp if we have one */
2083         if ((use_ast_dtmfdet)&&(p->vad)) {
2084                 ast_dsp_free(p->vad);
2085                 p->vad = NULL;
2086         }
2087
2088         ast_mutex_lock(&usecnt_lock); {
2089                 usecnt--;
2090         } ast_mutex_unlock(&usecnt_lock);
2091         ast_update_use_count();
2092
2093         if (option_verbose > 1)
2094                 ast_verbose(VERBOSE_PREFIX_2 "%s: Hangup complete\n", ast->name);
2095
2096         restart_monitor();
2097 /*
2098         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);
2099 */
2100         res = ast_mutex_unlock(&p->lock);
2101 /*
2102         if (option_verbose > 3) ast_verbose("%s: unLOCKING in hangup [%d]\n", p->dev,res);
2103         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);
2104 */
2105         return 0;
2106 }
2107
2108 static int vpb_answer(struct ast_channel *ast)
2109 {
2110         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
2111         int res = 0;
2112 /*
2113         VPB_EVENT je;
2114         int ret;
2115         if (option_verbose > 3) ast_verbose("%s: LOCKING in answer \n", p->dev);
2116         if (option_verbose > 3) ast_verbose("%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
2117 */
2118         ast_mutex_lock(&p->lock);
2119
2120         if (option_verbose > 3)
2121                         ast_verbose(VERBOSE_PREFIX_4 "%s: Answering channel\n",p->dev);
2122
2123         if (p->mode == MODE_FXO){
2124                 if (option_verbose > 3)
2125                                 ast_verbose("%s: Disabling Loop Drop detection\n",p->dev);
2126                 vpb_disable_event(p->handle, VPB_MDROP);
2127         }
2128
2129         if (ast->_state != AST_STATE_UP) {
2130                 if (p->mode == MODE_FXO){
2131                         vpb_sethook_sync(p->handle, VPB_OFFHOOK);
2132                         p->state=VPB_STATE_OFFHOOK;
2133 /*                      vpb_sleep(500);
2134                         ret = vpb_get_event_ch_async(p->handle,&je);
2135                         if ((ret == VPB_OK)&&((je.type != VPB_DROP)&&(je.type != VPB_RING))){
2136                                 if (option_verbose > 3){
2137                                                 ast_verbose(VERBOSE_PREFIX_4 "%s: Answer collected a wrong event!!\n",p->dev);
2138                                 }
2139                                 vpb_put_event(&je);
2140                         }
2141 */
2142                 }
2143                 ast_setstate(ast, AST_STATE_UP);
2144
2145                 if(option_verbose>1) 
2146 /*
2147                         ast_verbose( VERBOSE_PREFIX_2 "%s: Answered call from %s on %s [%s]\n", p->dev, 
2148                                         p->owner->callerid, ast->name,(p->mode == MODE_FXO)?"FXO":"FXS"); 
2149 */
2150                         ast_verbose( VERBOSE_PREFIX_2 "%s: Answered call on %s [%s]\n", p->dev,
2151                                          ast->name,(p->mode == MODE_FXO)?"FXO":"FXS");
2152
2153                 ast->rings = 0;
2154                 if( !p->readthread ){
2155         /*              res = ast_mutex_unlock(&p->lock); */
2156         /*              ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res); */
2157                         ast_pthread_create(&p->readthread, NULL, do_chanreads, (void *)p);
2158                 } else {
2159                         if(option_verbose>3) 
2160                                 ast_verbose(VERBOSE_PREFIX_4 "%s: Record thread already running!!\n",p->dev);
2161                 }
2162         } else {
2163                 if(option_verbose>3) {
2164                         ast_verbose(VERBOSE_PREFIX_4 "%s: Answered state is up\n",p->dev);
2165                 }
2166         /*      res = ast_mutex_unlock(&p->lock); */
2167         /*      ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res); */
2168         }
2169         vpb_sleep(500);
2170         if (p->mode == MODE_FXO){
2171                 if (option_verbose > 3)
2172                                 ast_verbose("%s: Re-enabling Loop Drop detection\n",p->dev);
2173                 vpb_enable_event(p->handle,VPB_MDROP);
2174         }
2175         res = ast_mutex_unlock(&p->lock);
2176 /*
2177         if(option_verbose>3) ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res);
2178 */
2179         return 0;
2180 }
2181
2182 static struct ast_frame  *vpb_read(struct ast_channel *ast)
2183 {
2184         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt; 
2185         static struct ast_frame f = {AST_FRAME_NULL}; 
2186
2187         f.src = "vpb";
2188         ast_log(LOG_NOTICE, "%s: vpb_read: should never be called!\n", p->dev);
2189         ast_verbose("%s: vpb_read: should never be called!\n", p->dev);
2190
2191         return &f;
2192 }
2193
2194 static inline int ast2vpbformat(int ast_format)
2195 {
2196         switch(ast_format) {
2197                 case AST_FORMAT_ALAW:
2198                         return VPB_ALAW;
2199                 case AST_FORMAT_SLINEAR:
2200                         return VPB_LINEAR;
2201                 case AST_FORMAT_ULAW:
2202                         return VPB_MULAW;
2203                 case AST_FORMAT_ADPCM:
2204                         return VPB_OKIADPCM;
2205                 default:
2206                         return -1;
2207         }
2208 }
2209
2210 static inline char * ast2vpbformatname(int ast_format)
2211 {
2212         switch(ast_format) {
2213                 case AST_FORMAT_ALAW:
2214                         return "AST_FORMAT_ALAW:VPB_ALAW";
2215                 case AST_FORMAT_SLINEAR:
2216                         return "AST_FORMAT_SLINEAR:VPB_LINEAR";
2217                 case AST_FORMAT_ULAW:
2218                         return "AST_FORMAT_ULAW:VPB_MULAW";
2219                 case AST_FORMAT_ADPCM:
2220                         return "AST_FORMAT_ADPCM:VPB_OKIADPCM";
2221                 default:
2222                         return "UNKN:UNKN";
2223         }
2224 }
2225
2226 static inline int astformatbits(int ast_format)
2227 {
2228         switch(ast_format) {
2229                 case AST_FORMAT_ALAW:
2230                 case AST_FORMAT_ULAW:
2231                         return 8;
2232                 case AST_FORMAT_SLINEAR:
2233                         return 16;
2234                 case AST_FORMAT_ADPCM:
2235                         return 4;
2236                 default:
2237                         return 8;
2238         }   
2239 }
2240
2241 int a_gain_vector(float g, short *v, int n) 
2242 {
2243         int i;
2244         float tmp;
2245         for ( i = 0; i<n; i++) {
2246                 tmp = g*v[i];
2247                 if (tmp > 32767.0)
2248                         tmp = 32767.0;
2249                 if (tmp < -32768.0)
2250                         tmp = -32768.0;
2251                 v[i] = (short)tmp;      
2252         }  
2253         return(i);
2254 }
2255
2256 /* Writes a frame of voice data to a VPB channel */
2257 static int vpb_write(struct ast_channel *ast, struct ast_frame *frame)
2258 {
2259         struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt; 
2260         int res = 0, fmt = 0;
2261         struct timeval play_buf_time_start;
2262         int tdiff;
2263
2264 /*      ast_mutex_lock(&p->lock); */
2265         if(option_verbose>5) 
2266                 ast_verbose("%s: vpb_write: Writing to channel\n", p->dev);
2267
2268         if (frame->frametype != AST_FRAME_VOICE) {
2269                 if(option_verbose>3) 
2270                         ast_verbose("%s: vpb_write: Don't know how to handle from type %d\n", ast->name, frame->frametype);
2271 /*              ast_mutex_unlock(&p->lock); */
2272                 return 0;
2273         } else if (ast->_state != AST_STATE_UP) {
2274                 if(option_verbose>3) 
2275                         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);
2276                 p->lastoutput = -1;
2277 /*              ast_mutex_unlock(&p->lock); */
2278                 return 0;
2279         }
2280 /*      ast_log(LOG_DEBUG, "%s: vpb_write: Checked frame type..\n", p->dev); */
2281
2282
2283         fmt = ast2vpbformat(frame->subclass);
2284         if (fmt < 0) {
2285                 ast_log(LOG_WARNING, "%s: vpb_write: Cannot handle frames of %d format!\n",ast->name, frame->subclass);
2286                 return -1;
2287         }
2288
2289         tdiff = ast_tvdiff_ms(ast_tvnow(), p->lastplay);
2290         ast_log(LOG_DEBUG, "%s: vpb_write: time since last play(%d) \n", p->dev, tdiff); 
2291         if (tdiff < (VPB_SAMPLES/8 - 1)){
2292                 ast_log(LOG_DEBUG, "%s: vpb_write: Asked to play too often (%d) (%d)\n", p->dev, tdiff,frame->datalen); 
2293 //              return 0;
2294         }
2295         p->lastplay = ast_tvnow();
2296 /*
2297         ast_log(LOG_DEBUG, "%s: vpb_write: Checked frame format..\n", p->dev); 
2298 */
2299
2300         ast_mutex_lock(&p->play_lock);
2301
2302 /*
2303         ast_log(LOG_DEBUG, "%s: vpb_write: Got play lock..\n", p->dev); 
2304 */
2305
2306         /* Check if we have set up the play_buf */
2307         if (p->lastoutput == -1) {
2308                 vpb_play_buf_start(p->handle, fmt);
2309                 if(option_verbose>1) {
2310                         ast_verbose("%s: vpb_write: Starting play mode (codec=%d)[%s]\n",p->dev,fmt,ast2vpbformatname(frame->subclass));
2311                 }
2312                 p->lastoutput = fmt;
2313                 ast_mutex_unlock(&p->play_lock);
2314                 return 0;
2315         } else if (p->lastoutput != fmt) {
2316                 vpb_play_buf_finish(p->handle);
2317                 vpb_play_buf_start(p->handle, fmt);
2318                 if(option_verbose>1) 
2319                         ast_verbose("%s: vpb_write: Changed play format (%d=>%d)\n",p->dev,p->lastoutput,fmt);
2320                 ast_mutex_unlock(&p->play_lock);
2321                 return 0;
2322         }
2323         p->lastoutput = fmt;
2324
2325
2326
2327         /* Apply extra gain ! */
2328         if( p->txswgain > MAX_VPB_GAIN )
2329                 a_gain_vector(p->txswgain - MAX_VPB_GAIN , (short*)frame->data, frame->datalen/sizeof(short));
2330
2331 /*      ast_log(LOG_DEBUG, "%s: vpb_write: Applied gain..\n", p->dev); */
2332 /*      ast_log(LOG_DEBUG, "%s: vpb_write: play_buf_time %d\n", p->dev, p->play_buf_time); */
2333
2334         if ((p->read_state == 1)&&(p->play_buf_time<5)){
2335                 play_buf_time_start = ast_tvnow();
2336 /*              res = vpb_play_buf_sync(p->handle, (char*)frame->data, tdiff*8*2); */
2337                 res = vpb_play_buf_sync(p->handle, (char*)frame->data, frame->datalen);
2338                 if( res == VPB_OK && option_verbose > 5 ) {
2339                         short * data = (short*)frame->data;
2340                         ast_verbose("%s: vpb_write: Wrote chan (codec=%d) %d %d\n", p->dev, fmt, data[0],data[1]);
2341                 }
2342                 p->play_buf_time = ast_tvdiff_ms(ast_tvnow(), play_buf_time_start);
2343         }
2344         else {
2345                 p->chuck_count++;
2346                 ast_log(LOG_DEBUG, "%s: vpb_write: Tossed data away, tooooo much data!![%d]\n", p->dev,p->chuck_count);
2347                 p->play_buf_time=0;
2348         }
2349
2350         ast_mutex_unlock(&p->play_lock);
2351 /*      ast_mutex_unlock(&p->lock); */
2352         if(option_verbose>5) 
2353                 ast_verbose("%s: vpb_write: Done Writing to channel\n", p->dev);
2354         return 0;
2355 }
2356
2357 /* Read monitor thread function. */
2358 static void *do_chanreads(void *pvt)
2359 {
2360         struct vpb_pvt *p = (struct vpb_pvt *)pvt;
2361         struct ast_frame *fr = &p->fr;
2362         char *readbuf = ((char *)p->buf) + AST_FRIENDLY_OFFSET;
2363         int bridgerec = 0;
2364         int afmt, readlen, res, fmt, trycnt=0;
2365         int ignore_dtmf;
2366         const char * getdtmf_var = NULL;
2367
2368         fr->frametype = AST_FRAME_VOICE;
2369         fr->src = "vpb";
2370         fr->mallocd = 0;
2371         fr->delivery.tv_sec = 0;
2372         fr->delivery.tv_usec = 0;
2373         fr->samples = VPB_SAMPLES;
2374         fr->offset = AST_FRIENDLY_OFFSET;
2375         memset(p->buf, 0, sizeof p->buf);
2376
2377         if (option_verbose > 2) {
2378                 ast_verbose("%s: chanreads: starting thread\n", p->dev);
2379         }  
2380         ast_mutex_lock(&p->record_lock);
2381
2382         p->stopreads = 0; 
2383         p->read_state = 1;
2384         while (!p->stopreads && p->owner) {
2385
2386                 if (option_verbose > 4)
2387                         ast_verbose("%s: chanreads: Starting cycle ...\n", p->dev);
2388                 if (option_verbose > 4)
2389                         ast_verbose("%s: chanreads: Checking bridge \n", p->dev);
2390                 if (p->bridge) {
2391                         if (p->bridge->c0 == p->owner && (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_0))
2392                                 bridgerec = 1;
2393                         else if (p->bridge->c1 == p->owner && (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_1))
2394                                 bridgerec = 1;
2395                         else 
2396                                 bridgerec = 0;
2397                 } else {
2398                         if (option_verbose > 4)
2399                                 ast_verbose("%s: chanreads: No native bridge.\n", p->dev);
2400                         if (p->owner->_bridge){
2401                                 if (option_verbose > 4){
2402                                         ast_verbose("%s: chanreads: Got Asterisk bridge with [%s].\n", p->dev,p->owner->_bridge->name);
2403                                 }
2404                                 bridgerec = 1;
2405                         }
2406                         else {
2407                                 bridgerec = 0;
2408                         }
2409                 }
2410
2411 /*              if ( (p->owner->_state != AST_STATE_UP) || !bridgerec) */
2412                 if ( (p->owner->_state != AST_STATE_UP) ) 
2413                 {
2414                         if (option_verbose > 4) {
2415                                 if (p->owner->_state != AST_STATE_UP)
2416                                         ast_verbose("%s: chanreads: Im not up[%d]\n", p->dev,p->owner->_state);
2417                                 else
2418                                         ast_verbose("%s: chanreads: No bridgerec[%d]\n", p->dev,bridgerec);
2419                         }  
2420                         vpb_sleep(10);
2421                         continue;
2422                 }
2423
2424                 /* Voicetronix DTMF detection can be triggered off ordinary speech
2425                  * This leads to annoying beeps during the conversation
2426                  * Avoid this problem by just setting VPB_GETDTMF when you want to listen for DTMF
2427                  */
2428                 /* ignore_dtmf = 1; */
2429                 ignore_dtmf = 0; /* set this to 1 to turn this feature on */
2430                 getdtmf_var = pbx_builtin_getvar_helper(p->owner,"VPB_GETDTMF");
2431                 if( getdtmf_var && ( strcasecmp( getdtmf_var, "yes" ) == 0 ) )
2432                         ignore_dtmf = 0;
2433
2434                 if(( ignore_dtmf != p->last_ignore_dtmf ) &&(!use_ast_dtmfdet)){
2435                         if(option_verbose>1) 
2436                                 ast_verbose( VERBOSE_PREFIX_2 "%s:Now %s DTMF \n",
2437                                         p->dev, ignore_dtmf ? "ignoring" : "listening for");
2438                         vpb_set_event_mask(p->handle, ignore_dtmf ? VPB_EVENTS_NODTMF : VPB_EVENTS_ALL );
2439                 }
2440                 p->last_ignore_dtmf = ignore_dtmf;
2441
2442                 /* Play DTMF digits here to avoid problem you get if playing a digit during 
2443                  * a record operation
2444                  */
2445                 if (option_verbose > 5) {
2446                         ast_verbose("%s: chanreads: Checking dtmf's \n", p->dev);
2447                 }  
2448                 ast_mutex_lock(&p->play_dtmf_lock);
2449                 if( p->play_dtmf[0] ) {
2450                         /* Try to ignore DTMF event we get after playing digit */
2451                         /* This DTMF is played by asterisk and leads to an annoying trailing beep on CISCO phones */
2452                         if( !ignore_dtmf) 
2453                                 vpb_set_event_mask(p->handle, VPB_EVENTS_NODTMF );
2454                         if (p->bridge == NULL){
2455                                 vpb_dial_sync(p->handle,p->play_dtmf);
2456                                 if(option_verbose>1) 
2457                                         ast_verbose( VERBOSE_PREFIX_2 "%s: chanreads: Played DTMF %s\n",p->dev,p->play_dtmf);
2458                         }
2459                         else {
2460                                 if (option_verbose > 1) 
2461                                         ast_verbose(VERBOSE_PREFIX_2 "%s: chanreads: Not playing DTMF frame on native bridge\n", p->dev);
2462                         }
2463                         p->play_dtmf[0] = '\0';
2464                         ast_mutex_unlock(&p->play_dtmf_lock);
2465                         vpb_sleep(700); /* Long enough to miss echo and DTMF event */
2466                         if( !ignore_dtmf) 
2467                                 vpb_set_event_mask(p->handle, VPB_EVENTS_ALL );
2468                         continue;
2469                 }
2470                 ast_mutex_unlock(&p->play_dtmf_lock);
2471
2472 /*              afmt = (p->owner) ? p->owner->rawreadformat : AST_FORMAT_SLINEAR; */
2473                 if (p->owner){
2474                         afmt = p->owner->rawreadformat;
2475 /*                      ast_log(LOG_DEBUG,"%s: Record using owner format [%s]\n", p->dev, ast2vpbformatname(afmt)); */
2476                 }
2477                 else {
2478                         afmt = AST_FORMAT_SLINEAR;
2479 /*                      ast_log(LOG_DEBUG,"%s: Record using default format [%s]\n", p->dev, ast2vpbformatname(afmt)); */
2480                 }
2481                 fmt = ast2vpbformat(afmt);
2482                 if (fmt < 0) {
2483                         ast_log(LOG_WARNING,"%s: Record failure (unsupported format %d)\n", p->dev, afmt);
2484                         return NULL;
2485                 }
2486                 readlen = VPB_SAMPLES * astformatbits(afmt) / 8;
2487
2488                 if (p->lastinput == -1) {
2489                         vpb_record_buf_start(p->handle, fmt);
2490                         vpb_reset_record_fifo_alarm(p->handle);
2491                         p->lastinput = fmt;
2492                         if(option_verbose>1) 
2493                                 ast_verbose( VERBOSE_PREFIX_2 "%s: Starting record mode (codec=%d)[%s]\n",p->dev,fmt,ast2vpbformatname(afmt));
2494                         continue;
2495                 } else if (p->lastinput != fmt) {
2496                         vpb_record_buf_finish(p->handle);
2497                         vpb_record_buf_start(p->handle, fmt);
2498                         p->lastinput = fmt;
2499                         if(option_verbose>1) 
2500                                 ast_verbose( VERBOSE_PREFIX_2 "%s: Changed record format (%d=>%d)\n",p->dev,p->lastinput,fmt);
2501                         continue;
2502                 }
2503
2504                 /* Read only if up and not bridged, or a bridge for which we can read. */
2505                 if (option_verbose > 5) {
2506                         ast_verbose("%s: chanreads: getting buffer!\n", p->dev);
2507                 }  
2508                 if( (res = vpb_record_buf_sync(p->handle, readbuf, readlen) ) == VPB_OK ) {
2509                         if (option_verbose > 5) {
2510                                 ast_verbose("%s: chanreads: got buffer!\n", p->dev);
2511                         }  
2512                         /* Apply extra gain ! */
2513                         if( p->rxswgain > MAX_VPB_GAIN )
2514                                 a_gain_vector(p->rxswgain - MAX_VPB_GAIN , (short*)readbuf, readlen/sizeof(short));
2515                         if (option_verbose > 5) {
2516                                 ast_verbose("%s: chanreads: applied gain\n", p->dev);
2517                         }  
2518
2519                         fr->subclass = afmt;
2520                         fr->data = readbuf;
2521                         fr->datalen = readlen;
2522                         fr->frametype = AST_FRAME_VOICE;
2523
2524                         if ((use_ast_dtmfdet)&&(p->vad)){
2525                                 fr = ast_dsp_process(p->owner,p->vad,fr);
2526                                 if (fr && (fr->frametype == AST_FRAME_DTMF))
2527                                         ast_log(LOG_DEBUG, "%s: chanreads: Detected DTMF '%c'\n",p->dev, fr->subclass);
2528                                 if (fr->subclass == 'm'){
2529                                         /* conf mute request */
2530                                         fr->frametype = AST_FRAME_NULL;
2531                                         fr->subclass = 0;
2532                                 }
2533                                 else if (fr->subclass == 'u'){
2534                                         /* Unmute */
2535                                         fr->frametype = AST_FRAME_NULL;
2536                                         fr->subclass = 0;
2537                                 }
2538                                 else if (fr->subclass == 'f'){
2539                                 }
2540                         }
2541                         /* Using trylock here to prevent deadlock when channel is hungup
2542                          * (ast_hangup() immediately gets lock)
2543                          */
2544                         if (p->owner && !p->stopreads ) {
2545                                 if (option_verbose > 5) {
2546                                         ast_verbose("%s: chanreads: queueing buffer on read frame q (state[%d])\n", p->dev,p->owner->_state);
2547                                 }  
2548                                 do {
2549                                         res = ast_mutex_trylock(&p->owner->lock);
2550                                         trycnt++;
2551                                 } while((res !=0)&&(trycnt<300));
2552                                 if (res==0)  {
2553                                         ast_queue_frame(p->owner, fr);
2554                                         ast_mutex_unlock(&p->owner->lock);
2555                                 } else {
2556                                         if (option_verbose > 4) 
2557                                                 ast_verbose("%s: chanreads: Couldnt get lock after %d tries!\n", p->dev,trycnt);
2558                                 }
2559                                 trycnt=0;
2560                                 
2561 /*
2562                                 res = ast_mutex_trylock(&p->owner->lock);
2563                                 if (res==0)  {
2564                                         ast_queue_frame(p->owner, fr);
2565                                         ast_mutex_unlock(&p->owner->lock);
2566                                 } else {
2567                                         if (res == EINVAL )
2568                                                 if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EINVAL[%d]\n", p->dev,res);
2569                                         else if (res == EBUSY )
2570                                                 if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EBUSY[%d]\n", p->dev,res);
2571                                         while(res !=0){
2572                                         res = ast_mutex_trylock(&p->owner->lock);
2573                                         }
2574                                         if (res==0)  {
2575                                                 ast_queue_frame(p->owner, fr);
2576                                                 ast_mutex_unlock(&p->owner->lock);
2577                                         }
2578                                         else {
2579                                                 if (res == EINVAL )
2580                                                         if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EINVAL[%d]\n", p->dev,res);
2581                                                 else if (res == EBUSY )
2582                                                         if (option_verbose > 4) ast_verbose("%s: chanreads: try owner->lock gave me EBUSY[%d]\n", p->dev,res);
2583                                                 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);
2584                                         }
2585                                 }
2586 */
2587                                 if (option_verbose > 6) {
2588                                         short * data = (short*)readbuf;
2589                                         ast_verbose("%s: Read channel (codec=%d) %d %d\n", p->dev, fmt, data[0], data[1] );
2590                                 }  
2591                         }
2592                         else {
2593                                 if (option_verbose > 4) {
2594                                         ast_verbose("%s: p->stopreads[%d] p->owner[%p]\n", p->dev, p->stopreads,(void *)p->owner);
2595                                 }  
2596                         }
2597                 }
2598                 if (option_verbose > 4)
2599                         ast_verbose("%s: chanreads: Finished cycle...\n", p->dev);
2600         }
2601         p->read_state=0;
2602
2603         /* When stopreads seen, go away! */
2604         vpb_record_buf_finish(p->handle);
2605         p->read_state=0;
2606         ast_mutex_unlock(&p->record_lock);
2607
2608         if (option_verbose > 1)
2609                 ast_verbose(VERBOSE_PREFIX_2 "%s: Ending record mode (%d/%s)\n",
2610                          p->dev, p->stopreads, p->owner? "yes" : "no");     
2611         return NULL;
2612 }
2613
2614 static struct ast_channel *vpb_new(struct vpb_pvt *me, int state, char *context)
2615 {
2616         struct ast_channel *tmp; 
2617         char cid_num[256];
2618         char cid_name[256];
2619
2620         if (me->owner) {
2621             ast_log(LOG_WARNING, "Called vpb_new on owned channel (%s) ?!\n", me->dev);
2622             return NULL;
2623         }
2624         if (option_verbose > 3)
2625                 ast_verbose("%s: New call for context [%s]\n",me->dev,context);
2626             
2627         tmp = ast_channel_alloc(1);
2628         if (tmp) {
2629                 if (use_ast_ind == 1){
2630                         tmp->tech = &vpb_tech_indicate;
2631                 }
2632                 else {
2633                         tmp->tech = &vpb_tech;
2634                 }
2635
2636                 ast_string_field_set(tmp, name, me->dev);
2637                 
2638                 tmp->callgroup = me->callgroup;
2639                 tmp->pickupgroup = me->pickupgroup;
2640                
2641                 /* Linear is the preferred format. Although Voicetronix supports other formats
2642                  * they are all converted to/from linear in the vpb code. Best for us to use
2643                  * linear since we can then adjust volume in this modules.
2644                  */
2645                 tmp->nativeformats = prefformat;
2646                 tmp->rawreadformat = AST_FORMAT_SLINEAR;
2647                 tmp->rawwriteformat =  AST_FORMAT_SLINEAR;
2648                 ast_setstate(tmp, state);
2649                 if (state == AST_STATE_RING) {
2650                         tmp->rings = 1;
2651                         cid_name[0] = '\0';
2652                         cid_num[0] = '\0';
2653                         ast_callerid_split(me->callerid, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
2654                         ast_set_callerid(tmp, cid_num, cid_name, cid_num);
2655                 }
2656                 tmp->tech_pvt = me;
2657                 
2658                 strncpy(tmp->context, context, sizeof(tmp->context)-1);
2659                 if (strlen(me->ext))
2660                         strncpy(tmp->exten, me->ext, sizeof(tmp->exten)-1);
2661                 else
2662                         strncpy(tmp->exten, "s",  sizeof(tmp->exten) - 1);
2663                 if (strlen(me->language))
2664                         ast_string_field_set(tmp, language, me->language);
2665
2666                 me->owner = tmp;
2667      
2668                 me->bridge = NULL;
2669                 me->lastoutput = -1;
2670                 me->lastinput = -1;
2671                 me->last_ignore_dtmf = 1;
2672                 me->readthread = 0;
2673                 me->play_dtmf[0] = '\0';
2674                 me->faxhandled =0;
2675                 
2676                 me->lastgrunt  = ast_tvnow(); /* Assume at least one grunt tone seen now. */
2677                 me->lastplay  = ast_tvnow(); /* Assume at least one grunt tone seen now. */
2678
2679                 ast_mutex_lock(&usecnt_lock);
2680                 usecnt++;
2681                 ast_mutex_unlock(&usecnt_lock);
2682                 ast_update_use_count();
2683                 if (state != AST_STATE_DOWN) {
2684                         if ((me->mode != MODE_FXO)&&(state != AST_STATE_UP)){
2685                                 vpb_answer(tmp);
2686                         }
2687                         if (ast_pbx_start(tmp)) {
2688                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2689                                 ast_hangup(tmp);
2690                         }
2691                 }
2692         } else {
2693                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2694         }
2695         return tmp;
2696 }
2697
2698 static struct ast_channel *vpb_request(const char *type, int format, void *data, int *cause) 
2699 {
2700         int oldformat;
2701         struct vpb_pvt *p;
2702         struct ast_channel *tmp = NULL;
2703         char *name = strdup(data ? (char *)data : "");
2704         char *s, *sepstr;
2705         int group=-1;
2706
2707         oldformat = format;
2708         format &= prefformat;
2709         if (!format) {
2710                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
2711                 return NULL;
2712         }
2713
2714         sepstr = name;
2715         s = strsep(&sepstr, "/"); /* Handle / issues */
2716         if (!s) 
2717                 s = "";
2718         /* Check if we are looking for a group */
2719         if (toupper(name[0]) == 'G' || toupper(name[0])=='R') {
2720                 group=atoi(name+1);     
2721         }
2722         /* Search for an unowned channel */
2723         ast_mutex_lock(&iflock); {
2724                 p = iflist;
2725                 while(p) {
2726                         if (group == -1){
2727                                 if (strncmp(s, p->dev + 4, sizeof p->dev) == 0) {
2728                                         if (!p->owner) {
2729                                                 tmp = vpb_new(p, AST_STATE_DOWN, p->context);
2730                                                 break;
2731                                         }
2732                                 }
2733                         }
2734                         else {
2735                                 if ((p->group == group) && (!p->owner)) {
2736                                         tmp = vpb_new(p, AST_STATE_DOWN, p->context);
2737                                         break;
2738                                 }
2739                         }
2740                         p = p->next;
2741                 }
2742         } ast_mutex_unlock(&iflock);
2743
2744
2745         if (option_verbose > 1) 
2746                 ast_verbose(VERBOSE_PREFIX_2 " %s requested, got: [%s]\n",
2747                 name, tmp ? tmp->name : "None");
2748
2749         free(name);
2750
2751         restart_monitor();
2752         return tmp;
2753 }
2754
2755 static float parse_gain_value(char *gain_type, char *value)
2756 {
2757         float gain;
2758
2759         /* try to scan number */
2760         if (sscanf(value, "%f", &gain) != 1)
2761         {
2762                 ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n", value, gain_type, config);
2763                 return DEFAULT_GAIN;
2764         }
2765
2766
2767         /* percentage? */
2768         /*if (value[strlen(value) - 1] == '%') */
2769         /*      return gain / (float)100; */
2770
2771         return gain;
2772 }
2773
2774 int load_module()
2775 {
2776         struct ast_config *cfg;
2777         struct ast_variable *v;
2778         struct vpb_pvt *tmp;
2779         int board = 0, group = 0;
2780         ast_group_t     callgroup = 0;
2781         ast_group_t     pickupgroup = 0;
2782         int mode = MODE_IMMEDIATE;
2783         float txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN; 
2784         float txswgain = 0, rxswgain = 0; 
2785         int got_gain=0;
2786         int first_channel = 1;
2787         int echo_cancel = DEFAULT_ECHO_CANCEL;
2788         int error = 0; /* Error flag */
2789         int bal1 = -1; /* Special value - means do not set */
2790         int bal2 = -1; 
2791         int bal3 = -1;
2792         char * callerid = NULL;
2793
2794         cfg = ast_config_load(config);
2795
2796         /* We *must* have a config file otherwise stop immediately */
2797         if (!cfg) {
2798                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
2799                 return -1;
2800         }  
2801
2802         vpb_seterrormode(VPB_ERROR_CODE);
2803
2804         ast_mutex_lock(&iflock); {
2805                 v = ast_variable_browse(cfg, "general");
2806                 while (v){
2807                         if (strcasecmp(v->name, "cards") == 0) {
2808                                 ast_log(LOG_NOTICE,"VPB Driver configured to use [%d] cards\n",atoi(v->value));
2809                         }
2810                         else if (strcasecmp(v->name, "indication") == 0) {
2811                                 use_ast_ind = 1;
2812                                 ast_log(LOG_NOTICE,"VPB driver using Asterisk Indication functions!\n");
2813                         }
2814                         else if (strcasecmp(v->name, "break-for-dtmf") == 0) {
2815                                 if (ast_true(v->value)){
2816                                         break_for_dtmf = 1;
2817                                 }
2818                                 else {
2819                                         break_for_dtmf = 0;
2820                                         ast_log(LOG_NOTICE,"VPB driver not stopping for DTMF's in native bridge\n");
2821                                 }
2822                         }
2823                         else if (strcasecmp(v->name, "ast-dtmf") == 0) {
2824                                 use_ast_dtmf = 1;
2825                                 ast_log(LOG_NOTICE,"VPB driver using Asterisk DTMF play functions!\n");
2826                         }
2827                         else if (strcasecmp(v->name, "ast-dtmf-det") == 0) {
2828                                 use_ast_dtmfdet = 1;
2829                                 ast_log(LOG_NOTICE,"VPB driver using Asterisk DTMF detection functions!\n");
2830                         }
2831                         else if (strcasecmp(v->name, "relaxdtmf") == 0) {
2832                                 relaxdtmf = 1;
2833                                 ast_log(LOG_NOTICE,"VPB driver using Relaxed DTMF with Asterisk DTMF detections functions!\n");
2834                         }
2835                         else if (strcasecmp(v->name, "timer_period_ring") ==0) {
2836                                 timer_period_ring = atoi(v->value);
2837                         }
2838                         else if (strcasecmp(v->name, "ecsuppthres") ==0) {
2839                                 ec_supp_threshold = atoi(v->value);
2840                         }
2841                         else if (strcasecmp(v->name, "dtmfidd") ==0) {
2842                                 dtmf_idd = atoi(v->value);
2843                                 ast_log(LOG_NOTICE,"VPB Driver setting DTMF IDD to [%d]ms\n",dtmf_idd);
2844                         }
2845                         v = v->next;
2846                 }
2847         
2848                 v = ast_variable_browse(cfg, "interfaces");
2849                 while(v) {
2850                         /* Create the interface list */
2851                         if (strcasecmp(v->name, "board") == 0) {
2852                                 board = atoi(v->value);
2853                         } else  if (strcasecmp(v->name, "group") == 0){
2854                                 group = atoi(v->value);
2855                         } else  if (strcasecmp(v->name, "callgroup") == 0){
2856                                 callgroup = ast_get_group(v->value);
2857                         } else  if (strcasecmp(v->name, "pickupgroup") == 0){
2858                                 pickupgroup = ast_get_group(v->value);
2859                         } else  if (strcasecmp(v->name, "usepolaritycid") == 0){
2860                                 UsePolarityCID = atoi(v->value);
2861                         } else  if (strcasecmp(v->name, "useloopdrop") == 0){
2862                                 UseLoopDrop = atoi(v->value);
2863                         } else  if (strcasecmp(v->name, "usenativebridge") == 0){
2864                                 UseNativeBridge = atoi(v->value);
2865                         } else if (strcasecmp(v->name, "channel") == 0) {
2866                                 int channel = atoi(v->value);
2867                                 tmp = mkif(board, channel, mode, got_gain, txgain, rxgain, txswgain, rxswgain, bal1, bal2, bal3, callerid, echo_cancel,group,callgroup,pickupgroup);
2868                                 if (tmp) {
2869                                         if(first_channel) {
2870                                                 mkbrd( tmp->vpb_model, echo_cancel );
2871                                                 first_channel = 0;
2872                                         }
2873                                         tmp->next = iflist;
2874                                         iflist = tmp;
2875                                 } else {
2876                                         ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
2877                                         error = -1;
2878                                         goto done;
2879                                 }
2880                         } else if (strcasecmp(v->name, "language") == 0) {
2881                                 strncpy(language, v->value, sizeof(language)-1);
2882                         } else if (strcasecmp(v->name, "callerid") == 0) {
2883                                 callerid = strdup(v->value);
2884                         } else if (strcasecmp(v->name, "mode") == 0) {
2885                                 if (strncasecmp(v->value, "di", 2) == 0) 
2886                                         mode = MODE_DIALTONE;
2887                                 else if (strncasecmp(v->value, "im", 2) == 0)
2888                                         mode = MODE_IMMEDIATE;
2889                                 else if (strncasecmp(v->value, "fx", 2) == 0)
2890                                         mode = MODE_FXO;
2891                                 else
2892                                         ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
2893                         } else if (!strcasecmp(v->name, "context")) {
2894                                 strncpy(context, v->value, sizeof(context)-1);
2895                         } else if (!strcasecmp(v->name, "echocancel")) {
2896                                 if (!strcasecmp(v->value, "off")) 
2897                                         echo_cancel = 0;
2898                         } else if (strcasecmp(v->name, "txgain") == 0) {
2899                                 txswgain = parse_gain_value(v->name, v->value);
2900                                 got_gain |=VPB_GOT_TXSWG;
2901                         } else if (strcasecmp(v->name, "rxgain") == 0) {
2902                                 rxswgain = parse_gain_value(v->name, v->value);
2903                                 got_gain |=VPB_GOT_RXSWG;
2904                         } else if (strcasecmp(v->name, "txhwgain") == 0) {
2905                                 txgain = parse_gain_value(v->name, v->value);
2906                                 got_gain |=VPB_GOT_TXHWG;
2907                         } else if (strcasecmp(v->name, "rxhwgain") == 0) {
2908                                 rxgain = parse_gain_value(v->name, v->value);
2909                                 got_gain |=VPB_GOT_RXHWG;
2910                         } else if (strcasecmp(v->name, "bal1") == 0) {
2911                                 bal1 = strtol(v->value, NULL, 16);
2912                                 if(bal1<0 || bal1>255) {
2913                                         ast_log(LOG_WARNING, "Bad bal1 value: %d\n", bal1);
2914                                         bal1 = -1;
2915                                 }
2916                         } else if (strcasecmp(v->name, "bal2") == 0) {
2917                                 bal2 = strtol(v->value, NULL, 16);
2918                                 if(bal2<0 || bal2>255) {
2919                                         ast_log(LOG_WARNING, "Bad bal2 value: %d\n", bal2);
2920                                         bal2 = -1;
2921                                 }
2922                         } else if (strcasecmp(v->name, "bal3") == 0) {
2923                                 bal3 = strtol(v->value, NULL, 16);
2924                                 if(bal3<0 || bal3>255) {
2925                                         ast_log(LOG_WARNING, "Bad bal3 value: %d\n", bal3);
2926                                         bal3 = -1;
2927                                 }
2928                         } else if (strcasecmp(v->name, "grunttimeout") == 0) {
2929                                 gruntdetect_timeout = 1000*atoi(v->value);
2930                         }
2931                         v = v->next;
2932                 }
2933
2934                 if (gruntdetect_timeout < 1000)
2935                         gruntdetect_timeout = 1000;
2936
2937                 done: (void)0;
2938         } ast_mutex_unlock(&iflock);
2939
2940         ast_config_destroy(cfg);
2941
2942         if (use_ast_ind == 1){
2943                 if (!error && ast_channel_register(&vpb_tech_indicate) != 0) {
2944                         ast_log(LOG_ERROR, "Unable to register channel class 'vpb'\n");
2945                         error = -1;
2946                 }
2947                 else {
2948                         ast_log(LOG_NOTICE,"VPB driver Registered (w/AstIndication)\n");
2949                 }
2950         }
2951         else {
2952                 if (!error && ast_channel_register(&vpb_tech) != 0) {
2953                         ast_log(LOG_ERROR, "Unable to register channel class 'vpb'\n");
2954                         error = -1;
2955                 }
2956                 else {
2957                         ast_log(LOG_NOTICE,"VPB driver Registered )\n");
2958                 }
2959         }
2960
2961
2962         if (error)
2963                 unload_module();
2964         else 
2965                 restart_monitor(); /* And start the monitor for the first time */
2966
2967         return error;
2968 }
2969
2970
2971 int unload_module()
2972 {
2973         struct vpb_pvt *p;
2974         /* First, take us out of the channel loop */
2975         if (use_ast_ind == 1){
2976                 ast_channel_unregister(&vpb_tech_indicate);
2977         }
2978         else {
2979                 ast_channel_unregister(&vpb_tech);
2980         }
2981
2982         ast_mutex_lock(&iflock); {
2983                 /* Hangup all interfaces if they have an owner */
2984                 p = iflist;
2985                 while(p) {
2986                         if (p->owner)
2987                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2988                         p = p->next;
2989                 }
2990                 iflist = NULL;
2991         } ast_mutex_unlock(&iflock);
2992
2993         ast_mutex_lock(&monlock); {
2994                 if (mthreadactive > -1) {
2995                         pthread_cancel(monitor_thread);
2996                         pthread_join(monitor_thread, NULL);
2997                 }
2998                 mthreadactive = -2;
2999         } ast_mutex_unlock(&monlock);
3000
3001         ast_mutex_lock(&iflock); {
3002                 /* Destroy all the interfaces and free their memory */
3003
3004                 while(iflist) {
3005                         p = iflist;                 
3006                         ast_mutex_destroy(&p->lock);
3007                         pthread_cancel(p->readthread);
3008                         ast_mutex_destroy(&p->owner_lock);
3009                         ast_mutex_destroy(&p->record_lock);
3010                         ast_mutex_destroy(&p->play_lock);
3011                         ast_mutex_destroy(&p->play_dtmf_lock);
3012                         p->readthread = 0;
3013
3014                         vpb_close(p->handle);
3015
3016                         iflist = iflist->next;
3017
3018                         free(p);
3019                 }
3020                 iflist = NULL;
3021         } ast_mutex_unlock(&iflock);
3022
3023         ast_mutex_lock(&bridge_lock); {
3024                 memset(bridges, 0, sizeof bridges);          
3025         } ast_mutex_unlock(&bridge_lock);
3026         ast_mutex_destroy(&bridge_lock);
3027         for(int i = 0; i < max_bridges; i++ ) {
3028                 ast_mutex_destroy(&bridges[i].lock);
3029                 ast_cond_destroy(&bridges[i].cond);
3030         }
3031         free(bridges);
3032
3033         return 0;
3034 }
3035
3036 int usecount()
3037 {
3038         return usecnt;
3039 }
3040
3041 char *description()
3042 {
3043         return (char *) desc;
3044 }
3045
3046 char *key()
3047 {
3048         return ASTERISK_GPL_KEY;
3049 }
3050
3051 /**/
3052 #if defined(__cplusplus) || defined(c_plusplus)
3053  }
3054 #endif
3055 /**/