2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, Digium, Inc.
5 * Copyright (C) 2007, Jim Dixon
7 * Jim Dixon, WB6NIL <jim@lambdatel.com>
8 * Steve Henke, W9SH <w9sh@arrl.net>
9 * Based upon work by Mark Spencer <markster@digium.com> and Luigi Rizzo
11 * See http://www.asterisk.org for more information about
12 * the Asterisk project. Please do not directly contact
13 * any of the maintainers of this project for assistance;
14 * the project provides a web site, mailing lists and IRC
15 * channels for your use.
17 * This program is free software, distributed under the terms of
18 * the GNU General Public License Version 2. See the LICENSE file
19 * at the top of the source tree.
24 * \brief Channel driver for CM108 USB Cards with Radio Interface
26 * \author Jim Dixon <jim@lambdatel.com>
27 * \author Steve Henke <w9sh@arrl.net>
30 * \arg \ref Config_usbradio
32 * \ingroup channel_drivers
36 <depend>asound</depend>
38 <defaultenabled>no</defaultenabled>
43 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
47 #include <sys/ioctl.h>
51 #include <alsa/asoundlib.h>
53 #define CHAN_USBRADIO 1
55 #define DEBUG_USBRADIO 0
56 #define DEBUG_CAPTURES 1
58 #define DEBUG_CAP_RX_OUT 0
59 #define DEBUG_CAP_TX_OUT 0
61 #define DEBUG_FILETEST 0
63 #define RX_CAP_RAW_FILE "/tmp/rx_cap_in.pcm"
64 #define RX_CAP_TRACE_FILE "/tmp/rx_trace.pcm"
65 #define RX_CAP_OUT_FILE "/tmp/rx_cap_out.pcm"
67 #define TX_CAP_RAW_FILE "/tmp/tx_cap_in.pcm"
68 #define TX_CAP_TRACE_FILE "/tmp/tx_trace.pcm"
69 #define TX_CAP_OUT_FILE "/tmp/tx_cap_out.pcm"
71 #define MIXER_PARAM_MIC_PLAYBACK_SW "Mic Playback Switch"
72 #define MIXER_PARAM_MIC_PLAYBACK_VOL "Mic Playback Volume"
73 #define MIXER_PARAM_MIC_CAPTURE_SW "Mic Capture Switch"
74 #define MIXER_PARAM_MIC_CAPTURE_VOL "Mic Capture Volume"
75 #define MIXER_PARAM_MIC_BOOST "Auto Gain Control"
76 #define MIXER_PARAM_SPKR_PLAYBACK_SW "Speaker Playback Switch"
77 #define MIXER_PARAM_SPKR_PLAYBACK_VOL "Speaker Playback Volume"
79 #include "./xpmr/xpmr.h"
82 #define traceusb1(a, ...) ast_debug(4, a __VA_ARGS__)
84 #define traceusb1(a, ...)
88 #define traceusb2(a, ...) ast_debug(4, a __VA_ARGS__)
90 #define traceusb2(a, ...)
94 #include <linux/soundcard.h>
95 #elif defined(__FreeBSD__)
96 #include <sys/soundcard.h>
98 #include <soundcard.h>
101 #include "asterisk/lock.h"
102 #include "asterisk/frame.h"
103 #include "asterisk/callerid.h"
104 #include "asterisk/channel.h"
105 #include "asterisk/module.h"
106 #include "asterisk/pbx.h"
107 #include "asterisk/config.h"
108 #include "asterisk/cli.h"
109 #include "asterisk/utils.h"
110 #include "asterisk/causes.h"
111 #include "asterisk/endian.h"
112 #include "asterisk/stringfields.h"
113 #include "asterisk/abstract_jb.h"
114 #include "asterisk/musiconhold.h"
115 #include "asterisk/dsp.h"
117 /* ringtones we use */
119 #include "ringtone.h"
123 #define C108_VENDOR_ID 0x0d8c
124 #define C108_PRODUCT_ID 0x000c
125 #define C108_HID_INTERFACE 3
127 #define HID_REPORT_GET 0x01
128 #define HID_REPORT_SET 0x09
130 #define HID_RT_INPUT 0x01
131 #define HID_RT_OUTPUT 0x02
133 /*! Global jitterbuffer configuration - by default, jb is disabled */
134 static struct ast_jb_conf default_jbconf =
138 .resync_threshold = -1,
141 static struct ast_jb_conf global_jbconf;
144 * usbradio.conf parameters are
148 ; General config options, with default values shown.
149 ; You should use one section per device, with [general] being used
153 ; debug = 0x0 ; misc debug flags, default is 0
155 ; Set the device to use for I/O
157 ; Set hardware type here
158 ; hdwtype=0 ; 0=limey, 1=sph
160 ; rxboostset=0 ; no rx gain boost
161 ; rxctcssrelax=1 ; reduce talkoff from radios w/o CTCSS Tx HPF
162 ; rxctcssfreq=100.0 ; rx ctcss freq in floating point. must be in table
163 ; txctcssfreq=100.0 ; tx ctcss freq, any frequency permitted
165 ; carrierfrom=dsp ;no,usb,usbinvert,dsp,vox
166 ; ctcssfrom=dsp ;no,usb,dsp
168 ; rxdemod=flat ; input type from radio: no,speaker,flat
169 ; txprelim=yes ; output is pre-emphasised and limited
170 ; txtoctype=no ; no,phase,notone
172 ; txmixa=composite ;no,voice,tone,composite,auxvoice
173 ; txmixb=no ;no,voice,tone,composite,auxvoice
177 ;------------------------------ JITTER BUFFER CONFIGURATION --------------------------
178 ; jbenable = yes ; Enables the use of a jitterbuffer on the receiving side of an
179 ; USBRADIO channel. Defaults to "no". An enabled jitterbuffer will
180 ; be used only if the sending side can create and the receiving
181 ; side can not accept jitter. The USBRADIO channel can't accept jitter,
182 ; thus an enabled jitterbuffer on the receive USBRADIO side will always
183 ; be used if the sending side can create jitter.
185 ; jbmaxsize = 200 ; Max length of the jitterbuffer in milliseconds.
187 ; jbresyncthreshold = 1000 ; Jump in the frame timestamps over which the jitterbuffer is
188 ; resynchronized. Useful to improve the quality of the voice, with
189 ; big jumps in/broken timestamps, usualy sent from exotic devices
190 ; and programs. Defaults to 1000.
192 ; jbimpl = fixed ; Jitterbuffer implementation, used on the receiving side of an USBRADIO
193 ; channel. Two implementations are currenlty available - "fixed"
194 ; (with size always equals to jbmax-size) and "adaptive" (with
195 ; variable size, actually the new jb of IAX2). Defaults to fixed.
197 ; jblog = no ; Enables jitterbuffer frame logging. Defaults to "no".
198 ;-----------------------------------------------------------------------------------
206 * Helper macros to parse config arguments. They will go in a common
207 * header file if their usage is globally accepted. In the meantime,
208 * we define them here. Typical usage is as below.
209 * Remember to open a block right before M_START (as it declares
210 * some variables) and use the M_* macros WITHOUT A SEMICOLON:
213 * M_START(v->name, v->value)
215 * M_BOOL("dothis", x->flag1)
216 * M_STR("name", x->somestring)
217 * M_F("bar", some_c_code)
218 * M_END(some_final_statement)
219 * ... other code in the block
222 * XXX NOTE these macros should NOT be replicated in other parts of asterisk.
223 * Likely we will come up with a better way of doing config file parsing.
225 #define M_START(var, val) \
226 const char *__s = var; const char *__val = val;
228 #define M_F(tag, f) if (!strcasecmp((__s), tag)) { f; } else
229 #define M_BOOL(tag, dst) M_F(tag, (dst) = ast_true(__val) )
230 #define M_UINT(tag, dst) M_F(tag, (dst) = strtoul(__val, NULL, 0) )
231 #define M_STR(tag, dst) M_F(tag, ast_copy_string(dst, __val, sizeof(dst)))
234 * The following parameters are used in the driver:
236 * FRAME_SIZE the size of an audio frame, in samples.
237 * 160 is used almost universally, so you should not change it.
239 * FRAGS the argument for the SETFRAGMENT ioctl.
240 * Overridden by the 'frags' parameter in usbradio.conf
242 * Bits 0-7 are the base-2 log of the device's block size,
243 * bits 16-31 are the number of blocks in the driver's queue.
244 * There are a lot of differences in the way this parameter
245 * is supported by different drivers, so you may need to
246 * experiment a bit with the value.
247 * A good default for linux is 30 blocks of 64 bytes, which
248 * results in 6 frames of 320 bytes (160 samples).
249 * FreeBSD works decently with blocks of 256 or 512 bytes,
250 * leaving the number unspecified.
251 * Note that this only refers to the device buffer size,
252 * this module will then try to keep the lenght of audio
253 * buffered within small constraints.
255 * QUEUE_SIZE The max number of blocks actually allowed in the device
256 * driver's buffer, irrespective of the available number.
257 * Overridden by the 'queuesize' parameter in usbradio.conf
259 * Should be >=2, and at most as large as the hw queue above
260 * (otherwise it will never be full).
263 #define FRAME_SIZE 160
264 #define QUEUE_SIZE 20
266 #if defined(__FreeBSD__)
269 #define FRAGS ( ( (6 * 5) << 16 ) | 0xc )
273 * XXX text message sizes are probably 256 chars, but i am
274 * not sure if there is a suitable definition anywhere.
276 #define TEXT_SIZE 256
279 #define TRYOPEN 1 /* try to open on startup */
281 #define O_CLOSE 0x444 /* special 'close' mode for device */
282 /* Which device to use */
283 #if defined( __OpenBSD__ ) || defined( __NetBSD__ )
284 #define DEV_DSP "/dev/audio"
286 #define DEV_DSP "/dev/dsp"
290 #define MIN(a,b) ((a) < (b) ? (a) : (b))
293 #define MAX(a,b) ((a) > (b) ? (a) : (b))
296 static char *config = "usbradio.conf"; /* default config file */
297 static char *config1 = "usbradio_tune.conf"; /* tune config file */
299 static FILE *frxcapraw = NULL, *frxcaptrace = NULL, *frxoutraw = NULL;
300 static FILE *ftxcapraw = NULL, *ftxcaptrace = NULL, *ftxoutraw = NULL;
302 static int usbradio_debug;
303 #if 0 /* maw asdf sph */
304 static int usbradio_debug_level = 0;
307 enum {RX_AUDIO_NONE,RX_AUDIO_SPEAKER,RX_AUDIO_FLAT};
308 enum {CD_IGNORE,CD_XPMR_NOISE,CD_XPMR_VOX,CD_HID,CD_HID_INVERT};
309 enum {SD_IGNORE,SD_HID,SD_HID_INVERT,SD_XPMR}; /* no,external,externalinvert,software */
310 enum {RX_KEY_CARRIER,RX_KEY_CARRIER_CODE};
311 enum {TX_OUT_OFF,TX_OUT_VOICE,TX_OUT_LSD,TX_OUT_COMPOSITE,TX_OUT_AUX};
312 enum {TOC_NONE,TOC_PHASE,TOC_NOTONE};
314 /* DECLARE STRUCTURES */
317 * Each sound is made of 'datalen' samples of sound, repeated as needed to
318 * generate 'samplen' samples of data, then followed by 'silencelen' samples
319 * of silence. The loop is repeated if 'repeat' is set.
331 static struct sound sounds[] = {
332 { AST_CONTROL_RINGING, "RINGING", ringtone, sizeof(ringtone)/2, 16000, 32000, 1 },
333 { AST_CONTROL_BUSY, "BUSY", busy, sizeof(busy)/2, 4000, 4000, 1 },
334 { AST_CONTROL_CONGESTION, "CONGESTION", busy, sizeof(busy)/2, 2000, 2000, 1 },
335 { AST_CONTROL_RING, "RING10", ring10, sizeof(ring10)/2, 16000, 32000, 1 },
336 { AST_CONTROL_ANSWER, "ANSWER", answer, sizeof(answer)/2, 2200, 0, 0 },
337 { -1, NULL, 0, 0, 0, 0 }, /* end marker */
342 * descriptor for one of our channels.
343 * There is one used for 'default' values (from the [general] entry in
344 * the configuration file), and then one instance for each device
345 * (the default is cloned from [general], others are only created
346 * if the relevant section exists).
348 struct chan_usbradio_pvt {
349 struct chan_usbradio_pvt *next;
353 * cursound indicates which in struct sound we play. -1 means nothing,
354 * any other value is a valid sound, in which case sampsent indicates
355 * the next sample to send in [0..samplen + silencelen]
356 * nosound is set to disable the audio data from the channel
357 * (so we can play the tones etc.).
359 int sndcmd[2]; /* Sound command pipe */
360 int cursound; /* index of sound to send */
361 int sampsent; /* # of sound samples sent */
362 int nosound; /* set to block audio from the PBX */
364 int total_blocks; /* total blocks in the output device */
366 enum { M_UNSET, M_FULL, M_READ, M_WRITE } duplex;
371 unsigned int queuesize; /* max fragments in queue */
372 unsigned int frags; /* parameter for SETFRAGMENT */
374 int warned; /* various flags used for warnings */
375 #define WARN_used_blocks 1
378 int w_errors; /* overfull in the write path */
379 struct timeval lastopen;
384 /* boost support. BOOST_SCALE * 10 ^(BOOST_MAX/20) must
385 * be representable in 16 bits to avoid overflows.
387 #define BOOST_SCALE (1<<9)
388 #define BOOST_MAX 40 /* slightly less than 7 bits */
389 int boost; /* input boost, scaled by BOOST_SCALE */
398 struct ast_channel *owner;
399 char ext[AST_MAX_EXTENSION];
400 char ctx[AST_MAX_CONTEXT];
401 char language[MAX_LANGUAGE];
402 char cid_name[256]; /* XXX */
403 char cid_num[256]; /* XXX */
404 char mohinterpret[MAX_MUSICCLASS];
406 /* buffers used in usbradio_write, 2 per int by 2 channels by 6 times oversampling (48KS/s) */
407 char usbradio_write_buf[FRAME_SIZE * 2 * 2 * 6];
408 char usbradio_write_buf_1[FRAME_SIZE * 2 * 2 * 6];
410 int usbradio_write_dst;
411 /* buffers used in usbradio_read - AST_FRIENDLY_OFFSET space for headers
412 * plus enough room for a full frame
414 char usbradio_read_buf[FRAME_SIZE * (2 * 12) + AST_FRIENDLY_OFFSET];
415 char usbradio_read_buf_8k[FRAME_SIZE * 2 + AST_FRIENDLY_OFFSET];
416 int readpos; /* read position above */
417 struct ast_frame read_f; /* returned by usbradio_read */
425 char rxcarrierdetect; /*!< status from pmr channel */
426 char rxctcssdecode; /*!< status from pmr channel */
429 char rxkeyed; /*!< indicates rx signal present */
432 char txkeyed; /*! tx key request from upper layers */
448 int rxsquelchadj; /*!< this copy needs to be here for initialization */
473 int hid_gpio_ctl_loc;
477 int hid_io_ctcss_loc;
489 /* maw add additional defaults !!! */
490 static struct chan_usbradio_pvt usbradio_default = {
493 .duplex = M_UNSET, /* XXX check this */
496 .queuesize = QUEUE_SIZE,
500 .readpos = AST_FRIENDLY_OFFSET, /* start here on reads */
501 .lastopen = { 0, 0 },
502 .boost = BOOST_SCALE,
505 /* DECLARE FUNCTION PROTOTYPES */
507 static void store_txtoctype(struct chan_usbradio_pvt *o, const char *s);
508 static int hidhdwconfig(struct chan_usbradio_pvt *o);
509 static int set_txctcss_level(struct chan_usbradio_pvt *o);
510 static void pmrdump(struct chan_usbradio_pvt *o);
511 static void mult_set(struct chan_usbradio_pvt *o);
512 static int mult_calc(int value);
513 static void mixer_write(struct chan_usbradio_pvt *o);
514 static void tune_rxinput(struct chan_usbradio_pvt *o);
515 static void tune_rxvoice(struct chan_usbradio_pvt *o);
516 static void tune_rxctcss(struct chan_usbradio_pvt *o);
517 static void tune_txoutput(struct chan_usbradio_pvt *o, int value);
518 static void tune_write(struct chan_usbradio_pvt *o);
520 static char *usbradio_active; /* the active device */
522 static int setformat(struct chan_usbradio_pvt *o, int mode);
524 static struct ast_channel *usbradio_request(const char *type, int format, void *data
526 static int usbradio_digit_begin(struct ast_channel *c, char digit);
527 static int usbradio_digit_end(struct ast_channel *c, char digit, unsigned int duration);
528 static int usbradio_text(struct ast_channel *c, const char *text);
529 static int usbradio_hangup(struct ast_channel *c);
530 static int usbradio_answer(struct ast_channel *c);
531 static struct ast_frame *usbradio_read(struct ast_channel *chan);
532 static int usbradio_call(struct ast_channel *c, char *dest, int timeout);
533 static int usbradio_write(struct ast_channel *chan, struct ast_frame *f);
534 static int usbradio_indicate(struct ast_channel *chan, int cond, const void *data, size_t datalen);
535 static int usbradio_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
537 #if DEBUG_FILETEST == 1
538 static int RxTestIt(struct chan_usbradio_pvt *o);
541 static char tdesc[] = "USB (CM108) Radio Channel Driver";
543 static const struct ast_channel_tech usbradio_tech = {
545 .description = tdesc,
546 .capabilities = AST_FORMAT_SLINEAR,
547 .requester = usbradio_request,
548 .send_digit_begin = usbradio_digit_begin,
549 .send_digit_end = usbradio_digit_end,
550 .send_text = usbradio_text,
551 .hangup = usbradio_hangup,
552 .answer = usbradio_answer,
553 .read = usbradio_read,
554 .call = usbradio_call,
555 .write = usbradio_write,
556 .indicate = usbradio_indicate,
557 .fixup = usbradio_fixup,
560 /* Call with: devnum: alsa major device number, param: ascii Formal
561 Parameter Name, val1, first or only value, val2 second value, or 0
562 if only 1 value. Values: 0-99 (percent) or 0-1 for baboon.
564 Note: must add -lasound to end of linkage */
566 static int amixer_max(int devnum,char *param)
571 snd_ctl_elem_id_t *id;
572 snd_hctl_elem_t *elem;
573 snd_ctl_elem_info_t *info;
575 snprintf(str, sizeof(str), "hw:%d", devnum);
576 if (snd_hctl_open(&hctl, str, 0))
579 id = alloca(snd_ctl_elem_id_sizeof());
580 memset(id, 0, snd_ctl_elem_id_sizeof());
581 snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER);
582 snd_ctl_elem_id_set_name(id, param);
583 elem = snd_hctl_find_elem(hctl, id);
585 snd_hctl_close(hctl);
588 info = alloca(snd_ctl_elem_info_sizeof());
589 memset(info, 0, snd_ctl_elem_info_sizeof());
590 snd_hctl_elem_info(elem,info);
591 type = snd_ctl_elem_info_get_type(info);
594 case SND_CTL_ELEM_TYPE_INTEGER:
595 rv = snd_ctl_elem_info_get_max(info);
597 case SND_CTL_ELEM_TYPE_BOOLEAN:
601 snd_hctl_close(hctl);
605 /*! \brief Call with: devnum: alsa major device number, param: ascii Formal
606 Parameter Name, val1, first or only value, val2 second value, or 0
607 if only 1 value. Values: 0-99 (percent) or 0-1 for baboon.
609 Note: must add -lasound to end of linkage */
611 static int setamixer(int devnum, char *param, int v1, int v2)
616 snd_ctl_elem_id_t *id;
617 snd_ctl_elem_value_t *control;
618 snd_hctl_elem_t *elem;
619 snd_ctl_elem_info_t *info;
621 snprintf(str, sizeof(str), "hw:%d", devnum);
622 if (snd_hctl_open(&hctl, str, 0))
625 id = alloca(snd_ctl_elem_id_sizeof());
626 memset(id, 0, snd_ctl_elem_id_sizeof());
627 snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER);
628 snd_ctl_elem_id_set_name(id, param);
629 elem = snd_hctl_find_elem(hctl, id);
631 snd_hctl_close(hctl);
634 info = alloca(snd_ctl_elem_info_sizeof());
635 memset(info, 0, snd_ctl_elem_info_sizeof());
636 snd_hctl_elem_info(elem,info);
637 type = snd_ctl_elem_info_get_type(info);
638 control = alloca(snd_ctl_elem_value_sizeof());
639 memset(control, 0, snd_ctl_elem_value_sizeof());
640 snd_ctl_elem_value_set_id(control, id);
642 case SND_CTL_ELEM_TYPE_INTEGER:
643 snd_ctl_elem_value_set_integer(control, 0, v1);
644 if (v2 > 0) snd_ctl_elem_value_set_integer(control, 1, v2);
646 case SND_CTL_ELEM_TYPE_BOOLEAN:
647 snd_ctl_elem_value_set_integer(control, 0, (v1 != 0));
650 if (snd_hctl_elem_write(elem, control)) {
651 snd_hctl_close(hctl);
654 snd_hctl_close(hctl);
658 static void hid_set_outputs(struct usb_dev_handle *handle,
659 unsigned char *outputs)
661 usb_control_msg(handle,
662 USB_ENDPOINT_OUT + USB_TYPE_CLASS + USB_RECIP_INTERFACE,
664 0 + (HID_RT_OUTPUT << 8),
666 (char *)outputs, 4, 5000);
669 static void hid_get_inputs(struct usb_dev_handle *handle,
670 unsigned char *inputs)
672 usb_control_msg(handle,
673 USB_ENDPOINT_IN + USB_TYPE_CLASS + USB_RECIP_INTERFACE,
675 0 + (HID_RT_INPUT << 8),
677 (char *)inputs, 4, 5000);
680 static struct usb_device *hid_device_init(void)
682 struct usb_bus *usb_bus;
683 struct usb_device *dev;
688 for (usb_bus = usb_busses; usb_bus; usb_bus = usb_bus->next) {
689 for (dev = usb_bus->devices; dev; dev = dev->next) {
690 if ((dev->descriptor.idVendor == C108_VENDOR_ID) && (dev->descriptor.idProduct == C108_PRODUCT_ID))
697 static int hidhdwconfig(struct chan_usbradio_pvt *o)
699 if (o->hdwtype == 1) { /*sphusb */
700 o->hid_gpio_ctl = 0x08; /* set GPIO4 to output mode */
701 o->hid_gpio_ctl_loc = 2; /* For CTL of GPIO */
702 o->hid_io_cor = 4; /* GPIO3 is COR */
703 o->hid_io_cor_loc = 1; /* GPIO3 is COR */
704 o->hid_io_ctcss = 2; /* GPIO 2 is External CTCSS */
705 o->hid_io_ctcss_loc = 1; /* is GPIO 2 */
706 o->hid_io_ptt = 8; /* GPIO 4 is PTT */
707 o->hid_gpio_loc = 1; /* For ALL GPIO */
708 } else if (o->hdwtype == 0) { /* dudeusb */
709 o->hid_gpio_ctl = 0x0c;/* set GPIO 3 & 4 to output mode */
710 o->hid_gpio_ctl_loc = 2; /* For CTL of GPIO */
711 o->hid_io_cor = 2; /* VOLD DN is COR */
712 o->hid_io_cor_loc = 0; /* VOL DN COR */
713 o->hid_io_ctcss = 2; /* GPIO 2 is External CTCSS */
714 o->hid_io_ctcss_loc = 1; /* is GPIO 2 */
715 o->hid_io_ptt = 4; /* GPIO 3 is PTT */
716 o->hid_gpio_loc = 1; /* For ALL GPIO */
717 } else if (o->hdwtype == 3) { /* custom version */
718 o->hid_gpio_ctl = 0x0c; /* set GPIO 3 & 4 to output mode */
719 o->hid_gpio_ctl_loc = 2; /* For CTL of GPIO */
720 o->hid_io_cor = 2; /* VOLD DN is COR */
721 o->hid_io_cor_loc = 0; /* VOL DN COR */
722 o->hid_io_ctcss = 2; /* GPIO 2 is External CTCSS */
723 o->hid_io_ctcss_loc = 1; /* is GPIO 2 */
724 o->hid_io_ptt = 4; /* GPIO 3 is PTT */
725 o->hid_gpio_loc = 1; /* For ALL GPIO */
732 static void *hidthread(void *arg)
734 unsigned char buf[4], keyed;
736 struct usb_device *usb_dev;
737 struct usb_dev_handle *usb_handle;
738 struct chan_usbradio_pvt *o = arg;
740 usb_dev = hid_device_init();
741 if (usb_dev == NULL) {
742 ast_log(LOG_ERROR, "USB HID device not found\n");
745 usb_handle = usb_open(usb_dev);
746 if (usb_handle == NULL) {
747 ast_log(LOG_ERROR, "Not able to open USB device\n");
750 if (usb_claim_interface(usb_handle, C108_HID_INTERFACE) < 0) {
751 if (usb_detach_kernel_driver_np(usb_handle, C108_HID_INTERFACE) < 0) {
752 ast_log(LOG_ERROR, "Not able to detach the USB device\n");
755 if (usb_claim_interface(usb_handle, C108_HID_INTERFACE) < 0) {
756 ast_log(LOG_ERROR, "Not able to claim the USB device\n");
760 memset(buf, 0, sizeof(buf));
761 buf[2] = o->hid_gpio_ctl;
763 hid_set_outputs(usb_handle, buf);
764 traceusb1("hidthread: Starting normally!!\n");
766 while (!o->stophid) {
767 buf[o->hid_gpio_ctl_loc] = o->hid_gpio_ctl;
768 hid_get_inputs(usb_handle, buf);
769 keyed = !(buf[o->hid_io_cor_loc] & o->hid_io_cor);
770 if (keyed != o->rxhidsq) {
772 ast_log(LOG_NOTICE, "chan_usbradio() hidthread: update rxhidsq = %d\n", keyed);
776 /* if change in tx stuff */
778 if (o->txkeyed || o->txchankey || o->txtestkey || o->pmrChan->txPttOut)
781 if (o->lasttx != txtmp) {
784 ast_log(LOG_NOTICE, "hidthread: tx set to %d\n", txtmp);
785 buf[o->hid_gpio_loc] = 0;
787 buf[o->hid_gpio_loc] = o->hid_io_ptt;
788 buf[o->hid_gpio_ctl_loc] = o->hid_gpio_ctl;
789 hid_set_outputs(usb_handle, buf);
792 time(&o->lasthidtime);
795 buf[o->hid_gpio_loc] = 0;
797 buf[o->hid_gpio_loc] = o->hid_io_ptt;
798 buf[o->hid_gpio_ctl_loc] = o->hid_gpio_ctl;
799 hid_set_outputs(usb_handle, buf);
804 * returns a pointer to the descriptor with the given name
806 static struct chan_usbradio_pvt *find_desc(char *dev)
808 struct chan_usbradio_pvt *o = NULL;
811 ast_log(LOG_WARNING, "null dev\n");
813 for (o = usbradio_default.next; o && o->name && dev && strcmp(o->name, dev) != 0; o = o->next);
816 ast_log(LOG_WARNING, "could not find <%s>\n", dev ? dev : "--no-device--");
822 * split a string in extension-context, returns pointers to malloc'ed
824 * If we do not have 'overridecontext' then the last @ is considered as
825 * a context separator, and the context is overridden.
826 * This is usually not very necessary as you can play with the dialplan,
827 * and it is nice not to need it because you have '@' in SIP addresses.
828 * Return value is the buffer address.
831 static char *ast_ext_ctx(const char *src, char **ext, char **ctx)
833 struct chan_usbradio_pvt *o = find_desc(usbradio_active);
835 if (ext == NULL || ctx == NULL)
836 return NULL; /* error */
840 if (src && *src != '\0')
841 *ext = ast_strdup(src);
846 if (!o->overridecontext) {
847 /* parse from the right */
848 *ctx = strrchr(*ext, '@');
858 * Returns the number of blocks used in the audio output channel
860 static int used_blocks(struct chan_usbradio_pvt *o)
862 struct audio_buf_info info;
864 if (ioctl(o->sounddev, SNDCTL_DSP_GETOSPACE, &info)) {
865 if (!(o->warned & WARN_used_blocks)) {
866 ast_log(LOG_WARNING, "Error reading output space\n");
867 o->warned |= WARN_used_blocks;
872 if (o->total_blocks == 0) {
873 ast_debug(4, "fragtotal %d size %d avail %d\n", info.fragstotal, info.fragsize, info.fragments);
874 o->total_blocks = info.fragments;
877 return o->total_blocks - info.fragments;
880 /*! \brief Write an exactly FRAME_SIZE sized frame */
881 static int soundcard_writeframe(struct chan_usbradio_pvt *o, short *data)
886 setformat(o, O_RDWR);
888 return 0; /* not fatal */
890 * Nothing complex to manage the audio device queue.
891 * If the buffer is full just drop the extra, otherwise write.
892 * XXX in some cases it might be useful to write anyways after
893 * a number of failures, to restart the output chain.
895 res = used_blocks(o);
896 if (res > o->queuesize) { /* no room to write a block */
897 if (o->w_errors++ == 0 && (usbradio_debug & 0x4))
898 ast_log(LOG_WARNING, "write: used %d blocks (%d)\n", res, o->w_errors);
903 return write(o->sounddev, ((void *) data), FRAME_SIZE * 2 * 12);
907 * Handler for 'sound writable' events from the sound thread.
908 * Builds a frame from the high level description of the sounds,
909 * and passes it to the audio device.
910 * The actual sound is made of 1 or more sequences of sound samples
911 * (s->datalen, repeated to make s->samplen samples) followed by
912 * s->silencelen samples of silence. The position in the sequence is stored
913 * in o->sampsent, which goes between 0 .. s->samplen+s->silencelen.
914 * In case we fail to write a frame, don't update o->sampsent.
916 static void send_sound(struct chan_usbradio_pvt *o)
918 short myframe[FRAME_SIZE];
920 int l_sampsent = o->sampsent;
923 if (o->cursound < 0) /* no sound to send */
926 s = &sounds[o->cursound];
928 for (ofs = 0; ofs < FRAME_SIZE; ofs += l) {
929 l = s->samplen - l_sampsent; /* # of available samples */
931 start = l_sampsent % s->datalen; /* source offset */
932 if (l > FRAME_SIZE - ofs) /* don't overflow the frame */
933 l = FRAME_SIZE - ofs;
934 if (l > s->datalen - start) /* don't overflow the source */
935 l = s->datalen - start;
936 memcpy(myframe + ofs, s->data + start, l * 2);
937 ast_debug(4, "send_sound sound %d/%d of %d into %d\n", l_sampsent, l, s->samplen, ofs);
939 } else { /* end of samples, maybe some silence */
940 static const short silence[FRAME_SIZE] = { 0, };
944 if (l > FRAME_SIZE - ofs)
945 l = FRAME_SIZE - ofs;
946 memcpy(myframe + ofs, silence, l * 2);
948 } else { /* silence is over, restart sound if loop */
949 if (s->repeat == 0) { /* last block */
951 o->nosound = 0; /* allow audio data */
952 if (ofs < FRAME_SIZE) /* pad with silence */
953 memcpy(myframe + ofs, silence, (FRAME_SIZE - ofs) * 2);
959 l = soundcard_writeframe(o, myframe);
961 o->sampsent = l_sampsent; /* update status */
964 static void *sound_thread(void *arg)
967 struct chan_usbradio_pvt *o = arg;
970 * Just in case, kick the driver by trying to read from it.
971 * Ignore errors - this read is almost guaranteed to fail.
973 read(o->sounddev, ign, sizeof(ign));
980 FD_SET(o->sndcmd[0], &rfds);
981 maxfd = o->sndcmd[0]; /* pipe from the main process */
982 if (o->cursound > -1 && o->sounddev < 0)
983 setformat(o, O_RDWR); /* need the channel, try to reopen */
984 else if (o->cursound == -1 && o->owner == NULL)
985 setformat(o, O_CLOSE); /* can close */
986 if (o->sounddev > -1) {
987 if (!o->owner) { /* no one owns the audio, so we must drain it */
988 FD_SET(o->sounddev, &rfds);
989 maxfd = MAX(o->sounddev, maxfd);
991 if (o->cursound > -1) {
992 FD_SET(o->sounddev, &wfds);
993 maxfd = MAX(o->sounddev, maxfd);
996 /* ast_select emulates linux behaviour in terms of timeout handling */
997 res = ast_select(maxfd + 1, &rfds, &wfds, NULL, NULL);
999 ast_log(LOG_WARNING, "select failed: %s\n", strerror(errno));
1003 if (FD_ISSET(o->sndcmd[0], &rfds)) {
1004 /* read which sound to play from the pipe */
1007 read(o->sndcmd[0], &what, sizeof(what));
1008 for (i = 0; sounds[i].ind != -1; i++) {
1009 if (sounds[i].ind == what) {
1012 o->nosound = 1; /* block audio from pbx */
1016 if (sounds[i].ind == -1)
1017 ast_log(LOG_WARNING, "invalid sound index: %d\n", what);
1019 if (o->sounddev > -1) {
1020 if (FD_ISSET(o->sounddev, &rfds)) /* read and ignore errors */
1021 read(o->sounddev, ign, sizeof(ign));
1022 if (FD_ISSET(o->sounddev, &wfds))
1026 return NULL; /* Never reached */
1030 * reset and close the device if opened,
1031 * then open and initialize it in the desired mode,
1032 * trigger reads and writes so we can start using it.
1034 static int setformat(struct chan_usbradio_pvt *o, int mode)
1036 int fmt, desired, res, fd;
1039 if (o->sounddev >= 0) {
1040 ioctl(o->sounddev, SNDCTL_DSP_RESET, 0);
1042 o->duplex = M_UNSET;
1045 if (mode == O_CLOSE) /* we are done */
1047 if (ast_tvdiff_ms(ast_tvnow(), o->lastopen) < 1000)
1048 return -1; /* don't open too often */
1049 o->lastopen = ast_tvnow();
1050 strcpy(device, "/dev/dsp");
1052 snprintf(device + strlen("/dev/dsp"), sizeof(device) - strlen("/dev/dsp"), "%d", o->devicenum);
1053 fd = o->sounddev = open(device, mode | O_NONBLOCK);
1055 ast_log(LOG_WARNING, "Unable to re-open DSP device %d: %s\n", o->devicenum, strerror(errno));
1059 o->owner->fds[0] = fd;
1061 #if __BYTE_ORDER == __LITTLE_ENDIAN
1066 res = ioctl(fd, SNDCTL_DSP_SETFMT, &fmt);
1068 ast_log(LOG_WARNING, "Unable to set format to 16-bit signed\n");
1073 res = ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
1074 /* Check to see if duplex set (FreeBSD Bug) */
1075 res = ioctl(fd, SNDCTL_DSP_GETCAPS, &fmt);
1076 if (res == 0 && (fmt & DSP_CAP_DUPLEX)) {
1077 if (option_verbose > 1)
1078 ast_verbose(VERBOSE_PREFIX_2 "Console is full duplex\n");
1083 o->duplex = M_WRITE;
1091 res = ioctl(fd, SNDCTL_DSP_STEREO, &fmt);
1093 ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
1096 fmt = desired = 48000; /* 8000 Hz desired */
1097 res = ioctl(fd, SNDCTL_DSP_SPEED, &fmt);
1100 ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
1103 if (fmt != desired) {
1104 if (!(o->warned & WARN_speed)) {
1105 ast_log(LOG_WARNING,
1106 "Requested %d Hz, got %d Hz -- sound may be choppy\n",
1108 o->warned |= WARN_speed;
1112 * on Freebsd, SETFRAGMENT does not work very well on some cards.
1113 * Default to use 256 bytes, let the user override
1117 res = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &fmt);
1119 if (!(o->warned & WARN_frag)) {
1120 ast_log(LOG_WARNING,
1121 "Unable to set fragment size -- sound may be choppy\n");
1122 o->warned |= WARN_frag;
1126 /* on some cards, we need SNDCTL_DSP_SETTRIGGER to start outputting */
1127 res = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;
1128 res = ioctl(fd, SNDCTL_DSP_SETTRIGGER, &res);
1129 /* it may fail if we are in half duplex, never mind */
1134 * some of the standard methods supported by channels.
1136 static int usbradio_digit_begin(struct ast_channel *c, char digit)
1141 static int usbradio_digit_end(struct ast_channel *c, char digit, unsigned int duration)
1143 /* no better use for received digits than print them */
1144 ast_verbose(" << Console Received digit %c of duration %u ms >> \n",
1149 static int usbradio_text(struct ast_channel *c, const char *text)
1151 /* print received messages */
1152 ast_verbose(" << Console Received text %s >> \n", text);
1156 /* Play ringtone 'x' on device 'o' */
1157 static void ring(struct chan_usbradio_pvt *o, int x)
1159 write(o->sndcmd[1], &x, sizeof(x));
1163 * handler for incoming calls. Either autoanswer, or start ringing
1165 static int usbradio_call(struct ast_channel *c, char *dest, int timeout)
1167 struct chan_usbradio_pvt *o = c->tech_pvt;
1169 time(&o->lasthidtime);
1170 ast_pthread_create_background(&o->hidthread, NULL, hidthread, o);
1171 ast_setstate(c, AST_STATE_UP);
1176 * remote side answered the phone
1178 static int usbradio_answer(struct ast_channel *c)
1180 struct chan_usbradio_pvt *o = c->tech_pvt;
1182 ast_setstate(c, AST_STATE_UP);
1188 static int usbradio_hangup(struct ast_channel *c)
1190 struct chan_usbradio_pvt *o = c->tech_pvt;
1196 ast_module_unref(ast_module_info->self);
1198 if (o->autoanswer || o->autohangup) {
1199 /* Assume auto-hangup too */
1201 setformat(o, O_CLOSE);
1203 /* Make congestion noise */
1204 ring(o, AST_CONTROL_CONGESTION);
1208 pthread_join(o->hidthread, NULL);
1213 /* used for data coming from the network */
1214 static int usbradio_write(struct ast_channel *c, struct ast_frame *f)
1217 struct chan_usbradio_pvt *o = c->tech_pvt;
1219 traceusb2("usbradio_write() o->nosound=%d\n", o->nosound); /*sph maw asdf */
1221 /* Immediately return if no sound is enabled */
1224 /* Stop any currently playing sound */
1227 * we could receive a block which is not a multiple of our
1228 * FRAME_SIZE, so buffer it locally and write to the device
1229 * in FRAME_SIZE chunks.
1230 * Keep the residue stored for future use.
1233 if (o->txkeyed || o->txtestkey)
1234 o->pmrChan->txPttIn = 1;
1236 o->pmrChan->txPttIn = 0;
1238 #if DEBUG_CAPTURES == 1 /* to write input data to a file datalen=320 */
1239 if (ftxcapraw && o->b.txcapraw) {
1240 i16 i, tbuff[f->datalen];
1241 for (i = 0; i < f->datalen; i += 2) {
1242 tbuff[i] = ((i16 *)(f->data))[i / 2];
1243 tbuff[i + 1] = o->txkeyed * M_Q13;
1245 fwrite(tbuff, 2, f->datalen, ftxcapraw);
1246 /*fwrite(f->data,1,f->datalen,ftxcapraw); */
1250 PmrTx(o->pmrChan,(i16*)f->data,(i16*)o->usbradio_write_buf_1);
1252 #if 0 /* to write 48KS/s stereo data to a file */
1253 if (!ftxoutraw) ftxoutraw = fopen(TX_CAP_OUT_FILE,"w");
1254 if (ftxoutraw) fwrite(o->usbradio_write_buf_1,1,f->datalen * 2 * 6,ftxoutraw);
1257 #if DEBUG_CAPTURES == 1
1258 if (o->b.txcap2 && ftxcaptrace)
1259 fwrite((o->pmrChan->ptxDebug), 1, FRAME_SIZE * 2 * 16, ftxcaptrace);
1262 src = 0; /* read position into f->data */
1263 datalen = f->datalen * 12;
1264 while (src < datalen) {
1265 /* Compute spare room in the buffer */
1266 int l = sizeof(o->usbradio_write_buf) - o->usbradio_write_dst;
1268 if (datalen - src >= l) { /* enough to fill a frame */
1269 memcpy(o->usbradio_write_buf + o->usbradio_write_dst, o->usbradio_write_buf_1 + src, l);
1270 soundcard_writeframe(o, (short *) o->usbradio_write_buf);
1272 o->usbradio_write_dst = 0;
1273 } else { /* copy residue */
1275 memcpy(o->usbradio_write_buf + o->usbradio_write_dst, o->usbradio_write_buf_1 + src, l);
1276 src += l; /* but really, we are done */
1277 o->usbradio_write_dst += l;
1283 static struct ast_frame *usbradio_read(struct ast_channel *c)
1286 struct chan_usbradio_pvt *o = c->tech_pvt;
1287 struct ast_frame *f = &o->read_f, *f1;
1288 struct ast_frame wf = { AST_FRAME_CONTROL };
1291 traceusb2("usbradio_read()\n"); /* sph maw asdf */
1293 if (o->lasthidtime) {
1295 if ((now - o->lasthidtime) > 3) {
1296 ast_log(LOG_ERROR, "HID process has died or something!!\n");
1300 if (o->lastrx && (!o->rxkeyed)) {
1302 wf.subclass = AST_CONTROL_RADIO_UNKEY;
1303 ast_queue_frame(o->owner, &wf);
1304 } else if ((!o->lastrx) && (o->rxkeyed)) {
1306 wf.subclass = AST_CONTROL_RADIO_KEY;
1307 ast_queue_frame(o->owner, &wf);
1309 /* XXX can be simplified returning &ast_null_frame */
1310 /* prepare a NULL frame in case we don't have enough data to return */
1311 memset(f, 0, sizeof(struct ast_frame));
1312 f->frametype = AST_FRAME_NULL;
1313 f->src = usbradio_tech.type;
1315 res = read(o->sounddev, o->usbradio_read_buf + o->readpos,
1316 sizeof(o->usbradio_read_buf) - o->readpos);
1317 if (res < 0) /* audio data not ready, return a NULL frame */
1321 if (o->readpos < sizeof(o->usbradio_read_buf)) /* not enough samples */
1327 #if DEBUG_CAPTURES == 1
1328 if (o->b.rxcapraw && frxcapraw)
1329 fwrite((o->usbradio_read_buf + AST_FRIENDLY_OFFSET), 1, FRAME_SIZE * 2 * 2 * 6, frxcapraw);
1334 (i16 *)(o->usbradio_read_buf + AST_FRIENDLY_OFFSET),
1335 (i16 *)(o->usbradio_read_buf_8k + AST_FRIENDLY_OFFSET));
1338 static FILE *hInput;
1339 i16 iBuff[FRAME_SIZE * 2 * 6];
1341 o->pmrChan->b.rxCapture = 1;
1344 hInput = fopen("/usr/src/xpmr/testdata/rx_in.pcm", "r");
1346 ast_log(LOG_ERROR, " Input Data File Not Found.\n");
1351 if (0 == fread((void *)iBuff, 2, FRAME_SIZE * 2 * 6, hInput))
1356 (i16 *)(o->usbradio_read_buf_8k + AST_FRIENDLY_OFFSET));
1361 if (!frxoutraw) frxoutraw = fopen(RX_CAP_OUT_FILE, "w");
1362 if (frxoutraw) fwrite((o->usbradio_read_buf_8k + AST_FRIENDLY_OFFSET), 1, FRAME_SIZE * 2, frxoutraw);
1365 #if DEBUG_CAPTURES == 1
1366 if (frxcaptrace && o->b.rxcap2) fwrite((o->pmrChan->prxDebug), 1, FRAME_SIZE * 2 * 16, frxcaptrace);
1369 if (o->rxcdtype == CD_HID && (o->pmrChan->rxExtCarrierDetect != o->rxhidsq))
1370 o->pmrChan->rxExtCarrierDetect = o->rxhidsq;
1371 if (o->rxcdtype == CD_HID_INVERT && (o->pmrChan->rxExtCarrierDetect == o->rxhidsq))
1372 o->pmrChan->rxExtCarrierDetect = !o->rxhidsq;
1374 if ( (o->rxcdtype == CD_HID && o->rxhidsq) ||
1375 (o->rxcdtype == CD_HID_INVERT && !o->rxhidsq) ||
1376 (o->rxcdtype == CD_XPMR_NOISE && o->pmrChan->rxCarrierDetect) ||
1377 (o->rxcdtype == CD_XPMR_VOX && o->pmrChan->rxCarrierDetect) )
1382 if (res != o->rxcarrierdetect) {
1383 o->rxcarrierdetect = res;
1385 ast_debug(4, "rxcarrierdetect = %d\n", res);
1388 if (o->pmrChan->rxCtcss->decode != o->rxctcssdecode) {
1390 ast_debug(4, "rxctcssdecode = %d\n", o->pmrChan->rxCtcss->decode);
1391 o->rxctcssdecode = o->pmrChan->rxCtcss->decode;
1394 if ( ( o->rxctcssfreq && (o->rxctcssdecode == o->pmrChan->rxCtcssIndex)) ||
1395 ( !o->rxctcssfreq && o->rxcarrierdetect) )
1401 o->readpos = AST_FRIENDLY_OFFSET; /* reset read pointer for next frame */
1402 if (c->_state != AST_STATE_UP) /* drop data if frame is not up */
1404 /* ok we can build and deliver the frame to the caller */
1405 f->frametype = AST_FRAME_VOICE;
1406 f->subclass = AST_FORMAT_SLINEAR;
1407 f->samples = FRAME_SIZE;
1408 f->datalen = FRAME_SIZE * 2;
1409 f->data = o->usbradio_read_buf_8k + AST_FRIENDLY_OFFSET;
1410 if (o->boost != BOOST_SCALE) { /* scale and clip values */
1412 int16_t *p = (int16_t *) f->data;
1413 for (i = 0; i < f->samples; i++) {
1414 x = (p[i] * o->boost) / BOOST_SCALE;
1417 else if (x < -32768)
1423 f->offset = AST_FRIENDLY_OFFSET;
1425 f1 = ast_dsp_process(c, o->dsp, f);
1426 if ((f1->frametype == AST_FRAME_DTMF_END) || (f1->frametype == AST_FRAME_DTMF_BEGIN)) {
1427 if ((f1->subclass == 'm') || (f1->subclass == 'u'))
1428 f1->frametype = AST_FRAME_DTMF_BEGIN;
1429 if (f1->frametype == AST_FRAME_DTMF_END)
1430 ast_log(LOG_NOTICE,"Got DTMF char %c\n",f1->subclass);
1437 static int usbradio_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1439 struct chan_usbradio_pvt *o = newchan->tech_pvt;
1440 ast_log(LOG_WARNING,"usbradio_fixup()\n");
1445 static int usbradio_indicate(struct ast_channel *c, int cond, const void *data, size_t datalen)
1447 struct chan_usbradio_pvt *o = c->tech_pvt;
1451 case AST_CONTROL_BUSY:
1452 case AST_CONTROL_CONGESTION:
1453 case AST_CONTROL_RINGING:
1459 o->nosound = 0; /* when cursound is -1 nosound must be 0 */
1462 case AST_CONTROL_VIDUPDATE:
1465 case AST_CONTROL_HOLD:
1466 ast_verbose(" << Console Has Been Placed on Hold >> \n");
1467 ast_moh_start(c, data, o->mohinterpret);
1469 case AST_CONTROL_UNHOLD:
1470 ast_verbose(" << Console Has Been Retrieved from Hold >> \n");
1473 case AST_CONTROL_PROCEEDING:
1474 ast_verbose(" << Call Proceeding... >> \n");
1477 case AST_CONTROL_PROGRESS:
1478 ast_verbose(" << Call Progress... >> \n");
1481 case AST_CONTROL_RADIO_KEY:
1483 if(o->debuglevel)ast_verbose(" << Radio Transmit On. >> \n");
1485 case AST_CONTROL_RADIO_UNKEY:
1487 if(o->debuglevel)ast_verbose(" << Radio Transmit Off. >> \n");
1490 ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, c->name);
1501 * allocate a new channel.
1503 static struct ast_channel *usbradio_new(struct chan_usbradio_pvt *o, char *ext, char *ctx, int state)
1505 struct ast_channel *c;
1506 char device[15] = "dsp";
1509 snprintf(device + 3, sizeof(device) - 3, "%d", o->devicenum);
1510 c = ast_channel_alloc(1, state, o->cid_num, o->cid_name, "", ext, ctx, 0, "usbRadio/%s", device);
1513 c->tech = &usbradio_tech;
1514 if (o->sounddev < 0)
1515 setformat(o, O_RDWR);
1516 c->fds[0] = o->sounddev; /* -1 if device closed, override later */
1517 c->nativeformats = AST_FORMAT_SLINEAR;
1518 c->readformat = AST_FORMAT_SLINEAR;
1519 c->writeformat = AST_FORMAT_SLINEAR;
1522 if (!ast_strlen_zero(o->language))
1523 ast_string_field_set(c, language, o->language);
1524 /* Don't use ast_set_callerid() here because it will
1525 * generate a needless NewCallerID event */
1526 c->cid.cid_num = ast_strdup(o->cid_num);
1527 c->cid.cid_ani = ast_strdup(o->cid_num);
1528 c->cid.cid_name = ast_strdup(o->cid_name);
1529 if (!ast_strlen_zero(ext))
1530 c->cid.cid_dnid = ast_strdup(ext);
1533 ast_module_ref(ast_module_info->self);
1534 ast_jb_configure(c, &global_jbconf);
1535 if (state != AST_STATE_DOWN) {
1536 if (ast_pbx_start(c)) {
1537 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", c->name);
1539 o->owner = c = NULL;
1540 /* XXX what about the channel itself ? */
1541 /* XXX what about usecnt ? */
1548 static struct ast_channel *usbradio_request(const char *type, int format, void *data, int *cause)
1550 struct ast_channel *c;
1551 struct chan_usbradio_pvt *o = find_desc(data);
1553 ast_debug(4, "usbradio_request ty <%s> data 0x%p <%s>\n", type, data, (char *) data);
1555 ast_log(LOG_NOTICE, "Device %s not found\n", (char *) data);
1556 /* XXX we could default to 'dsp' perhaps ? */
1559 if ((format & AST_FORMAT_SLINEAR) == 0) {
1560 ast_log(LOG_NOTICE, "Format 0x%x unsupported\n", format);
1564 ast_log(LOG_NOTICE, "Already have a call (chan %p) on the usb channel\n", o->owner);
1565 *cause = AST_CAUSE_BUSY;
1568 c = usbradio_new(o, NULL, NULL, AST_STATE_DOWN);
1570 ast_log(LOG_WARNING, "Unable to create new usb channel\n");
1576 static char *handle_cli_radio_key(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1578 struct chan_usbradio_pvt *o = NULL;
1582 e->command = "radio key";
1584 "Usage: radio key\n"
1585 " Simulates COR active.\n";
1592 return CLI_SHOWUSAGE;
1594 o = find_desc(usbradio_active);
1600 static char *handle_cli_radio_unkey(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1602 struct chan_usbradio_pvt *o = NULL;
1606 e->command = "radio unkey";
1608 "Usage: radio unkey\n"
1609 " Simulates COR un-active.\n";
1616 return CLI_SHOWUSAGE;
1618 o = find_desc(usbradio_active);
1624 static char *handle_cli_radio_tune(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1626 struct chan_usbradio_pvt *o = NULL;
1631 e->command = "radio tune [rxnoise|rxvoice|rxtone|rxsquelch|rxcap|rxtracecap|"
1632 "txvoice|txtone|txcap|txtracecap|auxvoice|nocap|dump|save]";
1633 /* radio tune 6 3000 measured tx value */
1635 "Usage: radio tune <function>\n"
1639 " rxsquelch [newsetting]\n"
1642 " txvoice [newsetting]\n"
1643 " txtone [newsetting]\n"
1646 " auxvoice [newsetting]\n"
1649 " save (settings to tuning file)\n"
1651 " All [newsetting]s are values 0-999\n";
1657 if ((a->argc < 2) || (a->argc > 4))
1658 return CLI_SHOWUSAGE;
1660 if (a->argc == 2) { /* just show stuff */
1661 ast_cli(a->fd, "Output A is currently set to %s.\n",
1662 o->txmixa == TX_OUT_COMPOSITE ? "composite" :
1663 o->txmixa == TX_OUT_VOICE ? "voice" :
1664 o->txmixa == TX_OUT_LSD ? "tone" :
1665 o->txmixa == TX_OUT_AUX ? "auxvoice" :
1668 ast_cli(a->fd, "Output B is currently set to %s.\n",
1669 o->txmixb == TX_OUT_COMPOSITE ? "composite" :
1670 o->txmixb == TX_OUT_VOICE ? "voice" :
1671 o->txmixb == TX_OUT_LSD ? "tone" :
1672 o->txmixb == TX_OUT_AUX ? "auxvoice" :
1675 ast_cli(a->fd, "Tx Voice Level currently set to %d\n", o->txmixaset);
1676 ast_cli(a->fd, "Tx Tone Level currently set to %d\n", o->txctcssadj);
1677 ast_cli(a->fd, "Rx Squelch currently set to %d\n", o->rxsquelchadj);
1678 return CLI_SHOWUSAGE;
1681 o = find_desc(usbradio_active);
1683 if (!strcasecmp(a->argv[2], "rxnoise"))
1685 else if (!strcasecmp(a->argv[2], "rxvoice"))
1687 else if (!strcasecmp(a->argv[2], "rxtone"))
1689 else if (!strcasecmp(a->argv[2], "rxsquelch")) {
1691 ast_cli(a->fd, "Current Signal Strength is %d\n", ((32767 - o->pmrChan->rxRssi) * 1000 / 32767));
1692 ast_cli(a->fd, "Current Squelch setting is %d\n", o->rxsquelchadj);
1694 ast_cli(a->fd,"Current Raw RSSI is %d\n",o->pmrChan->rxRssi);
1695 ast_cli(a->fd,"Current (real) Squelch setting is %d\n",*(o->pmrChan->prxSquelchAdjust));
1698 i = atoi(a->argv[3]);
1699 if ((i < 0) || (i > 999))
1700 return CLI_SHOWUSAGE;
1701 ast_cli(a->fd, "Changed Squelch setting to %d\n", i);
1702 o->rxsquelchadj = i;
1703 *(o->pmrChan->prxSquelchAdjust) = ((999 - i) * 32767) / 1000;
1705 } else if (!strcasecmp(a->argv[2], "txvoice")) {
1708 if ((o->txmixa != TX_OUT_VOICE) && (o->txmixb != TX_OUT_VOICE) &&
1709 (o->txmixa != TX_OUT_COMPOSITE) && (o->txmixb != TX_OUT_COMPOSITE)) {
1710 ast_log(LOG_ERROR, "No txvoice output configured.\n");
1711 } else if (a->argc == 3) {
1712 if ((o->txmixa == TX_OUT_VOICE) || (o->txmixa == TX_OUT_COMPOSITE))
1713 ast_cli(a->fd, "Current txvoice setting on Channel A is %d\n", o->txmixaset);
1715 ast_cli(a->fd, "Current txvoice setting on Channel B is %d\n", o->txmixbset);
1717 i = atoi(a->argv[3]);
1718 if ((i < 0) || (i > 999))
1719 return CLI_SHOWUSAGE;
1721 if ((o->txmixa == TX_OUT_VOICE) || (o->txmixa == TX_OUT_COMPOSITE)) {
1723 ast_cli(a->fd, "Changed txvoice setting on Channel A to %d\n", o->txmixaset);
1726 ast_cli(a->fd, "Changed txvoice setting on Channel B to %d\n", o->txmixbset);
1730 ast_cli(a->fd, "Changed Tx Voice Output setting to %d\n", i);
1733 } else if (!strcasecmp(a->argv[2], "auxvoice")) {
1735 if ( (o->txmixa != TX_OUT_AUX) && (o->txmixb != TX_OUT_AUX))
1736 ast_log(LOG_WARNING, "No auxvoice output configured.\n");
1737 else if (a->argc == 3) {
1738 if (o->txmixa == TX_OUT_AUX)
1739 ast_cli(a->fd, "Current auxvoice setting on Channel A is %d\n", o->txmixaset);
1741 ast_cli(a->fd, "Current auxvoice setting on Channel B is %d\n", o->txmixbset);
1743 i = atoi(a->argv[3]);
1744 if ((i < 0) || (i > 999))
1745 return CLI_SHOWUSAGE;
1746 if (o->txmixa == TX_OUT_AUX) {
1748 ast_cli(a->fd, "Changed auxvoice setting on Channel A to %d\n", o->txmixaset);
1751 ast_cli(a->fd, "Changed auxvoice setting on Channel B to %d\n", o->txmixbset);
1756 /* tune_auxoutput(o,i); */
1757 } else if (!strcasecmp(a->argv[2], "txtone")) {
1759 ast_cli(a->fd, "Current Tx CTCSS modulation setting = %d\n", o->txctcssadj);
1761 i = atoi(a->argv[3]);
1762 if ((i < 0) || (i > 999))
1763 return CLI_SHOWUSAGE;
1765 set_txctcss_level(o);
1766 ast_cli(a->fd, "Changed Tx CTCSS modulation setting to %i\n", i);
1771 } else if (!strcasecmp(a->argv[2],"dump"))
1773 else if (!strcasecmp(a->argv[2],"nocap")) {
1774 ast_cli(a->fd, "File capture (trace) was rx=%d tx=%d and now off.\n", o->b.rxcap2, o->b.txcap2);
1775 ast_cli(a->fd, "File capture (raw) was rx=%d tx=%d and now off.\n", o->b.rxcapraw, o->b.txcapraw);
1776 o->b.rxcapraw = o->b.txcapraw = o->b.rxcap2 = o->b.txcap2 = o->pmrChan->b.rxCapture = o->pmrChan->b.txCapture = 0;
1782 fclose(frxcaptrace);
1794 fclose(ftxcaptrace);
1801 } else if (!strcasecmp(a->argv[2], "rxtracecap")) {
1803 frxcaptrace = fopen(RX_CAP_TRACE_FILE, "w");
1804 ast_cli(a->fd, "Trace rx on.\n");
1805 o->b.rxcap2 = o->pmrChan->b.rxCapture = 1;
1806 } else if (!strcasecmp(a->argv[2], "txtracecap")) {
1808 ftxcaptrace = fopen(TX_CAP_TRACE_FILE, "w");
1809 ast_cli(a->fd, "Trace tx on.\n");
1810 o->b.txcap2 = o->pmrChan->b.txCapture = 1;
1811 } else if (!strcasecmp(a->argv[2], "rxcap")) {
1813 frxcapraw = fopen(RX_CAP_RAW_FILE, "w");
1814 ast_cli(a->fd, "cap rx raw on.\n");
1816 } else if (!strcasecmp(a->argv[2], "txcap")) {
1818 ftxcapraw = fopen(TX_CAP_RAW_FILE, "w");
1819 ast_cli(a->fd, "cap tx raw on.\n");
1821 } else if (!strcasecmp(a->argv[2], "save")) {
1823 ast_cli(a->fd, "Saved radio tuning settings to usbradio_tune.conf\n");
1825 return CLI_SHOWUSAGE;
1830 set transmit ctcss modulation level
1831 adjust mixer output or internal gain depending on output type
1832 setting range is 0.0 to 0.9
1834 static int set_txctcss_level(struct chan_usbradio_pvt *o)
1836 if (o->txmixa == TX_OUT_LSD) {
1837 o->txmixaset = (151 * o->txctcssadj) / 1000;
1840 } else if (o->txmixb == TX_OUT_LSD) {
1841 o->txmixbset = (151 * o->txctcssadj) / 1000;
1845 *o->pmrChan->ptxCtcssAdjust = (o->txctcssadj * M_Q8) / 1000;
1850 CLI debugging on and off
1852 static char *handle_cli_radio_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1854 struct chan_usbradio_pvt *o = NULL;
1858 e->command = "radio set debug [off]";
1860 "Usage: radio set debug [off]\n"
1861 " Enable/Disable radio debugging.\n";
1865 if (a->argc < 3 || a->argc > 4)
1866 return CLI_SHOWUSAGE;
1867 if (a->argc == 4 && strncasecmp(a->argv[3], "off", 3))
1868 return CLI_SHOWUSAGE;
1870 o = find_desc(usbradio_active);
1877 ast_cli(a->fd, "USB Radio debugging %s.\n", o->debuglevel ? "enabled" : "disabled");
1882 static struct ast_cli_entry cli_usbradio[] = {
1883 AST_CLI_DEFINE(handle_cli_radio_key, "Simulate Rx Signal Present"),
1884 AST_CLI_DEFINE(handle_cli_radio_unkey, "Simulate Rx Signal Lusb"),
1885 AST_CLI_DEFINE(handle_cli_radio_tune, "Radio Tune"),
1886 AST_CLI_DEFINE(handle_cli_radio_set_debug, "Enable/Disable Radio Debugging"),
1890 * store the callerid components
1893 static void store_callerid(struct chan_usbradio_pvt *o, const char *s)
1895 ast_callerid_split(s, o->cid_name, sizeof(o->cid_name), o->cid_num, sizeof(o->cid_num));
1899 static void store_rxdemod(struct chan_usbradio_pvt *o, const char *s)
1901 if (!strcasecmp(s, "no")) {
1902 o->rxdemod = RX_AUDIO_NONE;
1903 } else if (!strcasecmp(s, "speaker")) {
1904 o->rxdemod = RX_AUDIO_SPEAKER;
1905 } else if (!strcasecmp(s, "flat")) {
1906 o->rxdemod = RX_AUDIO_FLAT;
1908 ast_log(LOG_WARNING, "Unrecognized rxdemod parameter: %s\n", s);
1911 ast_debug(4, "set rxdemod = %s\n", s);
1915 static void store_txmixa(struct chan_usbradio_pvt *o, const char *s)
1917 if (!strcasecmp(s, "no"))
1918 o->txmixa = TX_OUT_OFF;
1920 else if (!strcasecmp(s, "voice"))
1921 o->txmixa = TX_OUT_VOICE;
1922 else if (!strcasecmp(s, "tone"))
1923 o->txmixa = TX_OUT_LSD;
1924 else if (!strcasecmp(s, "composite"))
1925 o->txmixa = TX_OUT_COMPOSITE;
1926 else if (!strcasecmp(s, "auxvoice"))
1927 o->txmixb = TX_OUT_AUX;
1929 ast_log(LOG_WARNING, "Unrecognized txmixa parameter: %s\n", s);
1931 ast_debug(4, "set txmixa = %s\n", s);
1934 static void store_txmixb(struct chan_usbradio_pvt *o, const char *s)
1936 if (!strcasecmp(s, "no"))
1937 o->txmixb = TX_OUT_OFF;
1938 else if (!strcasecmp(s, "voice"))
1939 o->txmixb = TX_OUT_VOICE;
1940 else if (!strcasecmp(s, "tone"))
1941 o->txmixb = TX_OUT_LSD;
1942 else if (!strcasecmp(s, "composite"))
1943 o->txmixb = TX_OUT_COMPOSITE;
1944 else if (!strcasecmp(s, "auxvoice"))
1945 o->txmixb = TX_OUT_AUX;
1947 ast_log(LOG_WARNING, "Unrecognized txmixb parameter: %s\n", s);
1949 ast_debug(4, "set txmixb = %s\n", s);
1952 static void store_rxcdtype(struct chan_usbradio_pvt *o, const char *s)
1954 if (!strcasecmp(s, "no"))
1955 o->rxcdtype = CD_IGNORE;
1956 else if (!strcasecmp(s, "usb"))
1957 o->rxcdtype = CD_HID;
1958 else if (!strcasecmp(s, "dsp"))
1959 o->rxcdtype = CD_XPMR_NOISE;
1960 else if (!strcasecmp(s, "vox"))
1961 o->rxcdtype = CD_XPMR_VOX;
1962 else if (!strcasecmp(s, "usbinvert"))
1963 o->rxcdtype = CD_HID_INVERT;
1965 ast_log(LOG_WARNING, "Unrecognized rxcdtype parameter: %s\n", s);
1967 ast_debug(4, "set rxcdtype = %s\n", s);
1970 static void store_rxsdtype(struct chan_usbradio_pvt *o, const char *s)
1972 if (!strcasecmp(s, "no") || !strcasecmp(s, "SD_IGNORE"))
1973 o->rxsdtype = SD_IGNORE;
1974 else if (!strcasecmp(s, "usb") || !strcasecmp(s, "SD_HID"))
1975 o->rxsdtype = SD_HID;
1976 else if (!strcasecmp(s, "usbinvert") || !strcasecmp(s, "SD_HID_INVERT"))
1977 o->rxsdtype = SD_HID_INVERT;
1978 else if (!strcasecmp(s, "software") || !strcasecmp(s, "SD_XPMR"))
1979 o->rxsdtype = SD_XPMR;
1981 ast_log(LOG_WARNING, "Unrecognized rxsdtype parameter: %s\n", s);
1983 ast_debug(4, "set rxsdtype = %s\n", s);
1986 static void store_rxgain(struct chan_usbradio_pvt *o, const char *s)
1989 if (sscanf(s, "%f", &f) == 1)
1991 ast_debug(4, "set rxgain = %f\n", f);
1994 static void store_rxvoiceadj(struct chan_usbradio_pvt *o, const char *s)
1997 if (sscanf(s, "%f", &f) == 1)
1999 ast_debug(4, "set rxvoiceadj = %f\n", f);
2002 static void store_rxctcssadj(struct chan_usbradio_pvt *o, const char *s)
2005 if (sscanf(s, "%f", &f) == 1)
2007 ast_debug(4, "set rxctcssadj = %f\n", f);
2010 static void store_txtoctype(struct chan_usbradio_pvt *o, const char *s)
2012 if (!strcasecmp(s, "no") || !strcasecmp(s, "TOC_NONE"))
2013 o->txtoctype = TOC_NONE;
2014 else if (!strcasecmp(s, "phase") || !strcasecmp(s, "TOC_PHASE"))
2015 o->txtoctype = TOC_PHASE;
2016 else if (!strcasecmp(s, "notone") || !strcasecmp(s, "TOC_NOTONE"))
2017 o->txtoctype = TOC_NOTONE;
2019 ast_log(LOG_WARNING, "Unrecognized txtoctype parameter: %s\n", s);
2021 ast_debug(4, "set txtoctype = %s\n", s);
2024 static void store_rxctcssfreq(struct chan_usbradio_pvt *o, const char *s)
2027 if (sscanf(s, "%f", &f) == 1)
2029 ast_debug(4, "set rxctcss = %f\n", f);
2032 static void store_txctcssfreq(struct chan_usbradio_pvt *o, const char *s)
2035 if (sscanf(s, "%f", &f) == 1)
2037 ast_debug(4, "set txctcss = %f\n", f);
2040 static void tune_txoutput(struct chan_usbradio_pvt *o, int value)
2043 o->pmrChan->txPttIn = 1;
2046 /* generate 1KHz tone at 7200 peak */
2047 o->pmrChan->spsSigGen1->freq = 10000;
2048 o->pmrChan->spsSigGen1->outputGain = (float)(0.22 * M_Q8);
2049 o->pmrChan->b.startSpecialTone = 1;
2052 TxTestTone(o->pmrChan, 1);
2055 /* o->pmrChan->b.stopSpecialTone = 1; */
2058 TxTestTone(o->pmrChan, 0);
2060 o->pmrChan->txPttIn = 0;
2064 static void tune_rxinput(struct chan_usbradio_pvt *o)
2066 const int target = 23000;
2067 const int tolerance = 2000;
2068 const int settingmin = 1;
2069 const int settingstart = 2;
2070 const int maxtries = 12;
2074 int setting = 0, tries = 0, tmpdiscfactor, meas;
2077 settingmax = o->micmax;
2079 if (o->pmrChan->rxDemod)
2082 setting = settingstart;
2084 while (tries < maxtries) {
2085 setamixer(o->devicenum, MIXER_PARAM_MIC_CAPTURE_VOL, setting, 0);
2086 setamixer(o->devicenum, MIXER_PARAM_MIC_BOOST, o->rxboostset, 0);
2088 if (o->rxcdtype == CD_XPMR_VOX || o->rxdemod == RX_AUDIO_SPEAKER) {
2089 ast_debug(4, "Measure Direct Input\n");
2090 o->pmrChan->spsMeasure->source = o->pmrChan->spsRx->source;
2091 o->pmrChan->spsMeasure->discfactor = 1000;
2092 o->pmrChan->spsMeasure->enabled = 1;
2093 o->pmrChan->spsMeasure->amax = o->pmrChan->spsMeasure->amin = 0;
2095 meas = o->pmrChan->spsMeasure->apeak;
2096 o->pmrChan->spsMeasure->enabled = 0;
2098 ast_debug(4, "Measure HF Noise\n");
2099 tmpdiscfactor = o->pmrChan->spsRx->discfactor;
2100 o->pmrChan->spsRx->discfactor = (i16)1000;
2101 o->pmrChan->spsRx->discounteru = o->pmrChan->spsRx->discounterl = 0;
2102 o->pmrChan->spsRx->amax = o->pmrChan->spsRx->amin = 0;
2104 meas = o->pmrChan->rxRssi;
2105 o->pmrChan->spsRx->discfactor = tmpdiscfactor;
2106 o->pmrChan->spsRx->discounteru = o->pmrChan->spsRx->discounterl = 0;
2107 o->pmrChan->spsRx->amax = o->pmrChan->spsRx->amin = 0;
2111 ast_log(LOG_NOTICE, "tries=%d, setting=%d, meas=%i\n", tries, setting, meas);
2113 if ( meas < (target - tolerance) || meas > (target + tolerance) || tries < 3)
2114 setting = setting * target / meas;
2115 else if (tries > 4 && meas > (target - tolerance) && meas < (target + tolerance) )
2118 if (setting < settingmin)
2119 setting = settingmin;
2120 else if (setting > settingmax)
2121 setting = settingmax;
2125 ast_log(LOG_NOTICE, "DONE tries=%d, setting=%d, meas=%i\n", tries,
2126 (setting * 1000) / o->micmax, meas);
2127 if (meas < (target - tolerance) || meas > (target + tolerance))
2128 ast_log(LOG_NOTICE, "ERROR: RX INPUT ADJUST FAILED.\n");
2130 ast_log(LOG_NOTICE, "INFO: RX INPUT ADJUST SUCCESS.\n");
2131 o->rxmixerset = (setting * 1000) / o->micmax;
2136 static void tune_rxvoice(struct chan_usbradio_pvt *o)
2138 const int target = 7200; /* peak */
2139 const int tolerance = 360; /* peak to peak */
2140 const float settingmin = 0.1;
2141 const float settingmax = 4;
2142 const float settingstart = 1;
2143 const int maxtries = 12;
2147 int tries = 0, meas;
2149 ast_log(LOG_NOTICE, "INFO: RX VOICE ADJUST START.\n");
2150 ast_log(LOG_NOTICE, "target=%d tolerance=%d\n", target, tolerance);
2152 if (!o->pmrChan->spsMeasure)
2153 ast_log(LOG_ERROR, "NO MEASURE BLOCK.\n");
2155 if (!o->pmrChan->spsMeasure->source || !o->pmrChan->prxVoiceAdjust )
2156 ast_log(LOG_ERROR, "NO SOURCE OR MEASURE SETTING.\n");
2158 o->pmrChan->spsMeasure->source = o->pmrChan->spsRxOut->sink;
2159 o->pmrChan->spsMeasure->enabled = 1;
2160 o->pmrChan->spsMeasure->discfactor = 1000;
2162 setting=settingstart;
2164 ast_debug(4, "ERROR: NO MEASURE BLOCK.\n");
2166 while (tries < maxtries) {
2167 *(o->pmrChan->prxVoiceAdjust) = setting * M_Q8;
2169 o->pmrChan->spsMeasure->amax = o->pmrChan->spsMeasure->amin = 0;
2171 meas = o->pmrChan->spsMeasure->apeak;
2172 ast_log(LOG_NOTICE, "tries=%d, setting=%f, meas=%i\n", tries, setting, meas);
2174 if (meas < (target - tolerance) || meas > (target + tolerance) || tries < 3)
2175 setting = setting * target / meas;
2176 else if (tries > 4 && meas > (target - tolerance) && meas < (target + tolerance))
2178 if (setting < settingmin)
2179 setting = settingmin;
2180 else if (setting > settingmax)
2181 setting = settingmax;
2186 o->pmrChan->spsMeasure->enabled = 0;
2188 ast_log(LOG_NOTICE, "DONE tries=%d, setting=%f, meas=%f\n", tries, setting, (float)meas);
2189 if (meas < (target - tolerance) || meas > (target + tolerance))
2190 ast_log(LOG_ERROR, "RX VOICE GAIN ADJUST FAILED.\n");
2192 ast_log(LOG_NOTICE, "RX VOICE GAIN ADJUST SUCCESS.\n");
2193 o->rxvoiceadj = setting;
2197 static void tune_rxctcss(struct chan_usbradio_pvt *o)
2199 const int target = 4096;
2200 const int tolerance = 100;
2201 const float settingmin = 0.1;
2202 const float settingmax = 4;
2203 const float settingstart = 1;
2204 const int maxtries = 12;
2207 int tries = 0, meas;
2209 ast_log(LOG_NOTICE, "RX CTCSS ADJUST START.\n");
2210 ast_log(LOG_NOTICE, "target=%d tolerance=%d \n", target, tolerance);
2212 o->pmrChan->spsMeasure->source = o->pmrChan->prxCtcssMeasure;
2213 o->pmrChan->spsMeasure->discfactor = 400;
2214 o->pmrChan->spsMeasure->enabled = 1;
2216 setting = settingstart;
2218 while (tries < maxtries) {
2219 *(o->pmrChan->prxCtcssAdjust) = setting * M_Q8;
2221 o->pmrChan->spsMeasure->amax = o->pmrChan->spsMeasure->amin = 0;
2223 meas = o->pmrChan->spsMeasure->apeak;
2224 ast_debug(4, "tries=%d, setting=%f, meas=%i\n", tries, setting, meas);
2226 if (meas < (target - tolerance) || meas > (target + tolerance) || tries < 3)
2227 setting = setting * target / meas;
2228 else if (tries > 4 && meas > (target - tolerance) && meas < (target + tolerance))
2230 if (setting < settingmin)
2231 setting = settingmin;
2232 else if (setting > settingmax)
2233 setting = settingmax;
2237 o->pmrChan->spsMeasure->enabled = 0;
2238 ast_debug(4, "DONE tries=%d, setting=%f, meas=%f\n", tries, setting, (float)meas);
2239 if (meas < (target - tolerance) || meas > (target + tolerance))
2240 ast_log(LOG_ERROR, "RX CTCSS GAIN ADJUST FAILED.\n");
2242 ast_log(LOG_NOTICE, "RX CTCSS GAIN ADJUST SUCCESS.\n");
2243 o->rxctcssadj = setting;
2247 this file then is included in chan_usbradio.conf
2248 #include /etc/asterisk/usbradio_tune.conf
2250 static void tune_write(struct chan_usbradio_pvt *o)
2254 fp = fopen("/etc/asterisk/usbradio_tune.conf", "w");
2256 if (!strcmp(o->name, "dsp"))
2257 fprintf(fp, "[general]\n");
2259 fprintf(fp, "[%s]\n", o->name);
2261 fprintf(fp, "; name=%s\n", o->name);
2262 fprintf(fp, "; devicenum=%d\n", o->devicenum);
2264 fprintf(fp, "rxmixerset=%d\n", o->rxmixerset);
2265 fprintf(fp, "rxboostset=%d\n", o->rxboostset);
2266 fprintf(fp, "txmixaset=%d\n", o->txmixaset);
2267 fprintf(fp, "txmixbset=%d\n", o->txmixbset);
2269 fprintf(fp, "rxvoiceadj=%f\n", o->rxvoiceadj);
2270 fprintf(fp, "rxctcssadj=%f\n", o->rxctcssadj);
2271 fprintf(fp, "txctcssadj=%d\n", o->txctcssadj);
2273 fprintf(fp, "rxsquelchadj=%d\n", o->rxsquelchadj);
2277 static void mixer_write(struct chan_usbradio_pvt *o)
2279 setamixer(o->devicenum, MIXER_PARAM_MIC_PLAYBACK_SW, 0, 0);
2280 setamixer(o->devicenum, MIXER_PARAM_MIC_PLAYBACK_VOL, 0, 0);
2281 setamixer(o->devicenum, MIXER_PARAM_SPKR_PLAYBACK_SW, 1, 0);
2282 setamixer(o->devicenum, MIXER_PARAM_SPKR_PLAYBACK_VOL,
2283 o->txmixaset * o->spkrmax / 1000,
2284 o->txmixbset * o->spkrmax / 1000);
2285 setamixer(o->devicenum, MIXER_PARAM_MIC_CAPTURE_VOL,
2286 o->rxmixerset * o->micmax / 1000, 0);
2287 setamixer(o->devicenum, MIXER_PARAM_MIC_BOOST, o->rxboostset, 0);
2288 setamixer(o->devicenum, MIXER_PARAM_MIC_CAPTURE_SW, 1, 0);
2291 adjust dsp multiplier to add resolution to tx level adjustment
2293 static void mult_set(struct chan_usbradio_pvt *o)
2296 if (o->pmrChan->spsTxOutA) {
2297 o->pmrChan->spsTxOutA->outputGain =
2298 mult_calc((o->txmixaset * 152) / 1000);
2300 if (o->pmrChan->spsTxOutB) {
2301 o->pmrChan->spsTxOutB->outputGain =
2302 mult_calc((o->txmixbset * 152) / 1000);
2306 * input 0 - 151 outputs are pot and multiplier
2308 static int mult_calc(int value)
2310 const int multx = M_Q8;
2313 pot= ((int)(value / 4) * 4) + 2;
2314 mult = multx - ((multx * (3 - (value % 4))) / (pot + 2));
2318 #define pd(x) ast_debug(4, #x" = %d\n", x)
2319 #define pp(x) ast_debug(4, #x" = %p\n", x)
2320 #define ps(x) ast_debug(4, #x" = %s\n", x)
2321 #define pf(x) ast_debug(4, #x" = %f\n", x)
2324 static void pmrdump(struct chan_usbradio_pvt *o)
2330 ast_debug(4, "odump()\n");
2342 pd(o->rxsquelchadj);
2351 ast_debug(4, "pmrdump()\n");
2353 ast_debug(4, "prxSquelchAdjust=%d\n", *(o->pmrChan->prxSquelchAdjust));
2355 pd(p->rxCarrierPoint);
2356 pd(p->rxCarrierHyst);
2358 pd(p->rxCtcss->relax);
2360 pd(p->rxCtcssIndex);
2366 pd(p->rxDeEmpEnable);
2367 pd(p->rxCenterSlicerEnable);
2368 pd(p->rxCtcssDecodeEnable);
2369 pd(p->rxDcsDecodeEnable);
2372 pd(p->txLimiterEnable);
2373 pd(p->txPreEmpEnable);
2377 pd(p->spsTxOutA->outputGain);
2379 pd(p->spsTxOutB->outputGain);
2386 * grab fields from the config file, init the descriptor and open the device.
2388 static struct chan_usbradio_pvt *store_config(struct ast_config *cfg, char *ctg)
2390 struct ast_variable *v;
2391 struct chan_usbradio_pvt *o;
2392 struct ast_config *cfg1;
2393 struct ast_flags config_flags = { 0 };
2396 traceusb1(" store_config() ctg == NULL\n");
2397 o = &usbradio_default;
2400 if (!(o = ast_calloc(1, sizeof(*o)))){
2403 *o = usbradio_default;
2404 /* "general" is also the default thing */
2405 if (strcmp(ctg, "general") == 0) {
2406 o->name = ast_strdup("dsp");
2407 usbradio_active = o->name;
2409 o->name = ast_strdup(ctg);
2412 strcpy(o->mohinterpret, "default");
2413 o->micmax = amixer_max(o->devicenum, MIXER_PARAM_MIC_CAPTURE_VOL);
2414 o->spkrmax = amixer_max(o->devicenum, MIXER_PARAM_SPKR_PLAYBACK_VOL);
2415 /* fill other fields from configuration */
2416 for (v = ast_variable_browse(cfg, ctg); v; v = v->next) {
2417 M_START(v->name, v->value);
2419 /* handle jb conf */
2420 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
2424 M_BOOL("autoanswer", o->autoanswer)
2425 M_BOOL("autohangup", o->autohangup)
2426 M_BOOL("overridecontext", o->overridecontext)
2427 M_STR("context", o->ctx)
2428 M_STR("language", o->language)
2429 M_STR("mohinterpret", o->mohinterpret)
2430 M_STR("extension", o->ext)
2431 M_F("callerid", store_callerid(o, v->value))
2433 M_UINT("frags", o->frags)
2434 M_UINT("queuesize", o->queuesize)
2435 M_UINT("devicenum", o->devicenum)
2436 M_UINT("debug", usbradio_debug)
2437 M_BOOL("rxcpusaver", o->rxcpusaver)
2438 M_BOOL("txcpusaver", o->txcpusaver)
2439 M_BOOL("invertptt", o->invertptt)
2440 M_F("rxdemod", store_rxdemod(o, v->value))
2441 M_BOOL("txprelim", o->txprelim);
2442 M_F("txmixa", store_txmixa(o, v->value))
2443 M_F("txmixb", store_txmixb(o, v->value))
2444 M_F("carrierfrom", store_rxcdtype(o, v->value))
2445 M_F("rxsdtype", store_rxsdtype(o, v->value))
2446 M_F("rxctcssfreq", store_rxctcssfreq(o, v->value))
2447 M_F("txctcssfreq", store_txctcssfreq(o, v->value))
2448 M_F("rxgain", store_rxgain(o, v->value))
2449 M_BOOL("rxboostset", o->rxboostset)
2450 M_UINT("rxctcssrelax", o->rxctcssrelax)
2451 M_F("txtoctype", store_txtoctype(o, v->value))
2452 M_UINT("hdwtype", o->hdwtype)
2453 M_UINT("duplex", o->radioduplex)
2458 cfg1 = ast_config_load(config1, config_flags);
2460 o->rxmixerset = 500;
2463 o->rxvoiceadj = 0.5;
2464 o->rxctcssadj = 0.5;
2465 o->txctcssadj = 200;
2466 o->rxsquelchadj = 500;
2467 ast_log(LOG_WARNING, "File %s not found, using default parameters.\n", config1);
2469 for (v = ast_variable_browse(cfg1, ctg); v; v = v->next) {
2471 M_START(v->name, v->value);
2472 M_UINT("rxmixerset", o->rxmixerset)
2473 M_UINT("txmixaset", o->txmixaset)
2474 M_UINT("txmixbset", o->txmixbset)
2475 M_F("rxvoiceadj", store_rxvoiceadj(o, v->value))
2476 M_F("rxctcssadj", store_rxctcssadj(o, v->value))
2477 M_UINT("txctcssadj", o->txctcssadj);
2478 M_UINT("rxsquelchadj", o->rxsquelchadj)
2482 ast_config_destroy(cfg1);
2487 if (o == &usbradio_default) /* we are done with the default */
2490 o->lastopen = ast_tvnow(); /* don't leave it 0 or tvdiff may wrap */
2491 o->dsp = ast_dsp_new();
2493 ast_dsp_set_features(o->dsp, DSP_FEATURE_DTMF_DETECT);
2494 ast_dsp_digitmode(o->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_RELAXDTMF);
2497 if (o->rxctcssfreq != 0 && o->rxdemod == RX_AUDIO_SPEAKER)
2498 ast_log(LOG_ERROR, "Incompatable Options o->rxctcssfreq=%f and o->rxdemod=speaker\n", o->rxctcssfreq);
2500 if (o->pmrChan == NULL) {
2503 memset(&tChan, 0, sizeof(tChan));
2505 tChan.rxDemod = o->rxdemod;
2506 tChan.rxCdType = o->rxcdtype;
2508 tChan.txMod = o->txprelim;
2510 tChan.txMixA = o->txmixa;
2511 tChan.txMixB = o->txmixb;
2513 tChan.rxCpuSaver = o->rxcpusaver;
2514 tChan.txCpuSaver = o->txcpusaver;
2516 tChan.rxCtcssFreq = o->rxctcssfreq;
2517 tChan.txCtcssFreq = o->txctcssfreq;
2519 o->pmrChan = createPmrChannel(&tChan, FRAME_SIZE);
2521 o->pmrChan->radioDuplex = o->radioduplex;
2523 o->pmrChan->rxCpuSaver = o->rxcpusaver;
2524 o->pmrChan->txCpuSaver = o->txcpusaver;
2526 *(o->pmrChan->prxSquelchAdjust) =
2527 ((999 - o->rxsquelchadj) * 32767) / 1000;
2529 o->pmrChan->spsRx->outputGain = o->rxvoiceadj*M_Q8;
2531 o->pmrChan->txTocType = o->txtoctype;
2533 if ((o->txmixa == TX_OUT_LSD) ||
2534 (o->txmixa == TX_OUT_COMPOSITE) ||
2535 (o->txmixb == TX_OUT_LSD) ||
2536 (o->txmixb == TX_OUT_COMPOSITE)) {
2537 *(o->pmrChan->prxCtcssAdjust) = o->rxctcssadj * M_Q8;
2538 set_txctcss_level(o);
2541 o->pmrChan->rxCtcss->relax = o->rxctcssrelax;
2545 if ((o->txmixa != TX_OUT_VOICE) && (o->txmixb != TX_OUT_VOICE) &&
2546 (o->txmixa != TX_OUT_COMPOSITE) && (o->txmixb != TX_OUT_COMPOSITE))
2547 ast_log(LOG_ERROR, "No txvoice output configured.\n");
2549 if (o->txctcssfreq &&
2550 o->txmixa != TX_OUT_LSD && o->txmixa != TX_OUT_COMPOSITE &&
2551 o->txmixb != TX_OUT_LSD && o->txmixb != TX_OUT_COMPOSITE)
2552 ast_log(LOG_ERROR, "No txtone output configured.\n");
2554 if (o->rxctcssfreq && o->pmrChan->rxCtcssIndex < 0)
2555 ast_log(LOG_ERROR, "Invalid CTCSS Frequency.\n");
2565 if (pipe(o->sndcmd) != 0) {
2566 ast_log(LOG_ERROR, "Unable to create pipe\n");
2570 ast_debug(4, "creating sound thread\n");
2571 ast_pthread_create_background(&o->sthread, NULL, sound_thread, o);
2573 /* link into list of devices */
2574 if (o != &usbradio_default) {
2575 o->next = usbradio_default.next;
2576 usbradio_default.next = o;
2581 if (o != &usbradio_default)
2586 #if DEBUG_FILETEST == 1
2590 int RxTestIt(struct chan_usbradio_pvt *o)
2592 const int numSamples = SAMPLES_PER_BLOCK;
2593 const int numChannels = 16;
2604 FILE *hInput = NULL, *hOutput = NULL, *hOutputTx = NULL;
2606 i16 iBuff[numSamples * 2 * 6], oBuff[numSamples];
2608 ast_debug(4, "RxTestIt()\n");
2611 pChan->b.txCapture = 1;
2612 pChan->b.rxCapture = 1;
2616 hInput = fopen("/usr/src/xpmr/testdata/rx_in.pcm", "r");
2618 ast_debug(4, " RxTestIt() File Not Found.\n");
2621 hOutput = fopen("/usr/src/xpmr/testdata/rx_debug.pcm", "w");
2623 ast_debug(4, " RxTestIt() Working...\n");
2625 while (!feof(hInput)) {
2626 fread((void *)iBuff, 2, numSamples * 2 * 6, hInput);
2629 txHangTime -= numSamples;
2633 if (pChan->rxCtcss->decode)
2634 txHangTime = (8000 / 1000 * 2000);
2636 if (pChan->rxCtcss->decode && !txEnable) {
2638 /* pChan->inputBlanking = (8000 / 1000 * 200); */
2639 } else if (!pChan->rxCtcss->decode && txEnable) {
2643 PmrRx(pChan, iBuff, oBuff);
2645 fwrite((void *)pChan->prxDebug, 2, numSamples * numChannels, hOutput);
2647 pChan->b.txCapture = 0;
2648 pChan->b.rxCapture = 0;
2655 ast_debug(4, " RxTestIt() Complete.\n");
2661 #include "./xpmr/xpmr.c"
2664 static int load_module(void)
2666 struct ast_config *cfg = NULL;
2668 struct ast_flags config_flags = { 0 };
2670 /* Copy the default jb config over global_jbconf */
2671 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
2673 /* load config file */
2674 if (!(cfg = ast_config_load(config, config_flags))) {
2675 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
2676 return AST_MODULE_LOAD_DECLINE;
2680 store_config(cfg, ctg);
2681 } while ( (ctg = ast_category_browse(cfg, ctg)) != NULL);
2683 ast_config_destroy(cfg);
2685 if (find_desc(usbradio_active) == NULL) {
2686 ast_log(LOG_NOTICE, "Device %s not found\n", usbradio_active);
2687 /* XXX we could default to 'dsp' perhaps ? */
2688 /* XXX should cleanup allocated memory etc. */
2689 return AST_MODULE_LOAD_FAILURE;
2692 if (ast_channel_register(&usbradio_tech)) {
2693 ast_log(LOG_ERROR, "Unable to register channel type 'usb'\n");
2694 return AST_MODULE_LOAD_FAILURE;
2697 ast_cli_register_multiple(cli_usbradio, sizeof(cli_usbradio) / sizeof(struct ast_cli_entry));
2699 return AST_MODULE_LOAD_SUCCESS;
2703 static int unload_module(void)
2705 struct chan_usbradio_pvt *o;
2707 ast_log(LOG_WARNING, "unload_module() called\n");
2709 ast_channel_unregister(&usbradio_tech);
2710 ast_cli_unregister_multiple(cli_usbradio, sizeof(cli_usbradio) / sizeof(struct ast_cli_entry));
2712 for (o = usbradio_default.next; o; o = o->next) {
2714 ast_log(LOG_WARNING, "destroyPmrChannel() called\n");
2716 destroyPmrChannel(o->pmrChan);
2718 #if DEBUG_CAPTURES == 1
2719 if (frxcapraw) { fclose(frxcapraw); frxcapraw = NULL; }
2720 if (frxcaptrace) { fclose(frxcaptrace); frxcaptrace = NULL; }
2721 if (frxoutraw) { fclose(frxoutraw); frxoutraw = NULL; }
2722 if (ftxcapraw) { fclose(ftxcapraw); ftxcapraw = NULL; }
2723 if (ftxcaptrace) { fclose(ftxcaptrace); ftxcaptrace = NULL; }
2724 if (ftxoutraw) { fclose(ftxoutraw); ftxoutraw = NULL; }
2728 if (o->sndcmd[0] > 0) {
2729 close(o->sndcmd[0]);
2730 close(o->sndcmd[1]);
2733 ast_dsp_free(o->dsp);
2735 ast_softhangup(o->owner, AST_SOFTHANGUP_APPUNLOAD);
2736 if (o->owner) /* XXX how ??? */
2738 /* XXX what about the thread ? */
2739 /* XXX what about the memory allocated ? */
2744 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "usb Console Channel Driver");