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