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