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