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