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