48024f7adb60d10df3a6f66f4aaf8f4bcd8e8a8e
[asterisk/asterisk.git] / channels / chan_usbradio.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  * Copyright (C) 2007, Jim Dixon
6  *
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
10  *
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.
16  *
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.
20  */
21
22 /*! \file
23  *
24  * \brief Channel driver for CM108 USB Cards with Radio Interface
25  *
26  * \author Jim Dixon  <jim@lambdatel.com>
27  * \author Steve Henke  <w9sh@arrl.net>
28  *
29  * \par See also
30  * \arg \ref Config_usbradio
31  *
32  * \ingroup channel_drivers
33  */
34
35 /*** MODULEINFO
36         <depend>asound</depend>
37         <depend>usb</depend>
38         <defaultenabled>no</defaultenabled>
39  ***/
40
41 #include "asterisk.h"
42
43 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
44
45 #include <ctype.h>
46 #include <math.h>
47 #include <sys/ioctl.h>
48 #include <fcntl.h>
49 #include <sys/time.h>
50 #include <usb.h>
51 #include <alsa/asoundlib.h>
52
53 #define CHAN_USBRADIO           1
54
55 #define DEBUG_USBRADIO          0       
56 #define DEBUG_CAPTURES                  1
57                 
58 #define DEBUG_CAP_RX_OUT                0               
59 #define DEBUG_CAP_TX_OUT            0                   
60
61 #define DEBUG_FILETEST                  0                        
62
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"
66
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"
70
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"
78
79 #include "./xpmr/xpmr.h"
80
81 #if 0
82 #define traceusb1(a) {printf a;}
83 #else
84 #define traceusb1(a)
85 #endif
86
87 #if 0
88 #define traceusb2(a) {printf a;}
89 #else
90 #define traceusb2(a)
91 #endif
92
93 #ifdef __linux
94 #include <linux/soundcard.h>
95 #elif defined(__FreeBSD__)
96 #include <sys/soundcard.h>
97 #else
98 #include <soundcard.h>
99 #endif
100
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"
116
117 /* ringtones we use */
118 #include "busy.h"
119 #include "ringtone.h"
120 #include "ring10.h"
121 #include "answer.h"
122
123 #define C108_VENDOR_ID          0x0d8c
124 #define C108_PRODUCT_ID         0x000c
125 #define C108_HID_INTERFACE      3
126
127 #define HID_REPORT_GET          0x01
128 #define HID_REPORT_SET          0x09
129
130 #define HID_RT_INPUT            0x01
131 #define HID_RT_OUTPUT           0x02
132
133 /*! Global jitterbuffer configuration - by default, jb is disabled */
134 static struct ast_jb_conf default_jbconf =
135 {
136         .flags = 0,
137         .max_size = -1,
138         .resync_threshold = -1,
139         .impl = "",
140 };
141 static struct ast_jb_conf global_jbconf;
142
143 /*! 
144  * usbradio.conf parameters are
145 START_CONFIG
146
147 [general]
148     ; General config options, with default values shown.
149     ; You should use one section per device, with [general] being used
150     ; for the device.
151     ;
152     ;
153     ; debug = 0x0               ; misc debug flags, default is 0
154
155         ; Set the device to use for I/O
156         ; devicenum = 0
157         ; Set hardware type here
158         ; hdwtype=0               ; 0=limey, 1=sph
159
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
164
165         ; carrierfrom=dsp     ;no,usb,usbinvert,dsp,vox
166         ; ctcssfrom=dsp       ;no,usb,dsp
167
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
171
172         ; txmixa=composite        ;no,voice,tone,composite,auxvoice
173         ; txmixb=no               ;no,voice,tone,composite,auxvoice
174
175         ; invertptt=0
176
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.
184
185     ; jbmaxsize = 200             ; Max length of the jitterbuffer in milliseconds.
186
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.
191
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.
196
197     ; jblog = no                  ; Enables jitterbuffer frame logging. Defaults to "no".
198     ;-----------------------------------------------------------------------------------
199
200
201 END_CONFIG
202
203  */
204
205 /*! \brief
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:
211  *
212  *      {
213  *              M_START(v->name, v->value) 
214  *
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
220  *      }
221  *
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.
224  */
225 #define M_START(var, val) \
226         const char *__s = var; const char *__val = val;
227 #define M_END(x)   x;
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)))
232
233 /*!
234  * The following parameters are used in the driver:
235  *
236  *  FRAME_SIZE  the size of an audio frame, in samples.
237  *              160 is used almost universally, so you should not change it.
238  *
239  *  FRAGS       the argument for the SETFRAGMENT ioctl.
240  *              Overridden by the 'frags' parameter in usbradio.conf
241  *
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.
254  *
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
258  *
259  *              Should be >=2, and at most as large as the hw queue above
260  *              (otherwise it will never be full).
261  */
262
263 #define FRAME_SIZE      160
264 #define QUEUE_SIZE      20
265
266 #if defined(__FreeBSD__)
267 #define FRAGS   0x8
268 #else
269 #define FRAGS   ( ( (6 * 5) << 16 ) | 0xc )
270 #endif
271
272 /*
273  * XXX text message sizes are probably 256 chars, but i am
274  * not sure if there is a suitable definition anywhere.
275  */
276 #define TEXT_SIZE       256
277
278 #if 0
279 #define TRYOPEN 1                               /* try to open on startup */
280 #endif
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"
285 #else
286 #define DEV_DSP "/dev/dsp"
287 #endif
288
289 #ifndef MIN
290 #define MIN(a,b) ((a) < (b) ? (a) : (b))
291 #endif
292 #ifndef MAX
293 #define MAX(a,b) ((a) > (b) ? (a) : (b))
294 #endif
295
296 static char *config = "usbradio.conf";  /* default config file */
297 static char *config1 = "usbradio_tune.conf";    /* tune config file */
298
299 static FILE *frxcapraw = NULL, *frxcaptrace = NULL, *frxoutraw = NULL;
300 static FILE *ftxcapraw = NULL, *ftxcaptrace = NULL, *ftxoutraw = NULL;
301
302 static int usbradio_debug;
303 #if 0 //maw asdf sph
304 static int usbradio_debug_level = 0;
305 #endif
306
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};
313
314 /*      DECLARE STRUCTURES */
315
316 /*
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.
320  */
321 struct sound {
322         int ind;
323         char *desc;
324         short *data;
325         int datalen;
326         int samplen;
327         int silencelen;
328         int repeat;
329 };
330
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 */
338 };
339
340
341 /*
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).
347  */
348 struct chan_usbradio_pvt {
349         struct chan_usbradio_pvt *next;
350
351         char *name;
352         /*
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.).
358          */
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 */
363
364         int total_blocks;                       /* total blocks in the output device */
365         int sounddev;
366         enum { M_UNSET, M_FULL, M_READ, M_WRITE } duplex;
367         i16 cdMethod;
368         int autoanswer;
369         int autohangup;
370         int hookstate;
371         unsigned int queuesize;         /* max fragments in queue */
372         unsigned int frags;                     /* parameter for SETFRAGMENT */
373
374         int warned;                                     /* various flags used for warnings */
375 #define WARN_used_blocks        1
376 #define WARN_speed              2
377 #define WARN_frag               4
378         int w_errors;                           /* overfull in the write path */
379         struct timeval lastopen;
380
381         int overridecontext;
382         int mute;
383
384         /* boost support. BOOST_SCALE * 10 ^(BOOST_MAX/20) must
385          * be representable in 16 bits to avoid overflows.
386          */
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 */
390         char devicenum;
391         int spkrmax;
392         int micmax;
393
394         pthread_t sthread;
395         pthread_t hidthread;
396
397         int stophid;
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];
405
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];
409
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
413          */
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 */
418         
419
420         char debuglevel;
421         char radioduplex;                       
422
423         char lastrx;
424         char rxhidsq;
425         char rxcarrierdetect;           /*!< status from pmr channel */
426         char rxctcssdecode;                     /*!< status from pmr channel */
427
428         char rxkeytype;
429         char rxkeyed;                           /*!< indicates rx signal present */
430
431         char lasttx;
432         char txkeyed;                           /*! tx key request from upper layers  */
433         char txchankey;
434         char txtestkey;
435
436         time_t lasthidtime;
437     struct ast_dsp *dsp;
438
439         t_pmr_chan      *pmrChan;
440
441         char    rxcpusaver;
442         char    txcpusaver;
443
444         char    rxdemod;
445         float   rxgain;
446         char    rxcdtype;
447         char    rxsdtype;
448         int     rxsquelchadj;   /*!< this copy needs to be here for initialization */
449         char    txtoctype;
450
451         char    txprelim;
452         float   txctcssgain;
453         char    txmixa;
454         char    txmixb;
455
456         char    invertptt;
457
458         char    rxctcssrelax;
459         float   rxctcssgain;
460         float   rxctcssfreq;
461         float   txctcssfreq;
462
463         int     rxmixerset;             
464         int     rxboostset;
465         float   rxvoiceadj;
466         float   rxctcssadj;
467         int     txmixaset;
468         int     txmixbset;
469         int     txctcssadj;
470
471         int     hdwtype;
472         int     hid_gpio_ctl;           
473         int     hid_gpio_ctl_loc;       
474         int     hid_io_cor;             
475         int     hid_io_cor_loc;         
476         int     hid_io_ctcss;           
477         int     hid_io_ctcss_loc;       
478         int     hid_io_ptt;             
479         int     hid_gpio_loc;           
480
481         struct {
482                 unsigned rxcapraw:1;
483                 unsigned txcapraw:1;
484                 unsigned txcap2:1;
485                 unsigned rxcap2:1;
486         }b;
487 };
488
489 /* maw add additional defaults !!! */
490 static struct chan_usbradio_pvt usbradio_default = {
491         .cursound = -1,
492         .sounddev = -1,
493         .duplex = M_UNSET,                      /* XXX check this */
494         .autoanswer = 1,
495         .autohangup = 1,
496         .queuesize = QUEUE_SIZE,
497         .frags = FRAGS,
498         .ext = "s",
499         .ctx = "default",
500         .readpos = AST_FRIENDLY_OFFSET, /* start here on reads */
501         .lastopen = { 0, 0 },
502         .boost = BOOST_SCALE,
503 };
504
505 /*      DECLARE FUNCTION PROTOTYPES     */
506
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);
519
520 static char *usbradio_active;    /* the active device */
521
522 static int setformat(struct chan_usbradio_pvt *o, int mode);
523
524 static struct ast_channel *usbradio_request(const char *type, int format, void *data
525 , int *cause);
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);
536
537 #if     DEBUG_FILETEST == 1
538 static int RxTestIt(struct chan_usbradio_pvt *o);
539 #endif
540
541 static char tdesc[] = "USB (CM108) Radio Channel Driver";
542
543 static const struct ast_channel_tech usbradio_tech = {
544         .type = "Radio",
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,
558 };
559
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.
563
564 Note: must add -lasound to end of linkage */
565
566 static int amixer_max(int devnum,char *param)
567 {
568         int     rv,type;
569         char    str[100];
570         snd_hctl_t *hctl;
571         snd_ctl_elem_id_t *id;
572         snd_hctl_elem_t *elem;
573         snd_ctl_elem_info_t *info;
574
575         sprintf(str,"hw:%d",devnum);
576         if (snd_hctl_open(&hctl, str, 0))
577                 return(-1);
578         snd_hctl_load(hctl);
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);
584         if (!elem) {
585                 snd_hctl_close(hctl);
586                 return(-1);
587         }
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);
592         rv = 0;
593         switch(type) {
594             case SND_CTL_ELEM_TYPE_INTEGER:
595                 rv = snd_ctl_elem_info_get_max(info);
596                 break;
597             case SND_CTL_ELEM_TYPE_BOOLEAN:
598                 rv = 1;
599                 break;
600         }
601         snd_hctl_close(hctl);
602         return(rv);
603 }
604
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.
608
609 Note: must add -lasound to end of linkage */
610
611 static int setamixer(int devnum,char *param, int v1, int v2)
612 {
613         int     type;
614         char    str[100];
615         snd_hctl_t *hctl;
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;
620
621         sprintf(str,"hw:%d",devnum);
622         if (snd_hctl_open(&hctl, str, 0))
623                 return(-1);
624         snd_hctl_load(hctl);
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);
630         if (!elem) {
631                 snd_hctl_close(hctl);
632                 return(-1);
633         }
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);    
641         switch(type) {
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);
645                 break;
646             case SND_CTL_ELEM_TYPE_BOOLEAN:
647                 snd_ctl_elem_value_set_integer(control, 0, (v1 != 0));
648                 break;
649         }
650         if (snd_hctl_elem_write(elem, control)) {
651                 snd_hctl_close(hctl);
652                 return(-1);
653         }
654         snd_hctl_close(hctl);
655         return(0);
656 }
657
658 static void hid_set_outputs(struct usb_dev_handle *handle,
659          unsigned char *outputs)
660 {
661         usb_control_msg(handle,
662               USB_ENDPOINT_OUT + USB_TYPE_CLASS + USB_RECIP_INTERFACE,
663               HID_REPORT_SET,
664               0 + (HID_RT_OUTPUT << 8),
665               C108_HID_INTERFACE,
666               (char*)outputs, 4, 5000);
667 }
668
669 static void hid_get_inputs(struct usb_dev_handle *handle,
670          unsigned char *inputs)
671 {
672         usb_control_msg(handle,
673               USB_ENDPOINT_IN + USB_TYPE_CLASS + USB_RECIP_INTERFACE,
674               HID_REPORT_GET,
675               0 + (HID_RT_INPUT << 8),
676               C108_HID_INTERFACE,
677               (char*)inputs, 4, 5000);
678 }
679
680 static struct usb_device *hid_device_init(void)
681 {
682         struct usb_bus *usb_bus;
683         struct usb_device *dev;
684
685         usb_init();
686         usb_find_busses();
687         usb_find_devices();
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))
691                                 return dev;
692                 }
693         }
694         return NULL;
695 }
696
697 static int hidhdwconfig(struct chan_usbradio_pvt *o)
698 {
699         if(o->hdwtype==1)         /*sphusb */
700         {
701                 o->hid_gpio_ctl         =  0x08;        /* set GPIO4 to output mode */
702                 o->hid_gpio_ctl_loc     =  2;   /* For CTL of GPIO */
703                 o->hid_io_cor           =  4;   /* GPIO3 is COR */
704                 o->hid_io_cor_loc       =  1;   /* GPIO3 is COR */
705                 o->hid_io_ctcss         =  2;   /* GPIO 2 is External CTCSS */
706                 o->hid_io_ctcss_loc =  1;       /* is GPIO 2 */
707                 o->hid_io_ptt           =  8;   /* GPIO 4 is PTT */
708                 o->hid_gpio_loc         =  1;   /* For ALL GPIO */
709         }
710         else if(o->hdwtype==0)  /* dudeusb */
711         {
712                 o->hid_gpio_ctl         =  0x0c;        /* set GPIO 3 & 4 to output mode */
713                 o->hid_gpio_ctl_loc     =  2;   /* For CTL of GPIO */
714                 o->hid_io_cor           =  2;   /* VOLD DN is COR */
715                 o->hid_io_cor_loc       =  0;   /* VOL DN COR */
716                 o->hid_io_ctcss         =  2;   /* GPIO 2 is External CTCSS */
717                 o->hid_io_ctcss_loc =  1;       /* is GPIO 2 */
718                 o->hid_io_ptt           =  4;   /* GPIO 3 is PTT */
719                 o->hid_gpio_loc         =  1;   /* For ALL GPIO */
720         }
721         else if(o->hdwtype==3)  /* custom version */
722         {
723                 o->hid_gpio_ctl         =  0x0c;        /* set GPIO 3 & 4 to output mode */
724                 o->hid_gpio_ctl_loc     =  2;   /* For CTL of GPIO */
725                 o->hid_io_cor           =  2;   /* VOLD DN is COR */
726                 o->hid_io_cor_loc       =  0;   /* VOL DN COR */
727                 o->hid_io_ctcss         =  2;   /* GPIO 2 is External CTCSS */
728                 o->hid_io_ctcss_loc =  1;       /* is GPIO 2 */
729                 o->hid_io_ptt           =  4;   /* GPIO 3 is PTT */
730                 o->hid_gpio_loc         =  1;   /* For ALL GPIO */
731         }
732
733         return 0;
734 }
735
736
737 static void *hidthread(void *arg)
738 {
739         unsigned char buf[4],keyed;
740         char lastrx, txtmp;
741         struct usb_device *usb_dev;
742         struct usb_dev_handle *usb_handle;
743         struct chan_usbradio_pvt *o = (struct chan_usbradio_pvt *) arg;
744
745         usb_dev = hid_device_init();
746         if (usb_dev == NULL) {
747                 ast_log(LOG_ERROR,"USB HID device not found\n");
748                 pthread_exit(NULL);
749         }
750         usb_handle = usb_open(usb_dev);
751         if (usb_handle == NULL) {
752                 ast_log(LOG_ERROR,"Not able to open USB device\n");
753                 pthread_exit(NULL);
754         }
755         if (usb_claim_interface(usb_handle,C108_HID_INTERFACE) < 0) {
756                 if (usb_detach_kernel_driver_np(usb_handle,C108_HID_INTERFACE) < 0) {
757                         ast_log(LOG_ERROR,"Not able to detach the USB device\n");
758                         pthread_exit(NULL);
759                 }
760                 if (usb_claim_interface(usb_handle,C108_HID_INTERFACE) < 0) {
761                         ast_log(LOG_ERROR,"Not able to claim the USB device\n");
762                         pthread_exit(NULL);
763                 }
764         }
765         memset(buf,0,sizeof(buf));
766         buf[2] = o->hid_gpio_ctl;
767         buf[1] = 0;
768         hid_set_outputs(usb_handle,buf);
769         traceusb1(("hidthread: Starting normally!!\n"));
770         lastrx = 0;
771         while(!o->stophid) {
772                 buf[o->hid_gpio_ctl_loc] = o->hid_gpio_ctl;
773                 hid_get_inputs(usb_handle,buf);
774                 keyed = !(buf[o->hid_io_cor_loc] & o->hid_io_cor);
775                 if (keyed != o->rxhidsq) {
776                         if(o->debuglevel)
777                                 printf("chan_usbradio() hidthread: update rxhidsq = %d\n", keyed);
778                         o->rxhidsq=keyed;                
779                 }
780
781                 /* if change in tx stuff */
782                 txtmp=0;
783                 if(o->txkeyed || o->txchankey || o->txtestkey || o->pmrChan->txPttOut)
784                         txtmp=1;
785                 
786                 if (o->lasttx != txtmp) {
787                         o->lasttx = txtmp;
788                         if(o->debuglevel)
789                                 printf("hidthread: tx set to %d\n", txtmp);
790                         buf[o->hid_gpio_loc] = 0;
791                         if (txtmp) buf[o->hid_gpio_loc] = o->hid_io_ptt;
792                         buf[o->hid_gpio_ctl_loc] = o->hid_gpio_ctl;
793                         hid_set_outputs(usb_handle,buf);
794                 }
795
796                 time(&o->lasthidtime);
797                 usleep(50000);
798         }
799         buf[o->hid_gpio_loc] = 0;
800         if (o->invertptt) buf[o->hid_gpio_loc] = o->hid_io_ptt;
801         buf[o->hid_gpio_ctl_loc] = o->hid_gpio_ctl;
802         hid_set_outputs(usb_handle,buf);
803         pthread_exit(0);
804 }
805
806 /*! \brief
807  * returns a pointer to the descriptor with the given name
808  */
809 static struct chan_usbradio_pvt *find_desc(char *dev)
810 {
811         struct chan_usbradio_pvt *o = NULL;
812
813         if (!dev)
814                 ast_log(LOG_WARNING, "null dev\n");
815
816         for (o = usbradio_default.next; o && o->name && dev && strcmp(o->name, dev) != 0; o = o->next);
817
818         if (!o)
819                 ast_log(LOG_WARNING, "could not find <%s>\n", dev ? dev : "--no-device--");
820
821         return o;
822 }
823
824 /*! \brief
825  * split a string in extension-context, returns pointers to malloc'ed
826  * strings.
827  * If we do not have 'overridecontext' then the last @ is considered as
828  * a context separator, and the context is overridden.
829  * This is usually not very necessary as you can play with the dialplan,
830  * and it is nice not to need it because you have '@' in SIP addresses.
831  * Return value is the buffer address.
832  */
833 #if     0
834 static char *ast_ext_ctx(const char *src, char **ext, char **ctx)
835 {
836         struct chan_usbradio_pvt *o = find_desc(usbradio_active);
837
838         if (ext == NULL || ctx == NULL)
839                 return NULL;                    /* error */
840
841         *ext = *ctx = NULL;
842
843         if (src && *src != '\0')
844                 *ext = ast_strdup(src);
845
846         if (*ext == NULL)
847                 return NULL;
848
849         if (!o->overridecontext) {
850                 /* parse from the right */
851                 *ctx = strrchr(*ext, '@');
852                 if (*ctx)
853                         *(*ctx)++ = '\0';
854         }
855
856         return *ext;
857 }
858 #endif
859
860 /*! \brief
861  * Returns the number of blocks used in the audio output channel
862  */
863 static int used_blocks(struct chan_usbradio_pvt *o)
864 {
865         struct audio_buf_info info;
866
867         if (ioctl(o->sounddev, SNDCTL_DSP_GETOSPACE, &info)) {
868                 if (!(o->warned & WARN_used_blocks)) {
869                         ast_log(LOG_WARNING, "Error reading output space\n");
870                         o->warned |= WARN_used_blocks;
871                 }
872                 return 1;
873         }
874
875         if (o->total_blocks == 0) {
876                 if (0)                                  /* debugging */
877                         ast_log(LOG_WARNING, "fragtotal %d size %d avail %d\n", info.fragstotal, info.fragsize, info.fragments);
878                 o->total_blocks = info.fragments;
879         }
880
881         return o->total_blocks - info.fragments;
882 }
883
884 /*! \brief Write an exactly FRAME_SIZE sized frame */
885 static int soundcard_writeframe(struct chan_usbradio_pvt *o, short *data)
886 {
887         int res;
888
889         if (o->sounddev < 0)
890                 setformat(o, O_RDWR);
891         if (o->sounddev < 0)
892                 return 0;                               /* not fatal */
893         /*
894          * Nothing complex to manage the audio device queue.
895          * If the buffer is full just drop the extra, otherwise write.
896          * XXX in some cases it might be useful to write anyways after
897          * a number of failures, to restart the output chain.
898          */
899         res = used_blocks(o);
900         if (res > o->queuesize) {       /* no room to write a block */
901                 if (o->w_errors++ == 0 && (usbradio_debug & 0x4))
902                         ast_log(LOG_WARNING, "write: used %d blocks (%d)\n", res, o->w_errors);
903                 return 0;
904         }
905         o->w_errors = 0;
906
907         return write(o->sounddev, ((void *) data), FRAME_SIZE * 2 * 12);
908 }
909
910 /*! \brief
911  * Handler for 'sound writable' events from the sound thread.
912  * Builds a frame from the high level description of the sounds,
913  * and passes it to the audio device.
914  * The actual sound is made of 1 or more sequences of sound samples
915  * (s->datalen, repeated to make s->samplen samples) followed by
916  * s->silencelen samples of silence. The position in the sequence is stored
917  * in o->sampsent, which goes between 0 .. s->samplen+s->silencelen.
918  * In case we fail to write a frame, don't update o->sampsent.
919  */
920 static void send_sound(struct chan_usbradio_pvt *o)
921 {
922         short myframe[FRAME_SIZE];
923         int ofs, l, start;
924         int l_sampsent = o->sampsent;
925         struct sound *s;
926
927         if (o->cursound < 0)            /* no sound to send */
928                 return;
929
930         s = &sounds[o->cursound];
931
932         for (ofs = 0; ofs < FRAME_SIZE; ofs += l) {
933                 l = s->samplen - l_sampsent;    /* # of available samples */
934                 if (l > 0) {
935                         start = l_sampsent % s->datalen;        /* source offset */
936                         if (l > FRAME_SIZE - ofs)       /* don't overflow the frame */
937                                 l = FRAME_SIZE - ofs;
938                         if (l > s->datalen - start)     /* don't overflow the source */
939                                 l = s->datalen - start;
940                         bcopy(s->data + start, myframe + ofs, l * 2);
941                         if (0)
942                                 ast_log(LOG_WARNING, "send_sound sound %d/%d of %d into %d\n", l_sampsent, l, s->samplen, ofs);
943                         l_sampsent += l;
944                 } else {                                /* end of samples, maybe some silence */
945                         static const short silence[FRAME_SIZE] = { 0, };
946
947                         l += s->silencelen;
948                         if (l > 0) {
949                                 if (l > FRAME_SIZE - ofs)
950                                         l = FRAME_SIZE - ofs;
951                                 bcopy(silence, myframe + ofs, l * 2);
952                                 l_sampsent += l;
953                         } else {                        /* silence is over, restart sound if loop */
954                                 if (s->repeat == 0) {   /* last block */
955                                         o->cursound = -1;
956                                         o->nosound = 0; /* allow audio data */
957                                         if (ofs < FRAME_SIZE)   /* pad with silence */
958                                                 bcopy(silence, myframe + ofs, (FRAME_SIZE - ofs) * 2);
959                                 }
960                                 l_sampsent = 0;
961                         }
962                 }
963         }
964         l = soundcard_writeframe(o, myframe);
965         if (l > 0)
966                 o->sampsent = l_sampsent;       /* update status */
967 }
968
969 static void *sound_thread(void *arg)
970 {
971         char ign[4096];
972         struct chan_usbradio_pvt *o = (struct chan_usbradio_pvt *) arg;
973
974         /*
975          * Just in case, kick the driver by trying to read from it.
976          * Ignore errors - this read is almost guaranteed to fail.
977          */
978         read(o->sounddev, ign, sizeof(ign));
979         for (;;) {
980                 fd_set rfds, wfds;
981                 int maxfd, res;
982
983                 FD_ZERO(&rfds);
984                 FD_ZERO(&wfds);
985                 FD_SET(o->sndcmd[0], &rfds);
986                 maxfd = o->sndcmd[0];   /* pipe from the main process */
987                 if (o->cursound > -1 && o->sounddev < 0)
988                         setformat(o, O_RDWR);   /* need the channel, try to reopen */
989                 else if (o->cursound == -1 && o->owner == NULL)
990                 {
991                         setformat(o, O_CLOSE);  /* can close */
992                 }
993                 if (o->sounddev > -1) {
994                         if (!o->owner) {        /* no one owns the audio, so we must drain it */
995                                 FD_SET(o->sounddev, &rfds);
996                                 maxfd = MAX(o->sounddev, maxfd);
997                         }
998                         if (o->cursound > -1) {
999                                 FD_SET(o->sounddev, &wfds);
1000                                 maxfd = MAX(o->sounddev, maxfd);
1001                         }
1002                 }
1003                 /* ast_select emulates linux behaviour in terms of timeout handling */
1004                 res = ast_select(maxfd + 1, &rfds, &wfds, NULL, NULL);
1005                 if (res < 1) {
1006                         ast_log(LOG_WARNING, "select failed: %s\n", strerror(errno));
1007                         sleep(1);
1008                         continue;
1009                 }
1010                 if (FD_ISSET(o->sndcmd[0], &rfds)) {
1011                         /* read which sound to play from the pipe */
1012                         int i, what = -1;
1013
1014                         read(o->sndcmd[0], &what, sizeof(what));
1015                         for (i = 0; sounds[i].ind != -1; i++) {
1016                                 if (sounds[i].ind == what) {
1017                                         o->cursound = i;
1018                                         o->sampsent = 0;
1019                                         o->nosound = 1; /* block audio from pbx */
1020                                         break;
1021                                 }
1022                         }
1023                         if (sounds[i].ind == -1)
1024                                 ast_log(LOG_WARNING, "invalid sound index: %d\n", what);
1025                 }
1026                 if (o->sounddev > -1) {
1027                         if (FD_ISSET(o->sounddev, &rfds))       /* read and ignore errors */
1028                                 read(o->sounddev, ign, sizeof(ign)); 
1029                         if (FD_ISSET(o->sounddev, &wfds))
1030                                 send_sound(o);
1031                 }
1032         }
1033         return NULL;                            /* Never reached */
1034 }
1035
1036 /*
1037  * reset and close the device if opened,
1038  * then open and initialize it in the desired mode,
1039  * trigger reads and writes so we can start using it.
1040  */
1041 static int setformat(struct chan_usbradio_pvt *o, int mode)
1042 {
1043         int fmt, desired, res, fd;
1044         char device[100];
1045
1046         if (o->sounddev >= 0) {
1047                 ioctl(o->sounddev, SNDCTL_DSP_RESET, 0);
1048                 close(o->sounddev);
1049                 o->duplex = M_UNSET;
1050                 o->sounddev = -1;
1051         }
1052         if (mode == O_CLOSE)            /* we are done */
1053                 return 0;
1054         if (ast_tvdiff_ms(ast_tvnow(), o->lastopen) < 1000)
1055                 return -1;                              /* don't open too often */
1056         o->lastopen = ast_tvnow();
1057         strcpy(device,"/dev/dsp");
1058         if (o->devicenum)
1059                 sprintf(device,"/dev/dsp%d",o->devicenum);
1060         fd = o->sounddev = open(device, mode | O_NONBLOCK);
1061         if (fd < 0) {
1062                 ast_log(LOG_WARNING, "Unable to re-open DSP device %d: %s\n", o->devicenum, strerror(errno));
1063                 return -1;
1064         }
1065         if (o->owner)
1066                 o->owner->fds[0] = fd;
1067
1068 #if __BYTE_ORDER == __LITTLE_ENDIAN
1069         fmt = AFMT_S16_LE;
1070 #else
1071         fmt = AFMT_S16_BE;
1072 #endif
1073         res = ioctl(fd, SNDCTL_DSP_SETFMT, &fmt);
1074         if (res < 0) {
1075                 ast_log(LOG_WARNING, "Unable to set format to 16-bit signed\n");
1076                 return -1;
1077         }
1078         switch (mode) {
1079                 case O_RDWR:
1080                         res = ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
1081                         /* Check to see if duplex set (FreeBSD Bug) */
1082                         res = ioctl(fd, SNDCTL_DSP_GETCAPS, &fmt);
1083                         if (res == 0 && (fmt & DSP_CAP_DUPLEX)) {
1084                                 if (option_verbose > 1)
1085                                         ast_verbose(VERBOSE_PREFIX_2 "Console is full duplex\n");
1086                                 o->duplex = M_FULL;
1087                         };
1088                         break;
1089                 case O_WRONLY:
1090                         o->duplex = M_WRITE;
1091                         break;
1092                 case O_RDONLY:
1093                         o->duplex = M_READ;
1094                         break;
1095         }
1096
1097         fmt = 1;
1098         res = ioctl(fd, SNDCTL_DSP_STEREO, &fmt);
1099         if (res < 0) {
1100                 ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
1101                 return -1;
1102         }
1103         fmt = desired = 48000;                                                  /* 8000 Hz desired */
1104         res = ioctl(fd, SNDCTL_DSP_SPEED, &fmt);
1105
1106         if (res < 0) {
1107                 ast_log(LOG_WARNING, "Failed to set audio device to mono\n");
1108                 return -1;
1109         }
1110         if (fmt != desired) {
1111                 if (!(o->warned & WARN_speed)) {
1112                         ast_log(LOG_WARNING,
1113                             "Requested %d Hz, got %d Hz -- sound may be choppy\n",
1114                             desired, fmt);
1115                         o->warned |= WARN_speed;
1116                 }
1117         }
1118         /*
1119          * on Freebsd, SETFRAGMENT does not work very well on some cards.
1120          * Default to use 256 bytes, let the user override
1121          */
1122         if (o->frags) {
1123                 fmt = o->frags;
1124                 res = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &fmt);
1125                 if (res < 0) {
1126                         if (!(o->warned & WARN_frag)) {
1127                                 ast_log(LOG_WARNING,
1128                                         "Unable to set fragment size -- sound may be choppy\n");
1129                                 o->warned |= WARN_frag;
1130                         }
1131                 }
1132         }
1133         /* on some cards, we need SNDCTL_DSP_SETTRIGGER to start outputting */
1134         res = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;
1135         res = ioctl(fd, SNDCTL_DSP_SETTRIGGER, &res);
1136         /* it may fail if we are in half duplex, never mind */
1137         return 0;
1138 }
1139
1140 /*
1141  * some of the standard methods supported by channels.
1142  */
1143 static int usbradio_digit_begin(struct ast_channel *c, char digit)
1144 {
1145         return 0;
1146 }
1147
1148 static int usbradio_digit_end(struct ast_channel *c, char digit, unsigned int duration)
1149 {
1150         /* no better use for received digits than print them */
1151         ast_verbose(" << Console Received digit %c of duration %u ms >> \n", 
1152                 digit, duration);
1153         return 0;
1154 }
1155
1156 static int usbradio_text(struct ast_channel *c, const char *text)
1157 {
1158         /* print received messages */
1159         ast_verbose(" << Console Received text %s >> \n", text);
1160         return 0;
1161 }
1162
1163 /* Play ringtone 'x' on device 'o' */
1164 static void ring(struct chan_usbradio_pvt *o, int x)
1165 {
1166         write(o->sndcmd[1], &x, sizeof(x));
1167 }
1168
1169 /*
1170  * handler for incoming calls. Either autoanswer, or start ringing
1171  */
1172 static int usbradio_call(struct ast_channel *c, char *dest, int timeout)
1173 {
1174         struct chan_usbradio_pvt *o = c->tech_pvt;
1175
1176         time(&o->lasthidtime);
1177         ast_pthread_create_background(&o->hidthread, NULL, hidthread, o);
1178         ast_setstate(c, AST_STATE_UP);
1179         return 0;
1180 }
1181
1182 /*
1183  * remote side answered the phone
1184  */
1185 static int usbradio_answer(struct ast_channel *c)
1186 {
1187         struct chan_usbradio_pvt *o = c->tech_pvt;
1188
1189         ast_setstate(c, AST_STATE_UP);
1190         o->cursound = -1;
1191         o->nosound = 0;
1192         return 0;
1193 }
1194
1195 static int usbradio_hangup(struct ast_channel *c)
1196 {
1197         struct chan_usbradio_pvt *o = c->tech_pvt;
1198
1199         o->cursound = -1;
1200         o->nosound = 0;
1201         c->tech_pvt = NULL;
1202         o->owner = NULL;
1203         ast_module_unref(ast_module_info->self);
1204         if (o->hookstate) {
1205                 if (o->autoanswer || o->autohangup) {
1206                         /* Assume auto-hangup too */
1207                         o->hookstate = 0;
1208                         setformat(o, O_CLOSE);
1209                 } else {
1210                         /* Make congestion noise */
1211                         ring(o, AST_CONTROL_CONGESTION);
1212                 }
1213         }
1214         o->stophid = 1;
1215         pthread_join(o->hidthread,NULL);
1216         return 0;
1217 }
1218
1219
1220 /* used for data coming from the network */
1221 static int usbradio_write(struct ast_channel *c, struct ast_frame *f)
1222 {
1223         int src,datalen;
1224         struct chan_usbradio_pvt *o = c->tech_pvt;
1225
1226         traceusb2(("usbradio_write() o->nosound= %i\n",o->nosound));    /*sph maw asdf */
1227
1228         /* Immediately return if no sound is enabled */
1229         if (o->nosound)
1230                 return 0;
1231         /* Stop any currently playing sound */
1232         o->cursound = -1;
1233         /*
1234          * we could receive a block which is not a multiple of our
1235          * FRAME_SIZE, so buffer it locally and write to the device
1236          * in FRAME_SIZE chunks.
1237          * Keep the residue stored for future use.
1238          */
1239
1240         if(o->txkeyed||o->txtestkey)o->pmrChan->txPttIn=1;
1241         else o->pmrChan->txPttIn=0;
1242
1243         #if DEBUG_CAPTURES == 1 /* to write input data to a file   datalen=320 */
1244         if (ftxcapraw && o->b.txcapraw) {
1245                 i16 i, tbuff[f->datalen];
1246                 for(i=0;i<f->datalen;i+=2) {
1247                         tbuff[i]= ((i16*)(f->data))[i/2];
1248                         tbuff[i+1]= o->txkeyed*M_Q13;
1249                 }
1250                 fwrite(tbuff,2,f->datalen,ftxcapraw);
1251                 /*fwrite(f->data,1,f->datalen,ftxcapraw); */
1252         }
1253         #endif
1254
1255         PmrTx(o->pmrChan,(i16*)f->data,(i16*)o->usbradio_write_buf_1);
1256
1257         #if 0   // to write 48KS/s stereo data to a file
1258         if (!ftxoutraw) ftxoutraw = fopen(TX_CAP_OUT_FILE,"w");
1259         if (ftxoutraw) fwrite(o->usbradio_write_buf_1,1,f->datalen * 2 * 6,ftxoutraw);
1260         #endif
1261
1262         #if DEBUG_CAPTURES == 1
1263     if (o->b.txcap2 && ftxcaptrace) fwrite((o->pmrChan->ptxDebug),1,FRAME_SIZE * 2 * 16,ftxcaptrace);
1264         #endif
1265
1266         src = 0;                                        /* read position into f->data */
1267         datalen = f->datalen * 12;
1268         while (src < datalen) {
1269                 /* Compute spare room in the buffer */
1270                 int l = sizeof(o->usbradio_write_buf) - o->usbradio_write_dst;
1271
1272                 if (datalen - src >= l) {       /* enough to fill a frame */
1273                         memcpy(o->usbradio_write_buf + o->usbradio_write_dst, o->usbradio_write_buf_1 + src, l);
1274                         soundcard_writeframe(o, (short *) o->usbradio_write_buf);
1275                         src += l;
1276                         o->usbradio_write_dst = 0;
1277                 } else {                                /* copy residue */
1278                         l = datalen - src;
1279                         memcpy(o->usbradio_write_buf + o->usbradio_write_dst, o->usbradio_write_buf_1 + src, l);
1280                         src += l;                       /* but really, we are done */
1281                         o->usbradio_write_dst += l;
1282                 }
1283         }
1284         return 0;
1285 }
1286
1287 static struct ast_frame *usbradio_read(struct ast_channel *c)
1288 {
1289         int res;
1290         struct chan_usbradio_pvt *o = c->tech_pvt;
1291         struct ast_frame *f = &o->read_f,*f1;
1292         struct ast_frame wf = { AST_FRAME_CONTROL };
1293         time_t now;
1294
1295         traceusb2(("usbradio_read()\n"));       //sph maw asdf
1296
1297         if (o->lasthidtime)
1298         {
1299                 time(&now);
1300                 if ((now - o->lasthidtime) > 3)
1301                 {
1302                         ast_log(LOG_ERROR,"HID process has died or something!!\n");
1303                         return NULL;
1304                 }
1305         }
1306         if (o->lastrx && (!o->rxkeyed))
1307         {
1308                 o->lastrx = 0;
1309                 wf.subclass = AST_CONTROL_RADIO_UNKEY;
1310                 ast_queue_frame(o->owner, &wf);
1311         } else if ((!o->lastrx) && (o->rxkeyed))
1312         {
1313                 o->lastrx = 1;
1314                 wf.subclass = AST_CONTROL_RADIO_KEY;
1315                 ast_queue_frame(o->owner, &wf);
1316         }
1317         /* XXX can be simplified returning &ast_null_frame */
1318         /* prepare a NULL frame in case we don't have enough data to return */
1319         bzero(f, sizeof(struct ast_frame));
1320         f->frametype = AST_FRAME_NULL;
1321         f->src = usbradio_tech.type;
1322
1323         res = read(o->sounddev, o->usbradio_read_buf + o->readpos, 
1324                 sizeof(o->usbradio_read_buf) - o->readpos);
1325         if (res < 0)                            /* audio data not ready, return a NULL frame */
1326                 return f;
1327
1328         o->readpos += res;
1329         if (o->readpos < sizeof(o->usbradio_read_buf))  /* not enough samples */
1330                 return f;
1331
1332         if (o->mute)
1333                 return f;
1334
1335         #if DEBUG_CAPTURES == 1
1336         if (o->b.rxcapraw && frxcapraw) fwrite((o->usbradio_read_buf + AST_FRIENDLY_OFFSET),1,FRAME_SIZE * 2 * 2 * 6,frxcapraw);
1337         #endif
1338
1339         #if 1
1340         PmrRx(         o->pmrChan, 
1341                    (i16 *)(o->usbradio_read_buf + AST_FRIENDLY_OFFSET),
1342                    (i16 *)(o->usbradio_read_buf_8k + AST_FRIENDLY_OFFSET));
1343
1344         #else
1345         static FILE *hInput;
1346         i16 iBuff[FRAME_SIZE*2*6];
1347
1348         o->pmrChan->b.rxCapture=1;
1349
1350         if(!hInput)
1351         {
1352                 hInput  = fopen("/usr/src/xpmr/testdata/rx_in.pcm","r");
1353                 if(!hInput)
1354                 {
1355                         printf(" Input Data File Not Found.\n");
1356                         return 0;
1357                 }
1358         }
1359
1360         if(0==fread((void *)iBuff,2,FRAME_SIZE*2*6,hInput))exit;
1361
1362         PmrRx(         o->pmrChan, 
1363                    (i16 *)iBuff,
1364                    (i16 *)(o->usbradio_read_buf_8k + AST_FRIENDLY_OFFSET));
1365
1366         #endif
1367
1368         #if 0
1369         if (!frxoutraw) frxoutraw = fopen(RX_CAP_OUT_FILE,"w");
1370     if (frxoutraw) fwrite((o->usbradio_read_buf_8k + AST_FRIENDLY_OFFSET),1,FRAME_SIZE * 2,frxoutraw);
1371         #endif
1372
1373         #if DEBUG_CAPTURES == 1
1374     if (frxcaptrace && o->b.rxcap2) fwrite((o->pmrChan->prxDebug),1,FRAME_SIZE * 2 * 16,frxcaptrace);
1375         #endif
1376
1377         if(o->rxcdtype==CD_HID && (o->pmrChan->rxExtCarrierDetect!=o->rxhidsq))
1378                 o->pmrChan->rxExtCarrierDetect=o->rxhidsq;
1379         if(o->rxcdtype==CD_HID_INVERT && (o->pmrChan->rxExtCarrierDetect==o->rxhidsq))
1380                 o->pmrChan->rxExtCarrierDetect=!o->rxhidsq;
1381                 
1382         if( (o->rxcdtype==CD_HID && o->rxhidsq) ||
1383                 (o->rxcdtype==CD_HID_INVERT && !o->rxhidsq) ||
1384                 (o->rxcdtype==CD_XPMR_NOISE && o->pmrChan->rxCarrierDetect) ||
1385                 (o->rxcdtype==CD_XPMR_VOX && o->pmrChan->rxCarrierDetect)
1386           )
1387         {
1388                 res=1;  
1389         }
1390         else res=0;
1391
1392         if(res!=o->rxcarrierdetect)
1393         {
1394                 o->rxcarrierdetect=res;
1395                 if(o->debuglevel)printf("rxcarrierdetect = %i\n",res);
1396         }
1397
1398         if(o->pmrChan->rxCtcss->decode!=o->rxctcssdecode)
1399         {
1400                 if(o->debuglevel)printf("rxctcssdecode = %i\n",o->pmrChan->rxCtcss->decode);
1401                 o->rxctcssdecode=o->pmrChan->rxCtcss->decode;
1402         }
1403
1404         if (     
1405               (  o->rxctcssfreq &&  (o->rxctcssdecode == o->pmrChan->rxCtcssIndex)) || 
1406               ( !o->rxctcssfreq &&      o->rxcarrierdetect)
1407            ) 
1408         {
1409                 o->rxkeyed = 1;
1410         }
1411         else o->rxkeyed = 0;
1412
1413
1414         o->readpos = AST_FRIENDLY_OFFSET;       /* reset read pointer for next frame */
1415         if (c->_state != AST_STATE_UP)  /* drop data if frame is not up */
1416                 return f;
1417         /* ok we can build and deliver the frame to the caller */
1418         f->frametype = AST_FRAME_VOICE;
1419         f->subclass = AST_FORMAT_SLINEAR;
1420         f->samples = FRAME_SIZE;
1421         f->datalen = FRAME_SIZE * 2;
1422         f->data = o->usbradio_read_buf_8k + AST_FRIENDLY_OFFSET;
1423         if (o->boost != BOOST_SCALE) {  /* scale and clip values */
1424                 int i, x;
1425                 int16_t *p = (int16_t *) f->data;
1426                 for (i = 0; i < f->samples; i++) {
1427                         x = (p[i] * o->boost) / BOOST_SCALE;
1428                         if (x > 32767)
1429                                 x = 32767;
1430                         else if (x < -32768)
1431                                 x = -32768;
1432                         p[i] = x;
1433                 }
1434         }
1435
1436         f->offset = AST_FRIENDLY_OFFSET;
1437         if (o->dsp)
1438           {
1439             f1 = ast_dsp_process(c,o->dsp,f);
1440                 if ((f1->frametype == AST_FRAME_DTMF_END) ||
1441                 (f1->frametype == AST_FRAME_DTMF_BEGIN))
1442                 {
1443                 if ((f1->subclass == 'm') || (f1->subclass == 'u'))
1444                     f1->frametype = AST_FRAME_DTMF_BEGIN;
1445                 if (f1->frametype == AST_FRAME_DTMF_END)
1446                     ast_log(LOG_NOTICE,"Got DTMF char %c\n",f1->subclass);
1447                 return(f1);
1448                 }
1449           }
1450         return f;
1451 }
1452
1453 static int usbradio_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1454 {
1455         struct chan_usbradio_pvt *o = newchan->tech_pvt;
1456         ast_log(LOG_WARNING,"usbradio_fixup()\n");
1457         o->owner = newchan;
1458         return 0;
1459 }
1460
1461 static int usbradio_indicate(struct ast_channel *c, int cond, const void *data, size_t datalen)
1462 {
1463         struct chan_usbradio_pvt *o = c->tech_pvt;
1464         int res = -1;
1465
1466         switch (cond) {
1467                 case AST_CONTROL_BUSY:
1468                 case AST_CONTROL_CONGESTION:
1469                 case AST_CONTROL_RINGING:
1470                         res = cond;
1471                         break;
1472
1473                 case -1:
1474                         o->cursound = -1;
1475                         o->nosound = 0;         /* when cursound is -1 nosound must be 0 */
1476                         return 0;
1477
1478                 case AST_CONTROL_VIDUPDATE:
1479                         res = -1;
1480                         break;
1481                 case AST_CONTROL_HOLD:
1482                         ast_verbose(" << Console Has Been Placed on Hold >> \n");
1483                         ast_moh_start(c, data, o->mohinterpret);
1484                         break;
1485                 case AST_CONTROL_UNHOLD:
1486                         ast_verbose(" << Console Has Been Retrieved from Hold >> \n");
1487                         ast_moh_stop(c);
1488                         break;
1489                 case AST_CONTROL_PROCEEDING:
1490                         ast_verbose(" << Call Proceeding... >> \n");
1491                         ast_moh_stop(c);
1492                         break;
1493                 case AST_CONTROL_PROGRESS:
1494                         ast_verbose(" << Call Progress... >> \n");
1495                         ast_moh_stop(c);
1496                         break;
1497                 case AST_CONTROL_RADIO_KEY:
1498                         o->txkeyed = 1;
1499                         if(o->debuglevel)ast_verbose(" << Radio Transmit On. >> \n");
1500                         break;
1501                 case AST_CONTROL_RADIO_UNKEY:
1502                         o->txkeyed = 0;
1503                         if(o->debuglevel)ast_verbose(" << Radio Transmit Off. >> \n");
1504                         break;
1505                 default:
1506                         ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", cond, c->name);
1507                         return -1;
1508         }
1509
1510         if (res > -1)
1511                 ring(o, res);
1512
1513         return 0;
1514 }
1515
1516 /*
1517  * allocate a new channel.
1518  */
1519 static struct ast_channel *usbradio_new(struct chan_usbradio_pvt *o, char *ext, char *ctx, int state)
1520 {
1521         struct ast_channel *c;
1522         char device[100];
1523
1524         strcpy(device,"dsp");
1525         if (o->devicenum) sprintf(device,"dsp%d",o->devicenum);
1526         c = ast_channel_alloc(1, state, o->cid_num, o->cid_name, "", ext, ctx, 0, "usbRadio/%s", device);
1527         if (c == NULL)
1528                 return NULL;
1529         c->tech = &usbradio_tech;
1530         if (o->sounddev < 0)
1531                 setformat(o, O_RDWR);
1532         c->fds[0] = o->sounddev;        /* -1 if device closed, override later */
1533         c->nativeformats = AST_FORMAT_SLINEAR;
1534         c->readformat = AST_FORMAT_SLINEAR;
1535         c->writeformat = AST_FORMAT_SLINEAR;
1536         c->tech_pvt = o;
1537
1538         if (!ast_strlen_zero(o->language))
1539                 ast_string_field_set(c, language, o->language);
1540         /* Don't use ast_set_callerid() here because it will
1541          * generate a needless NewCallerID event */
1542         c->cid.cid_num = ast_strdup(o->cid_num);
1543         c->cid.cid_ani = ast_strdup(o->cid_num);
1544         c->cid.cid_name = ast_strdup(o->cid_name);
1545         if (!ast_strlen_zero(ext))
1546                 c->cid.cid_dnid = ast_strdup(ext);
1547
1548         o->owner = c;
1549         ast_module_ref(ast_module_info->self);
1550         ast_jb_configure(c, &global_jbconf);
1551         if (state != AST_STATE_DOWN) {
1552                 if (ast_pbx_start(c)) {
1553                         ast_log(LOG_WARNING, "Unable to start PBX on %s\n", c->name);
1554                         ast_hangup(c);
1555                         o->owner = c = NULL;
1556                         /* XXX what about the channel itself ? */
1557                         /* XXX what about usecnt ? */
1558                 }
1559         }
1560
1561         return c;
1562 }
1563
1564 static struct ast_channel *usbradio_request(const char *type, int format, void *data, int *cause)
1565 {
1566         struct ast_channel *c;
1567         struct chan_usbradio_pvt *o = find_desc(data);
1568
1569         if (0)
1570         {
1571                 ast_log(LOG_WARNING, "usbradio_request ty <%s> data 0x%p <%s>\n", type, data, (char *) data);
1572         }
1573         if (o == NULL) {
1574                 ast_log(LOG_NOTICE, "Device %s not found\n", (char *) data);
1575                 /* XXX we could default to 'dsp' perhaps ? */
1576                 return NULL;
1577         }
1578         if ((format & AST_FORMAT_SLINEAR) == 0) {
1579                 ast_log(LOG_NOTICE, "Format 0x%x unsupported\n", format);
1580                 return NULL;
1581         }
1582         if (o->owner) {
1583                 ast_log(LOG_NOTICE, "Already have a call (chan %p) on the usb channel\n", o->owner);
1584                 *cause = AST_CAUSE_BUSY;
1585                 return NULL;
1586         }
1587         c = usbradio_new(o, NULL, NULL, AST_STATE_DOWN);
1588         if (c == NULL) {
1589                 ast_log(LOG_WARNING, "Unable to create new usb channel\n");
1590                 return NULL;
1591         }
1592         return c;
1593 }
1594
1595 static char *handle_cli_radio_key(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1596 {
1597         struct chan_usbradio_pvt *o = NULL;
1598
1599         switch (cmd) {
1600         case CLI_INIT:
1601                 e->command = "radio key";
1602                 e->usage =
1603                         "Usage: radio key\n"
1604                         "       Simulates COR active.\n";
1605                 return NULL;
1606         case CLI_GENERATE:
1607                 return NULL;
1608         }
1609
1610         if (a->argc != 2)
1611                 return CLI_SHOWUSAGE;
1612
1613         o = find_desc(usbradio_active);
1614         o->txtestkey = 1;
1615
1616         return CLI_SUCCESS;
1617 }
1618
1619 static char *handle_cli_radio_unkey(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1620 {
1621         struct chan_usbradio_pvt *o = NULL;
1622
1623         switch (cmd) {
1624         case CLI_INIT:
1625                 e->command = "radio unkey";
1626                 e->usage =
1627                         "Usage: radio unkey\n"
1628                         "       Simulates COR un-active.\n";
1629                 return NULL;
1630         case CLI_GENERATE:
1631                 return NULL;
1632         }
1633
1634         if (a->argc != 2)
1635                 return CLI_SHOWUSAGE;
1636
1637         o = find_desc(usbradio_active);
1638         o->txtestkey = 0;
1639
1640         return CLI_SUCCESS;
1641 }
1642
1643 static char *handle_cli_radio_tune(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1644 {
1645         struct chan_usbradio_pvt *o = NULL;
1646         int i = 0;
1647
1648         switch (cmd) {
1649         case CLI_INIT:
1650                 e->command = "radio tune [rxnoise|rxvoice|rxtone|rxsquelch|rxcap|rxtracecap|"
1651                         "txvoice|txtone|txcap|txtracecap|auxvoice|nocap|dump|save]";
1652                 /* radio tune 6 3000        measured tx value */
1653                 e->usage =
1654                         "Usage: radio tune <function>\n"
1655                         "       rxnoise\n"
1656                         "       rxvoice\n"
1657                         "       rxtone\n"
1658                         "       rxsquelch [newsetting]\n"
1659                         "       rxcap\n"
1660                         "       rxtracecap\n"
1661                         "       txvoice [newsetting]\n"
1662                         "       txtone [newsetting]\n"
1663                         "       txcap\n"
1664                         "       txtracecap\n"
1665                         "       auxvoice [newsetting]\n"
1666                         "       nocap\n"
1667                         "       dump\n"
1668                         "       save (settings to tuning file)\n"
1669                         "\n"
1670                         "       All [newsetting]s are values 0-999\n";
1671                 return NULL;
1672         case CLI_GENERATE:
1673                 return NULL;
1674         }
1675
1676         if ((a->argc < 2) || (a->argc > 4))
1677                 return CLI_SHOWUSAGE; 
1678
1679         if (a->argc == 2) /* just show stuff */
1680         {
1681                 ast_cli(a->fd,"Output A is currently set to ");
1682                 if(o->txmixa==TX_OUT_COMPOSITE)ast_cli(a->fd,"composite.\n");
1683                 else if (o->txmixa==TX_OUT_VOICE)ast_cli(a->fd,"voice.\n");
1684                 else if (o->txmixa==TX_OUT_LSD)ast_cli(a->fd,"tone.\n");
1685                 else if (o->txmixa==TX_OUT_AUX)ast_cli(a->fd,"auxvoice.\n");
1686                 else ast_cli(a->fd,"off.\n");
1687
1688                 ast_cli(a->fd,"Output B is currently set to ");
1689                 if(o->txmixb==TX_OUT_COMPOSITE)ast_cli(a->fd,"composite.\n");
1690                 else if (o->txmixb==TX_OUT_VOICE)ast_cli(a->fd,"voice.\n");
1691                 else if (o->txmixb==TX_OUT_LSD)ast_cli(a->fd,"tone.\n");
1692                 else if (o->txmixb==TX_OUT_AUX)ast_cli(a->fd,"auxvoice.\n");
1693                 else ast_cli(a->fd,"off.\n");
1694
1695                 ast_cli(a->fd,"Tx Voice Level currently set to %d\n",o->txmixaset);
1696                 ast_cli(a->fd,"Tx Tone Level currently set to %d\n",o->txctcssadj);
1697                 ast_cli(a->fd,"Rx Squelch currently set to %d\n",o->rxsquelchadj);
1698                 return CLI_SHOWUSAGE;
1699         }
1700
1701         o = find_desc(usbradio_active);
1702
1703         if (!strcasecmp(a->argv[2],"rxnoise")) tune_rxinput(o);
1704         else if (!strcasecmp(a->argv[2],"rxvoice")) tune_rxvoice(o);
1705         else if (!strcasecmp(a->argv[2],"rxtone")) tune_rxctcss(o);
1706         else if (!strcasecmp(a->argv[2],"rxsquelch"))
1707         {
1708                 if (a->argc == 3)
1709                 {
1710                     ast_cli(a->fd,"Current Signal Strength is %d\n",((32767-o->pmrChan->rxRssi)*1000/32767));
1711                     ast_cli(a->fd,"Current Squelch setting is %d\n",o->rxsquelchadj);
1712                         //ast_cli(a->fd,"Current Raw RSSI        is %d\n",o->pmrChan->rxRssi);
1713                     //ast_cli(a->fd,"Current (real) Squelch setting is %d\n",*(o->pmrChan->prxSquelchAdjust));
1714                 } else {
1715                         i = atoi(a->argv[3]);
1716                         if ((i < 0) || (i > 999)) return CLI_SHOWUSAGE;
1717                         ast_cli(a->fd,"Changed Squelch setting to %d\n",i);
1718                         o->rxsquelchadj = i;
1719                         *(o->pmrChan->prxSquelchAdjust)= ((999 - i) * 32767) / 1000;
1720                 }
1721         }
1722         else if (!strcasecmp(a->argv[2],"txvoice")) {
1723                 i = 0;
1724
1725                 if( (o->txmixa!=TX_OUT_VOICE) && (o->txmixb!=TX_OUT_VOICE) &&
1726                         (o->txmixa!=TX_OUT_COMPOSITE) && (o->txmixb!=TX_OUT_COMPOSITE)
1727                   )
1728                 {
1729                         ast_log(LOG_ERROR,"No txvoice output configured.\n");
1730                 }
1731                 else if (a->argc == 3)
1732                 {
1733                         if((o->txmixa==TX_OUT_VOICE)||(o->txmixa==TX_OUT_COMPOSITE))
1734                                 ast_cli(a->fd,"Current txvoice setting on Channel A is %d\n",o->txmixaset);
1735                         else
1736                                 ast_cli(a->fd,"Current txvoice setting on Channel B is %d\n",o->txmixbset);
1737                 }
1738                 else
1739                 {
1740                         i = atoi(a->argv[3]);
1741                         if ((i < 0) || (i > 999)) return CLI_SHOWUSAGE;
1742
1743                         if((o->txmixa==TX_OUT_VOICE)||(o->txmixa==TX_OUT_COMPOSITE))
1744                         {
1745                                 o->txmixaset=i;
1746                                 ast_cli(a->fd,"Changed txvoice setting on Channel A to %d\n",o->txmixaset);
1747                         }
1748                         else
1749                         {
1750                                 o->txmixbset=i;   
1751                                 ast_cli(a->fd,"Changed txvoice setting on Channel B to %d\n",o->txmixbset);
1752                         }
1753                         mixer_write(o);
1754                         mult_set(o);
1755                         ast_cli(a->fd,"Changed Tx Voice Output setting to %d\n",i);
1756                 }
1757                 tune_txoutput(o,i);
1758         }
1759         else if (!strcasecmp(a->argv[2],"auxvoice")) {
1760                 i = 0;
1761                 if( (o->txmixa!=TX_OUT_AUX) && (o->txmixb!=TX_OUT_AUX))
1762                 {
1763                         ast_log(LOG_WARNING,"No auxvoice output configured.\n");
1764                 }
1765                 else if (a->argc == 3)
1766                 {
1767                         if(o->txmixa==TX_OUT_AUX)
1768                                 ast_cli(a->fd,"Current auxvoice setting on Channel A is %d\n",o->txmixaset);
1769                         else
1770                                 ast_cli(a->fd,"Current auxvoice setting on Channel B is %d\n",o->txmixbset);
1771                 }
1772                 else
1773                 {
1774                         i = atoi(a->argv[3]);
1775                         if ((i < 0) || (i > 999)) return CLI_SHOWUSAGE;
1776                         if(o->txmixa==TX_OUT_AUX)
1777                         {
1778                                 o->txmixbset=i;
1779                                 ast_cli(a->fd,"Changed auxvoice setting on Channel A to %d\n",o->txmixaset);
1780                         }
1781                         else
1782                         {
1783                                 o->txmixbset=i;
1784                                 ast_cli(a->fd,"Changed auxvoice setting on Channel B to %d\n",o->txmixbset);
1785                         }
1786                         mixer_write(o);
1787                         mult_set(o);
1788                 }
1789                 //tune_auxoutput(o,i);
1790         }
1791         else if (!strcasecmp(a->argv[2],"txtone"))
1792         {
1793                 if (a->argc == 3)
1794                         ast_cli(a->fd,"Current Tx CTCSS modulation setting = %d\n",o->txctcssadj);
1795                 else
1796                 {
1797                         i = atoi(a->argv[3]);
1798                         if ((i < 0) || (i > 999)) return CLI_SHOWUSAGE;
1799                         o->txctcssadj = i;
1800                         set_txctcss_level(o);
1801                         ast_cli(a->fd,"Changed Tx CTCSS modulation setting to %i\n",i);
1802                 }
1803                 o->txtestkey=1;
1804                 usleep(5000000);
1805                 o->txtestkey=0;
1806         }
1807         else if (!strcasecmp(a->argv[2],"dump")) pmrdump(o);
1808         else if (!strcasecmp(a->argv[2],"nocap")) 
1809         {
1810                 ast_cli(a->fd,"File capture (trace) was rx=%d tx=%d and now off.\n",o->b.rxcap2,o->b.txcap2);
1811                 ast_cli(a->fd,"File capture (raw)   was rx=%d tx=%d and now off.\n",o->b.rxcapraw,o->b.txcapraw);
1812                 o->b.rxcapraw=o->b.txcapraw=o->b.rxcap2=o->b.txcap2=o->pmrChan->b.rxCapture=o->pmrChan->b.txCapture=0;
1813                 if (frxcapraw) { fclose(frxcapraw); frxcapraw = NULL; }
1814                 if (frxcaptrace) { fclose(frxcaptrace); frxcaptrace = NULL; }
1815                 if (frxoutraw) { fclose(frxoutraw); frxoutraw = NULL; }
1816                 if (ftxcapraw) { fclose(ftxcapraw); ftxcapraw = NULL; }
1817                 if (ftxcaptrace) { fclose(ftxcaptrace); ftxcaptrace = NULL; }
1818                 if (ftxoutraw) { fclose(ftxoutraw); ftxoutraw = NULL; }
1819         }
1820         else if (!strcasecmp(a->argv[2],"rxtracecap")) 
1821         {
1822                 if (!frxcaptrace) frxcaptrace= fopen(RX_CAP_TRACE_FILE,"w");
1823                 ast_cli(a->fd,"Trace rx on.\n");
1824                 o->b.rxcap2=o->pmrChan->b.rxCapture=1;
1825         }
1826         else if (!strcasecmp(a->argv[2],"txtracecap")) 
1827         {
1828                 if (!ftxcaptrace) ftxcaptrace= fopen(TX_CAP_TRACE_FILE,"w");
1829                 ast_cli(a->fd,"Trace tx on.\n");
1830                 o->b.txcap2=o->pmrChan->b.txCapture=1;
1831         }
1832         else if (!strcasecmp(a->argv[2],"rxcap")) 
1833         {
1834                 if (!frxcapraw) frxcapraw = fopen(RX_CAP_RAW_FILE,"w");
1835                 ast_cli(a->fd,"cap rx raw on.\n");
1836                 o->b.rxcapraw=1;
1837         }
1838         else if (!strcasecmp(a->argv[2],"txcap")) 
1839         {
1840                 if (!ftxcapraw) ftxcapraw = fopen(TX_CAP_RAW_FILE,"w");
1841                 ast_cli(a->fd,"cap tx raw on.\n");
1842                 o->b.txcapraw=1;
1843         }
1844         else if (!strcasecmp(a->argv[2],"save"))
1845         {
1846                 tune_write(o);
1847                 ast_cli(a->fd,"Saved radio tuning settings to usbradio_tune.conf\n");
1848         }
1849         else return CLI_SHOWUSAGE;
1850         return CLI_SUCCESS;
1851 }
1852
1853 /*
1854         set transmit ctcss modulation level
1855         adjust mixer output or internal gain depending on output type
1856         setting range is 0.0 to 0.9
1857 */
1858 static int set_txctcss_level(struct chan_usbradio_pvt *o)
1859 {                                                         
1860         if (o->txmixa == TX_OUT_LSD)
1861         {
1862                 o->txmixaset=(151*o->txctcssadj) / 1000;
1863                 mixer_write(o);
1864                 mult_set(o);
1865         }
1866         else if (o->txmixb == TX_OUT_LSD)
1867         {
1868                 o->txmixbset=(151*o->txctcssadj) / 1000;
1869                 mixer_write(o);
1870                 mult_set(o);
1871         }
1872         else
1873         {
1874                 *o->pmrChan->ptxCtcssAdjust=(o->txctcssadj * M_Q8) / 1000;
1875         }
1876         return 0;
1877 }
1878 /*
1879         CLI debugging on and off
1880 */
1881 static char *handle_cli_radio_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1882 {
1883         struct chan_usbradio_pvt *o = NULL;
1884
1885         switch (cmd) {
1886         case CLI_INIT:
1887                 e->command = "radio set debug [off]";
1888                 e->usage =
1889                         "Usage: radio set debug [off]\n"
1890                         "       Enable/Disable radio debugging.\n";
1891         case CLI_GENERATE:
1892                 return NULL;
1893         }
1894         if (a->argc < 3 || a->argc > 4)
1895                 return CLI_SHOWUSAGE;
1896         if (a->argc == 4 && strncasecmp(a->argv[3], "off", 3))
1897                 return CLI_SHOWUSAGE;
1898
1899         o = find_desc(usbradio_active);
1900
1901         if (a->argc == 3)
1902                 o->debuglevel = 1;
1903         else
1904                 o->debuglevel = 0;
1905
1906         ast_cli(a->fd, "USB Radio debugging %s.\n", o->debuglevel ? "enabled" : "disabled");
1907
1908         return CLI_SUCCESS;
1909 }
1910
1911 static struct ast_cli_entry cli_usbradio[] = {
1912         AST_CLI_DEFINE(handle_cli_radio_key,       "Simulate Rx Signal Present"),
1913         AST_CLI_DEFINE(handle_cli_radio_unkey,     "Simulate Rx Signal Lusb"),
1914         AST_CLI_DEFINE(handle_cli_radio_tune,      "Radio Tune"),
1915         AST_CLI_DEFINE(handle_cli_radio_set_debug, "Enable/Disable Radio Debugging"),
1916 };
1917
1918 /*
1919  * store the callerid components
1920  */
1921 #if 0
1922 static void store_callerid(struct chan_usbradio_pvt *o, const char *s)
1923 {
1924         ast_callerid_split(s, o->cid_name, sizeof(o->cid_name), o->cid_num, sizeof(o->cid_num));
1925 }
1926 #endif
1927
1928 static void store_rxdemod(struct chan_usbradio_pvt *o, const char *s)
1929 {
1930         if (!strcasecmp(s,"no")){
1931                 o->rxdemod = RX_AUDIO_NONE;
1932         }
1933         else if (!strcasecmp(s,"speaker")){
1934                 o->rxdemod = RX_AUDIO_SPEAKER;
1935         }
1936         else if (!strcasecmp(s,"flat")){
1937                         o->rxdemod = RX_AUDIO_FLAT;
1938         }       
1939         else {
1940                 ast_log(LOG_WARNING,"Unrecognized rxdemod parameter: %s\n",s);
1941         }
1942
1943         //ast_log(LOG_WARNING, "set rxdemod = %s\n", s);
1944 }
1945
1946                                            
1947 static void store_txmixa(struct chan_usbradio_pvt *o, const char *s)
1948 {
1949         if (!strcasecmp(s,"no")){
1950                 o->txmixa = TX_OUT_OFF;
1951         }
1952         else if (!strcasecmp(s,"voice")){
1953                 o->txmixa = TX_OUT_VOICE;
1954         }
1955         else if (!strcasecmp(s,"tone")){
1956                         o->txmixa = TX_OUT_LSD;
1957         }       
1958         else if (!strcasecmp(s,"composite")){
1959                 o->txmixa = TX_OUT_COMPOSITE;
1960         }       
1961         else if (!strcasecmp(s,"auxvoice")){
1962                 o->txmixb = TX_OUT_AUX;
1963         }       
1964         else {
1965                 ast_log(LOG_WARNING,"Unrecognized txmixa parameter: %s\n",s);
1966         }
1967
1968         //ast_log(LOG_WARNING, "set txmixa = %s\n", s);
1969 }
1970
1971 static void store_txmixb(struct chan_usbradio_pvt *o, const char *s)
1972 {
1973         if (!strcasecmp(s,"no")){
1974                 o->txmixb = TX_OUT_OFF;
1975         }
1976         else if (!strcasecmp(s,"voice")){
1977                 o->txmixb = TX_OUT_VOICE;
1978         }
1979         else if (!strcasecmp(s,"tone")){
1980                         o->txmixb = TX_OUT_LSD;
1981         }       
1982         else if (!strcasecmp(s,"composite")){
1983                 o->txmixb = TX_OUT_COMPOSITE;
1984         }       
1985         else if (!strcasecmp(s,"auxvoice")){
1986                 o->txmixb = TX_OUT_AUX;
1987         }       
1988         else {
1989                 ast_log(LOG_WARNING,"Unrecognized txmixb parameter: %s\n",s);
1990         }
1991
1992         //ast_log(LOG_WARNING, "set txmixb = %s\n", s);
1993 }
1994 /*
1995 */
1996 static void store_rxcdtype(struct chan_usbradio_pvt *o, const char *s)
1997 {
1998         if (!strcasecmp(s,"no")){
1999                 o->rxcdtype = CD_IGNORE;
2000         }
2001         else if (!strcasecmp(s,"usb")){
2002                 o->rxcdtype = CD_HID;
2003         }
2004         else if (!strcasecmp(s,"dsp")){
2005                 o->rxcdtype = CD_XPMR_NOISE;
2006         }       
2007         else if (!strcasecmp(s,"vox")){
2008                 o->rxcdtype = CD_XPMR_VOX;
2009         }       
2010         else if (!strcasecmp(s,"usbinvert")){
2011                 o->rxcdtype = CD_HID_INVERT;
2012         }       
2013         else {
2014                 ast_log(LOG_WARNING,"Unrecognized rxcdtype parameter: %s\n",s);
2015         }
2016
2017         //ast_log(LOG_WARNING, "set rxcdtype = %s\n", s);
2018 }
2019 /*
2020 */
2021 static void store_rxsdtype(struct chan_usbradio_pvt *o, const char *s)
2022 {
2023         if (!strcasecmp(s,"no") || !strcasecmp(s,"SD_IGNORE")){
2024                 o->rxsdtype = SD_IGNORE;
2025         }
2026         else if (!strcasecmp(s,"usb") || !strcasecmp(s,"SD_HID")){
2027                 o->rxsdtype = SD_HID;
2028         }
2029         else if (!strcasecmp(s,"usbinvert") || !strcasecmp(s,"SD_HID_INVERT")){
2030                 o->rxsdtype = SD_HID_INVERT;
2031         }       
2032         else if (!strcasecmp(s,"software") || !strcasecmp(s,"SD_XPMR")){
2033                 o->rxsdtype = SD_XPMR;
2034         }       
2035         else {
2036                 ast_log(LOG_WARNING,"Unrecognized rxsdtype parameter: %s\n",s);
2037         }
2038
2039         //ast_log(LOG_WARNING, "set rxsdtype = %s\n", s);
2040 }
2041 /*
2042 */
2043 static void store_rxgain(struct chan_usbradio_pvt *o, const char *s)
2044 {
2045         float f;
2046         sscanf(s,"%f",&f);
2047         o->rxgain = f;
2048         //ast_log(LOG_WARNING, "set rxgain = %f\n", f);
2049 }
2050 /*
2051 */
2052 static void store_rxvoiceadj(struct chan_usbradio_pvt *o, const char *s)
2053 {
2054         float f;
2055         sscanf(s,"%f",&f);
2056         o->rxvoiceadj = f;
2057         //ast_log(LOG_WARNING, "set rxvoiceadj = %f\n", f);
2058 }
2059 /*
2060 */
2061 static void store_rxctcssadj(struct chan_usbradio_pvt *o, const char *s)
2062 {
2063         float f;
2064         sscanf(s,"%f",&f);
2065         o->rxctcssadj = f;
2066         //ast_log(LOG_WARNING, "set rxctcssadj = %f\n", f);
2067 }
2068 /*
2069 */
2070 static void store_txtoctype(struct chan_usbradio_pvt *o, const char *s)
2071 {
2072         if (!strcasecmp(s,"no") || !strcasecmp(s,"TOC_NONE")){
2073                 o->txtoctype = TOC_NONE;
2074         }
2075         else if (!strcasecmp(s,"phase") || !strcasecmp(s,"TOC_PHASE")){
2076                 o->txtoctype = TOC_PHASE;
2077         }
2078         else if (!strcasecmp(s,"notone") || !strcasecmp(s,"TOC_NOTONE")){
2079                 o->txtoctype = TOC_NOTONE;
2080         }       
2081         else {
2082                 ast_log(LOG_WARNING,"Unrecognized txtoctype parameter: %s\n",s);
2083         }
2084
2085         //ast_log(LOG_WARNING, "set txtoctype = %s\n", s);
2086 }
2087 /*
2088 */
2089 static void store_rxctcssfreq(struct chan_usbradio_pvt *o, const char *s)
2090 {
2091         float f;
2092         sscanf(s,"%f",&f);
2093         o->rxctcssfreq = f;
2094         //ast_log(LOG_WARNING, "set rxctcss = %f\n", f);
2095 }
2096 /*
2097 */
2098 static void store_txctcssfreq(struct chan_usbradio_pvt *o, const char *s)
2099 {
2100         float f;
2101         sscanf(s,"%f",&f);
2102         o->txctcssfreq = f;
2103         //ast_log(LOG_WARNING, "set txctcss = %f\n", f);
2104 }
2105 /*
2106 */
2107 static void tune_txoutput(struct chan_usbradio_pvt *o, int value)
2108 {
2109         o->txtestkey=1;
2110         o->pmrChan->txPttIn=1;
2111
2112         // generate 1KHz tone at 7200 peak
2113         //o->pmrChan->spsSigGen1->freq=10000;
2114         //o->pmrChan->spsSigGen1->outputGain=(float)(0.22*M_Q8);
2115         //o->pmrChan->b.startSpecialTone=1;
2116
2117         TxTestTone(o->pmrChan, 1);
2118
2119         usleep(5000000);
2120         //o->pmrChan->b.stopSpecialTone=1;
2121         usleep(100000);
2122
2123         TxTestTone(o->pmrChan, 0);
2124
2125         o->pmrChan->txPttIn=0;
2126         o->txtestkey=0;
2127 }
2128 /*
2129 */
2130 static void tune_rxinput(struct chan_usbradio_pvt *o)
2131 {
2132         const int target=23000;
2133         const int tolerance=2000;
2134         const int settingmin=1;
2135         const int settingstart=2;
2136         const int maxtries=12;
2137
2138         float settingmax;
2139         
2140         int setting=0, tries=0, tmpdiscfactor, meas;
2141         int tunetype=0;
2142
2143         settingmax = o->micmax;
2144
2145         if(o->pmrChan->rxDemod)tunetype=1;
2146
2147         setting = settingstart;
2148
2149         while(tries<maxtries)
2150         {
2151                 setamixer(o->devicenum,MIXER_PARAM_MIC_CAPTURE_VOL,setting,0);
2152                 setamixer(o->devicenum,MIXER_PARAM_MIC_BOOST,o->rxboostset,0);
2153                 usleep(100000);
2154                 if(o->rxcdtype==CD_XPMR_VOX || o->rxdemod==RX_AUDIO_SPEAKER)
2155                 {
2156                         // printf("Measure Direct Input\n");
2157                         o->pmrChan->spsMeasure->source = o->pmrChan->spsRx->source;
2158                         o->pmrChan->spsMeasure->discfactor=1000;
2159                         o->pmrChan->spsMeasure->enabled=1;
2160                         o->pmrChan->spsMeasure->amax = o->pmrChan->spsMeasure->amin = 0;
2161                         usleep(400000); 
2162                         meas=o->pmrChan->spsMeasure->apeak;
2163                         o->pmrChan->spsMeasure->enabled=0;      
2164                 }
2165                 else
2166                 {
2167                         // printf("Measure HF Noise\n");
2168                         tmpdiscfactor=o->pmrChan->spsRx->discfactor;
2169                         o->pmrChan->spsRx->discfactor=(i16)1000;
2170                         o->pmrChan->spsRx->discounteru=o->pmrChan->spsRx->discounterl=0;
2171                         o->pmrChan->spsRx->amax=o->pmrChan->spsRx->amin=0;
2172                         usleep(200000);
2173                         meas=o->pmrChan->rxRssi;
2174                         o->pmrChan->spsRx->discfactor=tmpdiscfactor;
2175                         o->pmrChan->spsRx->discounteru=o->pmrChan->spsRx->discounterl=0;
2176                         o->pmrChan->spsRx->amax=o->pmrChan->spsRx->amin=0;
2177                 }
2178         if(!meas)meas++;
2179                 printf("tries=%d, setting=%d, meas=%i\n",tries,setting,meas);
2180
2181                 if( meas<(target-tolerance) || meas>(target+tolerance) || tries<3){
2182                         setting=setting*target/meas;
2183                 }
2184                 else if(tries>4 && meas>(target-tolerance) && meas<(target+tolerance) )
2185                 {
2186                         break;
2187                 }
2188
2189                 if(setting<settingmin)setting=settingmin;
2190                 else if(setting>settingmax)setting=settingmax;
2191
2192                 tries++;
2193         }
2194         printf("DONE tries=%d, setting=%d, meas=%i\n",tries,
2195                 (setting * 1000) / o->micmax,meas);
2196         if( meas<(target-tolerance) || meas>(target+tolerance) ){
2197                 printf("ERROR: RX INPUT ADJUST FAILED.\n");
2198         }else{
2199                 printf("INFO: RX INPUT ADJUST SUCCESS.\n");     
2200                 o->rxmixerset=(setting * 1000) / o->micmax;
2201         }
2202 }
2203 /*
2204 */
2205 static void tune_rxvoice(struct chan_usbradio_pvt *o)
2206 {
2207         const int target=7200;                          // peak
2208         const int tolerance=360;                        // peak to peak
2209         const float settingmin=0.1;
2210         const float settingmax=4;
2211         const float settingstart=1;
2212         const int maxtries=12;
2213
2214         float setting;
2215
2216         int tries=0, meas;
2217
2218         printf("INFO: RX VOICE ADJUST START.\n");       
2219         printf("target=%i tolerance=%i \n",target,tolerance);
2220
2221         if(!o->pmrChan->spsMeasure)
2222                 printf("ERROR: NO MEASURE BLOCK.\n");
2223
2224         if(!o->pmrChan->spsMeasure->source || !o->pmrChan->prxVoiceAdjust )
2225                 printf("ERROR: NO SOURCE OR MEASURE SETTING.\n");
2226
2227         o->pmrChan->spsMeasure->source=o->pmrChan->spsRxOut->sink;
2228         o->pmrChan->spsMeasure->enabled=1;
2229         o->pmrChan->spsMeasure->discfactor=1000;
2230         
2231         setting=settingstart;
2232
2233         // printf("ERROR: NO MEASURE BLOCK.\n");
2234
2235         while(tries<maxtries)
2236         {
2237                 *(o->pmrChan->prxVoiceAdjust)=setting*M_Q8;
2238                 usleep(10000);
2239         o->pmrChan->spsMeasure->amax = o->pmrChan->spsMeasure->amin = 0;
2240                 usleep(1000000);
2241                 meas = o->pmrChan->spsMeasure->apeak;
2242                 printf("tries=%d, setting=%f, meas=%i\n",tries,setting,meas);
2243
2244                 if( meas<(target-tolerance) || meas>(target+tolerance) || tries<3){
2245                         setting=setting*target/meas;
2246                 }
2247                 else if(tries>4 && meas>(target-tolerance) && meas<(target+tolerance) )
2248                 {
2249                         break;
2250                 }
2251                 if(setting<settingmin)setting=settingmin;
2252                 else if(setting>settingmax)setting=settingmax;
2253
2254                 tries++;
2255         }
2256
2257         o->pmrChan->spsMeasure->enabled=0;
2258
2259         printf("DONE tries=%d, setting=%f, meas=%f\n",tries,setting,(float)meas);
2260         if( meas<(target-tolerance) || meas>(target+tolerance) ){
2261                 printf("ERROR: RX VOICE GAIN ADJUST FAILED.\n");
2262         }else{
2263                 printf("INFO: RX VOICE GAIN ADJUST SUCCESS.\n");
2264                 o->rxvoiceadj=setting;
2265         }
2266 }
2267 /*
2268 */
2269 static void tune_rxctcss(struct chan_usbradio_pvt *o)
2270 {
2271         const int target=4096;
2272         const int tolerance=100;
2273         const float settingmin=0.1;
2274         const float settingmax=4;
2275         const float settingstart=1;
2276         const int maxtries=12;
2277
2278         float setting;
2279         int tries=0, meas;
2280
2281         printf("INFO: RX CTCSS ADJUST START.\n");       
2282         printf("target=%i tolerance=%i \n",target,tolerance);
2283
2284         o->pmrChan->spsMeasure->source=o->pmrChan->prxCtcssMeasure;
2285         o->pmrChan->spsMeasure->discfactor=400;
2286         o->pmrChan->spsMeasure->enabled=1;
2287
2288         setting=settingstart;
2289
2290         while(tries<maxtries)
2291         {
2292                 *(o->pmrChan->prxCtcssAdjust)=setting*M_Q8;
2293                 usleep(10000);
2294         o->pmrChan->spsMeasure->amax = o->pmrChan->spsMeasure->amin = 0;
2295                 usleep(500000);
2296                 meas = o->pmrChan->spsMeasure->apeak;
2297                 printf("tries=%d, setting=%f, meas=%i\n",tries,setting,meas);
2298
2299                 if( meas<(target-tolerance) || meas>(target+tolerance) || tries<3){
2300                         setting=setting*target/meas;
2301                 }
2302                 else if(tries>4 && meas>(target-tolerance) && meas<(target+tolerance) )
2303                 {
2304                         break;
2305                 }
2306                 if(setting<settingmin)setting=settingmin;
2307                 else if(setting>settingmax)setting=settingmax;
2308
2309                 tries++;
2310         }
2311         o->pmrChan->spsMeasure->enabled=0;
2312         printf("DONE tries=%d, setting=%f, meas=%f\n",tries,setting,(float)meas);
2313         if( meas<(target-tolerance) || meas>(target+tolerance) ){
2314                 printf("ERROR: RX CTCSS GAIN ADJUST FAILED.\n");
2315         }else{
2316                 printf("INFO: RX CTCSS GAIN ADJUST SUCCESS.\n");
2317                 o->rxctcssadj=setting;
2318         }
2319 }
2320 /*
2321         this file then is included in chan_usbradio.conf
2322         #include /etc/asterisk/usbradio_tune.conf 
2323 */
2324 static void tune_write(struct chan_usbradio_pvt *o)
2325 {
2326         FILE *fp;
2327         
2328         fp=fopen("/etc/asterisk/usbradio_tune.conf","w");
2329  
2330         if (!strcmp(o->name,"dsp"))
2331                 fprintf(fp,"[general]\n");
2332         else
2333                 fprintf(fp,"[%s]\n",o->name);
2334
2335         fprintf(fp,"; name=%s\n",o->name);
2336         fprintf(fp,"; devicenum=%i\n",o->devicenum);
2337
2338         fprintf(fp,"rxmixerset=%i\n",o->rxmixerset);
2339         fprintf(fp,"rxboostset=%i\n",o->rxboostset);
2340         fprintf(fp,"txmixaset=%i\n",o->txmixaset);
2341         fprintf(fp,"txmixbset=%i\n",o->txmixbset);
2342
2343         fprintf(fp,"rxvoiceadj=%f\n",o->rxvoiceadj);
2344         fprintf(fp,"rxctcssadj=%f\n",o->rxctcssadj);
2345         fprintf(fp,"txctcssadj=%i\n",o->txctcssadj);
2346
2347         fprintf(fp,"rxsquelchadj=%i\n",o->rxsquelchadj);
2348         fclose(fp);
2349 }
2350 //
2351 static void mixer_write(struct chan_usbradio_pvt *o)
2352 {
2353         setamixer(o->devicenum,MIXER_PARAM_MIC_PLAYBACK_SW,0,0);
2354         setamixer(o->devicenum,MIXER_PARAM_MIC_PLAYBACK_VOL,0,0);
2355         setamixer(o->devicenum,MIXER_PARAM_SPKR_PLAYBACK_SW,1,0);
2356         setamixer(o->devicenum,MIXER_PARAM_SPKR_PLAYBACK_VOL,
2357                 o->txmixaset * o->spkrmax / 1000,
2358                 o->txmixbset * o->spkrmax / 1000);
2359         setamixer(o->devicenum,MIXER_PARAM_MIC_CAPTURE_VOL,
2360                 o->rxmixerset * o->micmax / 1000,0);
2361         setamixer(o->devicenum,MIXER_PARAM_MIC_BOOST,o->rxboostset,0);
2362         setamixer(o->devicenum,MIXER_PARAM_MIC_CAPTURE_SW,1,0);
2363 }
2364 /*
2365         adjust dsp multiplier to add resolution to tx level adjustment
2366 */
2367 static void mult_set(struct chan_usbradio_pvt *o)
2368 {
2369
2370         if(o->pmrChan->spsTxOutA) {
2371                 o->pmrChan->spsTxOutA->outputGain = 
2372                         mult_calc((o->txmixaset * 152) / 1000);
2373         }
2374         if(o->pmrChan->spsTxOutB){
2375                 o->pmrChan->spsTxOutB->outputGain = 
2376                         mult_calc((o->txmixbset * 152) / 1000);
2377         }
2378 }
2379 //
2380 // input 0 - 151 outputs are pot and multiplier
2381 //
2382 static int mult_calc(int value)
2383 {
2384         const int multx=M_Q8;
2385         int pot,mult;
2386
2387         pot=((int)(value/4)*4)+2;
2388         mult = multx-( ( multx * (3-(value%4)) ) / (pot+2) );
2389         return(mult);
2390 }
2391
2392 #define pd(x) {printf(#x" = %d\n",x);}
2393 #define pp(x) {printf(#x" = %p\n",x);}
2394 #define ps(x) {printf(#x" = %s\n",x);}
2395 #define pf(x) {printf(#x" = %f\n",x);}
2396 /*
2397 */
2398 static void pmrdump(struct chan_usbradio_pvt *o)
2399 {
2400         t_pmr_chan *p;
2401
2402         p=o->pmrChan;
2403
2404         printf("\nodump()\n");
2405
2406         pd(o->devicenum);
2407
2408         pd(o->rxdemod);
2409         pd(o->rxcdtype);
2410         pd(o->rxsdtype);
2411         pd(o->txtoctype);
2412
2413         pd(o->rxmixerset);
2414         pf(o->rxvoiceadj);
2415         pf(o->rxctcssadj);
2416         pd(o->rxsquelchadj);
2417          
2418         pd(o->txprelim);
2419         pd(o->txmixa);
2420         pd(o->txmixb);
2421         
2422         pd(o->txmixaset);
2423         pd(o->txmixbset);
2424         
2425         printf("\npmrdump()\n");
2426  
2427         printf("prxSquelchAdjust=%i\n",*(o->pmrChan->prxSquelchAdjust));
2428
2429         pd(p->rxCarrierPoint);
2430         pd(p->rxCarrierHyst);
2431
2432         pd(p->rxCtcss->relax);
2433         pf(p->rxCtcssFreq);     
2434         pd(p->rxCtcssIndex);
2435         pf(p->txCtcssFreq);
2436
2437         pd(p->txMixA);
2438         pd(p->txMixB);
2439     
2440         pd(p->rxDeEmpEnable);
2441         pd(p->rxCenterSlicerEnable);
2442         pd(p->rxCtcssDecodeEnable);
2443         pd(p->rxDcsDecodeEnable);
2444
2445         pd(p->txHpfEnable);
2446         pd(p->txLimiterEnable);
2447         pd(p->txPreEmpEnable);
2448         pd(p->txLpfEnable);
2449
2450         if(p->spsTxOutA)pd(p->spsTxOutA->outputGain);
2451         if(p->spsTxOutB)pd(p->spsTxOutB->outputGain);
2452
2453         return;
2454 }
2455
2456
2457 /*
2458  * grab fields from the config file, init the descriptor and open the device.
2459  */
2460 static struct chan_usbradio_pvt *store_config(struct ast_config *cfg, char *ctg)
2461 {
2462         struct ast_variable *v;
2463         struct chan_usbradio_pvt *o;
2464         struct ast_config *cfg1;
2465         struct ast_flags config_flags = { 0 };
2466
2467         if (ctg == NULL) {
2468                 traceusb1((" store_config() ctg == NULL\n"));
2469                 o = &usbradio_default;
2470                 ctg = "general";
2471         } else {
2472                 if (!(o = ast_calloc(1, sizeof(*o)))){
2473                         return NULL;
2474                 }
2475                 *o = usbradio_default;
2476                 /* "general" is also the default thing */
2477                 if (strcmp(ctg, "general") == 0) {
2478                         o->name = ast_strdup("dsp");
2479                         usbradio_active = o->name;
2480                 }
2481                 else o->name = ast_strdup(ctg);
2482         }
2483
2484         strcpy(o->mohinterpret, "default");
2485         o->micmax = amixer_max(o->devicenum,MIXER_PARAM_MIC_CAPTURE_VOL);
2486         o->spkrmax = amixer_max(o->devicenum,MIXER_PARAM_SPKR_PLAYBACK_VOL);
2487         /* fill other fields from configuration */
2488         for (v = ast_variable_browse(cfg, ctg); v; v = v->next) {
2489                 M_START(v->name, v->value);
2490
2491                 /* handle jb conf */
2492                 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
2493                         continue;
2494
2495 #if     0
2496                         M_BOOL("autoanswer", o->autoanswer)
2497                         M_BOOL("autohangup", o->autohangup)
2498                         M_BOOL("overridecontext", o->overridecontext)
2499                         M_STR("context", o->ctx)
2500                         M_STR("language", o->language)
2501                         M_STR("mohinterpret", o->mohinterpret)
2502                         M_STR("extension", o->ext)
2503                         M_F("callerid", store_callerid(o, v->value))
2504 #endif
2505                         M_UINT("frags", o->frags)
2506                         M_UINT("queuesize", o->queuesize)
2507                         M_UINT("devicenum", o->devicenum)
2508                         M_UINT("debug", usbradio_debug)
2509                         M_BOOL("rxcpusaver",o->rxcpusaver)
2510                         M_BOOL("txcpusaver",o->txcpusaver)
2511                         M_BOOL("invertptt",o->invertptt)
2512                         M_F("rxdemod",store_rxdemod(o,v->value))
2513                         M_BOOL("txprelim",o->txprelim);
2514                         M_F("txmixa",store_txmixa(o,v->value))
2515                         M_F("txmixb",store_txmixb(o,v->value))
2516                         M_F("carrierfrom",store_rxcdtype(o,v->value))
2517                         M_F("rxsdtype",store_rxsdtype(o,v->value))
2518                         M_F("rxctcssfreq",store_rxctcssfreq(o,v->value))
2519                         M_F("txctcssfreq",store_txctcssfreq(o,v->value))
2520                         M_F("rxgain",store_rxgain(o,v->value))
2521                         M_BOOL("rxboostset", o->rxboostset)
2522                         M_UINT("rxctcssrelax", o->rxctcssrelax)
2523                         M_F("txtoctype",store_txtoctype(o,v->value))
2524                         M_UINT("hdwtype", o->hdwtype)
2525                         M_UINT("duplex", o->radioduplex)
2526                         M_END(;
2527                         );
2528         }
2529         
2530         cfg1 = ast_config_load(config1, config_flags);
2531         if (!cfg1)
2532         {
2533                 o->rxmixerset = 500;
2534                 o->txmixaset = 500;
2535                 o->txmixbset = 500;
2536                 o->rxvoiceadj = 0.5;
2537                 o->rxctcssadj = 0.5;
2538                 o->txctcssadj = 200;
2539                 o->rxsquelchadj = 500;
2540                 ast_log(LOG_WARNING,"File %s not found, using default parameters.\n",config1);
2541         } else  {
2542                 for (v = ast_variable_browse(cfg1, ctg); v; v = v->next) {
2543         
2544                         M_START(v->name, v->value);
2545                         M_UINT("rxmixerset", o->rxmixerset)
2546                         M_UINT("txmixaset", o->txmixaset)
2547                         M_UINT("txmixbset", o->txmixbset)
2548                         M_F("rxvoiceadj",store_rxvoiceadj(o,v->value))
2549                         M_F("rxctcssadj",store_rxctcssadj(o,v->value))
2550                         M_UINT("txctcssadj",o->txctcssadj);
2551                         M_UINT("rxsquelchadj", o->rxsquelchadj)
2552                         M_END(;
2553                         );
2554                 }
2555                 ast_config_destroy(cfg1);
2556         }
2557
2558         o->debuglevel=0;
2559
2560         if (o == &usbradio_default)             /* we are done with the default */
2561                 return NULL;
2562
2563         o->lastopen = ast_tvnow();      /* don't leave it 0 or tvdiff may wrap */
2564         o->dsp = ast_dsp_new();
2565           if (o->dsp)
2566           {
2567             ast_dsp_set_features(o->dsp,DSP_FEATURE_DTMF_DETECT);
2568             ast_dsp_digitmode(o->dsp,DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_RELAXDTMF);
2569           }
2570
2571         if(o->rxctcssfreq!=0 && o->rxdemod==RX_AUDIO_SPEAKER)
2572         {
2573                 ast_log(LOG_ERROR, "Incompatable Options  o->rxctcssfreq=%f and o->rxdemod=speaker\n", o->rxctcssfreq); 
2574         }
2575
2576         if(o->pmrChan==NULL)
2577         {
2578                 t_pmr_chan      tChan;
2579
2580                 memset(&tChan,0,sizeof(t_pmr_chan));
2581
2582                 tChan.rxDemod=o->rxdemod;
2583                 tChan.rxCdType=o->rxcdtype;
2584
2585                 tChan.txMod=o->txprelim;
2586
2587                 tChan.txMixA = o->txmixa;
2588                 tChan.txMixB = o->txmixb;
2589
2590                 tChan.rxCpuSaver=o->rxcpusaver;
2591                 tChan.txCpuSaver=o->txcpusaver;
2592
2593                 tChan.rxCtcssFreq=o->rxctcssfreq;
2594                 tChan.txCtcssFreq=o->txctcssfreq;
2595
2596                 o->pmrChan=createPmrChannel(&tChan,FRAME_SIZE);
2597
2598                 o->pmrChan->radioDuplex=o->radioduplex;
2599
2600                 o->pmrChan->rxCpuSaver=o->rxcpusaver;
2601                 o->pmrChan->txCpuSaver=o->txcpusaver;
2602
2603                 *(o->pmrChan->prxSquelchAdjust) = 
2604                         ((999 - o->rxsquelchadj) * 32767) / 1000;
2605
2606                 o->pmrChan->spsRx->outputGain = o->rxvoiceadj*M_Q8;
2607
2608                 o->pmrChan->txTocType = o->txtoctype;
2609
2610         if ((o->txmixa ==  TX_OUT_LSD) ||
2611                 (o->txmixa == TX_OUT_COMPOSITE) ||
2612                 (o->txmixb ==  TX_OUT_LSD) ||
2613                 (o->txmixb == TX_OUT_COMPOSITE))
2614         {
2615                 *(o->pmrChan->prxCtcssAdjust)=o->rxctcssadj*M_Q8;
2616                 set_txctcss_level(o);
2617         }
2618
2619         o->pmrChan->rxCtcss->relax=o->rxctcssrelax;
2620
2621         }
2622
2623         if( (o->txmixa!=TX_OUT_VOICE) && (o->txmixb!=TX_OUT_VOICE) &&
2624                 (o->txmixa!=TX_OUT_COMPOSITE) && (o->txmixb!=TX_OUT_COMPOSITE)
2625           )
2626         {
2627                 ast_log(LOG_ERROR,"No txvoice output configured.\n");
2628         }
2629
2630         if( o->txctcssfreq && 
2631             o->txmixa!=TX_OUT_LSD && o->txmixa!=TX_OUT_COMPOSITE  &&
2632                 o->txmixb!=TX_OUT_LSD && o->txmixb!=TX_OUT_COMPOSITE
2633           )
2634         {
2635                 ast_log(LOG_ERROR,"No txtone output configured.\n");
2636         }
2637
2638         if( o->rxctcssfreq && o->pmrChan->rxCtcssIndex<0 )
2639         {
2640                 ast_log(LOG_ERROR,"Invalid CTCSS Frequency.\n");
2641         }
2642
2643         // RxTestIt(o);
2644
2645         mixer_write(o);
2646         mult_set(o);    
2647         hidhdwconfig(o);
2648
2649         // pmrdump(o);
2650
2651         if (pipe(o->sndcmd) != 0) {
2652                 ast_log(LOG_ERROR, "Unable to create pipe\n");
2653                 goto error;
2654         }
2655
2656         printf("creating sound thread\n");
2657         ast_pthread_create_background(&o->sthread, NULL, sound_thread, o);
2658
2659         /* link into list of devices */
2660         if (o != &usbradio_default) {
2661                 o->next = usbradio_default.next;
2662                 usbradio_default.next = o;
2663         }
2664         return o;
2665   
2666   error:
2667         if (o != &usbradio_default)
2668                 free(o);
2669         return NULL;
2670 }
2671
2672 #if     DEBUG_FILETEST == 1
2673 /*
2674         Test It on a File
2675 */
2676 int RxTestIt(struct chan_usbradio_pvt *o)
2677 {
2678         const int numSamples = SAMPLES_PER_BLOCK;
2679         const int numChannels = 16;
2680
2681         i16 sample,i,ii;
2682         
2683         i32 txHangTime;
2684
2685         i16 txEnable;
2686
2687         t_pmr_chan      tChan;
2688         t_pmr_chan *pChan;
2689
2690         FILE *hInput=NULL, *hOutput=NULL, *hOutputTx=NULL;
2691  
2692         i16 iBuff[numSamples*2*6], oBuff[numSamples];
2693                                   
2694         printf("RxTestIt()\n");
2695
2696         pChan=o->pmrChan;
2697         pChan->b.txCapture=1;
2698         pChan->b.rxCapture=1;
2699
2700         txEnable = 0;
2701
2702         hInput  = fopen("/usr/src/xpmr/testdata/rx_in.pcm","r");
2703         if(!hInput){
2704                 printf(" RxTestIt() File Not Found.\n");
2705                 return 0;
2706         }
2707         hOutput = fopen("/usr/src/xpmr/testdata/rx_debug.pcm","w");
2708
2709         printf(" RxTestIt() Working...\n");
2710                                 
2711         while(!feof(hInput))
2712         {
2713                 fread((void *)iBuff,2,numSamples*2*6,hInput);
2714                  
2715                 if(txHangTime)txHangTime-=numSamples;
2716                 if(txHangTime<0)txHangTime=0;
2717                 
2718                 if(pChan->rxCtcss->decode)txHangTime=(8000/1000*2000);
2719
2720                 if(pChan->rxCtcss->decode && !txEnable)
2721                 {
2722                         txEnable=1;
2723                         //pChan->inputBlanking=(8000/1000*200);
2724                 }
2725                 else if(!pChan->rxCtcss->decode && txEnable)
2726                 {
2727                         txEnable=0;     
2728                 }
2729
2730                 PmrRx(pChan,iBuff,oBuff);
2731
2732                 fwrite((void *)pChan->prxDebug,2,numSamples*numChannels,hOutput);
2733         }
2734         pChan->b.txCapture=0;
2735         pChan->b.rxCapture=0;
2736
2737         if(hInput)fclose(hInput);
2738         if(hOutput)fclose(hOutput);
2739
2740         printf(" RxTestIt() Complete.\n");
2741
2742         return 0;
2743 }
2744 #endif
2745
2746 #include "./xpmr/xpmr.c"
2747 /*
2748 */
2749 static int load_module(void)
2750 {
2751         struct ast_config *cfg = NULL;
2752         char *ctg = NULL;
2753         struct ast_flags config_flags = { 0 };
2754
2755         /* Copy the default jb config over global_jbconf */
2756         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
2757
2758         /* load config file */
2759         if (!(cfg = ast_config_load(config, config_flags))) {
2760                 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
2761                 return AST_MODULE_LOAD_DECLINE;
2762         }
2763
2764         do {
2765                 store_config(cfg, ctg);
2766         } while ( (ctg = ast_category_browse(cfg, ctg)) != NULL);
2767
2768         ast_config_destroy(cfg);
2769
2770         if (find_desc(usbradio_active) == NULL) {
2771                 ast_log(LOG_NOTICE, "Device %s not found\n", usbradio_active);
2772                 /* XXX we could default to 'dsp' perhaps ? */
2773                 /* XXX should cleanup allocated memory etc. */
2774                 return AST_MODULE_LOAD_FAILURE;
2775         }
2776
2777         if (ast_channel_register(&usbradio_tech)) {
2778                 ast_log(LOG_ERROR, "Unable to register channel type 'usb'\n");
2779                 return AST_MODULE_LOAD_FAILURE;
2780         }
2781
2782         ast_cli_register_multiple(cli_usbradio, sizeof(cli_usbradio) / sizeof(struct ast_cli_entry));
2783
2784         return AST_MODULE_LOAD_SUCCESS;
2785 }
2786 /*
2787 */
2788 static int unload_module(void)
2789 {
2790         struct chan_usbradio_pvt *o;
2791
2792         ast_log(LOG_WARNING, "unload_module() called\n");
2793
2794         ast_channel_unregister(&usbradio_tech);
2795         ast_cli_unregister_multiple(cli_usbradio, sizeof(cli_usbradio) / sizeof(struct ast_cli_entry));
2796
2797         for (o = usbradio_default.next; o; o = o->next) {
2798
2799                 ast_log(LOG_WARNING, "destroyPmrChannel() called\n");
2800                 if(o->pmrChan)destroyPmrChannel(o->pmrChan);
2801                 
2802                 #if DEBUG_CAPTURES == 1
2803                 if (frxcapraw) { fclose(frxcapraw); frxcapraw = NULL; }
2804                 if (frxcaptrace) { fclose(frxcaptrace); frxcaptrace = NULL; }
2805                 if (frxoutraw) { fclose(frxoutraw); frxoutraw = NULL; }
2806                 if (ftxcapraw) { fclose(ftxcapraw); ftxcapraw = NULL; }
2807                 if (ftxcaptrace) { fclose(ftxcaptrace); ftxcaptrace = NULL; }
2808                 if (ftxoutraw) { fclose(ftxoutraw); ftxoutraw = NULL; }
2809                 #endif
2810
2811                 close(o->sounddev);
2812                 if (o->sndcmd[0] > 0) {
2813                         close(o->sndcmd[0]);
2814                         close(o->sndcmd[1]);
2815                 }
2816                 if (o->dsp) ast_dsp_free(o->dsp);
2817                 if (o->owner)
2818                         ast_softhangup(o->owner, AST_SOFTHANGUP_APPUNLOAD);
2819                 if (o->owner)                   /* XXX how ??? */
2820                         return -1;
2821                 /* XXX what about the thread ? */
2822                 /* XXX what about the memory allocated ? */
2823         }
2824         return 0;
2825 }
2826
2827 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "usb Console Channel Driver");
2828
2829 /*      end of file */
2830
2831