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