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