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