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