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