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