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