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