initialize send_message to make chan_vpb build
[asterisk-bristuff.git] / channels / chan_vpb.cc
blobe702fe611ca82d8f04c778ad9626cf9d63201b58
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_message: NULL,
391 send_image: NULL,
392 send_html: NULL,
393 exception: NULL,
394 bridge: ast_vpb_bridge,
395 indicate: vpb_indicate,
396 fixup: vpb_fixup,
397 setoption: NULL,
398 queryoption: NULL,
399 transfer: NULL,
400 write_video: NULL,
401 bridged_channel: NULL
404 static struct ast_channel_tech vpb_tech_indicate = {
405 type: "vpb",
406 description: tdesc,
407 capabilities: AST_FORMAT_SLINEAR,
408 properties: 0,
409 requester: vpb_request,
410 devicestate: NULL,
411 send_digit_begin: vpb_digit_begin,
412 send_digit_end: vpb_digit_end,
413 call: vpb_call,
414 hangup: vpb_hangup,
415 answer: vpb_answer,
416 read: vpb_read,
417 write: vpb_write,
418 send_text: NULL,
419 send_message: NULL,
420 send_image: NULL,
421 send_html: NULL,
422 exception: NULL,
423 bridge: ast_vpb_bridge,
424 indicate: NULL,
425 fixup: vpb_fixup,
426 setoption: NULL,
427 queryoption: NULL,
428 transfer: NULL,
429 write_video: NULL,
430 bridged_channel: NULL
433 /* Can't get ast_vpb_bridge() working on v4pci without either a horrible
434 * high pitched feedback noise or bad hiss noise depending on gain settings
435 * Get asterisk to do the bridging
437 #define BAD_V4PCI_BRIDGE
439 /* This one enables a half duplex bridge which may be required to prevent high pitched
440 * feedback when getting asterisk to do the bridging and when using certain gain settings.
442 /* #define HALF_DUPLEX_BRIDGE */
444 /* This is the Native bridge code, which Asterisk will try before using its own bridging code */
445 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)
447 struct vpb_pvt *p0 = (struct vpb_pvt *)c0->tech_pvt;
448 struct vpb_pvt *p1 = (struct vpb_pvt *)c1->tech_pvt;
449 int i;
450 int res;
451 struct ast_channel *cs[3];
452 struct ast_channel *who;
453 struct ast_frame *f;
455 cs[0] = c0;
456 cs[1] = c1;
458 #ifdef BAD_V4PCI_BRIDGE
459 if (p0->vpb_model==vpb_model_v4pci)
460 return AST_BRIDGE_FAILED_NOWARN;
461 #endif
462 if ( UseNativeBridge != 1){
463 return AST_BRIDGE_FAILED_NOWARN;
467 ast_mutex_lock(&p0->lock);
468 ast_mutex_lock(&p1->lock);
471 /* Bridge channels, check if we can. I believe we always can, so find a slot.*/
473 ast_mutex_lock(&bridge_lock);
474 for (i = 0; i < max_bridges; i++)
475 if (!bridges[i].inuse)
476 break;
477 if (i < max_bridges) {
478 bridges[i].inuse = 1;
479 bridges[i].endbridge = 0;
480 bridges[i].flags = flags;
481 bridges[i].rc = rc;
482 bridges[i].fo = fo;
483 bridges[i].c0 = c0;
484 bridges[i].c1 = c1;
486 ast_mutex_unlock(&bridge_lock);
488 if (i == max_bridges) {
489 ast_log(LOG_WARNING, "%s: vpb_bridge: Failed to bridge %s and %s!\n", p0->dev, c0->name, c1->name);
490 ast_mutex_unlock(&p0->lock);
491 ast_mutex_unlock(&p1->lock);
492 return AST_BRIDGE_FAILED_NOWARN;
493 } else {
494 /* Set bridge pointers. You don't want to take these locks while holding bridge lock.*/
495 ast_mutex_lock(&p0->lock);
496 p0->bridge = &bridges[i];
497 ast_mutex_unlock(&p0->lock);
499 ast_mutex_lock(&p1->lock);
500 p1->bridge = &bridges[i];
501 ast_mutex_unlock(&p1->lock);
503 ast_verb(2, "%s: vpb_bridge: Bridging call entered with [%s, %s]\n", p0->dev, c0->name, c1->name);
506 ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
508 #ifdef HALF_DUPLEX_BRIDGE
510 ast_debug(2, "%s: vpb_bridge: Starting half-duplex bridge [%s, %s]\n", p0->dev, c0->name, c1->name);
512 int dir = 0;
514 memset(p0->buf, 0, sizeof(p0->buf));
515 memset(p1->buf, 0, sizeof(p1->buf));
517 vpb_record_buf_start(p0->handle, VPB_ALAW);
518 vpb_record_buf_start(p1->handle, VPB_ALAW);
520 vpb_play_buf_start(p0->handle, VPB_ALAW);
521 vpb_play_buf_start(p1->handle, VPB_ALAW);
523 while (!bridges[i].endbridge) {
524 struct vpb_pvt *from, *to;
525 if (++dir % 2) {
526 from = p0;
527 to = p1;
528 } else {
529 from = p1;
530 to = p0;
532 vpb_record_buf_sync(from->handle, from->buf, VPB_SAMPLES);
533 vpb_play_buf_sync(to->handle, from->buf, VPB_SAMPLES);
536 vpb_record_buf_finish(p0->handle);
537 vpb_record_buf_finish(p1->handle);
539 vpb_play_buf_finish(p0->handle);
540 vpb_play_buf_finish(p1->handle);
542 ast_debug(2, "%s: vpb_bridge: Finished half-duplex bridge [%s, %s]\n", p0->dev, c0->name, c1->name);
544 res = VPB_OK;
546 #else
548 res = vpb_bridge(p0->handle, p1->handle, VPB_BRIDGE_ON);
549 if (res == VPB_OK) {
550 /* pthread_cond_wait(&bridges[i].cond, &bridges[i].lock);*/ /* Wait for condition signal. */
551 while (!bridges[i].endbridge) {
552 /* Are we really ment to be doing nothing ?!?! */
553 who = ast_waitfor_n(cs, 2, &timeoutms);
554 if (!who) {
555 if (!timeoutms) {
556 res = AST_BRIDGE_RETRY;
557 break;
559 ast_debug(1, "%s: vpb_bridge: Empty frame read...\n", p0->dev);
560 /* check for hangup / whentohangup */
561 if (ast_check_hangup(c0) || ast_check_hangup(c1))
562 break;
563 continue;
565 f = ast_read(who);
566 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
567 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
568 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
569 *fo = f;
570 *rc = who;
571 ast_debug(1, "%s: vpb_bridge: Got a [%s]\n", p0->dev, f ? "digit" : "hangup");
572 #if 0
573 if ((c0->tech_pvt == pvt0) && (!ast_check_hangup(c0))) {
574 if (pr0->set_rtp_peer(c0, NULL, NULL, 0))
575 ast_log(LOG_WARNING, "Channel '%s' failed to revert\n", c0->name);
577 if ((c1->tech_pvt == pvt1) && (!ast_check_hangup(c1))) {
578 if (pr1->set_rtp_peer(c1, NULL, NULL, 0))
579 ast_log(LOG_WARNING, "Channel '%s' failed to revert back\n", c1->name);
581 /* That's all we needed */
582 return 0;
583 #endif
584 /* Check if we need to break */
585 if (break_for_dtmf) {
586 break;
587 } else if ((f->frametype == AST_FRAME_DTMF) && ((f->subclass == '#') || (f->subclass == '*'))) {
588 break;
590 } else {
591 if ((f->frametype == AST_FRAME_DTMF) ||
592 (f->frametype == AST_FRAME_VOICE) ||
593 (f->frametype == AST_FRAME_VIDEO))
595 /* Forward voice or DTMF frames if they happen upon us */
596 /* Actually I dont think we want to forward on any frames!
597 if (who == c0) {
598 ast_write(c1, f);
599 } else if (who == c1) {
600 ast_write(c0, f);
604 ast_frfree(f);
606 /* Swap priority not that it's a big deal at this point */
607 cs[2] = cs[0];
608 cs[0] = cs[1];
609 cs[1] = cs[2];
611 vpb_bridge(p0->handle, p1->handle, VPB_BRIDGE_OFF);
614 #endif
616 ast_mutex_lock(&bridge_lock);
617 bridges[i].inuse = 0;
618 ast_mutex_unlock(&bridge_lock);
620 p0->bridge = NULL;
621 p1->bridge = NULL;
624 ast_verb(2, "Bridging call done with [%s, %s] => %d\n", c0->name, c1->name, res);
627 ast_mutex_unlock(&p0->lock);
628 ast_mutex_unlock(&p1->lock);
630 return (res == VPB_OK) ? AST_BRIDGE_COMPLETE : AST_BRIDGE_FAILED;
633 /* Caller ID can be located in different positions between the rings depending on your Telco
634 * Australian (Telstra) callerid starts 700ms after 1st ring and finishes 1.5s after first ring
635 * Use ANALYSE_CID to record rings and determine location of callerid
637 /* #define ANALYSE_CID */
638 #define RING_SKIP 300
639 #define CID_MSECS 2000
641 static void get_callerid(struct vpb_pvt *p)
643 short buf[CID_MSECS*8]; /* 8kHz sampling rate */
644 struct timeval cid_record_time;
645 int rc;
646 struct ast_channel *owner = p->owner;
648 char callerid[AST_MAX_EXTENSION] = "";
650 #ifdef ANALYSE_CID
651 void * ws;
652 char * file="cidsams.wav";
653 #endif
656 if (ast_mutex_trylock(&p->record_lock) == 0) {
658 cid_record_time = ast_tvnow();
659 ast_verb(4, "CID record - start\n");
661 /* Skip any trailing ringtone */
662 if (UsePolarityCID != 1){
663 vpb_sleep(RING_SKIP);
666 ast_verb(4, "CID record - skipped %dms trailing ring\n",
667 ast_tvdiff_ms(ast_tvnow(), cid_record_time));
668 cid_record_time = ast_tvnow();
670 /* Record bit between the rings which contains the callerid */
671 vpb_record_buf_start(p->handle, VPB_LINEAR);
672 rc = vpb_record_buf_sync(p->handle, (char*)buf, sizeof(buf));
673 vpb_record_buf_finish(p->handle);
674 #ifdef ANALYSE_CID
675 vpb_wave_open_write(&ws, file, VPB_LINEAR);
676 vpb_wave_write(ws, (char *)buf, sizeof(buf));
677 vpb_wave_close_write(ws);
678 #endif
680 ast_verb(4, "CID record - recorded %dms between rings\n",
681 ast_tvdiff_ms(ast_tvnow(), cid_record_time));
683 ast_mutex_unlock(&p->record_lock);
685 if (rc != VPB_OK) {
686 ast_log(LOG_ERROR, "Failed to record caller id sample on %s\n", p->dev);
687 return;
690 VPB_CID *cli_struct = new VPB_CID;
691 cli_struct->ra_cldn[0] = 0;
692 cli_struct->ra_cn[0] = 0;
693 /* This decodes FSK 1200baud type callerid */
694 if ((rc = vpb_cid_decode2(cli_struct, buf, CID_MSECS * 8)) == VPB_OK ) {
696 if (owner->cid.cid_num)
697 ast_free(owner->cid.cid_num);
698 owner->cid.cid_num=NULL;
699 if (owner->cid.cid_name)
700 ast_free(owner->cid.cid_name);
701 owner->cid.cid_name=NULL;
704 if (cli_struct->ra_cldn[0] == '\0') {
706 owner->cid.cid_num = ast_strdup(cli_struct->cldn);
707 owner->cid.cid_name = ast_strdup(cli_struct->cn);
709 if (owner) {
710 ast_set_callerid(owner, cli_struct->cldn, cli_struct->cn, cli_struct->cldn);
711 } else {
712 strcpy(p->cid_num, cli_struct->cldn);
713 strcpy(p->cid_name, cli_struct->cn);
715 ast_verb(4, "CID record - got [%s] [%s]\n", owner->cid.cid_num, owner->cid.cid_name);
716 snprintf(p->callerid, sizeof(p->callerid), "%s %s", cli_struct->cldn, cli_struct->cn);
717 } else {
718 ast_log(LOG_ERROR, "CID record - No caller id avalable on %s \n", p->dev);
721 } else {
722 ast_log(LOG_ERROR, "CID record - Failed to decode caller id on %s - %d\n", p->dev, rc);
723 ast_copy_string(p->callerid, "unknown", sizeof(p->callerid));
725 delete cli_struct;
727 } else
728 ast_log(LOG_ERROR, "CID record - Failed to set record mode for caller id on %s\n", p->dev);
731 static void get_callerid_ast(struct vpb_pvt *p)
733 struct callerid_state *cs;
734 char buf[1024];
735 char *name = NULL, *number = NULL;
736 int flags;
737 int rc = 0, vrc;
738 int sam_count = 0;
739 struct ast_channel *owner = p->owner;
740 int which_cid;
742 float old_gain;
744 #ifdef ANALYSE_CID
745 void * ws;
746 char * file = "cidsams.wav";
747 #endif
749 if (p->callerid_type == 1) {
750 ast_verb(4, "Collected caller ID already\n");
751 return;
753 else if (p->callerid_type == 2 ) {
754 which_cid = CID_SIG_V23;
755 ast_verb(4, "Collecting Caller ID v23...\n");
757 else if (p->callerid_type == 3) {
758 which_cid = CID_SIG_BELL;
759 ast_verb(4, "Collecting Caller ID bell...\n");
760 } else {
761 ast_verb(4, "Caller ID disabled\n");
762 return;
764 /* vpb_sleep(RING_SKIP); */
765 /* vpb_record_get_gain(p->handle, &old_gain); */
766 cs = callerid_new(which_cid);
767 if (cs) {
768 #ifdef ANALYSE_CID
769 vpb_wave_open_write(&ws, file, VPB_MULAW);
770 vpb_record_set_gain(p->handle, 3.0);
771 vpb_record_set_hw_gain(p->handle, 12.0);
772 #endif
773 vpb_record_buf_start(p->handle, VPB_MULAW);
774 while ((rc == 0) && (sam_count < 8000 * 3)) {
775 vrc = vpb_record_buf_sync(p->handle, (char*)buf, sizeof(buf));
776 if (vrc != VPB_OK)
777 ast_log(LOG_ERROR, "%s: Caller ID couldn't read audio buffer!\n", p->dev);
778 rc = callerid_feed(cs, (unsigned char *)buf, sizeof(buf), AST_FORMAT_ULAW);
779 #ifdef ANALYSE_CID
780 vpb_wave_write(ws, (char *)buf, sizeof(buf));
781 #endif
782 sam_count += sizeof(buf);
783 ast_verb(4, "Collecting Caller ID samples [%d][%d]...\n", sam_count, rc);
785 vpb_record_buf_finish(p->handle);
786 #ifdef ANALYSE_CID
787 vpb_wave_close_write(ws);
788 #endif
789 if (rc == 1) {
790 callerid_get(cs, &name, &number, &flags);
791 ast_debug(1, "%s: Caller ID name [%s] number [%s] flags [%d]\n", p->dev, name, number, flags);
792 } else {
793 ast_log(LOG_ERROR, "%s: Failed to decode Caller ID \n", p->dev);
795 /* vpb_record_set_gain(p->handle, old_gain); */
796 /* vpb_record_set_hw_gain(p->handle,6.0); */
797 } else {
798 ast_log(LOG_ERROR, "%s: Failed to create Caller ID struct\n", p->dev);
800 if (owner->cid.cid_num) {
801 ast_free(owner->cid.cid_num);
802 owner->cid.cid_num = NULL;
804 if (owner->cid.cid_name) {
805 ast_free(owner->cid.cid_name);
806 owner->cid.cid_name = NULL;
808 if (number)
809 ast_shrink_phone_number(number);
810 ast_set_callerid(owner,
811 number, name,
812 owner->cid.cid_ani ? NULL : number);
813 if (!ast_strlen_zero(name)){
814 snprintf(p->callerid, sizeof(p->callerid), "%s %s", number, name);
815 } else {
816 ast_copy_string(p->callerid, number, sizeof(p->callerid));
818 if (cs)
819 callerid_free(cs);
822 /* Terminate any tones we are presently playing */
823 static void stoptone(int handle)
825 int ret;
826 VPB_EVENT je;
827 while (vpb_playtone_state(handle) != VPB_OK) {
828 vpb_tone_terminate(handle);
829 ret = vpb_get_event_ch_async(handle, &je);
830 if ((ret == VPB_OK) && (je.type != VPB_DIALEND)) {
831 ast_verb(4, "Stop tone collected a wrong event!![%d]\n", je.type);
832 /* vpb_put_event(&je); */
834 vpb_sleep(10);
838 /* Safe vpb_playtone_async */
839 static int playtone( int handle, VPB_TONE *tone)
841 int ret = VPB_OK;
842 stoptone(handle);
843 ast_verb(4, "[%02d]: Playing tone\n", handle);
844 ret = vpb_playtone_async(handle, tone);
845 return ret;
848 static inline int monitor_handle_owned(struct vpb_pvt *p, VPB_EVENT *e)
850 struct ast_frame f = {AST_FRAME_CONTROL}; /* default is control, Clear rest. */
851 int endbridge = 0;
852 int res = 0;
854 ast_verb(4, "%s: handle_owned: got event: [%d=>%d]\n", p->dev, e->type, e->data);
856 f.src = "vpb";
857 switch (e->type) {
858 case VPB_RING:
859 if (p->mode == MODE_FXO) {
860 f.subclass = AST_CONTROL_RING;
861 vpb_timer_stop(p->ring_timer);
862 vpb_timer_start(p->ring_timer);
863 } else
864 f.frametype = AST_FRAME_NULL; /* ignore ring on station port. */
865 break;
867 case VPB_RING_OFF:
868 f.frametype = AST_FRAME_NULL;
869 break;
871 case VPB_TIMEREXP:
872 if (e->data == p->busy_timer_id) {
873 playtone(p->handle, &Busytone);
874 p->state = VPB_STATE_PLAYBUSY;
875 vpb_timer_stop(p->busy_timer);
876 vpb_timer_start(p->busy_timer);
877 f.frametype = AST_FRAME_NULL;
878 } else if (e->data == p->ringback_timer_id) {
879 playtone(p->handle, &Ringbacktone);
880 vpb_timer_stop(p->ringback_timer);
881 vpb_timer_start(p->ringback_timer);
882 f.frametype = AST_FRAME_NULL;
883 } else if (e->data == p->ring_timer_id) {
884 /* We didnt get another ring in time! */
885 if (p->owner->_state != AST_STATE_UP) {
886 /* Assume caller has hung up */
887 vpb_timer_stop(p->ring_timer);
888 f.subclass = AST_CONTROL_HANGUP;
889 } else {
890 vpb_timer_stop(p->ring_timer);
891 f.frametype = AST_FRAME_NULL;
894 } else {
895 f.frametype = AST_FRAME_NULL; /* Ignore. */
897 break;
899 case VPB_DTMF_DOWN:
900 case VPB_DTMF:
901 if (use_ast_dtmfdet) {
902 f.frametype = AST_FRAME_NULL;
903 } else if (p->owner->_state == AST_STATE_UP) {
904 f.frametype = AST_FRAME_DTMF;
905 f.subclass = e->data;
906 } else
907 f.frametype = AST_FRAME_NULL;
908 break;
910 case VPB_TONEDETECT:
911 if (e->data == VPB_BUSY || e->data == VPB_BUSY_308 || e->data == VPB_BUSY_AUST ) {
912 ast_debug(4, "%s: handle_owned: got event: BUSY\n", p->dev);
913 if (p->owner->_state == AST_STATE_UP) {
914 f.subclass = AST_CONTROL_HANGUP;
915 } else {
916 f.subclass = AST_CONTROL_BUSY;
918 } else if (e->data == VPB_FAX) {
919 if (!p->faxhandled) {
920 if (strcmp(p->owner->exten, "fax")) {
921 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
923 if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
924 ast_verb(3, "Redirecting %s to fax extension\n", p->owner->name);
925 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
926 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
927 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
928 ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
930 } else {
931 ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
933 } else {
934 ast_debug(1, "Already in a fax extension, not redirecting\n");
936 } else {
937 ast_debug(1, "Fax already handled\n");
939 } else if (e->data == VPB_GRUNT) {
940 if (ast_tvdiff_ms(ast_tvnow(), p->lastgrunt) > gruntdetect_timeout) {
941 /* Nothing heard on line for a very long time
942 * Timeout connection */
943 ast_verb(3, "grunt timeout\n");
944 ast_log(LOG_NOTICE, "%s: Line hangup due of lack of conversation\n", p->dev);
945 f.subclass = AST_CONTROL_HANGUP;
946 } else {
947 p->lastgrunt = ast_tvnow();
948 f.frametype = AST_FRAME_NULL;
950 } else {
951 f.frametype = AST_FRAME_NULL;
953 break;
955 case VPB_CALLEND:
956 #ifdef DIAL_WITH_CALL_PROGRESS
957 if (e->data == VPB_CALL_CONNECTED) {
958 f.subclass = AST_CONTROL_ANSWER;
959 } else if (e->data == VPB_CALL_NO_DIAL_TONE || e->data == VPB_CALL_NO_RING_BACK) {
960 f.subclass = AST_CONTROL_CONGESTION;
961 } else if (e->data == VPB_CALL_NO_ANSWER || e->data == VPB_CALL_BUSY) {
962 f.subclass = AST_CONTROL_BUSY;
963 } else if (e->data == VPB_CALL_DISCONNECTED) {
964 f.subclass = AST_CONTROL_HANGUP;
966 #else
967 ast_log(LOG_NOTICE, "%s: Got call progress callback but blind dialing \n", p->dev);
968 f.frametype = AST_FRAME_NULL;
969 #endif
970 break;
972 case VPB_STATION_OFFHOOK:
973 f.subclass = AST_CONTROL_ANSWER;
974 break;
976 case VPB_DROP:
977 if ((p->mode == MODE_FXO) && (UseLoopDrop)) { /* ignore loop drop on stations */
978 if (p->owner->_state == AST_STATE_UP) {
979 f.subclass = AST_CONTROL_HANGUP;
980 } else {
981 f.frametype = AST_FRAME_NULL;
984 break;
985 case VPB_LOOP_ONHOOK:
986 if (p->owner->_state == AST_STATE_UP) {
987 f.subclass = AST_CONTROL_HANGUP;
988 } else {
989 f.frametype = AST_FRAME_NULL;
991 break;
992 case VPB_STATION_ONHOOK:
993 f.subclass = AST_CONTROL_HANGUP;
994 break;
996 case VPB_STATION_FLASH:
997 f.subclass = AST_CONTROL_FLASH;
998 break;
1000 /* Called when dialing has finished and ringing starts
1001 * No indication that call has really been answered when using blind dialing
1003 case VPB_DIALEND:
1004 if (p->state < 5) {
1005 f.subclass = AST_CONTROL_ANSWER;
1006 ast_verb(2, "%s: Dialend\n", p->dev);
1007 } else {
1008 f.frametype = AST_FRAME_NULL;
1010 break;
1012 /* case VPB_PLAY_UNDERFLOW:
1013 f.frametype = AST_FRAME_NULL;
1014 vpb_reset_play_fifo_alarm(p->handle);
1015 break;
1017 case VPB_RECORD_OVERFLOW:
1018 f.frametype = AST_FRAME_NULL;
1019 vpb_reset_record_fifo_alarm(p->handle);
1020 break;
1022 default:
1023 f.frametype = AST_FRAME_NULL;
1024 break;
1028 ast_verb(4, "%s: LOCKING in handle_owned [%d]\n", p->dev,res);
1029 res = ast_mutex_lock(&p->lock);
1030 ast_verb(4, "%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1032 if (p->bridge) { /* Check what happened, see if we need to report it. */
1033 switch (f.frametype) {
1034 case AST_FRAME_DTMF:
1035 if ( !(p->bridge->c0 == p->owner &&
1036 (p->bridge->flags & AST_BRIDGE_DTMF_CHANNEL_0) ) &&
1037 !(p->bridge->c1 == p->owner &&
1038 (p->bridge->flags & AST_BRIDGE_DTMF_CHANNEL_1) )) {
1039 /* Kill bridge, this is interesting. */
1040 endbridge = 1;
1042 break;
1044 case AST_FRAME_CONTROL:
1045 if (!(p->bridge->flags & AST_BRIDGE_IGNORE_SIGS)) {
1046 #if 0
1047 if (f.subclass == AST_CONTROL_BUSY ||
1048 f.subclass == AST_CONTROL_CONGESTION ||
1049 f.subclass == AST_CONTROL_HANGUP ||
1050 f.subclass == AST_CONTROL_FLASH)
1051 #endif
1052 endbridge = 1;
1054 break;
1056 default:
1057 break;
1060 if (endbridge) {
1061 if (p->bridge->fo) {
1062 *p->bridge->fo = ast_frisolate(&f);
1065 if (p->bridge->rc) {
1066 *p->bridge->rc = p->owner;
1069 ast_mutex_lock(&p->bridge->lock);
1070 p->bridge->endbridge = 1;
1071 ast_cond_signal(&p->bridge->cond);
1072 ast_mutex_unlock(&p->bridge->lock);
1076 if (endbridge) {
1077 res = ast_mutex_unlock(&p->lock);
1079 ast_verb(4, "%s: unLOCKING in handle_owned [%d]\n", p->dev,res);
1081 return 0;
1084 ast_verb(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);
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
1091 if ((f.frametype >= 0) && (f.frametype != AST_FRAME_NULL) && (p->owner)) {
1092 if (ast_channel_trylock(p->owner) == 0) {
1093 ast_queue_frame(p->owner, &f);
1094 ast_channel_unlock(p->owner);
1095 ast_verb(4, "%s: handled_owned: Queued Frame to [%s]\n", p->dev, p->owner->name);
1096 } else {
1097 ast_verbose("%s: handled_owned: Missed event %d/%d \n",
1098 p->dev, f.frametype, f.subclass);
1101 res = ast_mutex_unlock(&p->lock);
1103 ast_verb(4, "%s: unLOCKING in handle_owned [%d]\n", p->dev,res);
1106 return 0;
1109 static inline int monitor_handle_notowned(struct vpb_pvt *p, VPB_EVENT *e)
1111 char s[2] = {0};
1112 struct ast_channel *owner = p->owner;
1113 char cid_num[256];
1114 char cid_name[256];
1116 struct ast_channel *c;
1119 char str[VPB_MAX_STR];
1121 vpb_translate_event(e, str);
1122 ast_verb(4, "%s: handle_notowned: mode=%d, event[%d][%s]=[%d]\n", p->dev, p->mode, e->type,str, e->data);
1124 switch (e->type) {
1125 case VPB_LOOP_ONHOOK:
1126 case VPB_LOOP_POLARITY:
1127 if (UsePolarityCID == 1) {
1128 ast_verb(4, "Polarity reversal\n");
1129 if (p->callerid_type == 1) {
1130 ast_verb(4, "Using VPB Caller ID\n");
1131 get_callerid(p); /* UK CID before 1st ring*/
1133 /* get_callerid_ast(p); */ /* Caller ID using the ast functions */
1135 break;
1136 case VPB_RING:
1137 if (p->mode == MODE_FXO) /* FXO port ring, start * */ {
1138 vpb_new(p, AST_STATE_RING, p->context);
1139 if (UsePolarityCID != 1) {
1140 if (p->callerid_type == 1) {
1141 ast_verb(4, "Using VPB Caller ID\n");
1142 get_callerid(p); /* Australian CID only between 1st and 2nd ring */
1144 get_callerid_ast(p); /* Caller ID using the ast functions */
1145 } else {
1146 ast_log(LOG_ERROR, "Setting caller ID: %s %s\n", p->cid_num, p->cid_name);
1147 ast_set_callerid(p->owner, p->cid_num, p->cid_name, p->cid_num);
1148 p->cid_num[0] = 0;
1149 p->cid_name[0] = 0;
1152 vpb_timer_stop(p->ring_timer);
1153 vpb_timer_start(p->ring_timer);
1155 break;
1157 case VPB_RING_OFF:
1158 break;
1160 case VPB_STATION_OFFHOOK:
1161 if (p->mode == MODE_IMMEDIATE) {
1162 vpb_new(p,AST_STATE_RING, p->context);
1163 } else {
1164 ast_verb(4, "%s: handle_notowned: playing dialtone\n", p->dev);
1165 playtone(p->handle, &Dialtone);
1166 p->state = VPB_STATE_PLAYDIAL;
1167 p->wantdtmf = 1;
1168 p->ext[0] = 0; /* Just to be sure & paranoid.*/
1170 break;
1172 case VPB_DIALEND:
1173 if (p->mode == MODE_DIALTONE) {
1174 if (p->state == VPB_STATE_PLAYDIAL) {
1175 playtone(p->handle, &Dialtone);
1176 p->wantdtmf = 1;
1177 p->ext[0] = 0; /* Just to be sure & paranoid. */
1179 #if 0
1180 /* These are not needed as they have timers to restart them */
1181 else if (p->state == VPB_STATE_PLAYBUSY) {
1182 playtone(p->handle, &Busytone);
1183 p->wantdtmf = 1;
1184 p->ext[0] = 0;
1185 } else if (p->state == VPB_STATE_PLAYRING) {
1186 playtone(p->handle, &Ringbacktone);
1187 p->wantdtmf = 1;
1188 p->ext[0] = 0;
1190 #endif
1191 } else {
1192 ast_verb(4, "%s: handle_notowned: Got a DIALEND when not really expected\n",p->dev);
1194 break;
1196 case VPB_STATION_ONHOOK: /* clear ext */
1197 stoptone(p->handle);
1198 p->wantdtmf = 1 ;
1199 p->ext[0] = 0;
1200 p->state = VPB_STATE_ONHOOK;
1201 break;
1202 case VPB_TIMEREXP:
1203 if (e->data == p->dtmfidd_timer_id) {
1204 if (ast_exists_extension(NULL, p->context, p->ext, 1, p->callerid)){
1205 ast_verb(4, "%s: handle_notowned: DTMF IDD timer out, matching on [%s] in [%s]\n", p->dev, p->ext, p->context);
1207 vpb_new(p, AST_STATE_RING, p->context);
1209 } else if (e->data == p->ring_timer_id) {
1210 /* We didnt get another ring in time! */
1211 if (p->owner) {
1212 if (p->owner->_state != AST_STATE_UP) {
1213 /* Assume caller has hung up */
1214 vpb_timer_stop(p->ring_timer);
1216 } else {
1217 /* No owner any more, Assume caller has hung up */
1218 vpb_timer_stop(p->ring_timer);
1221 break;
1223 case VPB_DTMF:
1224 if (p->state == VPB_STATE_ONHOOK){
1225 /* DTMF's being passed while on-hook maybe Caller ID */
1226 if (p->mode == MODE_FXO) {
1227 if (e->data == DTMF_CID_START) { /* CallerID Start signal */
1228 p->dtmf_caller_pos = 0; /* Leaves the first digit out */
1229 memset(p->callerid, 0, sizeof(p->callerid));
1230 } else if (e->data == DTMF_CID_STOP) { /* CallerID End signal */
1231 p->callerid[p->dtmf_caller_pos] = '\0';
1232 ast_verb(3, " %s: DTMF CallerID %s\n", p->dev, p->callerid);
1233 if (owner) {
1235 if (owner->cid.cid_num)
1236 ast_free(owner->cid.cid_num);
1237 owner->cid.cid_num=NULL;
1238 if (owner->cid.cid_name)
1239 ast_free(owner->cid.cid_name);
1240 owner->cid.cid_name=NULL;
1241 owner->cid.cid_num = strdup(p->callerid);
1243 cid_name[0] = '\0';
1244 cid_num[0] = '\0';
1245 ast_callerid_split(p->callerid, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
1246 ast_set_callerid(owner, cid_num, cid_name, cid_num);
1248 } else {
1249 ast_verb(3, " %s: DTMF CallerID: no owner to assign CID \n", p->dev);
1251 } else if (p->dtmf_caller_pos < AST_MAX_EXTENSION) {
1252 if (p->dtmf_caller_pos >= 0) {
1253 p->callerid[p->dtmf_caller_pos] = e->data;
1255 p->dtmf_caller_pos++;
1258 break;
1260 if (p->wantdtmf == 1) {
1261 stoptone(p->handle);
1262 p->wantdtmf = 0;
1264 p->state = VPB_STATE_GETDTMF;
1265 s[0] = e->data;
1266 strncat(p->ext, s, sizeof(p->ext) - strlen(p->ext) - 1);
1267 #if 0
1268 if (!strcmp(p->ext, ast_pickup_ext())) {
1269 /* Call pickup has been dialled! */
1270 if (ast_pickup_call(c)) {
1271 /* Call pickup wasnt possible */
1273 } else
1274 #endif
1275 if (ast_exists_extension(NULL, p->context, p->ext, 1, p->callerid)) {
1276 if (ast_canmatch_extension(NULL, p->context, p->ext, 1, p->callerid)) {
1277 ast_verb(4, "%s: handle_notowned: Multiple matches on [%s] in [%s]\n", p->dev, p->ext, p->context);
1278 /* Start DTMF IDD timer */
1279 vpb_timer_stop(p->dtmfidd_timer);
1280 vpb_timer_start(p->dtmfidd_timer);
1281 } else {
1282 ast_verb(4, "%s: handle_notowned: Matched on [%s] in [%s]\n", p->dev, p->ext , p->context);
1283 vpb_new(p, AST_STATE_UP, p->context);
1285 } else if (!ast_canmatch_extension(NULL, p->context, p->ext, 1, p->callerid)) {
1286 if (ast_exists_extension(NULL, "default", p->ext, 1, p->callerid)) {
1287 vpb_new(p, AST_STATE_UP, "default");
1288 } else if (!ast_canmatch_extension(NULL, "default", p->ext, 1, p->callerid)) {
1289 ast_verb(4, "%s: handle_notowned: can't match anything in %s or default\n", p->dev, p->context);
1290 playtone(p->handle, &Busytone);
1291 vpb_timer_stop(p->busy_timer);
1292 vpb_timer_start(p->busy_timer);
1293 p->state = VPB_STATE_PLAYBUSY;
1296 break;
1298 default:
1299 /* Ignore.*/
1300 break;
1303 ast_verb(4, "%s: handle_notowned: mode=%d, [%d=>%d]\n", p->dev, p->mode, e->type, e->data);
1305 return 0;
1308 static void *do_monitor(void *unused)
1311 /* Monitor thread, doesn't die until explicitly killed. */
1313 ast_verb(2, "Starting vpb monitor thread[%ld]\n", pthread_self());
1315 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
1317 for (;;) {
1318 VPB_EVENT e;
1319 VPB_EVENT je;
1320 char str[VPB_MAX_STR];
1321 struct vpb_pvt *p;
1324 ast_verb(4, "Monitor waiting for event\n");
1327 int res = vpb_get_event_sync(&e, VPB_WAIT_TIMEOUT);
1328 if ((res == VPB_NO_EVENTS) || (res == VPB_TIME_OUT)) {
1330 if (res == VPB_NO_EVENTS) {
1331 ast_verb(4, "No events....\n");
1332 } else {
1333 ast_verb(4, "No events, timed out....\n");
1336 continue;
1339 if (res != VPB_OK) {
1340 ast_log(LOG_ERROR,"Monitor get event error %d\n", res );
1341 ast_verbose("Monitor get event error %d\n", res );
1342 continue;
1345 str[0] = 0;
1347 p = NULL;
1349 ast_mutex_lock(&monlock);
1350 if (e.type == VPB_NULL_EVENT) {
1351 ast_verb(4, "Monitor got null event\n");
1352 } else {
1353 vpb_translate_event(&e, str);
1354 if (*str && *(str + 1)) {
1355 str[strlen(str) - 1] = '\0';
1358 ast_mutex_lock(&iflock);
1359 for (p = iflist; p && p->handle != e.handle; p = p->next);
1360 ast_mutex_unlock(&iflock);
1362 if (p) {
1363 ast_verb(4, "%s: Event [%d=>%s]\n",
1364 p ? p->dev : "null", e.type, str);
1368 ast_mutex_unlock(&monlock);
1370 if (!p) {
1371 if (e.type != VPB_NULL_EVENT) {
1372 ast_log(LOG_WARNING, "Got event [%s][%d], no matching iface!\n", str, e.type);
1373 ast_verb(4, "vpb/ERR: No interface for Event [%d=>%s] \n", e.type, str);
1375 continue;
1378 /* flush the event from the channel event Q */
1379 vpb_get_event_ch_async(e.handle, &je);
1380 vpb_translate_event(&je, str);
1381 ast_verb(5, "%s: Flushing event [%d]=>%s\n", p->dev, je.type, str);
1383 /* Check for ownership and locks */
1384 if ((p->owner) && (!p->golock)) {
1385 /* Need to get owner lock */
1386 /* Safely grab both p->lock and p->owner->lock so that there
1387 cannot be a race with something from the other side */
1389 ast_mutex_lock(&p->lock);
1390 while (ast_mutex_trylock(&p->owner->lock)) {
1391 ast_mutex_unlock(&p->lock);
1392 usleep(1);
1393 ast_mutex_lock(&p->lock);
1394 if (!p->owner)
1395 break;
1397 if (p->owner)
1398 p->golock = 1;
1401 /* Two scenarios: Are you owned or not. */
1402 if (p->owner) {
1403 monitor_handle_owned(p, &e);
1404 } else {
1405 monitor_handle_notowned(p, &e);
1407 /* if ((!p->owner)&&(p->golock)) {
1408 ast_mutex_unlock(&p->owner->lock);
1409 ast_mutex_unlock(&p->lock);
1415 return NULL;
1418 static int restart_monitor(void)
1420 int error = 0;
1422 /* If we're supposed to be stopped -- stay stopped */
1423 if (mthreadactive == -2)
1424 return 0;
1426 ast_verb(4, "Restarting monitor\n");
1428 ast_mutex_lock(&monlock);
1429 if (monitor_thread == pthread_self()) {
1430 ast_log(LOG_WARNING, "Cannot kill myself\n");
1431 error = -1;
1432 ast_verb(4, "Monitor trying to kill monitor\n");
1433 } else {
1434 if (mthreadactive != -1) {
1435 /* Why do other drivers kill the thread? No need says I, simply awake thread with event. */
1436 VPB_EVENT e;
1437 e.handle = 0;
1438 e.type = VPB_EVT_NONE;
1439 e.data = 0;
1441 ast_verb(4, "Trying to reawake monitor\n");
1443 vpb_put_event(&e);
1444 } else {
1445 /* Start a new monitor */
1446 int pid = ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL);
1447 ast_verb(4, "Created new monitor thread %d\n", pid);
1448 if (pid < 0) {
1449 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1450 error = -1;
1451 } else {
1452 mthreadactive = 0; /* Started the thread!*/
1456 ast_mutex_unlock(&monlock);
1458 ast_verb(4, "Monitor restarted\n");
1460 return error;
1463 /* Per board config that must be called after vpb_open() */
1464 static void mkbrd(vpb_model_t model, int echo_cancel)
1466 if (!bridges) {
1467 if (model == vpb_model_v4pci) {
1468 max_bridges = MAX_BRIDGES_V4PCI;
1470 bridges = (vpb_bridge_t *)ast_calloc(1, max_bridges * sizeof(vpb_bridge_t));
1471 if (!bridges) {
1472 ast_log(LOG_ERROR, "Failed to initialize bridges\n");
1473 } else {
1474 int i;
1475 for (i = 0; i < max_bridges; i++) {
1476 ast_mutex_init(&bridges[i].lock);
1477 ast_cond_init(&bridges[i].cond, NULL);
1481 if (!echo_cancel) {
1482 if (model == vpb_model_v4pci) {
1483 vpb_echo_canc_disable();
1484 ast_log(LOG_NOTICE, "Voicetronix echo cancellation OFF\n");
1485 } else {
1486 /* need to do it port by port for OpenSwitch */
1488 } else {
1489 if (model == vpb_model_v4pci) {
1490 vpb_echo_canc_enable();
1491 ast_log(LOG_NOTICE, "Voicetronix echo cancellation ON\n");
1492 if (ec_supp_threshold > -1) {
1493 vpb_echo_canc_set_sup_thresh(0, &ec_supp_threshold);
1494 ast_log(LOG_NOTICE, "Voicetronix EC Sup Thres set\n");
1496 } else {
1497 /* need to do it port by port for OpenSwitch */
1502 static struct vpb_pvt *mkif(int board, int channel, int mode, int gains, float txgain, float rxgain,
1503 float txswgain, float rxswgain, int bal1, int bal2, int bal3,
1504 char * callerid, int echo_cancel, int group, ast_group_t callgroup, ast_group_t pickupgroup )
1506 struct vpb_pvt *tmp;
1507 char buf[64];
1509 tmp = (vpb_pvt *)ast_calloc(1, sizeof(*tmp));
1511 if (!tmp)
1512 return NULL;
1514 tmp->handle = vpb_open(board, channel);
1516 if (tmp->handle < 0) {
1517 ast_log(LOG_WARNING, "Unable to create channel vpb/%d-%d: %s\n",
1518 board, channel, strerror(errno));
1519 ast_free(tmp);
1520 return NULL;
1523 snprintf(tmp->dev, sizeof(tmp->dev), "vpb/%d-%d", board, channel);
1525 tmp->mode = mode;
1527 tmp->group = group;
1528 tmp->callgroup = callgroup;
1529 tmp->pickupgroup = pickupgroup;
1531 /* Initilize dtmf caller ID position variable */
1532 tmp->dtmf_caller_pos = 0;
1534 ast_copy_string(tmp->language, language, sizeof(tmp->language));
1535 ast_copy_string(tmp->context, context, sizeof(tmp->context));
1537 tmp->callerid_type = 0;
1538 if (callerid) {
1539 if (strcasecmp(callerid, "on") == 0) {
1540 tmp->callerid_type = 1;
1541 ast_copy_string(tmp->callerid, "unknown", sizeof(tmp->callerid));
1542 } else if (strcasecmp(callerid, "v23") == 0) {
1543 tmp->callerid_type = 2;
1544 ast_copy_string(tmp->callerid, "unknown", sizeof(tmp->callerid));
1545 } else if (strcasecmp(callerid, "bell") == 0) {
1546 tmp->callerid_type = 3;
1547 ast_copy_string(tmp->callerid, "unknown", sizeof(tmp->callerid));
1548 } else {
1549 ast_copy_string(tmp->callerid, callerid, sizeof(tmp->callerid));
1551 } else {
1552 ast_copy_string(tmp->callerid, "unknown", sizeof(tmp->callerid));
1555 /* check if codec balances have been set in the config file */
1556 if (bal3 >= 0) {
1557 if ((bal1>=0) && !(bal1 & 32)) bal1 |= 32;
1558 vpb_set_codec_reg(tmp->handle, 0x42, bal3);
1560 if (bal1 >= 0) {
1561 vpb_set_codec_reg(tmp->handle, 0x32, bal1);
1563 if (bal2 >= 0) {
1564 vpb_set_codec_reg(tmp->handle, 0x3a, bal2);
1567 if (gains & VPB_GOT_TXHWG) {
1568 if (txgain > MAX_VPB_GAIN) {
1569 tmp->txgain = MAX_VPB_GAIN;
1570 } else if (txgain < MIN_VPB_GAIN) {
1571 tmp->txgain = MIN_VPB_GAIN;
1572 } else {
1573 tmp->txgain = txgain;
1576 ast_log(LOG_NOTICE, "VPB setting Tx Hw gain to [%f]\n", tmp->txgain);
1577 vpb_play_set_hw_gain(tmp->handle, tmp->txgain);
1580 if (gains & VPB_GOT_RXHWG) {
1581 if (rxgain > MAX_VPB_GAIN) {
1582 tmp->rxgain = MAX_VPB_GAIN;
1583 } else if (rxgain < MIN_VPB_GAIN) {
1584 tmp->rxgain = MIN_VPB_GAIN;
1585 } else {
1586 tmp->rxgain = rxgain;
1588 ast_log(LOG_NOTICE, "VPB setting Rx Hw gain to [%f]\n", tmp->rxgain);
1589 vpb_record_set_hw_gain(tmp->handle, tmp->rxgain);
1592 if (gains & VPB_GOT_TXSWG) {
1593 tmp->txswgain = txswgain;
1594 ast_log(LOG_NOTICE, "VPB setting Tx Sw gain to [%f]\n", tmp->txswgain);
1595 vpb_play_set_gain(tmp->handle, tmp->txswgain);
1598 if (gains & VPB_GOT_RXSWG) {
1599 tmp->rxswgain = rxswgain;
1600 ast_log(LOG_NOTICE, "VPB setting Rx Sw gain to [%f]\n", tmp->rxswgain);
1601 vpb_record_set_gain(tmp->handle, tmp->rxswgain);
1604 tmp->vpb_model = vpb_model_unknown;
1605 if (vpb_get_model(tmp->handle, buf) == VPB_OK) {
1606 if (strcmp(buf, "V12PCI") == 0) {
1607 tmp->vpb_model = vpb_model_v12pci;
1608 } else if (strcmp(buf, "VPB4") == 0) {
1609 tmp->vpb_model = vpb_model_v4pci;
1613 ast_mutex_init(&tmp->owner_lock);
1614 ast_mutex_init(&tmp->lock);
1615 ast_mutex_init(&tmp->record_lock);
1616 ast_mutex_init(&tmp->play_lock);
1617 ast_mutex_init(&tmp->play_dtmf_lock);
1619 /* set default read state */
1620 tmp->read_state = 0;
1622 tmp->golock = 0;
1624 tmp->busy_timer_id = vpb_timer_get_unique_timer_id();
1625 vpb_timer_open(&tmp->busy_timer, tmp->handle, tmp->busy_timer_id, TIMER_PERIOD_BUSY);
1627 tmp->ringback_timer_id = vpb_timer_get_unique_timer_id();
1628 vpb_timer_open(&tmp->ringback_timer, tmp->handle, tmp->ringback_timer_id, TIMER_PERIOD_RINGBACK);
1630 tmp->ring_timer_id = vpb_timer_get_unique_timer_id();
1631 vpb_timer_open(&tmp->ring_timer, tmp->handle, tmp->ring_timer_id, timer_period_ring);
1633 tmp->dtmfidd_timer_id = vpb_timer_get_unique_timer_id();
1634 vpb_timer_open(&tmp->dtmfidd_timer, tmp->handle, tmp->dtmfidd_timer_id, dtmf_idd);
1636 if (mode == MODE_FXO){
1637 if (use_ast_dtmfdet)
1638 vpb_set_event_mask(tmp->handle, VPB_EVENTS_NODTMF);
1639 else
1640 vpb_set_event_mask(tmp->handle, VPB_EVENTS_ALL);
1641 } else {
1643 if (use_ast_dtmfdet)
1644 vpb_set_event_mask(tmp->handle, VPB_EVENTS_NODTMF);
1645 else
1647 vpb_set_event_mask(tmp->handle, VPB_EVENTS_STAT);
1650 if ((tmp->vpb_model == vpb_model_v12pci) && (echo_cancel)) {
1651 vpb_hostecho_on(tmp->handle);
1653 if (use_ast_dtmfdet) {
1654 tmp->vad = ast_dsp_new();
1655 ast_dsp_set_features(tmp->vad, DSP_FEATURE_DTMF_DETECT);
1656 ast_dsp_digitmode(tmp->vad, DSP_DIGITMODE_DTMF);
1657 if (relaxdtmf)
1658 ast_dsp_digitmode(tmp->vad, DSP_DIGITMODE_DTMF|DSP_DIGITMODE_RELAXDTMF);
1659 } else {
1660 tmp->vad = NULL;
1663 /* define grunt tone */
1664 vpb_settonedet(tmp->handle,&toned_ungrunt);
1666 ast_log(LOG_NOTICE,"Voicetronix %s channel %s initialized (rxsg=%f/txsg=%f/rxhg=%f/txhg=%f)(0x%x/0x%x/0x%x)\n",
1667 (tmp->vpb_model == vpb_model_v4pci) ? "V4PCI" :
1668 (tmp->vpb_model == vpb_model_v12pci) ? "V12PCI" : "[Unknown model]",
1669 tmp->dev, tmp->rxswgain, tmp->txswgain, tmp->rxgain, tmp->txgain, bal1, bal2, bal3);
1671 return tmp;
1674 static int vpb_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1676 struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1677 int res = 0;
1678 int tmp = 0;
1680 if (use_ast_ind == 1) {
1681 ast_verb(4, "%s: vpb_indicate called when using Ast Indications !?!\n", p->dev);
1682 return 0;
1685 ast_verb(4, "%s: vpb_indicate [%d] state[%d]\n", p->dev, condition,ast->_state);
1687 if (ast->_state != AST_STATE_UP) {
1688 ast_verb(4, "%s: vpb_indicate Not in AST_STATE_UP\n", p->dev, condition,ast->_state);
1689 return res;
1694 ast_verb(4, "%s: LOCKING in indicate \n", p->dev);
1695 ast_verb(4, "%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count, p->lock.__m_owner);
1697 ast_mutex_lock(&p->lock);
1698 switch (condition) {
1699 case AST_CONTROL_BUSY:
1700 case AST_CONTROL_CONGESTION:
1701 if (ast->_state == AST_STATE_UP) {
1702 playtone(p->handle, &Busytone);
1703 p->state = VPB_STATE_PLAYBUSY;
1704 vpb_timer_stop(p->busy_timer);
1705 vpb_timer_start(p->busy_timer);
1707 break;
1708 case AST_CONTROL_RINGING:
1709 if (ast->_state == AST_STATE_UP) {
1710 playtone(p->handle, &Ringbacktone);
1711 p->state = VPB_STATE_PLAYRING;
1712 ast_verb(4, "%s: vpb indicate: setting ringback timer [%d]\n", p->dev,p->ringback_timer_id);
1714 vpb_timer_stop(p->ringback_timer);
1715 vpb_timer_start(p->ringback_timer);
1717 break;
1718 case AST_CONTROL_ANSWER:
1719 case -1: /* -1 means stop playing? */
1720 vpb_timer_stop(p->ringback_timer);
1721 vpb_timer_stop(p->busy_timer);
1722 stoptone(p->handle);
1723 break;
1724 case AST_CONTROL_HANGUP:
1725 if (ast->_state == AST_STATE_UP) {
1726 playtone(p->handle, &Busytone);
1727 p->state = VPB_STATE_PLAYBUSY;
1728 vpb_timer_stop(p->busy_timer);
1729 vpb_timer_start(p->busy_timer);
1731 break;
1732 case AST_CONTROL_HOLD:
1733 ast_moh_start(ast, (const char *) data, NULL);
1734 break;
1735 case AST_CONTROL_UNHOLD:
1736 ast_moh_stop(ast);
1737 break;
1738 default:
1739 res = 0;
1740 break;
1742 tmp = ast_mutex_unlock(&p->lock);
1744 ast_verb(4, "%s: unLOCKING in indicate [%d]\n", p->dev,tmp);
1746 return res;
1749 static int vpb_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1751 struct vpb_pvt *p = (struct vpb_pvt *)newchan->tech_pvt;
1752 int res = 0;
1755 ast_verb(4, "%s: LOCKING in fixup \n", p->dev);
1756 ast_verb(4, "%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1758 ast_mutex_lock(&p->lock);
1759 ast_debug(1, "New owner for channel %s is %s\n", p->dev, newchan->name);
1761 if (p->owner == oldchan) {
1762 p->owner = newchan;
1765 if (newchan->_state == AST_STATE_RINGING){
1766 if (use_ast_ind == 1) {
1767 ast_verb(4, "%s: vpb_fixup Calling ast_indicate\n", p->dev);
1768 ast_indicate(newchan, AST_CONTROL_RINGING);
1769 } else {
1770 ast_verb(4, "%s: vpb_fixup Calling vpb_indicate\n", p->dev);
1771 vpb_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
1775 res = ast_mutex_unlock(&p->lock);
1777 ast_verb(4, "%s: unLOCKING in fixup [%d]\n", p->dev,res);
1779 return 0;
1782 static int vpb_digit_begin(struct ast_channel *ast, char digit)
1784 /* XXX Modify this callback to let Asterisk control the length of DTMF */
1785 return 0;
1787 static int vpb_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1789 struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1790 char s[2];
1791 int res = 0;
1793 if (use_ast_dtmf) {
1794 ast_verb(4, "%s: vpb_digit: asked to play digit[%c] but we are using asterisk dtmf play back?!\n", p->dev, digit);
1795 return 0;
1799 ast_verb(4, "%s: LOCKING in digit \n", p->dev);
1800 ast_verb(4, "%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1802 ast_mutex_lock(&p->lock);
1805 s[0] = digit;
1806 s[1] = '\0';
1808 ast_verb(4, "%s: vpb_digit: asked to play digit[%s]\n", p->dev, s);
1810 ast_mutex_lock(&p->play_dtmf_lock);
1811 strncat(p->play_dtmf, s, sizeof(*p->play_dtmf) - strlen(p->play_dtmf) - 1);
1812 ast_mutex_unlock(&p->play_dtmf_lock);
1814 res = ast_mutex_unlock(&p->lock);
1816 ast_verb(4, "%s: unLOCKING in digit [%d]\n", p->dev,res);
1818 return 0;
1821 /* Places a call out of a VPB channel */
1822 static int vpb_call(struct ast_channel *ast, char *dest, int timeout)
1824 struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1825 int res = 0, i;
1826 char *s = strrchr(dest, '/');
1827 char dialstring[254] = "";
1828 int tmp = 0;
1831 ast_verb(4, "%s: LOCKING in call \n", p->dev);
1832 ast_verb(4, "%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1834 ast_mutex_lock(&p->lock);
1835 ast_verb(4, "%s: starting call to [%s]\n", p->dev, dest);
1837 if (s)
1838 s = s + 1;
1839 else
1840 s = dest;
1841 ast_copy_string(dialstring, s, sizeof(dialstring));
1842 for (i = 0; dialstring[i] != '\0'; i++) {
1843 if ((dialstring[i] == 'w') || (dialstring[i] == 'W'))
1844 dialstring[i] = ',';
1845 else if ((dialstring[i] == 'f') || (dialstring[i] == 'F'))
1846 dialstring[i] = '&';
1849 if (ast->_state != AST_STATE_DOWN && ast->_state != AST_STATE_RESERVED) {
1850 ast_log(LOG_WARNING, "vpb_call on %s neither down nor reserved!\n", ast->name);
1851 tmp = ast_mutex_unlock(&p->lock);
1853 ast_verb(4, "%s: unLOCKING in call [%d]\n", p->dev,tmp);
1855 return -1;
1857 if (p->mode != MODE_FXO) /* Station port, ring it. */
1858 vpb_ring_station_async(p->handle, 2);
1859 else {
1860 VPB_CALL call;
1861 int j;
1863 /* Dial must timeout or it can leave channels unuseable */
1864 if (timeout == 0) {
1865 timeout = TIMER_PERIOD_NOANSWER;
1866 } else {
1867 timeout = timeout * 1000; /* convert from secs to ms. */
1870 /* These timeouts are only used with call progress dialing */
1871 call.dialtones = 1; /* Number of dialtones to get outside line */
1872 call.dialtone_timeout = VPB_DIALTONE_WAIT; /* Wait this long for dialtone (ms) */
1873 call.ringback_timeout = VPB_RINGWAIT; /* Wait this long for ringing after dialing (ms) */
1874 call.inter_ringback_timeout = VPB_CONNECTED_WAIT; /* If ringing stops for this long consider it connected (ms) */
1875 call.answer_timeout = timeout; /* Time to wait for answer after ringing starts (ms) */
1876 memcpy(&call.tone_map, DialToneMap, sizeof(DialToneMap));
1877 vpb_set_call(p->handle, &call);
1879 ast_verb(2, "%s: Calling %s on %s \n",p->dev, dialstring, ast->name);
1881 ast_verb(2, "%s: Dial parms for %s %d/%dms/%dms/%dms/%dms\n", p->dev,
1882 ast->name, call.dialtones, call.dialtone_timeout,
1883 call.ringback_timeout, call.inter_ringback_timeout,
1884 call.answer_timeout);
1885 for (j = 0; !call.tone_map[j].terminate; j++) {
1886 ast_verb(2, "%s: Dial parms for %s tone %d->%d\n", p->dev,
1887 ast->name, call.tone_map[j].tone_id, call.tone_map[j].call_id);
1890 ast_verb(4, "%s: Disabling Loop Drop detection\n", p->dev);
1891 vpb_disable_event(p->handle, VPB_MDROP);
1892 vpb_sethook_sync(p->handle, VPB_OFFHOOK);
1893 p->state = VPB_STATE_OFFHOOK;
1895 #ifndef DIAL_WITH_CALL_PROGRESS
1896 vpb_sleep(300);
1897 ast_verb(4, "%s: Enabling Loop Drop detection\n", p->dev);
1898 vpb_enable_event(p->handle, VPB_MDROP);
1899 res = vpb_dial_async(p->handle, dialstring);
1900 #else
1901 ast_verb(4, "%s: Enabling Loop Drop detection\n", p->dev);
1902 vpb_enable_event(p->handle, VPB_MDROP);
1903 res = vpb_call_async(p->handle, dialstring);
1904 #endif
1906 if (res != VPB_OK) {
1907 ast_debug(1, "Call on %s to %s failed: %d\n", ast->name, s, res);
1908 res = -1;
1909 } else
1910 res = 0;
1913 ast_verb(3, "%s: VPB Calling %s [t=%d] on %s returned %d\n", p->dev , s, timeout, ast->name, res);
1914 if (res == 0) {
1915 ast_setstate(ast, AST_STATE_RINGING);
1916 ast_queue_control(ast, AST_CONTROL_RINGING);
1919 if (!p->readthread) {
1920 ast_pthread_create(&p->readthread, NULL, do_chanreads, (void *)p);
1923 tmp = ast_mutex_unlock(&p->lock);
1925 ast_verb(4, "%s: unLOCKING in call [%d]\n", p->dev,tmp);
1927 return res;
1930 static int vpb_hangup(struct ast_channel *ast)
1932 struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
1933 VPB_EVENT je;
1934 char str[VPB_MAX_STR];
1935 int res = 0;
1938 ast_verb(4, "%s: LOCKING in hangup \n", p->dev);
1939 ast_verb(4, "%s: LOCKING in hangup count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1940 ast_verb(4, "%s: LOCKING pthread_self(%d)\n", p->dev,pthread_self());
1941 ast_mutex_lock(&p->lock);
1943 ast_verb(2, "%s: Hangup requested\n", ast->name);
1945 if (!ast->tech || !ast->tech_pvt) {
1946 ast_log(LOG_WARNING, "%s: channel not connected?\n", ast->name);
1947 res = ast_mutex_unlock(&p->lock);
1949 ast_verb(4, "%s: unLOCKING in hangup [%d]\n", p->dev,res);
1951 /* Free up ast dsp if we have one */
1952 if (use_ast_dtmfdet && p->vad) {
1953 ast_dsp_free(p->vad);
1954 p->vad = NULL;
1956 return 0;
1961 /* Stop record */
1962 p->stopreads = 1;
1963 if (p->readthread) {
1964 pthread_join(p->readthread, NULL);
1965 ast_verb(4, "%s: stopped record thread \n", ast->name);
1968 /* Stop play */
1969 if (p->lastoutput != -1) {
1970 ast_verb(2, "%s: Ending play mode \n", ast->name);
1971 vpb_play_terminate(p->handle);
1972 ast_mutex_lock(&p->play_lock);
1973 vpb_play_buf_finish(p->handle);
1974 ast_mutex_unlock(&p->play_lock);
1977 ast_verb(4, "%s: Setting state down\n", ast->name);
1978 ast_setstate(ast, AST_STATE_DOWN);
1982 ast_verb(4, "%s: LOCKING in hangup \n", p->dev);
1983 ast_verb(4, "%s: LOCKING in hangup count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
1984 ast_verb(4, "%s: LOCKING pthread_self(%d)\n", p->dev,pthread_self());
1986 ast_mutex_lock(&p->lock);
1988 if (p->mode != MODE_FXO) {
1989 /* station port. */
1990 vpb_ring_station_async(p->handle, 0);
1991 if (p->state != VPB_STATE_ONHOOK) {
1992 /* This is causing a "dial end" "play tone" loop
1993 playtone(p->handle, &Busytone);
1994 p->state = VPB_STATE_PLAYBUSY;
1995 ast_verb(5, "%s: Station offhook[%d], playing busy tone\n",
1996 ast->name,p->state);
1998 } else {
1999 stoptone(p->handle);
2001 #ifdef VPB_PRI
2002 vpb_setloop_async(p->handle, VPB_OFFHOOK);
2003 vpb_sleep(100);
2004 vpb_setloop_async(p->handle, VPB_ONHOOK);
2005 #endif
2006 } else {
2007 stoptone(p->handle); /* Terminates any dialing */
2008 vpb_sethook_sync(p->handle, VPB_ONHOOK);
2009 p->state=VPB_STATE_ONHOOK;
2011 while (VPB_OK == vpb_get_event_ch_async(p->handle, &je)) {
2012 vpb_translate_event(&je, str);
2013 ast_verb(4, "%s: Flushing event [%d]=>%s\n", ast->name, je.type, str);
2016 p->readthread = 0;
2017 p->lastoutput = -1;
2018 p->lastinput = -1;
2019 p->last_ignore_dtmf = 1;
2020 p->ext[0] = 0;
2021 p->dialtone = 0;
2023 p->owner = NULL;
2024 ast->tech_pvt = NULL;
2026 /* Free up ast dsp if we have one */
2027 if (use_ast_dtmfdet && p->vad) {
2028 ast_dsp_free(p->vad);
2029 p->vad = NULL;
2032 ast_verb(2, "%s: Hangup complete\n", ast->name);
2034 restart_monitor();
2036 ast_verb(4, "%s: LOCKING in hangup count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
2038 res = ast_mutex_unlock(&p->lock);
2040 ast_verb(4, "%s: unLOCKING in hangup [%d]\n", p->dev,res);
2041 ast_verb(4, "%s: LOCKING in hangup count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
2043 return 0;
2046 static int vpb_answer(struct ast_channel *ast)
2048 struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
2049 int res = 0;
2051 VPB_EVENT je;
2052 int ret;
2053 ast_verb(4, "%s: LOCKING in answer \n", p->dev);
2054 ast_verb(4, "%s: LOCKING count[%d] owner[%d] \n", p->dev, p->lock.__m_count,p->lock.__m_owner);
2056 ast_mutex_lock(&p->lock);
2058 ast_verb(4, "%s: Answering channel\n", p->dev);
2060 if (p->mode == MODE_FXO) {
2061 ast_verb(4, "%s: Disabling Loop Drop detection\n", p->dev);
2062 vpb_disable_event(p->handle, VPB_MDROP);
2065 if (ast->_state != AST_STATE_UP) {
2066 if (p->mode == MODE_FXO) {
2067 vpb_sethook_sync(p->handle, VPB_OFFHOOK);
2068 p->state = VPB_STATE_OFFHOOK;
2069 /* vpb_sleep(500);
2070 ret = vpb_get_event_ch_async(p->handle, &je);
2071 if ((ret == VPB_OK) && ((je.type != VPB_DROP)&&(je.type != VPB_RING))){
2072 ast_verb(4, "%s: Answer collected a wrong event!!\n", p->dev);
2073 vpb_put_event(&je);
2077 ast_setstate(ast, AST_STATE_UP);
2079 ast_verb(2, "%s: Answered call on %s [%s]\n", p->dev,
2080 ast->name, (p->mode == MODE_FXO) ? "FXO" : "FXS");
2082 ast->rings = 0;
2083 if (!p->readthread) {
2084 /* res = ast_mutex_unlock(&p->lock); */
2085 /* ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res); */
2086 ast_pthread_create(&p->readthread, NULL, do_chanreads, (void *)p);
2087 } else {
2088 ast_verb(4, "%s: Record thread already running!!\n", p->dev);
2090 } else {
2091 ast_verb(4, "%s: Answered state is up\n", p->dev);
2092 /* res = ast_mutex_unlock(&p->lock); */
2093 /* ast_verbose("%s: unLOCKING in answer [%d]\n", p->dev,res); */
2095 vpb_sleep(500);
2096 if (p->mode == MODE_FXO) {
2097 ast_verb(4, "%s: Re-enabling Loop Drop detection\n", p->dev);
2098 vpb_enable_event(p->handle, VPB_MDROP);
2100 res = ast_mutex_unlock(&p->lock);
2102 ast_verb(4, "%s: unLOCKING in answer [%d]\n", p->dev,res);
2104 return 0;
2107 static struct ast_frame *vpb_read(struct ast_channel *ast)
2109 struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
2110 static struct ast_frame f = { AST_FRAME_NULL };
2112 f.src = "vpb";
2113 ast_log(LOG_NOTICE, "%s: vpb_read: should never be called!\n", p->dev);
2114 ast_verbose("%s: vpb_read: should never be called!\n", p->dev);
2116 return &f;
2119 static inline AudioCompress ast2vpbformat(int ast_format)
2121 switch (ast_format) {
2122 case AST_FORMAT_ALAW:
2123 return VPB_ALAW;
2124 case AST_FORMAT_SLINEAR:
2125 return VPB_LINEAR;
2126 case AST_FORMAT_ULAW:
2127 return VPB_MULAW;
2128 case AST_FORMAT_ADPCM:
2129 return VPB_OKIADPCM;
2130 default:
2131 return VPB_RAW;
2135 static inline const char * ast2vpbformatname(int ast_format)
2137 switch(ast_format) {
2138 case AST_FORMAT_ALAW:
2139 return "AST_FORMAT_ALAW:VPB_ALAW";
2140 case AST_FORMAT_SLINEAR:
2141 return "AST_FORMAT_SLINEAR:VPB_LINEAR";
2142 case AST_FORMAT_ULAW:
2143 return "AST_FORMAT_ULAW:VPB_MULAW";
2144 case AST_FORMAT_ADPCM:
2145 return "AST_FORMAT_ADPCM:VPB_OKIADPCM";
2146 default:
2147 return "UNKN:UNKN";
2151 static inline int astformatbits(int ast_format)
2153 switch (ast_format) {
2154 case AST_FORMAT_SLINEAR:
2155 return 16;
2156 case AST_FORMAT_ADPCM:
2157 return 4;
2158 case AST_FORMAT_ALAW:
2159 case AST_FORMAT_ULAW:
2160 default:
2161 return 8;
2165 int a_gain_vector(float g, short *v, int n)
2167 int i;
2168 float tmp;
2169 for (i = 0; i < n; i++) {
2170 tmp = g * v[i];
2171 if (tmp > 32767.0)
2172 tmp = 32767.0;
2173 if (tmp < -32768.0)
2174 tmp = -32768.0;
2175 v[i] = (short)tmp;
2177 return i;
2180 /* Writes a frame of voice data to a VPB channel */
2181 static int vpb_write(struct ast_channel *ast, struct ast_frame *frame)
2183 struct vpb_pvt *p = (struct vpb_pvt *)ast->tech_pvt;
2184 int res = 0;
2185 AudioCompress fmt = VPB_RAW;
2186 struct timeval play_buf_time_start;
2187 int tdiff;
2189 /* ast_mutex_lock(&p->lock); */
2190 ast_verb(6, "%s: vpb_write: Writing to channel\n", p->dev);
2192 if (frame->frametype != AST_FRAME_VOICE) {
2193 ast_verb(4, "%s: vpb_write: Don't know how to handle from type %d\n", ast->name, frame->frametype);
2194 /* ast_mutex_unlock(&p->lock); */
2195 return 0;
2196 } else if (ast->_state != AST_STATE_UP) {
2197 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);
2198 p->lastoutput = -1;
2199 /* ast_mutex_unlock(&p->lock); */
2200 return 0;
2202 /* ast_debug(1, "%s: vpb_write: Checked frame type..\n", p->dev); */
2205 fmt = ast2vpbformat(frame->subclass);
2206 if (fmt < 0) {
2207 ast_log(LOG_WARNING, "%s: vpb_write: Cannot handle frames of %d format!\n", ast->name, frame->subclass);
2208 return -1;
2211 tdiff = ast_tvdiff_ms(ast_tvnow(), p->lastplay);
2212 ast_debug(1, "%s: vpb_write: time since last play(%d) \n", p->dev, tdiff);
2213 if (tdiff < (VPB_SAMPLES / 8 - 1)) {
2214 ast_debug(1, "%s: vpb_write: Asked to play too often (%d) (%d)\n", p->dev, tdiff, frame->datalen);
2215 /* return 0; */
2217 p->lastplay = ast_tvnow();
2219 ast_debug(1, "%s: vpb_write: Checked frame format..\n", p->dev);
2222 ast_mutex_lock(&p->play_lock);
2225 ast_debug(1, "%s: vpb_write: Got play lock..\n", p->dev);
2228 /* Check if we have set up the play_buf */
2229 if (p->lastoutput == -1) {
2230 vpb_play_buf_start(p->handle, fmt);
2231 ast_verb(2, "%s: vpb_write: Starting play mode (codec=%d)[%s]\n", p->dev, fmt, ast2vpbformatname(frame->subclass));
2232 p->lastoutput = fmt;
2233 ast_mutex_unlock(&p->play_lock);
2234 return 0;
2235 } else if (p->lastoutput != fmt) {
2236 vpb_play_buf_finish(p->handle);
2237 vpb_play_buf_start(p->handle, fmt);
2238 ast_verb(2, "%s: vpb_write: Changed play format (%d=>%d)\n", p->dev, p->lastoutput, fmt);
2239 ast_mutex_unlock(&p->play_lock);
2240 return 0;
2242 p->lastoutput = fmt;
2246 /* Apply extra gain ! */
2247 if( p->txswgain > MAX_VPB_GAIN )
2248 a_gain_vector(p->txswgain - MAX_VPB_GAIN , (short*)frame->data, frame->datalen / sizeof(short));
2250 /* ast_debug(1, "%s: vpb_write: Applied gain..\n", p->dev); */
2251 /* ast_debug(1, "%s: vpb_write: play_buf_time %d\n", p->dev, p->play_buf_time); */
2253 if ((p->read_state == 1) && (p->play_buf_time < 5)){
2254 play_buf_time_start = ast_tvnow();
2255 /* res = vpb_play_buf_sync(p->handle, (char *)frame->data, tdiff * 8 * 2); */
2256 res = vpb_play_buf_sync(p->handle, (char *)frame->data, frame->datalen);
2257 if(res == VPB_OK) {
2258 short * data = (short*)frame->data;
2259 ast_verb(6, "%s: vpb_write: Wrote chan (codec=%d) %d %d\n", p->dev, fmt, data[0], data[1]);
2261 p->play_buf_time = ast_tvdiff_ms(ast_tvnow(), play_buf_time_start);
2262 } else {
2263 p->chuck_count++;
2264 ast_debug(1, "%s: vpb_write: Tossed data away, tooooo much data!![%d]\n", p->dev, p->chuck_count);
2265 p->play_buf_time = 0;
2268 ast_mutex_unlock(&p->play_lock);
2269 /* ast_mutex_unlock(&p->lock); */
2270 ast_verb(6, "%s: vpb_write: Done Writing to channel\n", p->dev);
2271 return 0;
2274 /* Read monitor thread function. */
2275 static void *do_chanreads(void *pvt)
2277 struct vpb_pvt *p = (struct vpb_pvt *)pvt;
2278 struct ast_frame *fr = &p->fr;
2279 char *readbuf = ((char *)p->buf) + AST_FRIENDLY_OFFSET;
2280 int bridgerec = 0;
2281 int afmt, readlen, res, trycnt=0;
2282 AudioCompress fmt;
2283 int ignore_dtmf;
2284 const char * getdtmf_var = NULL;
2286 fr->frametype = AST_FRAME_VOICE;
2287 fr->src = "vpb";
2288 fr->mallocd = 0;
2289 fr->delivery.tv_sec = 0;
2290 fr->delivery.tv_usec = 0;
2291 fr->samples = VPB_SAMPLES;
2292 fr->offset = AST_FRIENDLY_OFFSET;
2293 memset(p->buf, 0, sizeof p->buf);
2295 ast_verb(3, "%s: chanreads: starting thread\n", p->dev);
2296 ast_mutex_lock(&p->record_lock);
2298 p->stopreads = 0;
2299 p->read_state = 1;
2300 while (!p->stopreads && p->owner) {
2302 ast_verb(5, "%s: chanreads: Starting cycle ...\n", p->dev);
2303 ast_verb(5, "%s: chanreads: Checking bridge \n", p->dev);
2304 if (p->bridge) {
2305 if (p->bridge->c0 == p->owner && (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_0))
2306 bridgerec = 1;
2307 else if (p->bridge->c1 == p->owner && (p->bridge->flags & AST_BRIDGE_REC_CHANNEL_1))
2308 bridgerec = 1;
2309 else
2310 bridgerec = 0;
2311 } else {
2312 ast_verb(5, "%s: chanreads: No native bridge.\n", p->dev);
2313 if (p->owner->_bridge) {
2314 ast_verb(5, "%s: chanreads: Got Asterisk bridge with [%s].\n", p->dev, p->owner->_bridge->name);
2315 bridgerec = 1;
2316 } else {
2317 bridgerec = 0;
2321 /* if ((p->owner->_state != AST_STATE_UP) || !bridgerec) */
2322 if ((p->owner->_state != AST_STATE_UP)) {
2323 if (p->owner->_state != AST_STATE_UP) {
2324 ast_verb(5, "%s: chanreads: Im not up[%d]\n", p->dev, p->owner->_state);
2325 } else {
2326 ast_verb(5, "%s: chanreads: No bridgerec[%d]\n", p->dev, bridgerec);
2328 vpb_sleep(10);
2329 continue;
2332 /* Voicetronix DTMF detection can be triggered off ordinary speech
2333 * This leads to annoying beeps during the conversation
2334 * Avoid this problem by just setting VPB_GETDTMF when you want to listen for DTMF
2336 /* ignore_dtmf = 1; */
2337 ignore_dtmf = 0; /* set this to 1 to turn this feature on */
2338 getdtmf_var = pbx_builtin_getvar_helper(p->owner, "VPB_GETDTMF");
2339 if (getdtmf_var && strcasecmp(getdtmf_var, "yes") == 0)
2340 ignore_dtmf = 0;
2342 if ((ignore_dtmf != p->last_ignore_dtmf) && (!use_ast_dtmfdet)){
2343 ast_verb(2, "%s:Now %s DTMF \n",
2344 p->dev, ignore_dtmf ? "ignoring" : "listening for");
2345 vpb_set_event_mask(p->handle, ignore_dtmf ? VPB_EVENTS_NODTMF : VPB_EVENTS_ALL );
2347 p->last_ignore_dtmf = ignore_dtmf;
2349 /* Play DTMF digits here to avoid problem you get if playing a digit during
2350 * a record operation
2352 ast_verb(6, "%s: chanreads: Checking dtmf's \n", p->dev);
2353 ast_mutex_lock(&p->play_dtmf_lock);
2354 if (p->play_dtmf[0]) {
2355 /* Try to ignore DTMF event we get after playing digit */
2356 /* This DTMF is played by asterisk and leads to an annoying trailing beep on CISCO phones */
2357 if (!ignore_dtmf) {
2358 vpb_set_event_mask(p->handle, VPB_EVENTS_NODTMF );
2360 if (p->bridge == NULL) {
2361 vpb_dial_sync(p->handle, p->play_dtmf);
2362 ast_verb(2, "%s: chanreads: Played DTMF %s\n", p->dev, p->play_dtmf);
2363 } else {
2364 ast_verb(2, "%s: chanreads: Not playing DTMF frame on native bridge\n", p->dev);
2366 p->play_dtmf[0] = '\0';
2367 ast_mutex_unlock(&p->play_dtmf_lock);
2368 vpb_sleep(700); /* Long enough to miss echo and DTMF event */
2369 if( !ignore_dtmf)
2370 vpb_set_event_mask(p->handle, VPB_EVENTS_ALL);
2371 continue;
2373 ast_mutex_unlock(&p->play_dtmf_lock);
2375 /* afmt = (p->owner) ? p->owner->rawreadformat : AST_FORMAT_SLINEAR; */
2376 if (p->owner) {
2377 afmt = p->owner->rawreadformat;
2378 /* ast_debug(1,"%s: Record using owner format [%s]\n", p->dev, ast2vpbformatname(afmt)); */
2379 } else {
2380 afmt = AST_FORMAT_SLINEAR;
2381 /* ast_debug(1,"%s: Record using default format [%s]\n", p->dev, ast2vpbformatname(afmt)); */
2383 fmt = ast2vpbformat(afmt);
2384 if (fmt < 0) {
2385 ast_log(LOG_WARNING, "%s: Record failure (unsupported format %d)\n", p->dev, afmt);
2386 return NULL;
2388 readlen = VPB_SAMPLES * astformatbits(afmt) / 8;
2390 if (p->lastinput == -1) {
2391 vpb_record_buf_start(p->handle, fmt);
2392 /* vpb_reset_record_fifo_alarm(p->handle); */
2393 p->lastinput = fmt;
2394 ast_verb(2, "%s: Starting record mode (codec=%d)[%s]\n", p->dev, fmt, ast2vpbformatname(afmt));
2395 continue;
2396 } else if (p->lastinput != fmt) {
2397 vpb_record_buf_finish(p->handle);
2398 vpb_record_buf_start(p->handle, fmt);
2399 p->lastinput = fmt;
2400 ast_verb(2, "%s: Changed record format (%d=>%d)\n", p->dev, p->lastinput, fmt);
2401 continue;
2404 /* Read only if up and not bridged, or a bridge for which we can read. */
2405 ast_verb(6, "%s: chanreads: getting buffer!\n", p->dev);
2406 if( (res = vpb_record_buf_sync(p->handle, readbuf, readlen) ) == VPB_OK ) {
2407 ast_verb(6, "%s: chanreads: got buffer!\n", p->dev);
2408 /* Apply extra gain ! */
2409 if( p->rxswgain > MAX_VPB_GAIN )
2410 a_gain_vector(p->rxswgain - MAX_VPB_GAIN, (short *)readbuf, readlen / sizeof(short));
2411 ast_verb(6, "%s: chanreads: applied gain\n", p->dev);
2413 fr->subclass = afmt;
2414 fr->data = readbuf;
2415 fr->datalen = readlen;
2416 fr->frametype = AST_FRAME_VOICE;
2418 if ((use_ast_dtmfdet)&&(p->vad)) {
2419 fr = ast_dsp_process(p->owner,p->vad,fr);
2420 if (fr && (fr->frametype == AST_FRAME_DTMF)) {
2421 ast_debug(1, "%s: chanreads: Detected DTMF '%c'\n", p->dev, fr->subclass);
2422 } else if (fr->subclass == 'f') {
2425 /* Using trylock here to prevent deadlock when channel is hungup
2426 * (ast_hangup() immediately gets lock)
2428 if (p->owner && !p->stopreads) {
2429 ast_verb(6, "%s: chanreads: queueing buffer on read frame q (state[%d])\n", p->dev, p->owner->_state);
2430 do {
2431 res = ast_channel_trylock(p->owner);
2432 trycnt++;
2433 } while ((res !=0 ) && (trycnt < 300));
2434 if (res == 0) {
2435 ast_queue_frame(p->owner, fr);
2436 ast_channel_unlock(p->owner);
2437 } else {
2438 ast_verb(5, "%s: chanreads: Couldnt get lock after %d tries!\n", p->dev, trycnt);
2440 trycnt = 0;
2443 res = ast_mutex_trylock(&p->owner->lock);
2444 if (res == 0) {
2445 ast_queue_frame(p->owner, fr);
2446 ast_mutex_unlock(&p->owner->lock);
2447 } else {
2448 if (res == EINVAL)
2449 ast_verb(5, "%s: chanreads: try owner->lock gave me EINVAL[%d]\n", p->dev, res);
2450 else if (res == EBUSY)
2451 ast_verb(5, "%s: chanreads: try owner->lock gave me EBUSY[%d]\n", p->dev, res);
2452 while (res != 0) {
2453 res = ast_mutex_trylock(&p->owner->lock);
2455 if (res == 0) {
2456 ast_queue_frame(p->owner, fr);
2457 ast_mutex_unlock(&p->owner->lock);
2458 } else {
2459 if (res == EINVAL) {
2460 ast_verb(5, "%s: chanreads: try owner->lock gave me EINVAL[%d]\n", p->dev, res);
2461 } else if (res == EBUSY) {
2462 ast_verb(5, "%s: chanreads: try owner->lock gave me EBUSY[%d]\n", p->dev, res);
2464 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);
2468 short *data = (short *)readbuf;
2469 ast_verb(7, "%s: Read channel (codec=%d) %d %d\n", p->dev, fmt, data[0], data[1]);
2470 } else {
2471 ast_verb(5, "%s: p->stopreads[%d] p->owner[%p]\n", p->dev, p->stopreads, (void *)p->owner);
2474 ast_verb(5, "%s: chanreads: Finished cycle...\n", p->dev);
2476 p->read_state = 0;
2478 /* When stopreads seen, go away! */
2479 vpb_record_buf_finish(p->handle);
2480 p->read_state = 0;
2481 ast_mutex_unlock(&p->record_lock);
2483 ast_verb(2, "%s: Ending record mode (%d/%s)\n",
2484 p->dev, p->stopreads, p->owner ? "yes" : "no");
2485 return NULL;
2488 static struct ast_channel *vpb_new(struct vpb_pvt *me, enum ast_channel_state state, const char *context)
2490 struct ast_channel *tmp;
2491 char cid_num[256];
2492 char cid_name[256];
2494 if (me->owner) {
2495 ast_log(LOG_WARNING, "Called vpb_new on owned channel (%s) ?!\n", me->dev);
2496 return NULL;
2498 ast_verb(4, "%s: New call for context [%s]\n", me->dev, context);
2500 tmp = ast_channel_alloc(1, state, 0, 0, "", me->ext, me->context, 0, me->dev);
2501 if (tmp) {
2502 if (use_ast_ind == 1){
2503 tmp->tech = &vpb_tech_indicate;
2504 } else {
2505 tmp->tech = &vpb_tech;
2508 tmp->callgroup = me->callgroup;
2509 tmp->pickupgroup = me->pickupgroup;
2511 /* Linear is the preferred format. Although Voicetronix supports other formats
2512 * they are all converted to/from linear in the vpb code. Best for us to use
2513 * linear since we can then adjust volume in this modules.
2515 tmp->nativeformats = prefformat;
2516 tmp->rawreadformat = AST_FORMAT_SLINEAR;
2517 tmp->rawwriteformat = AST_FORMAT_SLINEAR;
2518 if (state == AST_STATE_RING) {
2519 tmp->rings = 1;
2520 cid_name[0] = '\0';
2521 cid_num[0] = '\0';
2522 ast_callerid_split(me->callerid, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
2523 ast_set_callerid(tmp, cid_num, cid_name, cid_num);
2525 tmp->tech_pvt = me;
2527 ast_copy_string(tmp->context, context, sizeof(tmp->context));
2528 if (!ast_strlen_zero(me->ext))
2529 ast_copy_string(tmp->exten, me->ext, sizeof(tmp->exten));
2530 else
2531 strcpy(tmp->exten, "s");
2532 if (!ast_strlen_zero(me->language))
2533 ast_string_field_set(tmp, language, me->language);
2535 me->owner = tmp;
2537 me->bridge = NULL;
2538 me->lastoutput = -1;
2539 me->lastinput = -1;
2540 me->last_ignore_dtmf = 1;
2541 me->readthread = 0;
2542 me->play_dtmf[0] = '\0';
2543 me->faxhandled = 0;
2545 me->lastgrunt = ast_tvnow(); /* Assume at least one grunt tone seen now. */
2546 me->lastplay = ast_tvnow(); /* Assume at least one grunt tone seen now. */
2548 if (state != AST_STATE_DOWN) {
2549 if ((me->mode != MODE_FXO) && (state != AST_STATE_UP)) {
2550 vpb_answer(tmp);
2552 if (ast_pbx_start(tmp)) {
2553 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2554 ast_hangup(tmp);
2557 } else {
2558 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2560 return tmp;
2563 static struct ast_channel *vpb_request(const char *type, int format, void *vdata, int *cause)
2565 int oldformat;
2566 struct vpb_pvt *p;
2567 struct ast_channel *tmp = NULL;
2568 char *sepstr, *data = (char *)vdata, *name;
2569 const char *s;
2570 int group = -1;
2572 oldformat = format;
2573 format &= prefformat;
2574 if (!format) {
2575 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", oldformat);
2576 return NULL;
2579 name = ast_strdup(S_OR(data, ""));
2581 sepstr = name;
2582 s = strsep(&sepstr, "/"); /* Handle / issues */
2583 if (!s)
2584 s = "";
2585 /* Check if we are looking for a group */
2586 if (toupper(name[0]) == 'G' || toupper(name[0]) == 'R') {
2587 group = atoi(name + 1);
2589 /* Search for an unowned channel */
2590 ast_mutex_lock(&iflock);
2591 for (p = iflist; p; p = p->next) {
2592 if (group == -1) {
2593 if (strncmp(s, p->dev + 4, sizeof p->dev) == 0) {
2594 if (!p->owner) {
2595 tmp = vpb_new(p, AST_STATE_DOWN, p->context);
2596 break;
2599 } else {
2600 if ((p->group == group) && (!p->owner)) {
2601 tmp = vpb_new(p, AST_STATE_DOWN, p->context);
2602 break;
2606 ast_mutex_unlock(&iflock);
2609 ast_verb(2, " %s requested, got: [%s]\n", name, tmp ? tmp->name : "None");
2611 ast_free(name);
2613 restart_monitor();
2614 return tmp;
2617 static float parse_gain_value(const char *gain_type, const char *value)
2619 float gain;
2621 /* try to scan number */
2622 if (sscanf(value, "%f", &gain) != 1) {
2623 ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n", value, gain_type, config);
2624 return DEFAULT_GAIN;
2628 /* percentage? */
2629 /*if (value[strlen(value) - 1] == '%') */
2630 /* return gain / (float)100; */
2632 return gain;
2636 static int unload_module(void)
2638 struct vpb_pvt *p;
2639 /* First, take us out of the channel loop */
2640 if (use_ast_ind == 1){
2641 ast_channel_unregister(&vpb_tech_indicate);
2642 } else {
2643 ast_channel_unregister(&vpb_tech);
2646 ast_mutex_lock(&iflock);
2647 /* Hangup all interfaces if they have an owner */
2648 for (p = iflist; p; p = p->next) {
2649 if (p->owner)
2650 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2652 iflist = NULL;
2653 ast_mutex_unlock(&iflock);
2655 ast_mutex_lock(&monlock);
2656 if (mthreadactive > -1) {
2657 pthread_cancel(monitor_thread);
2658 pthread_join(monitor_thread, NULL);
2660 mthreadactive = -2;
2661 ast_mutex_unlock(&monlock);
2663 ast_mutex_lock(&iflock);
2664 /* Destroy all the interfaces and free their memory */
2666 while (iflist) {
2667 p = iflist;
2668 ast_mutex_destroy(&p->lock);
2669 pthread_cancel(p->readthread);
2670 ast_mutex_destroy(&p->owner_lock);
2671 ast_mutex_destroy(&p->record_lock);
2672 ast_mutex_destroy(&p->play_lock);
2673 ast_mutex_destroy(&p->play_dtmf_lock);
2674 p->readthread = 0;
2676 vpb_close(p->handle);
2678 iflist = iflist->next;
2680 ast_free(p);
2682 iflist = NULL;
2683 ast_mutex_unlock(&iflock);
2685 if (bridges) {
2686 ast_mutex_lock(&bridge_lock);
2687 memset(bridges, 0, sizeof bridges);
2688 ast_mutex_unlock(&bridge_lock);
2689 ast_mutex_destroy(&bridge_lock);
2690 for (int i = 0; i < max_bridges; i++) {
2691 ast_mutex_destroy(&bridges[i].lock);
2692 ast_cond_destroy(&bridges[i].cond);
2694 ast_free(bridges);
2697 return 0;
2700 static enum ast_module_load_result load_module()
2702 struct ast_config *cfg;
2703 struct ast_variable *v;
2704 struct vpb_pvt *tmp;
2705 int board = 0, group = 0;
2706 ast_group_t callgroup = 0;
2707 ast_group_t pickupgroup = 0;
2708 int mode = MODE_IMMEDIATE;
2709 float txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN;
2710 float txswgain = 0, rxswgain = 0;
2711 int got_gain=0;
2712 int first_channel = 1;
2713 int echo_cancel = DEFAULT_ECHO_CANCEL;
2714 enum ast_module_load_result error = AST_MODULE_LOAD_SUCCESS; /* Error flag */
2715 int bal1 = -1; /* Special value - means do not set */
2716 int bal2 = -1;
2717 int bal3 = -1;
2718 char * callerid = NULL;
2720 int num_cards = 0;
2721 try {
2722 num_cards = vpb_get_num_cards();
2723 } catch (VpbException e) {
2724 ast_log(LOG_ERROR, "No Voicetronix cards detected\n");
2725 return AST_MODULE_LOAD_DECLINE;
2728 int ports_per_card[num_cards];
2729 for (int i = 0; i < num_cards; ++i)
2730 ports_per_card[i] = vpb_get_ports_per_card(i);
2732 cfg = ast_config_load(config);
2734 /* We *must* have a config file otherwise stop immediately */
2735 if (!cfg) {
2736 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
2737 return AST_MODULE_LOAD_DECLINE;
2740 ast_mutex_lock(&iflock);
2741 v = ast_variable_browse(cfg, "general");
2742 while (v){
2743 if (strcasecmp(v->name, "cards") == 0) {
2744 ast_log(LOG_NOTICE, "VPB Driver configured to use [%d] cards\n", atoi(v->value));
2745 } else if (strcasecmp(v->name, "indication") == 0) {
2746 use_ast_ind = 1;
2747 ast_log(LOG_NOTICE, "VPB driver using Asterisk Indication functions!\n");
2748 } else if (strcasecmp(v->name, "break-for-dtmf") == 0) {
2749 if (ast_true(v->value)) {
2750 break_for_dtmf = 1;
2751 } else {
2752 break_for_dtmf = 0;
2753 ast_log(LOG_NOTICE, "VPB driver not stopping for DTMF's in native bridge\n");
2755 } else if (strcasecmp(v->name, "ast-dtmf") == 0) {
2756 use_ast_dtmf = 1;
2757 ast_log(LOG_NOTICE, "VPB driver using Asterisk DTMF play functions!\n");
2758 } else if (strcasecmp(v->name, "ast-dtmf-det") == 0) {
2759 use_ast_dtmfdet = 1;
2760 ast_log(LOG_NOTICE, "VPB driver using Asterisk DTMF detection functions!\n");
2761 } else if (strcasecmp(v->name, "relaxdtmf") == 0) {
2762 relaxdtmf = 1;
2763 ast_log(LOG_NOTICE, "VPB driver using Relaxed DTMF with Asterisk DTMF detections functions!\n");
2764 } else if (strcasecmp(v->name, "timer_period_ring") == 0) {
2765 timer_period_ring = atoi(v->value);
2766 } else if (strcasecmp(v->name, "ecsuppthres") == 0) {
2767 ec_supp_threshold = (short)atoi(v->value);
2768 } else if (strcasecmp(v->name, "dtmfidd") == 0) {
2769 dtmf_idd = atoi(v->value);
2770 ast_log(LOG_NOTICE, "VPB Driver setting DTMF IDD to [%d]ms\n", dtmf_idd);
2772 v = v->next;
2775 v = ast_variable_browse(cfg, "interfaces");
2776 while (v) {
2777 /* Create the interface list */
2778 if (strcasecmp(v->name, "board") == 0) {
2779 board = atoi(v->value);
2780 } else if (strcasecmp(v->name, "group") == 0) {
2781 group = atoi(v->value);
2782 } else if (strcasecmp(v->name, "callgroup") == 0) {
2783 callgroup = ast_get_group(v->value);
2784 } else if (strcasecmp(v->name, "pickupgroup") == 0) {
2785 pickupgroup = ast_get_group(v->value);
2786 } else if (strcasecmp(v->name, "usepolaritycid") == 0) {
2787 UsePolarityCID = atoi(v->value);
2788 } else if (strcasecmp(v->name, "useloopdrop") == 0) {
2789 UseLoopDrop = atoi(v->value);
2790 } else if (strcasecmp(v->name, "usenativebridge") == 0) {
2791 UseNativeBridge = atoi(v->value);
2792 } else if (strcasecmp(v->name, "channel") == 0) {
2793 int channel = atoi(v->value);
2794 if (board >= num_cards || board < 0 || channel < 0 || channel >= ports_per_card[board]) {
2795 ast_log(LOG_ERROR, "Invalid board/channel (%d/%d) for channel '%s'\n", board, channel, v->value);
2796 error = AST_MODULE_LOAD_FAILURE;
2797 goto done;
2799 tmp = mkif(board, channel, mode, got_gain, txgain, rxgain, txswgain, rxswgain, bal1, bal2, bal3, callerid, echo_cancel,group,callgroup,pickupgroup);
2800 if (tmp) {
2801 if (first_channel) {
2802 mkbrd(tmp->vpb_model, echo_cancel);
2803 first_channel = 0;
2805 tmp->next = iflist;
2806 iflist = tmp;
2807 } else {
2808 ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
2809 error = AST_MODULE_LOAD_FAILURE;
2810 goto done;
2812 } else if (strcasecmp(v->name, "language") == 0) {
2813 ast_copy_string(language, v->value, sizeof(language));
2814 } else if (strcasecmp(v->name, "callerid") == 0) {
2815 callerid = ast_strdup(v->value);
2816 } else if (strcasecmp(v->name, "mode") == 0) {
2817 if (strncasecmp(v->value, "di", 2) == 0) {
2818 mode = MODE_DIALTONE;
2819 } else if (strncasecmp(v->value, "im", 2) == 0) {
2820 mode = MODE_IMMEDIATE;
2821 } else if (strncasecmp(v->value, "fx", 2) == 0) {
2822 mode = MODE_FXO;
2823 } else {
2824 ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
2826 } else if (!strcasecmp(v->name, "context")) {
2827 ast_copy_string(context, v->value, sizeof(context));
2828 } else if (!strcasecmp(v->name, "echocancel")) {
2829 if (!strcasecmp(v->value, "off")) {
2830 echo_cancel = 0;
2832 } else if (strcasecmp(v->name, "txgain") == 0) {
2833 txswgain = parse_gain_value(v->name, v->value);
2834 got_gain |= VPB_GOT_TXSWG;
2835 } else if (strcasecmp(v->name, "rxgain") == 0) {
2836 rxswgain = parse_gain_value(v->name, v->value);
2837 got_gain |= VPB_GOT_RXSWG;
2838 } else if (strcasecmp(v->name, "txhwgain") == 0) {
2839 txgain = parse_gain_value(v->name, v->value);
2840 got_gain |= VPB_GOT_TXHWG;
2841 } else if (strcasecmp(v->name, "rxhwgain") == 0) {
2842 rxgain = parse_gain_value(v->name, v->value);
2843 got_gain |= VPB_GOT_RXHWG;
2844 } else if (strcasecmp(v->name, "bal1") == 0) {
2845 bal1 = strtol(v->value, NULL, 16);
2846 if (bal1 < 0 || bal1 > 255) {
2847 ast_log(LOG_WARNING, "Bad bal1 value: %d\n", bal1);
2848 bal1 = -1;
2850 } else if (strcasecmp(v->name, "bal2") == 0) {
2851 bal2 = strtol(v->value, NULL, 16);
2852 if (bal2 < 0 || bal2 > 255) {
2853 ast_log(LOG_WARNING, "Bad bal2 value: %d\n", bal2);
2854 bal2 = -1;
2856 } else if (strcasecmp(v->name, "bal3") == 0) {
2857 bal3 = strtol(v->value, NULL, 16);
2858 if (bal3 < 0 || bal3 > 255) {
2859 ast_log(LOG_WARNING, "Bad bal3 value: %d\n", bal3);
2860 bal3 = -1;
2862 } else if (strcasecmp(v->name, "grunttimeout") == 0) {
2863 gruntdetect_timeout = 1000 * atoi(v->value);
2865 v = v->next;
2868 if (gruntdetect_timeout < 1000)
2869 gruntdetect_timeout = 1000;
2871 done: (void)0;
2872 ast_mutex_unlock(&iflock);
2874 ast_config_destroy(cfg);
2876 if (use_ast_ind == 1) {
2877 if (error == AST_MODULE_LOAD_SUCCESS && ast_channel_register(&vpb_tech_indicate) != 0) {
2878 ast_log(LOG_ERROR, "Unable to register channel class 'vpb'\n");
2879 error = AST_MODULE_LOAD_FAILURE;
2880 } else {
2881 ast_log(LOG_NOTICE, "VPB driver Registered (w/AstIndication)\n");
2883 } else {
2884 if (error == AST_MODULE_LOAD_SUCCESS && ast_channel_register(&vpb_tech) != 0) {
2885 ast_log(LOG_ERROR, "Unable to register channel class 'vpb'\n");
2886 error = AST_MODULE_LOAD_FAILURE;
2887 } else {
2888 ast_log(LOG_NOTICE, "VPB driver Registered )\n");
2893 if (error != AST_MODULE_LOAD_SUCCESS)
2894 unload_module();
2895 else
2896 restart_monitor(); /* And start the monitor for the first time */
2898 return error;
2901 /**/
2902 #if defined(__cplusplus) || defined(c_plusplus)
2904 #endif
2905 /**/
2907 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Voicetronix API driver");