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