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