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