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