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