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