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