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