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