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