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