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