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