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