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