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