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