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