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