From f8b84cf48099fb020b1174c8cc6195dde42308c3 Mon Sep 17 00:00:00 2001 From: FreeArtMan <=> Date: Sat, 19 Sep 2015 14:36:47 +0100 Subject: Initial --- .gitignore | 4 + Makefile | 41 + build/src/.empty | 0 build/utils/convenience/.empty | 0 include/reg_field.h | 60 ++ include/rtl-sdr.h | 387 ++++++++ include/rtl-sdr_export.h | 47 + include/rtlsdr_i2c.h | 8 + include/tuner_e4k.h | 222 +++++ include/tuner_fc0012.h | 36 + include/tuner_fc0013.h | 37 + include/tuner_fc2580.h | 127 +++ include/tuner_r82xx.h | 120 +++ src/librtlsdr.c | 1938 +++++++++++++++++++++++++++++++++++++++ src/make.mk | 13 + src/tuner_e4k.c | 1000 ++++++++++++++++++++ src/tuner_fc0012.c | 345 +++++++ src/tuner_fc0013.c | 500 ++++++++++ src/tuner_fc2580.c | 494 ++++++++++ src/tuner_r82xx.c | 1328 +++++++++++++++++++++++++++ utils/convenience/convenience.c | 304 ++++++ utils/convenience/convenience.h | 142 +++ utils/getopt/getopt.c | 1059 +++++++++++++++++++++ utils/getopt/getopt.h | 180 ++++ utils/make.mk | 15 + utils/rtl_adsb.c | 496 ++++++++++ utils/rtl_eeprom.c | 425 +++++++++ utils/rtl_fm.c | 1264 +++++++++++++++++++++++++ utils/rtl_power.c | 998 ++++++++++++++++++++ utils/rtl_sdr.c | 278 ++++++ utils/rtl_tcp.c | 603 ++++++++++++ utils/rtl_test.c | 423 +++++++++ 32 files changed, 12894 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 build/src/.empty create mode 100644 build/utils/convenience/.empty create mode 100644 include/reg_field.h create mode 100644 include/rtl-sdr.h create mode 100644 include/rtl-sdr_export.h create mode 100644 include/rtlsdr_i2c.h create mode 100644 include/tuner_e4k.h create mode 100644 include/tuner_fc0012.h create mode 100644 include/tuner_fc0013.h create mode 100644 include/tuner_fc2580.h create mode 100644 include/tuner_r82xx.h create mode 100644 src/librtlsdr.c create mode 100644 src/make.mk create mode 100644 src/tuner_e4k.c create mode 100644 src/tuner_fc0012.c create mode 100644 src/tuner_fc0013.c create mode 100644 src/tuner_fc2580.c create mode 100644 src/tuner_r82xx.c create mode 100644 utils/convenience/convenience.c create mode 100644 utils/convenience/convenience.h create mode 100644 utils/getopt/getopt.c create mode 100644 utils/getopt/getopt.h create mode 100644 utils/make.mk create mode 100644 utils/rtl_adsb.c create mode 100644 utils/rtl_eeprom.c create mode 100644 utils/rtl_fm.c create mode 100644 utils/rtl_power.c create mode 100644 utils/rtl_sdr.c create mode 100644 utils/rtl_tcp.c create mode 100644 utils/rtl_test.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0d9484d --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +build/* +*.a +*.so +*.so.1 \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..2388da1 --- /dev/null +++ b/Makefile @@ -0,0 +1,41 @@ +PROJECT=r820t +CC=gcc +CFLAGS= +INCLUDE=-I./include +INCLUDE+=`pkg-config --cflags libusb` +LDFLAGS= +LDFLAGS+=`pkg-config --libs libusb` + +SOURCES= +SRC_LIB= +OBJ_LIB= +SRC_UTILS= +OBJ_UTILS= + +BUILD_DIR=build/ + +include src/make.mk +include utils/make.mk + +OBJECTS=$(SOURCES:.c=.o) + +lib: src-lib + +utils: $(DIR)-pre $(OBJ_UTILS) + +all: $(OBJECTS) + +make: $(OBJECTS) + echo $(OBJECTS) + + +%.o: %.c + $(CC) $(CFLAGS) $(INCLUDE) -c $< -o $(BUILD_DIR)$@ + +clean: + rm -f *.a + rm -f *.so + rm -f *.so.1 + rm -f build/src/*.o + rm -f build/utils/rtl_* + rm -f build/utils/convenience/*.o diff --git a/build/src/.empty b/build/src/.empty new file mode 100644 index 0000000..e69de29 diff --git a/build/utils/convenience/.empty b/build/utils/convenience/.empty new file mode 100644 index 0000000..e69de29 diff --git a/include/reg_field.h b/include/reg_field.h new file mode 100644 index 0000000..18a6922 --- /dev/null +++ b/include/reg_field.h @@ -0,0 +1,60 @@ +#ifndef _REG_FIELD_H +#define _REG_FIELD_H + +#include +#include + +enum cmd_op { + CMD_OP_GET = (1 << 0), + CMD_OP_SET = (1 << 1), + CMD_OP_EXEC = (1 << 2), +}; + +enum pstate { + ST_IN_CMD, + ST_IN_ARG, +}; + +struct strbuf { + uint8_t idx; + char buf[32]; +}; + +struct cmd_state { + struct strbuf cmd; + struct strbuf arg; + enum pstate state; + void (*out)(const char *format, va_list ap); +}; + +struct cmd { + const char *cmd; + uint32_t ops; + int (*cb)(struct cmd_state *cs, enum cmd_op op, const char *cmd, + int argc, char **argv); + const char *help; +}; + +/* structure describing a field in a register */ +struct reg_field { + uint8_t reg; + uint8_t shift; + uint8_t width; +}; + +struct reg_field_ops { + const struct reg_field *fields; + const char **field_names; + uint32_t num_fields; + void *data; + int (*write_cb)(void *data, uint32_t reg, uint32_t val); + uint32_t (*read_cb)(void *data, uint32_t reg); +}; + +uint32_t reg_field_read(struct reg_field_ops *ops, struct reg_field *field); +int reg_field_write(struct reg_field_ops *ops, struct reg_field *field, uint32_t val); +int reg_field_cmd(struct cmd_state *cs, enum cmd_op op, + const char *cmd, int argc, char **argv, + struct reg_field_ops *ops); + +#endif diff --git a/include/rtl-sdr.h b/include/rtl-sdr.h new file mode 100644 index 0000000..fe64bea --- /dev/null +++ b/include/rtl-sdr.h @@ -0,0 +1,387 @@ +/* + * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver + * Copyright (C) 2012-2013 by Steve Markgraf + * Copyright (C) 2012 by Dimitri Stolnikov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __RTL_SDR_H +#define __RTL_SDR_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +typedef struct rtlsdr_dev rtlsdr_dev_t; + +RTLSDR_API uint32_t rtlsdr_get_device_count(void); + +RTLSDR_API const char* rtlsdr_get_device_name(uint32_t index); + +/*! + * Get USB device strings. + * + * NOTE: The string arguments must provide space for up to 256 bytes. + * + * \param index the device index + * \param manufact manufacturer name, may be NULL + * \param product product name, may be NULL + * \param serial serial number, may be NULL + * \return 0 on success + */ +RTLSDR_API int rtlsdr_get_device_usb_strings(uint32_t index, + char *manufact, + char *product, + char *serial); + +/*! + * Get device index by USB serial string descriptor. + * + * \param serial serial string of the device + * \return device index of first device where the name matched + * \return -1 if name is NULL + * \return -2 if no devices were found at all + * \return -3 if devices were found, but none with matching name + */ +RTLSDR_API int rtlsdr_get_index_by_serial(const char *serial); + +RTLSDR_API int rtlsdr_open(rtlsdr_dev_t **dev, uint32_t index); + +RTLSDR_API int rtlsdr_close(rtlsdr_dev_t *dev); + +/* configuration functions */ + +/*! + * Set crystal oscillator frequencies used for the RTL2832 and the tuner IC. + * + * Usually both ICs use the same clock. Changing the clock may make sense if + * you are applying an external clock to the tuner or to compensate the + * frequency (and samplerate) error caused by the original (cheap) crystal. + * + * NOTE: Call this function only if you fully understand the implications. + * + * \param dev the device handle given by rtlsdr_open() + * \param rtl_freq frequency value used to clock the RTL2832 in Hz + * \param tuner_freq frequency value used to clock the tuner IC in Hz + * \return 0 on success + */ +RTLSDR_API int rtlsdr_set_xtal_freq(rtlsdr_dev_t *dev, uint32_t rtl_freq, + uint32_t tuner_freq); + +/*! + * Get crystal oscillator frequencies used for the RTL2832 and the tuner IC. + * + * Usually both ICs use the same clock. + * + * \param dev the device handle given by rtlsdr_open() + * \param rtl_freq frequency value used to clock the RTL2832 in Hz + * \param tuner_freq frequency value used to clock the tuner IC in Hz + * \return 0 on success + */ +RTLSDR_API int rtlsdr_get_xtal_freq(rtlsdr_dev_t *dev, uint32_t *rtl_freq, + uint32_t *tuner_freq); + +/*! + * Get USB device strings. + * + * NOTE: The string arguments must provide space for up to 256 bytes. + * + * \param dev the device handle given by rtlsdr_open() + * \param manufact manufacturer name, may be NULL + * \param product product name, may be NULL + * \param serial serial number, may be NULL + * \return 0 on success + */ +RTLSDR_API int rtlsdr_get_usb_strings(rtlsdr_dev_t *dev, char *manufact, + char *product, char *serial); + +/*! + * Write the device EEPROM + * + * \param dev the device handle given by rtlsdr_open() + * \param data buffer of data to be written + * \param offset address where the data should be written + * \param len length of the data + * \return 0 on success + * \return -1 if device handle is invalid + * \return -2 if EEPROM size is exceeded + * \return -3 if no EEPROM was found + */ + +RTLSDR_API int rtlsdr_write_eeprom(rtlsdr_dev_t *dev, uint8_t *data, + uint8_t offset, uint16_t len); + +/*! + * Read the device EEPROM + * + * \param dev the device handle given by rtlsdr_open() + * \param data buffer where the data should be written + * \param offset address where the data should be read from + * \param len length of the data + * \return 0 on success + * \return -1 if device handle is invalid + * \return -2 if EEPROM size is exceeded + * \return -3 if no EEPROM was found + */ + +RTLSDR_API int rtlsdr_read_eeprom(rtlsdr_dev_t *dev, uint8_t *data, + uint8_t offset, uint16_t len); + +RTLSDR_API int rtlsdr_set_center_freq(rtlsdr_dev_t *dev, uint32_t freq); + +/*! + * Get actual frequency the device is tuned to. + * + * \param dev the device handle given by rtlsdr_open() + * \return 0 on error, frequency in Hz otherwise + */ +RTLSDR_API uint32_t rtlsdr_get_center_freq(rtlsdr_dev_t *dev); + +/*! + * Set the frequency correction value for the device. + * + * \param dev the device handle given by rtlsdr_open() + * \param ppm correction value in parts per million (ppm) + * \return 0 on success + */ +RTLSDR_API int rtlsdr_set_freq_correction(rtlsdr_dev_t *dev, int ppm); + +/*! + * Get actual frequency correction value of the device. + * + * \param dev the device handle given by rtlsdr_open() + * \return correction value in parts per million (ppm) + */ +RTLSDR_API int rtlsdr_get_freq_correction(rtlsdr_dev_t *dev); + +enum rtlsdr_tuner { + RTLSDR_TUNER_UNKNOWN = 0, + RTLSDR_TUNER_E4000, + RTLSDR_TUNER_FC0012, + RTLSDR_TUNER_FC0013, + RTLSDR_TUNER_FC2580, + RTLSDR_TUNER_R820T, + RTLSDR_TUNER_R828D +}; + +/*! + * Get the tuner type. + * + * \param dev the device handle given by rtlsdr_open() + * \return RTLSDR_TUNER_UNKNOWN on error, tuner type otherwise + */ +RTLSDR_API enum rtlsdr_tuner rtlsdr_get_tuner_type(rtlsdr_dev_t *dev); + +/*! + * Get a list of gains supported by the tuner. + * + * NOTE: The gains argument must be preallocated by the caller. If NULL is + * being given instead, the number of available gain values will be returned. + * + * \param dev the device handle given by rtlsdr_open() + * \param gains array of gain values. In tenths of a dB, 115 means 11.5 dB. + * \return <= 0 on error, number of available (returned) gain values otherwise + */ +RTLSDR_API int rtlsdr_get_tuner_gains(rtlsdr_dev_t *dev, int *gains); + +/*! + * Set the gain for the device. + * Manual gain mode must be enabled for this to work. + * + * Valid gain values (in tenths of a dB) for the E4000 tuner: + * -10, 15, 40, 65, 90, 115, 140, 165, 190, + * 215, 240, 290, 340, 420, 430, 450, 470, 490 + * + * Valid gain values may be queried with \ref rtlsdr_get_tuner_gains function. + * + * \param dev the device handle given by rtlsdr_open() + * \param gain in tenths of a dB, 115 means 11.5 dB. + * \return 0 on success + */ +RTLSDR_API int rtlsdr_set_tuner_gain(rtlsdr_dev_t *dev, int gain); + +/*! + * Set the bandwidth for the device. + * + * \param dev the device handle given by rtlsdr_open() + * \param bw bandwidth in Hz. Zero means automatic BW selection. + * \return 0 on success + */ +RTLSDR_API int rtlsdr_set_tuner_bandwidth(rtlsdr_dev_t *dev, uint32_t bw); + +/*! + * Get actual gain the device is configured to. + * + * \param dev the device handle given by rtlsdr_open() + * \return 0 on error, gain in tenths of a dB, 115 means 11.5 dB. + */ +RTLSDR_API int rtlsdr_get_tuner_gain(rtlsdr_dev_t *dev); + +/*! + * Set the intermediate frequency gain for the device. + * + * \param dev the device handle given by rtlsdr_open() + * \param stage intermediate frequency gain stage number (1 to 6 for E4000) + * \param gain in tenths of a dB, -30 means -3.0 dB. + * \return 0 on success + */ +RTLSDR_API int rtlsdr_set_tuner_if_gain(rtlsdr_dev_t *dev, int stage, int gain); + +/*! + * Set the gain mode (automatic/manual) for the device. + * Manual gain mode must be enabled for the gain setter function to work. + * + * \param dev the device handle given by rtlsdr_open() + * \param manual gain mode, 1 means manual gain mode shall be enabled. + * \return 0 on success + */ +RTLSDR_API int rtlsdr_set_tuner_gain_mode(rtlsdr_dev_t *dev, int manual); + +/*! + * Set the sample rate for the device, also selects the baseband filters + * according to the requested sample rate for tuners where this is possible. + * + * \param dev the device handle given by rtlsdr_open() + * \param samp_rate the sample rate to be set, possible values are: + * 225001 - 300000 Hz + * 900001 - 3200000 Hz + * sample loss is to be expected for rates > 2400000 + * \return 0 on success, -EINVAL on invalid rate + */ +RTLSDR_API int rtlsdr_set_sample_rate(rtlsdr_dev_t *dev, uint32_t rate); + +/*! + * Get actual sample rate the device is configured to. + * + * \param dev the device handle given by rtlsdr_open() + * \return 0 on error, sample rate in Hz otherwise + */ +RTLSDR_API uint32_t rtlsdr_get_sample_rate(rtlsdr_dev_t *dev); + +/*! + * Enable test mode that returns an 8 bit counter instead of the samples. + * The counter is generated inside the RTL2832. + * + * \param dev the device handle given by rtlsdr_open() + * \param test mode, 1 means enabled, 0 disabled + * \return 0 on success + */ +RTLSDR_API int rtlsdr_set_testmode(rtlsdr_dev_t *dev, int on); + +/*! + * Enable or disable the internal digital AGC of the RTL2832. + * + * \param dev the device handle given by rtlsdr_open() + * \param digital AGC mode, 1 means enabled, 0 disabled + * \return 0 on success + */ +RTLSDR_API int rtlsdr_set_agc_mode(rtlsdr_dev_t *dev, int on); + +/*! + * Enable or disable the direct sampling mode. When enabled, the IF mode + * of the RTL2832 is activated, and rtlsdr_set_center_freq() will control + * the IF-frequency of the DDC, which can be used to tune from 0 to 28.8 MHz + * (xtal frequency of the RTL2832). + * + * \param dev the device handle given by rtlsdr_open() + * \param on 0 means disabled, 1 I-ADC input enabled, 2 Q-ADC input enabled + * \return 0 on success + */ +RTLSDR_API int rtlsdr_set_direct_sampling(rtlsdr_dev_t *dev, int on); + +/*! + * Get state of the direct sampling mode + * + * \param dev the device handle given by rtlsdr_open() + * \return -1 on error, 0 means disabled, 1 I-ADC input enabled + * 2 Q-ADC input enabled + */ +RTLSDR_API int rtlsdr_get_direct_sampling(rtlsdr_dev_t *dev); + +/*! + * Enable or disable offset tuning for zero-IF tuners, which allows to avoid + * problems caused by the DC offset of the ADCs and 1/f noise. + * + * \param dev the device handle given by rtlsdr_open() + * \param on 0 means disabled, 1 enabled + * \return 0 on success + */ +RTLSDR_API int rtlsdr_set_offset_tuning(rtlsdr_dev_t *dev, int on); + +/*! + * Get state of the offset tuning mode + * + * \param dev the device handle given by rtlsdr_open() + * \return -1 on error, 0 means disabled, 1 enabled + */ +RTLSDR_API int rtlsdr_get_offset_tuning(rtlsdr_dev_t *dev); + +/* streaming functions */ + +RTLSDR_API int rtlsdr_reset_buffer(rtlsdr_dev_t *dev); + +RTLSDR_API int rtlsdr_read_sync(rtlsdr_dev_t *dev, void *buf, int len, int *n_read); + +typedef void(*rtlsdr_read_async_cb_t)(unsigned char *buf, uint32_t len, void *ctx); + +/*! + * Read samples from the device asynchronously. This function will block until + * it is being canceled using rtlsdr_cancel_async() + * + * NOTE: This function is deprecated and is subject for removal. + * + * \param dev the device handle given by rtlsdr_open() + * \param cb callback function to return received samples + * \param ctx user specific context to pass via the callback function + * \return 0 on success + */ +RTLSDR_API int rtlsdr_wait_async(rtlsdr_dev_t *dev, rtlsdr_read_async_cb_t cb, void *ctx); + +/*! + * Read samples from the device asynchronously. This function will block until + * it is being canceled using rtlsdr_cancel_async() + * + * \param dev the device handle given by rtlsdr_open() + * \param cb callback function to return received samples + * \param ctx user specific context to pass via the callback function + * \param buf_num optional buffer count, buf_num * buf_len = overall buffer size + * set to 0 for default buffer count (15) + * \param buf_len optional buffer length, must be multiple of 512, + * should be a multiple of 16384 (URB size), set to 0 + * for default buffer length (16 * 32 * 512) + * \return 0 on success + */ +RTLSDR_API int rtlsdr_read_async(rtlsdr_dev_t *dev, + rtlsdr_read_async_cb_t cb, + void *ctx, + uint32_t buf_num, + uint32_t buf_len); + +/*! + * Cancel all pending asynchronous operations on the device. + * + * \param dev the device handle given by rtlsdr_open() + * \return 0 on success + */ +RTLSDR_API int rtlsdr_cancel_async(rtlsdr_dev_t *dev); + +#ifdef __cplusplus +} +#endif + +#endif /* __RTL_SDR_H */ diff --git a/include/rtl-sdr_export.h b/include/rtl-sdr_export.h new file mode 100644 index 0000000..69e178d --- /dev/null +++ b/include/rtl-sdr_export.h @@ -0,0 +1,47 @@ +/* + * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver + * Copyright (C) 2012 by Hoernchen + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef RTLSDR_EXPORT_H +#define RTLSDR_EXPORT_H + +#if defined __GNUC__ +# if __GNUC__ >= 4 +# define __SDR_EXPORT __attribute__((visibility("default"))) +# define __SDR_IMPORT __attribute__((visibility("default"))) +# else +# define __SDR_EXPORT +# define __SDR_IMPORT +# endif +#elif _MSC_VER +# define __SDR_EXPORT __declspec(dllexport) +# define __SDR_IMPORT __declspec(dllimport) +#else +# define __SDR_EXPORT +# define __SDR_IMPORT +#endif + +#ifndef rtlsdr_STATIC +# ifdef rtlsdr_EXPORTS +# define RTLSDR_API __SDR_EXPORT +# else +# define RTLSDR_API __SDR_IMPORT +# endif +#else +#define RTLSDR_API +#endif +#endif /* RTLSDR_EXPORT_H */ diff --git a/include/rtlsdr_i2c.h b/include/rtlsdr_i2c.h new file mode 100644 index 0000000..7676689 --- /dev/null +++ b/include/rtlsdr_i2c.h @@ -0,0 +1,8 @@ +#ifndef __I2C_H +#define __I2C_H + +uint32_t rtlsdr_get_tuner_clock(void *dev); +int rtlsdr_i2c_write_fn(void *dev, uint8_t addr, uint8_t *buf, int len); +int rtlsdr_i2c_read_fn(void *dev, uint8_t addr, uint8_t *buf, int len); + +#endif diff --git a/include/tuner_e4k.h b/include/tuner_e4k.h new file mode 100644 index 0000000..79591ce --- /dev/null +++ b/include/tuner_e4k.h @@ -0,0 +1,222 @@ +#ifndef _E4K_TUNER_H +#define _E4K_TUNER_H + +/* + * Elonics E4000 tuner driver + * + * (C) 2011-2012 by Harald Welte + * (C) 2012 by Sylvain Munaut + * (C) 2012 by Hoernchen + * + * All Rights Reserved + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#define E4K_I2C_ADDR 0xc8 +#define E4K_CHECK_ADDR 0x02 +#define E4K_CHECK_VAL 0x40 + +enum e4k_reg { + E4K_REG_MASTER1 = 0x00, + E4K_REG_MASTER2 = 0x01, + E4K_REG_MASTER3 = 0x02, + E4K_REG_MASTER4 = 0x03, + E4K_REG_MASTER5 = 0x04, + E4K_REG_CLK_INP = 0x05, + E4K_REG_REF_CLK = 0x06, + E4K_REG_SYNTH1 = 0x07, + E4K_REG_SYNTH2 = 0x08, + E4K_REG_SYNTH3 = 0x09, + E4K_REG_SYNTH4 = 0x0a, + E4K_REG_SYNTH5 = 0x0b, + E4K_REG_SYNTH6 = 0x0c, + E4K_REG_SYNTH7 = 0x0d, + E4K_REG_SYNTH8 = 0x0e, + E4K_REG_SYNTH9 = 0x0f, + E4K_REG_FILT1 = 0x10, + E4K_REG_FILT2 = 0x11, + E4K_REG_FILT3 = 0x12, + // gap + E4K_REG_GAIN1 = 0x14, + E4K_REG_GAIN2 = 0x15, + E4K_REG_GAIN3 = 0x16, + E4K_REG_GAIN4 = 0x17, + // gap + E4K_REG_AGC1 = 0x1a, + E4K_REG_AGC2 = 0x1b, + E4K_REG_AGC3 = 0x1c, + E4K_REG_AGC4 = 0x1d, + E4K_REG_AGC5 = 0x1e, + E4K_REG_AGC6 = 0x1f, + E4K_REG_AGC7 = 0x20, + E4K_REG_AGC8 = 0x21, + // gap + E4K_REG_AGC11 = 0x24, + E4K_REG_AGC12 = 0x25, + // gap + E4K_REG_DC1 = 0x29, + E4K_REG_DC2 = 0x2a, + E4K_REG_DC3 = 0x2b, + E4K_REG_DC4 = 0x2c, + E4K_REG_DC5 = 0x2d, + E4K_REG_DC6 = 0x2e, + E4K_REG_DC7 = 0x2f, + E4K_REG_DC8 = 0x30, + // gap + E4K_REG_QLUT0 = 0x50, + E4K_REG_QLUT1 = 0x51, + E4K_REG_QLUT2 = 0x52, + E4K_REG_QLUT3 = 0x53, + // gap + E4K_REG_ILUT0 = 0x60, + E4K_REG_ILUT1 = 0x61, + E4K_REG_ILUT2 = 0x62, + E4K_REG_ILUT3 = 0x63, + // gap + E4K_REG_DCTIME1 = 0x70, + E4K_REG_DCTIME2 = 0x71, + E4K_REG_DCTIME3 = 0x72, + E4K_REG_DCTIME4 = 0x73, + E4K_REG_PWM1 = 0x74, + E4K_REG_PWM2 = 0x75, + E4K_REG_PWM3 = 0x76, + E4K_REG_PWM4 = 0x77, + E4K_REG_BIAS = 0x78, + E4K_REG_CLKOUT_PWDN = 0x7a, + E4K_REG_CHFILT_CALIB = 0x7b, + E4K_REG_I2C_REG_ADDR = 0x7d, + // FIXME +}; + +#define E4K_MASTER1_RESET (1 << 0) +#define E4K_MASTER1_NORM_STBY (1 << 1) +#define E4K_MASTER1_POR_DET (1 << 2) + +#define E4K_SYNTH1_PLL_LOCK (1 << 0) +#define E4K_SYNTH1_BAND_SHIF 1 + +#define E4K_SYNTH7_3PHASE_EN (1 << 3) + +#define E4K_SYNTH8_VCOCAL_UPD (1 << 2) + +#define E4K_FILT3_DISABLE (1 << 5) + +#define E4K_AGC1_LIN_MODE (1 << 4) +#define E4K_AGC1_LNA_UPDATE (1 << 5) +#define E4K_AGC1_LNA_G_LOW (1 << 6) +#define E4K_AGC1_LNA_G_HIGH (1 << 7) + +#define E4K_AGC6_LNA_CAL_REQ (1 << 4) + +#define E4K_AGC7_MIX_GAIN_AUTO (1 << 0) +#define E4K_AGC7_GAIN_STEP_5dB (1 << 5) + +#define E4K_AGC8_SENS_LIN_AUTO (1 << 0) + +#define E4K_AGC11_LNA_GAIN_ENH (1 << 0) + +#define E4K_DC1_CAL_REQ (1 << 0) + +#define E4K_DC5_I_LUT_EN (1 << 0) +#define E4K_DC5_Q_LUT_EN (1 << 1) +#define E4K_DC5_RANGE_DET_EN (1 << 2) +#define E4K_DC5_RANGE_EN (1 << 3) +#define E4K_DC5_TIMEVAR_EN (1 << 4) + +#define E4K_CLKOUT_DISABLE 0x96 + +#define E4K_CHFCALIB_CMD (1 << 0) + +#define E4K_AGC1_MOD_MASK 0xF + +enum e4k_agc_mode { + E4K_AGC_MOD_SERIAL = 0x0, + E4K_AGC_MOD_IF_PWM_LNA_SERIAL = 0x1, + E4K_AGC_MOD_IF_PWM_LNA_AUTONL = 0x2, + E4K_AGC_MOD_IF_PWM_LNA_SUPERV = 0x3, + E4K_AGC_MOD_IF_SERIAL_LNA_PWM = 0x4, + E4K_AGC_MOD_IF_PWM_LNA_PWM = 0x5, + E4K_AGC_MOD_IF_DIG_LNA_SERIAL = 0x6, + E4K_AGC_MOD_IF_DIG_LNA_AUTON = 0x7, + E4K_AGC_MOD_IF_DIG_LNA_SUPERV = 0x8, + E4K_AGC_MOD_IF_SERIAL_LNA_AUTON = 0x9, + E4K_AGC_MOD_IF_SERIAL_LNA_SUPERV = 0xa, +}; + +enum e4k_band { + E4K_BAND_VHF2 = 0, + E4K_BAND_VHF3 = 1, + E4K_BAND_UHF = 2, + E4K_BAND_L = 3, +}; + +enum e4k_mixer_filter_bw { + E4K_F_MIX_BW_27M = 0, + E4K_F_MIX_BW_4M6 = 8, + E4K_F_MIX_BW_4M2 = 9, + E4K_F_MIX_BW_3M8 = 10, + E4K_F_MIX_BW_3M4 = 11, + E4K_F_MIX_BW_3M = 12, + E4K_F_MIX_BW_2M7 = 13, + E4K_F_MIX_BW_2M3 = 14, + E4K_F_MIX_BW_1M9 = 15, +}; + +enum e4k_if_filter { + E4K_IF_FILTER_MIX, + E4K_IF_FILTER_CHAN, + E4K_IF_FILTER_RC +}; +struct e4k_pll_params { + uint32_t fosc; + uint32_t intended_flo; + uint32_t flo; + uint16_t x; + uint8_t z; + uint8_t r; + uint8_t r_idx; + uint8_t threephase; +}; + +struct e4k_state { + void *i2c_dev; + uint8_t i2c_addr; + enum e4k_band band; + struct e4k_pll_params vco; + void *rtl_dev; +}; + +int e4k_init(struct e4k_state *e4k); +int e4k_standby(struct e4k_state *e4k, int enable); +int e4k_if_gain_set(struct e4k_state *e4k, uint8_t stage, int8_t value); +int e4k_mixer_gain_set(struct e4k_state *e4k, int8_t value); +int e4k_commonmode_set(struct e4k_state *e4k, int8_t value); +int e4k_tune_freq(struct e4k_state *e4k, uint32_t freq); +int e4k_tune_params(struct e4k_state *e4k, struct e4k_pll_params *p); +uint32_t e4k_compute_pll_params(struct e4k_pll_params *oscp, uint32_t fosc, uint32_t intended_flo); +int e4k_if_filter_bw_get(struct e4k_state *e4k, enum e4k_if_filter filter); +int e4k_if_filter_bw_set(struct e4k_state *e4k, enum e4k_if_filter filter, + uint32_t bandwidth); +int e4k_if_filter_chan_enable(struct e4k_state *e4k, int on); +int e4k_rf_filter_set(struct e4k_state *e4k); + +int e4k_manual_dc_offset(struct e4k_state *e4k, int8_t iofs, int8_t irange, int8_t qofs, int8_t qrange); +int e4k_dc_offset_calibrate(struct e4k_state *e4k); +int e4k_dc_offset_gen_table(struct e4k_state *e4k); + +int e4k_set_lna_gain(struct e4k_state *e4k, int32_t gain); +int e4k_enable_manual_gain(struct e4k_state *e4k, uint8_t manual); +int e4k_set_enh_gain(struct e4k_state *e4k, int32_t gain); +#endif /* _E4K_TUNER_H */ diff --git a/include/tuner_fc0012.h b/include/tuner_fc0012.h new file mode 100644 index 0000000..9dd5356 --- /dev/null +++ b/include/tuner_fc0012.h @@ -0,0 +1,36 @@ +/* + * Fitipower FC0012 tuner driver + * + * Copyright (C) 2012 Hans-Frieder Vogt + * + * modified for use in librtlsdr + * Copyright (C) 2012 Steve Markgraf + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + */ + +#ifndef _FC0012_H_ +#define _FC0012_H_ + +#define FC0012_I2C_ADDR 0xc6 +#define FC0012_CHECK_ADDR 0x00 +#define FC0012_CHECK_VAL 0xa1 + +int fc0012_init(void *dev); +int fc0012_set_params(void *dev, uint32_t freq, uint32_t bandwidth); +int fc0012_set_gain(void *dev, int gain); + +#endif diff --git a/include/tuner_fc0013.h b/include/tuner_fc0013.h new file mode 100644 index 0000000..68a26ee --- /dev/null +++ b/include/tuner_fc0013.h @@ -0,0 +1,37 @@ +/* + * Fitipower FC0013 tuner driver + * + * Copyright (C) 2012 Hans-Frieder Vogt + * + * modified for use in librtlsdr + * Copyright (C) 2012 Steve Markgraf + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + */ + +#ifndef _FC0013_H_ +#define _FC0013_H_ + +#define FC0013_I2C_ADDR 0xc6 +#define FC0013_CHECK_ADDR 0x00 +#define FC0013_CHECK_VAL 0xa3 + +int fc0013_init(void *dev); +int fc0013_set_params(void *dev, uint32_t freq, uint32_t bandwidth); +int fc0013_set_gain_mode(void *dev, int manual); +int fc0013_set_lna_gain(void *dev, int gain); + +#endif diff --git a/include/tuner_fc2580.h b/include/tuner_fc2580.h new file mode 100644 index 0000000..9ebd935 --- /dev/null +++ b/include/tuner_fc2580.h @@ -0,0 +1,127 @@ +#ifndef __TUNER_FC2580_H +#define __TUNER_FC2580_H + +#define BORDER_FREQ 2600000 //2.6GHz : The border frequency which determines whether Low VCO or High VCO is used +#define USE_EXT_CLK 0 //0 : Use internal XTAL Oscillator / 1 : Use External Clock input +#define OFS_RSSI 57 + +#define FC2580_I2C_ADDR 0xac +#define FC2580_CHECK_ADDR 0x01 +#define FC2580_CHECK_VAL 0x56 + +typedef enum { + FC2580_UHF_BAND, + FC2580_L_BAND, + FC2580_VHF_BAND, + FC2580_NO_BAND +} fc2580_band_type; + +typedef enum { + FC2580_FCI_FAIL, + FC2580_FCI_SUCCESS +} fc2580_fci_result_type; + +enum FUNCTION_STATUS +{ + FUNCTION_SUCCESS, + FUNCTION_ERROR, +}; + +extern void fc2580_wait_msec(void *pTuner, int a); + +fc2580_fci_result_type fc2580_i2c_write(void *pTuner, unsigned char reg, unsigned char val); +fc2580_fci_result_type fc2580_i2c_read(void *pTuner, unsigned char reg, unsigned char *read_data); + +/*============================================================================== + fc2580 initial setting + + This function is a generic function which gets called to initialize + + fc2580 in DVB-H mode or L-Band TDMB mode + + + + ifagc_mode + type : integer + 1 : Internal AGC + 2 : Voltage Control Mode + +==============================================================================*/ +fc2580_fci_result_type fc2580_set_init(void *pTuner, int ifagc_mode, unsigned int freq_xtal ); + +/*============================================================================== + fc2580 frequency setting + + This function is a generic function which gets called to change LO Frequency + + of fc2580 in DVB-H mode or L-Band TDMB mode + + + + f_lo + Value of target LO Frequency in 'kHz' unit + ex) 2.6GHz = 2600000 + +==============================================================================*/ +fc2580_fci_result_type fc2580_set_freq(void *pTuner, unsigned int f_lo, unsigned int freq_xtal ); + + +/*============================================================================== + fc2580 filter BW setting + + This function is a generic function which gets called to change Bandwidth + + frequency of fc2580's channel selection filter + + + + filter_bw + 1 : 1.53MHz(TDMB) + 6 : 6MHz + 7 : 7MHz + 8 : 7.8MHz + + +==============================================================================*/ +fc2580_fci_result_type fc2580_set_filter( void *pTuner, unsigned char filter_bw, unsigned int freq_xtal ); + +// The following context is FC2580 tuner API source code +// Definitions + +// AGC mode +enum FC2580_AGC_MODE +{ + FC2580_AGC_INTERNAL = 1, + FC2580_AGC_EXTERNAL = 2, +}; + + +// Bandwidth mode +enum FC2580_BANDWIDTH_MODE +{ + FC2580_BANDWIDTH_1530000HZ = 1, + FC2580_BANDWIDTH_6000000HZ = 6, + FC2580_BANDWIDTH_7000000HZ = 7, + FC2580_BANDWIDTH_8000000HZ = 8, +}; + +// Manipulaing functions +int +fc2580_Initialize( + void *pTuner + ); + +int +fc2580_SetRfFreqHz( + void *pTuner, + unsigned long RfFreqHz + ); + +// Extra manipulaing functions +int +fc2580_SetBandwidthMode( + void *pTuner, + int BandwidthMode + ); + +#endif diff --git a/include/tuner_r82xx.h b/include/tuner_r82xx.h new file mode 100644 index 0000000..f6c206a --- /dev/null +++ b/include/tuner_r82xx.h @@ -0,0 +1,120 @@ +/* + * Rafael Micro R820T/R828D driver + * + * Copyright (C) 2013 Mauro Carvalho Chehab + * Copyright (C) 2013 Steve Markgraf + * + * This driver is a heavily modified version of the driver found in the + * Linux kernel: + * http://git.linuxtv.org/linux-2.6.git/history/HEAD:/drivers/media/tuners/r820t.c + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef R82XX_H +#define R82XX_H + +#define R820T_I2C_ADDR 0x34 +#define R828D_I2C_ADDR 0x74 +#define R828D_XTAL_FREQ 16000000 + +#define R82XX_CHECK_ADDR 0x00 +#define R82XX_CHECK_VAL 0x69 + +#define R82XX_IF_FREQ 3570000 + +#define REG_SHADOW_START 5 +#define NUM_REGS 30 +#define NUM_IMR 5 +#define IMR_TRIAL 9 + +#define VER_NUM 49 + +enum r82xx_chip { + CHIP_R820T, + CHIP_R620D, + CHIP_R828D, + CHIP_R828, + CHIP_R828S, + CHIP_R820C, +}; + +enum r82xx_tuner_type { + TUNER_RADIO = 1, + TUNER_ANALOG_TV, + TUNER_DIGITAL_TV +}; + +enum r82xx_xtal_cap_value { + XTAL_LOW_CAP_30P = 0, + XTAL_LOW_CAP_20P, + XTAL_LOW_CAP_10P, + XTAL_LOW_CAP_0P, + XTAL_HIGH_CAP_0P +}; + +struct r82xx_config { + uint8_t i2c_addr; + uint32_t xtal; + enum r82xx_chip rafael_chip; + unsigned int max_i2c_msg_len; + int use_predetect; +}; + +struct r82xx_priv { + struct r82xx_config *cfg; + + uint8_t regs[NUM_REGS]; + uint8_t buf[NUM_REGS + 1]; + enum r82xx_xtal_cap_value xtal_cap_sel; + uint16_t pll; /* kHz */ + uint32_t int_freq; + uint8_t fil_cal_code; + uint8_t input; + int has_lock; + int init_done; + + /* Store current mode */ + uint32_t delsys; + enum r82xx_tuner_type type; + + uint32_t bw; /* in MHz */ + + void *rtl_dev; +}; + +struct r82xx_freq_range { + uint32_t freq; + uint8_t open_d; + uint8_t rf_mux_ploy; + uint8_t tf_c; + uint8_t xtal_cap20p; + uint8_t xtal_cap10p; + uint8_t xtal_cap0p; +}; + +enum r82xx_delivery_system { + SYS_UNDEFINED, + SYS_DVBT, + SYS_DVBT2, + SYS_ISDBT, +}; + +int r82xx_standby(struct r82xx_priv *priv); +int r82xx_init(struct r82xx_priv *priv); +int r82xx_set_freq(struct r82xx_priv *priv, uint32_t freq); +int r82xx_set_gain(struct r82xx_priv *priv, int set_manual_gain, int gain); +int r82xx_set_bandwidth(struct r82xx_priv *priv, int bandwidth, uint32_t rate); + +#endif diff --git a/src/librtlsdr.c b/src/librtlsdr.c new file mode 100644 index 0000000..cdf1ca9 --- /dev/null +++ b/src/librtlsdr.c @@ -0,0 +1,1938 @@ +/* + * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver + * Copyright (C) 2012-2014 by Steve Markgraf + * Copyright (C) 2012 by Dimitri Stolnikov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#ifndef _WIN32 +#include +#define min(a, b) (((a) < (b)) ? (a) : (b)) +#endif + +#include + +/* + * All libusb callback functions should be marked with the LIBUSB_CALL macro + * to ensure that they are compiled with the same calling convention as libusb. + * + * If the macro isn't available in older libusb versions, we simply define it. + */ +#ifndef LIBUSB_CALL +#define LIBUSB_CALL +#endif + +/* libusb < 1.0.9 doesn't have libusb_handle_events_timeout_completed */ +#ifndef HAVE_LIBUSB_HANDLE_EVENTS_TIMEOUT_COMPLETED +#define libusb_handle_events_timeout_completed(ctx, tv, c) \ + libusb_handle_events_timeout(ctx, tv) +#endif + +/* two raised to the power of n */ +#define TWO_POW(n) ((double)(1ULL<<(n))) + +#include "rtl-sdr.h" +#include "tuner_e4k.h" +#include "tuner_fc0012.h" +#include "tuner_fc0013.h" +#include "tuner_fc2580.h" +#include "tuner_r82xx.h" + +typedef struct rtlsdr_tuner_iface { + /* tuner interface */ + int (*init)(void *); + int (*exit)(void *); + int (*set_freq)(void *, uint32_t freq /* Hz */); + int (*set_bw)(void *, int bw /* Hz */); + int (*set_gain)(void *, int gain /* tenth dB */); + int (*set_if_gain)(void *, int stage, int gain /* tenth dB */); + int (*set_gain_mode)(void *, int manual); +} rtlsdr_tuner_iface_t; + +enum rtlsdr_async_status { + RTLSDR_INACTIVE = 0, + RTLSDR_CANCELING, + RTLSDR_RUNNING +}; + +#define FIR_LEN 16 + +/* + * FIR coefficients. + * + * The filter is running at XTal frequency. It is symmetric filter with 32 + * coefficients. Only first 16 coefficients are specified, the other 16 + * use the same values but in reversed order. The first coefficient in + * the array is the outer one, the last, the last is the inner one. + * First 8 coefficients are 8 bit signed integers, the next 8 coefficients + * are 12 bit signed integers. All coefficients have the same weight. + * + * Default FIR coefficients used for DAB/FM by the Windows driver, + * the DVB driver uses different ones + */ +static const int fir_default[FIR_LEN] = { + -54, -36, -41, -40, -32, -14, 14, 53, /* 8 bit signed */ + 101, 156, 215, 273, 327, 372, 404, 421 /* 12 bit signed */ +}; + +struct rtlsdr_dev { + libusb_context *ctx; + struct libusb_device_handle *devh; + uint32_t xfer_buf_num; + uint32_t xfer_buf_len; + struct libusb_transfer **xfer; + unsigned char **xfer_buf; + rtlsdr_read_async_cb_t cb; + void *cb_ctx; + enum rtlsdr_async_status async_status; + int async_cancel; + /* rtl demod context */ + uint32_t rate; /* Hz */ + uint32_t rtl_xtal; /* Hz */ + int fir[FIR_LEN]; + int direct_sampling; + /* tuner context */ + enum rtlsdr_tuner tuner_type; + rtlsdr_tuner_iface_t *tuner; + uint32_t tun_xtal; /* Hz */ + uint32_t freq; /* Hz */ + uint32_t bw; + uint32_t offs_freq; /* Hz */ + int corr; /* ppm */ + int gain; /* tenth dB */ + struct e4k_state e4k_s; + struct r82xx_config r82xx_c; + struct r82xx_priv r82xx_p; + /* status */ + int dev_lost; + int driver_active; + unsigned int xfer_errors; +}; + +void rtlsdr_set_gpio_bit(rtlsdr_dev_t *dev, uint8_t gpio, int val); +static int rtlsdr_set_if_freq(rtlsdr_dev_t *dev, uint32_t freq); + +/* generic tuner interface functions, shall be moved to the tuner implementations */ +int e4000_init(void *dev) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + devt->e4k_s.i2c_addr = E4K_I2C_ADDR; + rtlsdr_get_xtal_freq(devt, NULL, &devt->e4k_s.vco.fosc); + devt->e4k_s.rtl_dev = dev; + return e4k_init(&devt->e4k_s); +} +int e4000_exit(void *dev) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + return e4k_standby(&devt->e4k_s, 1); +} +int e4000_set_freq(void *dev, uint32_t freq) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + return e4k_tune_freq(&devt->e4k_s, freq); +} + +int e4000_set_bw(void *dev, int bw) { + int r = 0; + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + + r |= e4k_if_filter_bw_set(&devt->e4k_s, E4K_IF_FILTER_MIX, bw); + r |= e4k_if_filter_bw_set(&devt->e4k_s, E4K_IF_FILTER_RC, bw); + r |= e4k_if_filter_bw_set(&devt->e4k_s, E4K_IF_FILTER_CHAN, bw); + + return r; +} + +int e4000_set_gain(void *dev, int gain) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + int mixgain = (gain > 340) ? 12 : 4; +#if 0 + int enhgain = (gain - 420); +#endif + if(e4k_set_lna_gain(&devt->e4k_s, min(300, gain - mixgain * 10)) == -EINVAL) + return -1; + if(e4k_mixer_gain_set(&devt->e4k_s, mixgain) == -EINVAL) + return -1; +#if 0 /* enhanced mixer gain seems to have no effect */ + if(enhgain >= 0) + if(e4k_set_enh_gain(&devt->e4k_s, enhgain) == -EINVAL) + return -1; +#endif + return 0; +} +int e4000_set_if_gain(void *dev, int stage, int gain) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + return e4k_if_gain_set(&devt->e4k_s, (uint8_t)stage, (int8_t)(gain / 10)); +} +int e4000_set_gain_mode(void *dev, int manual) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + return e4k_enable_manual_gain(&devt->e4k_s, manual); +} + +int _fc0012_init(void *dev) { return fc0012_init(dev); } +int fc0012_exit(void *dev) { return 0; } +int fc0012_set_freq(void *dev, uint32_t freq) { + /* select V-band/U-band filter */ + rtlsdr_set_gpio_bit(dev, 6, (freq > 300000000) ? 1 : 0); + return fc0012_set_params(dev, freq, 6000000); +} +int fc0012_set_bw(void *dev, int bw) { return 0; } +int _fc0012_set_gain(void *dev, int gain) { return fc0012_set_gain(dev, gain); } +int fc0012_set_gain_mode(void *dev, int manual) { return 0; } + +int _fc0013_init(void *dev) { return fc0013_init(dev); } +int fc0013_exit(void *dev) { return 0; } +int fc0013_set_freq(void *dev, uint32_t freq) { + return fc0013_set_params(dev, freq, 6000000); +} +int fc0013_set_bw(void *dev, int bw) { return 0; } +int _fc0013_set_gain(void *dev, int gain) { return fc0013_set_lna_gain(dev, gain); } + +int fc2580_init(void *dev) { return fc2580_Initialize(dev); } +int fc2580_exit(void *dev) { return 0; } +int _fc2580_set_freq(void *dev, uint32_t freq) { + return fc2580_SetRfFreqHz(dev, freq); +} +int fc2580_set_bw(void *dev, int bw) { return fc2580_SetBandwidthMode(dev, 1); } +int fc2580_set_gain(void *dev, int gain) { return 0; } +int fc2580_set_gain_mode(void *dev, int manual) { return 0; } + +int r820t_init(void *dev) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + devt->r82xx_p.rtl_dev = dev; + + if (devt->tuner_type == RTLSDR_TUNER_R828D) { + devt->r82xx_c.i2c_addr = R828D_I2C_ADDR; + devt->r82xx_c.rafael_chip = CHIP_R828D; + } else { + devt->r82xx_c.i2c_addr = R820T_I2C_ADDR; + devt->r82xx_c.rafael_chip = CHIP_R820T; + } + + rtlsdr_get_xtal_freq(devt, NULL, &devt->r82xx_c.xtal); + + devt->r82xx_c.max_i2c_msg_len = 8; + devt->r82xx_c.use_predetect = 0; + devt->r82xx_p.cfg = &devt->r82xx_c; + + return r82xx_init(&devt->r82xx_p); +} +int r820t_exit(void *dev) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + return r82xx_standby(&devt->r82xx_p); +} + +int r820t_set_freq(void *dev, uint32_t freq) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + return r82xx_set_freq(&devt->r82xx_p, freq); +} + +int r820t_set_bw(void *dev, int bw) { + int r; + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + + r = r82xx_set_bandwidth(&devt->r82xx_p, bw, devt->rate); + if(r < 0) + return r; + r = rtlsdr_set_if_freq(devt, r); + if (r) + return r; + return rtlsdr_set_center_freq(devt, devt->freq); +} + +int r820t_set_gain(void *dev, int gain) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + return r82xx_set_gain(&devt->r82xx_p, 1, gain); +} +int r820t_set_gain_mode(void *dev, int manual) { + rtlsdr_dev_t* devt = (rtlsdr_dev_t*)dev; + return r82xx_set_gain(&devt->r82xx_p, manual, 0); +} + +/* definition order must match enum rtlsdr_tuner */ +static rtlsdr_tuner_iface_t tuners[] = { + { + NULL, NULL, NULL, NULL, NULL, NULL, NULL /* dummy for unknown tuners */ + }, + { + e4000_init, e4000_exit, + e4000_set_freq, e4000_set_bw, e4000_set_gain, e4000_set_if_gain, + e4000_set_gain_mode + }, + { + _fc0012_init, fc0012_exit, + fc0012_set_freq, fc0012_set_bw, _fc0012_set_gain, NULL, + fc0012_set_gain_mode + }, + { + _fc0013_init, fc0013_exit, + fc0013_set_freq, fc0013_set_bw, _fc0013_set_gain, NULL, + fc0013_set_gain_mode + }, + { + fc2580_init, fc2580_exit, + _fc2580_set_freq, fc2580_set_bw, fc2580_set_gain, NULL, + fc2580_set_gain_mode + }, + { + r820t_init, r820t_exit, + r820t_set_freq, r820t_set_bw, r820t_set_gain, NULL, + r820t_set_gain_mode + }, + { + r820t_init, r820t_exit, + r820t_set_freq, r820t_set_bw, r820t_set_gain, NULL, + r820t_set_gain_mode + }, +}; + +typedef struct rtlsdr_dongle { + uint16_t vid; + uint16_t pid; + const char *name; +} rtlsdr_dongle_t; + +/* + * Please add your device here and send a patch to osmocom-sdr@lists.osmocom.org + */ +static rtlsdr_dongle_t known_devices[] = { + { 0x0bda, 0x2832, "Generic RTL2832U" }, + { 0x0bda, 0x2838, "Generic RTL2832U OEM" }, + { 0x0413, 0x6680, "DigitalNow Quad DVB-T PCI-E card" }, + { 0x0413, 0x6f0f, "Leadtek WinFast DTV Dongle mini D" }, + { 0x0458, 0x707f, "Genius TVGo DVB-T03 USB dongle (Ver. B)" }, + { 0x0ccd, 0x00a9, "Terratec Cinergy T Stick Black (rev 1)" }, + { 0x0ccd, 0x00b3, "Terratec NOXON DAB/DAB+ USB dongle (rev 1)" }, + { 0x0ccd, 0x00b4, "Terratec Deutschlandradio DAB Stick" }, + { 0x0ccd, 0x00b5, "Terratec NOXON DAB Stick - Radio Energy" }, + { 0x0ccd, 0x00b7, "Terratec Media Broadcast DAB Stick" }, + { 0x0ccd, 0x00b8, "Terratec BR DAB Stick" }, + { 0x0ccd, 0x00b9, "Terratec WDR DAB Stick" }, + { 0x0ccd, 0x00c0, "Terratec MuellerVerlag DAB Stick" }, + { 0x0ccd, 0x00c6, "Terratec Fraunhofer DAB Stick" }, + { 0x0ccd, 0x00d3, "Terratec Cinergy T Stick RC (Rev.3)" }, + { 0x0ccd, 0x00d7, "Terratec T Stick PLUS" }, + { 0x0ccd, 0x00e0, "Terratec NOXON DAB/DAB+ USB dongle (rev 2)" }, + { 0x1554, 0x5020, "PixelView PV-DT235U(RN)" }, + { 0x15f4, 0x0131, "Astrometa DVB-T/DVB-T2" }, + { 0x185b, 0x0620, "Compro Videomate U620F"}, + { 0x185b, 0x0650, "Compro Videomate U650F"}, + { 0x185b, 0x0680, "Compro Videomate U680F"}, + { 0x1b80, 0xd393, "GIGABYTE GT-U7300" }, + { 0x1b80, 0xd394, "DIKOM USB-DVBT HD" }, + { 0x1b80, 0xd395, "Peak 102569AGPK" }, + { 0x1b80, 0xd397, "KWorld KW-UB450-T USB DVB-T Pico TV" }, + { 0x1b80, 0xd398, "Zaapa ZT-MINDVBZP" }, + { 0x1b80, 0xd39d, "SVEON STV20 DVB-T USB & FM" }, + { 0x1b80, 0xd3a4, "Twintech UT-40" }, + { 0x1b80, 0xd3a8, "ASUS U3100MINI_PLUS_V2" }, + { 0x1b80, 0xd3af, "SVEON STV27 DVB-T USB & FM" }, + { 0x1b80, 0xd3b0, "SVEON STV21 DVB-T USB & FM" }, + { 0x1d19, 0x1101, "Dexatek DK DVB-T Dongle (Logilink VG0002A)" }, + { 0x1d19, 0x1102, "Dexatek DK DVB-T Dongle (MSI DigiVox mini II V3.0)" }, + { 0x1d19, 0x1103, "Dexatek Technology Ltd. DK 5217 DVB-T Dongle" }, + { 0x1d19, 0x1104, "MSI DigiVox Micro HD" }, + { 0x1f4d, 0xa803, "Sweex DVB-T USB" }, + { 0x1f4d, 0xb803, "GTek T803" }, + { 0x1f4d, 0xc803, "Lifeview LV5TDeluxe" }, + { 0x1f4d, 0xd286, "MyGica TD312" }, + { 0x1f4d, 0xd803, "PROlectrix DV107669" }, +}; + +#define DEFAULT_BUF_NUMBER 15 +#define DEFAULT_BUF_LENGTH (16 * 32 * 512) + +#define DEF_RTL_XTAL_FREQ 28800000 +#define MIN_RTL_XTAL_FREQ (DEF_RTL_XTAL_FREQ - 1000) +#define MAX_RTL_XTAL_FREQ (DEF_RTL_XTAL_FREQ + 1000) + +#define CTRL_IN (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN) +#define CTRL_OUT (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT) +#define CTRL_TIMEOUT 300 +#define BULK_TIMEOUT 0 + +#define EEPROM_ADDR 0xa0 + +enum usb_reg { + USB_SYSCTL = 0x2000, + USB_CTRL = 0x2010, + USB_STAT = 0x2014, + USB_EPA_CFG = 0x2144, + USB_EPA_CTL = 0x2148, + USB_EPA_MAXPKT = 0x2158, + USB_EPA_MAXPKT_2 = 0x215a, + USB_EPA_FIFO_CFG = 0x2160, +}; + +enum sys_reg { + DEMOD_CTL = 0x3000, + GPO = 0x3001, + GPI = 0x3002, + GPOE = 0x3003, + GPD = 0x3004, + SYSINTE = 0x3005, + SYSINTS = 0x3006, + GP_CFG0 = 0x3007, + GP_CFG1 = 0x3008, + SYSINTE_1 = 0x3009, + SYSINTS_1 = 0x300a, + DEMOD_CTL_1 = 0x300b, + IR_SUSPEND = 0x300c, +}; + +enum blocks { + DEMODB = 0, + USBB = 1, + SYSB = 2, + TUNB = 3, + ROMB = 4, + IRB = 5, + IICB = 6, +}; + +int rtlsdr_read_array(rtlsdr_dev_t *dev, uint8_t block, uint16_t addr, uint8_t *array, uint8_t len) +{ + int r; + uint16_t index = (block << 8); + + r = libusb_control_transfer(dev->devh, CTRL_IN, 0, addr, index, array, len, CTRL_TIMEOUT); +#if 0 + if (r < 0) + fprintf(stderr, "%s failed with %d\n", __FUNCTION__, r); +#endif + return r; +} + +int rtlsdr_write_array(rtlsdr_dev_t *dev, uint8_t block, uint16_t addr, uint8_t *array, uint8_t len) +{ + int r; + uint16_t index = (block << 8) | 0x10; + + r = libusb_control_transfer(dev->devh, CTRL_OUT, 0, addr, index, array, len, CTRL_TIMEOUT); +#if 0 + if (r < 0) + fprintf(stderr, "%s failed with %d\n", __FUNCTION__, r); +#endif + return r; +} + +int rtlsdr_i2c_write_reg(rtlsdr_dev_t *dev, uint8_t i2c_addr, uint8_t reg, uint8_t val) +{ + uint16_t addr = i2c_addr; + uint8_t data[2]; + + data[0] = reg; + data[1] = val; + return rtlsdr_write_array(dev, IICB, addr, (uint8_t *)&data, 2); +} + +uint8_t rtlsdr_i2c_read_reg(rtlsdr_dev_t *dev, uint8_t i2c_addr, uint8_t reg) +{ + uint16_t addr = i2c_addr; + uint8_t data = 0; + + rtlsdr_write_array(dev, IICB, addr, ®, 1); + rtlsdr_read_array(dev, IICB, addr, &data, 1); + + return data; +} + +int rtlsdr_i2c_write(rtlsdr_dev_t *dev, uint8_t i2c_addr, uint8_t *buffer, int len) +{ + uint16_t addr = i2c_addr; + + if (!dev) + return -1; + + return rtlsdr_write_array(dev, IICB, addr, buffer, len); +} + +int rtlsdr_i2c_read(rtlsdr_dev_t *dev, uint8_t i2c_addr, uint8_t *buffer, int len) +{ + uint16_t addr = i2c_addr; + + if (!dev) + return -1; + + return rtlsdr_read_array(dev, IICB, addr, buffer, len); +} + +uint16_t rtlsdr_read_reg(rtlsdr_dev_t *dev, uint8_t block, uint16_t addr, uint8_t len) +{ + int r; + unsigned char data[2]; + uint16_t index = (block << 8); + uint16_t reg; + + r = libusb_control_transfer(dev->devh, CTRL_IN, 0, addr, index, data, len, CTRL_TIMEOUT); + + if (r < 0) + fprintf(stderr, "%s failed with %d\n", __FUNCTION__, r); + + reg = (data[1] << 8) | data[0]; + + return reg; +} + +int rtlsdr_write_reg(rtlsdr_dev_t *dev, uint8_t block, uint16_t addr, uint16_t val, uint8_t len) +{ + int r; + unsigned char data[2]; + + uint16_t index = (block << 8) | 0x10; + + if (len == 1) + data[0] = val & 0xff; + else + data[0] = val >> 8; + + data[1] = val & 0xff; + + r = libusb_control_transfer(dev->devh, CTRL_OUT, 0, addr, index, data, len, CTRL_TIMEOUT); + + if (r < 0) + fprintf(stderr, "%s failed with %d\n", __FUNCTION__, r); + + return r; +} + +uint16_t rtlsdr_demod_read_reg(rtlsdr_dev_t *dev, uint8_t page, uint16_t addr, uint8_t len) +{ + int r; + unsigned char data[2]; + + uint16_t index = page; + uint16_t reg; + addr = (addr << 8) | 0x20; + + r = libusb_control_transfer(dev->devh, CTRL_IN, 0, addr, index, data, len, CTRL_TIMEOUT); + + if (r < 0) + fprintf(stderr, "%s failed with %d\n", __FUNCTION__, r); + + reg = (data[1] << 8) | data[0]; + + return reg; +} + +int rtlsdr_demod_write_reg(rtlsdr_dev_t *dev, uint8_t page, uint16_t addr, uint16_t val, uint8_t len) +{ + int r; + unsigned char data[2]; + uint16_t index = 0x10 | page; + addr = (addr << 8) | 0x20; + + if (len == 1) + data[0] = val & 0xff; + else + data[0] = val >> 8; + + data[1] = val & 0xff; + + r = libusb_control_transfer(dev->devh, CTRL_OUT, 0, addr, index, data, len, CTRL_TIMEOUT); + + if (r < 0) + fprintf(stderr, "%s failed with %d\n", __FUNCTION__, r); + + rtlsdr_demod_read_reg(dev, 0x0a, 0x01, 1); + + return (r == len) ? 0 : -1; +} + +void rtlsdr_set_gpio_bit(rtlsdr_dev_t *dev, uint8_t gpio, int val) +{ + uint16_t r; + + gpio = 1 << gpio; + r = rtlsdr_read_reg(dev, SYSB, GPO, 1); + r = val ? (r | gpio) : (r & ~gpio); + rtlsdr_write_reg(dev, SYSB, GPO, r, 1); +} + +void rtlsdr_set_gpio_output(rtlsdr_dev_t *dev, uint8_t gpio) +{ + int r; + gpio = 1 << gpio; + + r = rtlsdr_read_reg(dev, SYSB, GPD, 1); + rtlsdr_write_reg(dev, SYSB, GPO, r & ~gpio, 1); + r = rtlsdr_read_reg(dev, SYSB, GPOE, 1); + rtlsdr_write_reg(dev, SYSB, GPOE, r | gpio, 1); +} + +void rtlsdr_set_i2c_repeater(rtlsdr_dev_t *dev, int on) +{ + rtlsdr_demod_write_reg(dev, 1, 0x01, on ? 0x18 : 0x10, 1); +} + +int rtlsdr_set_fir(rtlsdr_dev_t *dev) +{ + uint8_t fir[20]; + + int i; + /* format: int8_t[8] */ + for (i = 0; i < 8; ++i) { + const int val = dev->fir[i]; + if (val < -128 || val > 127) { + return -1; + } + fir[i] = val; + } + /* format: int12_t[8] */ + for (i = 0; i < 8; i += 2) { + const int val0 = dev->fir[8+i]; + const int val1 = dev->fir[8+i+1]; + if (val0 < -2048 || val0 > 2047 || val1 < -2048 || val1 > 2047) { + return -1; + } + fir[8+i*3/2] = val0 >> 4; + fir[8+i*3/2+1] = (val0 << 4) | ((val1 >> 8) & 0x0f); + fir[8+i*3/2+2] = val1; + } + + for (i = 0; i < (int)sizeof(fir); i++) { + if (rtlsdr_demod_write_reg(dev, 1, 0x1c + i, fir[i], 1)) + return -1; + } + + return 0; +} + +void rtlsdr_init_baseband(rtlsdr_dev_t *dev) +{ + unsigned int i; + + /* initialize USB */ + rtlsdr_write_reg(dev, USBB, USB_SYSCTL, 0x09, 1); + rtlsdr_write_reg(dev, USBB, USB_EPA_MAXPKT, 0x0002, 2); + rtlsdr_write_reg(dev, USBB, USB_EPA_CTL, 0x1002, 2); + + /* poweron demod */ + rtlsdr_write_reg(dev, SYSB, DEMOD_CTL_1, 0x22, 1); + rtlsdr_write_reg(dev, SYSB, DEMOD_CTL, 0xe8, 1); + + /* reset demod (bit 3, soft_rst) */ + rtlsdr_demod_write_reg(dev, 1, 0x01, 0x14, 1); + rtlsdr_demod_write_reg(dev, 1, 0x01, 0x10, 1); + + /* disable spectrum inversion and adjacent channel rejection */ + rtlsdr_demod_write_reg(dev, 1, 0x15, 0x00, 1); + rtlsdr_demod_write_reg(dev, 1, 0x16, 0x0000, 2); + + /* clear both DDC shift and IF frequency registers */ + for (i = 0; i < 6; i++) + rtlsdr_demod_write_reg(dev, 1, 0x16 + i, 0x00, 1); + + rtlsdr_set_fir(dev); + + /* enable SDR mode, disable DAGC (bit 5) */ + rtlsdr_demod_write_reg(dev, 0, 0x19, 0x05, 1); + + /* init FSM state-holding register */ + rtlsdr_demod_write_reg(dev, 1, 0x93, 0xf0, 1); + rtlsdr_demod_write_reg(dev, 1, 0x94, 0x0f, 1); + + /* disable AGC (en_dagc, bit 0) (this seems to have no effect) */ + rtlsdr_demod_write_reg(dev, 1, 0x11, 0x00, 1); + + /* disable RF and IF AGC loop */ + rtlsdr_demod_write_reg(dev, 1, 0x04, 0x00, 1); + + /* disable PID filter (enable_PID = 0) */ + rtlsdr_demod_write_reg(dev, 0, 0x61, 0x60, 1); + + /* opt_adc_iq = 0, default ADC_I/ADC_Q datapath */ + rtlsdr_demod_write_reg(dev, 0, 0x06, 0x80, 1); + + /* Enable Zero-IF mode (en_bbin bit), DC cancellation (en_dc_est), + * IQ estimation/compensation (en_iq_comp, en_iq_est) */ + rtlsdr_demod_write_reg(dev, 1, 0xb1, 0x1b, 1); + + /* disable 4.096 MHz clock output on pin TP_CK0 */ + rtlsdr_demod_write_reg(dev, 0, 0x0d, 0x83, 1); +} + +int rtlsdr_deinit_baseband(rtlsdr_dev_t *dev) +{ + int r = 0; + + if (!dev) + return -1; + + if (dev->tuner && dev->tuner->exit) { + rtlsdr_set_i2c_repeater(dev, 1); + r = dev->tuner->exit(dev); /* deinitialize tuner */ + rtlsdr_set_i2c_repeater(dev, 0); + } + + /* poweroff demodulator and ADCs */ + rtlsdr_write_reg(dev, SYSB, DEMOD_CTL, 0x20, 1); + + return r; +} + +static int rtlsdr_set_if_freq(rtlsdr_dev_t *dev, uint32_t freq) +{ + uint32_t rtl_xtal; + int32_t if_freq; + uint8_t tmp; + int r; + + if (!dev) + return -1; + + /* read corrected clock value */ + if (rtlsdr_get_xtal_freq(dev, &rtl_xtal, NULL)) + return -2; + + if_freq = ((freq * TWO_POW(22)) / rtl_xtal) * (-1); + + tmp = (if_freq >> 16) & 0x3f; + r = rtlsdr_demod_write_reg(dev, 1, 0x19, tmp, 1); + tmp = (if_freq >> 8) & 0xff; + r |= rtlsdr_demod_write_reg(dev, 1, 0x1a, tmp, 1); + tmp = if_freq & 0xff; + r |= rtlsdr_demod_write_reg(dev, 1, 0x1b, tmp, 1); + + return r; +} + +int rtlsdr_set_sample_freq_correction(rtlsdr_dev_t *dev, int ppm) +{ + int r = 0; + uint8_t tmp; + int16_t offs = ppm * (-1) * TWO_POW(24) / 1000000; + + tmp = offs & 0xff; + r |= rtlsdr_demod_write_reg(dev, 1, 0x3f, tmp, 1); + tmp = (offs >> 8) & 0x3f; + r |= rtlsdr_demod_write_reg(dev, 1, 0x3e, tmp, 1); + + return r; +} + +int rtlsdr_set_xtal_freq(rtlsdr_dev_t *dev, uint32_t rtl_freq, uint32_t tuner_freq) +{ + int r = 0; + + if (!dev) + return -1; + + if (rtl_freq > 0 && + (rtl_freq < MIN_RTL_XTAL_FREQ || rtl_freq > MAX_RTL_XTAL_FREQ)) + return -2; + + if (rtl_freq > 0 && dev->rtl_xtal != rtl_freq) { + dev->rtl_xtal = rtl_freq; + + /* update xtal-dependent settings */ + if (dev->rate) + r = rtlsdr_set_sample_rate(dev, dev->rate); + } + + if (dev->tun_xtal != tuner_freq) { + if (0 == tuner_freq) + dev->tun_xtal = dev->rtl_xtal; + else + dev->tun_xtal = tuner_freq; + + /* read corrected clock value into e4k and r82xx structure */ + if (rtlsdr_get_xtal_freq(dev, NULL, &dev->e4k_s.vco.fosc) || + rtlsdr_get_xtal_freq(dev, NULL, &dev->r82xx_c.xtal)) + return -3; + + /* update xtal-dependent settings */ + if (dev->freq) + r = rtlsdr_set_center_freq(dev, dev->freq); + } + + return r; +} + +int rtlsdr_get_xtal_freq(rtlsdr_dev_t *dev, uint32_t *rtl_freq, uint32_t *tuner_freq) +{ + if (!dev) + return -1; + + #define APPLY_PPM_CORR(val,ppm) (((val) * (1.0 + (ppm) / 1e6))) + + if (rtl_freq) + *rtl_freq = (uint32_t) APPLY_PPM_CORR(dev->rtl_xtal, dev->corr); + + if (tuner_freq) + *tuner_freq = (uint32_t) APPLY_PPM_CORR(dev->tun_xtal, dev->corr); + + return 0; +} + +int rtlsdr_get_usb_strings(rtlsdr_dev_t *dev, char *manufact, char *product, + char *serial) +{ + struct libusb_device_descriptor dd; + libusb_device *device = NULL; + const int buf_max = 256; + int r = 0; + + if (!dev || !dev->devh) + return -1; + + device = libusb_get_device(dev->devh); + + r = libusb_get_device_descriptor(device, &dd); + if (r < 0) + return -1; + + if (manufact) { + memset(manufact, 0, buf_max); + libusb_get_string_descriptor_ascii(dev->devh, dd.iManufacturer, + (unsigned char *)manufact, + buf_max); + } + + if (product) { + memset(product, 0, buf_max); + libusb_get_string_descriptor_ascii(dev->devh, dd.iProduct, + (unsigned char *)product, + buf_max); + } + + if (serial) { + memset(serial, 0, buf_max); + libusb_get_string_descriptor_ascii(dev->devh, dd.iSerialNumber, + (unsigned char *)serial, + buf_max); + } + + return 0; +} + +int rtlsdr_write_eeprom(rtlsdr_dev_t *dev, uint8_t *data, uint8_t offset, uint16_t len) +{ + int r = 0; + int i; + uint8_t cmd[2]; + + if (!dev) + return -1; + + if ((len + offset) > 256) + return -2; + + for (i = 0; i < len; i++) { + cmd[0] = i + offset; + r = rtlsdr_write_array(dev, IICB, EEPROM_ADDR, cmd, 1); + r = rtlsdr_read_array(dev, IICB, EEPROM_ADDR, &cmd[1], 1); + + /* only write the byte if it differs */ + if (cmd[1] == data[i]) + continue; + + cmd[1] = data[i]; + r = rtlsdr_write_array(dev, IICB, EEPROM_ADDR, cmd, 2); + if (r != sizeof(cmd)) + return -3; + + /* for some EEPROMs (e.g. ATC 240LC02) we need a delay + * between write operations, otherwise they will fail */ +#ifdef _WIN32 + Sleep(5); +#else + usleep(5000); +#endif + } + + return 0; +} + +int rtlsdr_read_eeprom(rtlsdr_dev_t *dev, uint8_t *data, uint8_t offset, uint16_t len) +{ + int r = 0; + int i; + + if (!dev) + return -1; + + if ((len + offset) > 256) + return -2; + + r = rtlsdr_write_array(dev, IICB, EEPROM_ADDR, &offset, 1); + if (r < 0) + return -3; + + for (i = 0; i < len; i++) { + r = rtlsdr_read_array(dev, IICB, EEPROM_ADDR, data + i, 1); + + if (r < 0) + return -3; + } + + return r; +} + +int rtlsdr_set_center_freq(rtlsdr_dev_t *dev, uint32_t freq) +{ + int r = -1; + + if (!dev || !dev->tuner) + return -1; + + if (dev->direct_sampling) { + r = rtlsdr_set_if_freq(dev, freq); + } else if (dev->tuner && dev->tuner->set_freq) { + rtlsdr_set_i2c_repeater(dev, 1); + r = dev->tuner->set_freq(dev, freq - dev->offs_freq); + rtlsdr_set_i2c_repeater(dev, 0); + } + + if (!r) + dev->freq = freq; + else + dev->freq = 0; + + return r; +} + +uint32_t rtlsdr_get_center_freq(rtlsdr_dev_t *dev) +{ + if (!dev) + return 0; + + return dev->freq; +} + +int rtlsdr_set_freq_correction(rtlsdr_dev_t *dev, int ppm) +{ + int r = 0; + + if (!dev) + return -1; + + if (dev->corr == ppm) + return -2; + + dev->corr = ppm; + + r |= rtlsdr_set_sample_freq_correction(dev, ppm); + + /* read corrected clock value into e4k and r82xx structure */ + if (rtlsdr_get_xtal_freq(dev, NULL, &dev->e4k_s.vco.fosc) || + rtlsdr_get_xtal_freq(dev, NULL, &dev->r82xx_c.xtal)) + return -3; + + if (dev->freq) /* retune to apply new correction value */ + r |= rtlsdr_set_center_freq(dev, dev->freq); + + return r; +} + +int rtlsdr_get_freq_correction(rtlsdr_dev_t *dev) +{ + if (!dev) + return 0; + + return dev->corr; +} + +enum rtlsdr_tuner rtlsdr_get_tuner_type(rtlsdr_dev_t *dev) +{ + if (!dev) + return RTLSDR_TUNER_UNKNOWN; + + return dev->tuner_type; +} + +int rtlsdr_get_tuner_gains(rtlsdr_dev_t *dev, int *gains) +{ + /* all gain values are expressed in tenths of a dB */ + const int e4k_gains[] = { -10, 15, 40, 65, 90, 115, 140, 165, 190, 215, + 240, 290, 340, 420 }; + const int fc0012_gains[] = { -99, -40, 71, 179, 192 }; + const int fc0013_gains[] = { -99, -73, -65, -63, -60, -58, -54, 58, 61, + 63, 65, 67, 68, 70, 71, 179, 181, 182, + 184, 186, 188, 191, 197 }; + const int fc2580_gains[] = { 0 /* no gain values */ }; + const int r82xx_gains[] = { 0, 9, 14, 27, 37, 77, 87, 125, 144, 157, + 166, 197, 207, 229, 254, 280, 297, 328, + 338, 364, 372, 386, 402, 421, 434, 439, + 445, 480, 496 }; + const int unknown_gains[] = { 0 /* no gain values */ }; + + const int *ptr = NULL; + int len = 0; + + if (!dev) + return -1; + + switch (dev->tuner_type) { + case RTLSDR_TUNER_E4000: + ptr = e4k_gains; len = sizeof(e4k_gains); + break; + case RTLSDR_TUNER_FC0012: + ptr = fc0012_gains; len = sizeof(fc0012_gains); + break; + case RTLSDR_TUNER_FC0013: + ptr = fc0013_gains; len = sizeof(fc0013_gains); + break; + case RTLSDR_TUNER_FC2580: + ptr = fc2580_gains; len = sizeof(fc2580_gains); + break; + case RTLSDR_TUNER_R820T: + case RTLSDR_TUNER_R828D: + ptr = r82xx_gains; len = sizeof(r82xx_gains); + break; + default: + ptr = unknown_gains; len = sizeof(unknown_gains); + break; + } + + if (!gains) { /* no buffer provided, just return the count */ + return len / sizeof(int); + } else { + if (len) + memcpy(gains, ptr, len); + + return len / sizeof(int); + } +} + +int rtlsdr_set_tuner_bandwidth(rtlsdr_dev_t *dev, uint32_t bw) +{ + int r = 0; + + if (!dev || !dev->tuner) + return -1; + + if (dev->tuner->set_bw) { + rtlsdr_set_i2c_repeater(dev, 1); + r = dev->tuner->set_bw(dev, bw > 0 ? bw : dev->rate); + rtlsdr_set_i2c_repeater(dev, 0); + if (r) + return r; + dev->bw = bw; + } + return r; +} + +int rtlsdr_set_tuner_gain(rtlsdr_dev_t *dev, int gain) +{ + int r = 0; + + if (!dev || !dev->tuner) + return -1; + + if (dev->tuner->set_gain) { + rtlsdr_set_i2c_repeater(dev, 1); + r = dev->tuner->set_gain((void *)dev, gain); + rtlsdr_set_i2c_repeater(dev, 0); + } + + if (!r) + dev->gain = gain; + else + dev->gain = 0; + + return r; +} + +int rtlsdr_get_tuner_gain(rtlsdr_dev_t *dev) +{ + if (!dev) + return 0; + + return dev->gain; +} + +int rtlsdr_set_tuner_if_gain(rtlsdr_dev_t *dev, int stage, int gain) +{ + int r = 0; + + if (!dev || !dev->tuner) + return -1; + + if (dev->tuner->set_if_gain) { + rtlsdr_set_i2c_repeater(dev, 1); + r = dev->tuner->set_if_gain(dev, stage, gain); + rtlsdr_set_i2c_repeater(dev, 0); + } + + return r; +} + +int rtlsdr_set_tuner_gain_mode(rtlsdr_dev_t *dev, int mode) +{ + int r = 0; + + if (!dev || !dev->tuner) + return -1; + + if (dev->tuner->set_gain_mode) { + rtlsdr_set_i2c_repeater(dev, 1); + r = dev->tuner->set_gain_mode((void *)dev, mode); + rtlsdr_set_i2c_repeater(dev, 0); + } + + return r; +} + +int rtlsdr_set_sample_rate(rtlsdr_dev_t *dev, uint32_t samp_rate) +{ + int r = 0; + uint16_t tmp; + uint32_t rsamp_ratio, real_rsamp_ratio; + double real_rate; + + if (!dev) + return -1; + + /* check if the rate is supported by the resampler */ + if ((samp_rate <= 225000) || (samp_rate > 3200000) || + ((samp_rate > 300000) && (samp_rate <= 900000))) { + fprintf(stderr, "Invalid sample rate: %u Hz\n", samp_rate); + return -EINVAL; + } + + rsamp_ratio = (dev->rtl_xtal * TWO_POW(22)) / samp_rate; + rsamp_ratio &= 0x0ffffffc; + + real_rsamp_ratio = rsamp_ratio | ((rsamp_ratio & 0x08000000) << 1); + real_rate = (dev->rtl_xtal * TWO_POW(22)) / real_rsamp_ratio; + + if ( ((double)samp_rate) != real_rate ) + fprintf(stderr, "Exact sample rate is: %f Hz\n", real_rate); + + dev->rate = (uint32_t)real_rate; + + if (dev->tuner && dev->tuner->set_bw) { + rtlsdr_set_i2c_repeater(dev, 1); + dev->tuner->set_bw(dev, dev->bw > 0 ? dev->bw : dev->rate); + rtlsdr_set_i2c_repeater(dev, 0); + } + + tmp = (rsamp_ratio >> 16); + r |= rtlsdr_demod_write_reg(dev, 1, 0x9f, tmp, 2); + tmp = rsamp_ratio & 0xffff; + r |= rtlsdr_demod_write_reg(dev, 1, 0xa1, tmp, 2); + + r |= rtlsdr_set_sample_freq_correction(dev, dev->corr); + + /* reset demod (bit 3, soft_rst) */ + r |= rtlsdr_demod_write_reg(dev, 1, 0x01, 0x14, 1); + r |= rtlsdr_demod_write_reg(dev, 1, 0x01, 0x10, 1); + + /* recalculate offset frequency if offset tuning is enabled */ + if (dev->offs_freq) + rtlsdr_set_offset_tuning(dev, 1); + + return r; +} + +uint32_t rtlsdr_get_sample_rate(rtlsdr_dev_t *dev) +{ + if (!dev) + return 0; + + return dev->rate; +} + +int rtlsdr_set_testmode(rtlsdr_dev_t *dev, int on) +{ + if (!dev) + return -1; + + return rtlsdr_demod_write_reg(dev, 0, 0x19, on ? 0x03 : 0x05, 1); +} + +int rtlsdr_set_agc_mode(rtlsdr_dev_t *dev, int on) +{ + if (!dev) + return -1; + + return rtlsdr_demod_write_reg(dev, 0, 0x19, on ? 0x25 : 0x05, 1); +} + +int rtlsdr_set_direct_sampling(rtlsdr_dev_t *dev, int on) +{ + int r = 0; + + if (!dev) + return -1; + + if (on) { + if (dev->tuner && dev->tuner->exit) { + rtlsdr_set_i2c_repeater(dev, 1); + r = dev->tuner->exit(dev); + rtlsdr_set_i2c_repeater(dev, 0); + } + + /* disable Zero-IF mode */ + r |= rtlsdr_demod_write_reg(dev, 1, 0xb1, 0x1a, 1); + + /* disable spectrum inversion */ + r |= rtlsdr_demod_write_reg(dev, 1, 0x15, 0x00, 1); + + /* only enable In-phase ADC input */ + r |= rtlsdr_demod_write_reg(dev, 0, 0x08, 0x4d, 1); + + /* swap I and Q ADC, this allows to select between two inputs */ + r |= rtlsdr_demod_write_reg(dev, 0, 0x06, (on > 1) ? 0x90 : 0x80, 1); + + fprintf(stderr, "Enabled direct sampling mode, input %i\n", on); + dev->direct_sampling = on; + } else { + if (dev->tuner && dev->tuner->init) { + rtlsdr_set_i2c_repeater(dev, 1); + r |= dev->tuner->init(dev); + rtlsdr_set_i2c_repeater(dev, 0); + } + + if ((dev->tuner_type == RTLSDR_TUNER_R820T) || + (dev->tuner_type == RTLSDR_TUNER_R828D)) { + r |= rtlsdr_set_if_freq(dev, R82XX_IF_FREQ); + + /* enable spectrum inversion */ + r |= rtlsdr_demod_write_reg(dev, 1, 0x15, 0x01, 1); + } else { + r |= rtlsdr_set_if_freq(dev, 0); + + /* enable In-phase + Quadrature ADC input */ + r |= rtlsdr_demod_write_reg(dev, 0, 0x08, 0xcd, 1); + + /* Enable Zero-IF mode */ + r |= rtlsdr_demod_write_reg(dev, 1, 0xb1, 0x1b, 1); + } + + /* opt_adc_iq = 0, default ADC_I/ADC_Q datapath */ + r |= rtlsdr_demod_write_reg(dev, 0, 0x06, 0x80, 1); + + fprintf(stderr, "Disabled direct sampling mode\n"); + dev->direct_sampling = 0; + } + + r |= rtlsdr_set_center_freq(dev, dev->freq); + + return r; +} + +int rtlsdr_get_direct_sampling(rtlsdr_dev_t *dev) +{ + if (!dev) + return -1; + + return dev->direct_sampling; +} + +int rtlsdr_set_offset_tuning(rtlsdr_dev_t *dev, int on) +{ + int r = 0; + int bw; + + if (!dev) + return -1; + + if ((dev->tuner_type == RTLSDR_TUNER_R820T) || + (dev->tuner_type == RTLSDR_TUNER_R828D)) + return -2; + + if (dev->direct_sampling) + return -3; + + /* based on keenerds 1/f noise measurements */ + dev->offs_freq = on ? ((dev->rate / 2) * 170 / 100) : 0; + r |= rtlsdr_set_if_freq(dev, dev->offs_freq); + + if (dev->tuner && dev->tuner->set_bw) { + rtlsdr_set_i2c_repeater(dev, 1); + if (on) { + bw = 2 * dev->offs_freq; + } else if (dev->bw > 0) { + bw = dev->bw; + } else { + bw = dev->rate; + } + dev->tuner->set_bw(dev, bw); + rtlsdr_set_i2c_repeater(dev, 0); + } + + if (dev->freq > dev->offs_freq) + r |= rtlsdr_set_center_freq(dev, dev->freq); + + return r; +} + +int rtlsdr_get_offset_tuning(rtlsdr_dev_t *dev) +{ + if (!dev) + return -1; + + return (dev->offs_freq) ? 1 : 0; +} + +static rtlsdr_dongle_t *find_known_device(uint16_t vid, uint16_t pid) +{ + unsigned int i; + rtlsdr_dongle_t *device = NULL; + + for (i = 0; i < sizeof(known_devices)/sizeof(rtlsdr_dongle_t); i++ ) { + if (known_devices[i].vid == vid && known_devices[i].pid == pid) { + device = &known_devices[i]; + break; + } + } + + return device; +} + +uint32_t rtlsdr_get_device_count(void) +{ + int i,r; + libusb_context *ctx; + libusb_device **list; + uint32_t device_count = 0; + struct libusb_device_descriptor dd; + ssize_t cnt; + + r = libusb_init(&ctx); + if(r < 0) + return 0; + + cnt = libusb_get_device_list(ctx, &list); + + for (i = 0; i < cnt; i++) { + libusb_get_device_descriptor(list[i], &dd); + + if (find_known_device(dd.idVendor, dd.idProduct)) + device_count++; + } + + libusb_free_device_list(list, 1); + + libusb_exit(ctx); + + return device_count; +} + +const char *rtlsdr_get_device_name(uint32_t index) +{ + int i,r; + libusb_context *ctx; + libusb_device **list; + struct libusb_device_descriptor dd; + rtlsdr_dongle_t *device = NULL; + uint32_t device_count = 0; + ssize_t cnt; + + r = libusb_init(&ctx); + if(r < 0) + return ""; + + cnt = libusb_get_device_list(ctx, &list); + + for (i = 0; i < cnt; i++) { + libusb_get_device_descriptor(list[i], &dd); + + device = find_known_device(dd.idVendor, dd.idProduct); + + if (device) { + device_count++; + + if (index == device_count - 1) + break; + } + } + + libusb_free_device_list(list, 1); + + libusb_exit(ctx); + + if (device) + return device->name; + else + return ""; +} + +int rtlsdr_get_device_usb_strings(uint32_t index, char *manufact, + char *product, char *serial) +{ + int r = -2; + int i; + libusb_context *ctx; + libusb_device **list; + struct libusb_device_descriptor dd; + rtlsdr_dongle_t *device = NULL; + rtlsdr_dev_t devt; + uint32_t device_count = 0; + ssize_t cnt; + + r = libusb_init(&ctx); + if(r < 0) + return r; + + cnt = libusb_get_device_list(ctx, &list); + + for (i = 0; i < cnt; i++) { + libusb_get_device_descriptor(list[i], &dd); + + device = find_known_device(dd.idVendor, dd.idProduct); + + if (device) { + device_count++; + + if (index == device_count - 1) { + r = libusb_open(list[i], &devt.devh); + if (!r) { + r = rtlsdr_get_usb_strings(&devt, + manufact, + product, + serial); + libusb_close(devt.devh); + } + break; + } + } + } + + libusb_free_device_list(list, 1); + + libusb_exit(ctx); + + return r; +} + +int rtlsdr_get_index_by_serial(const char *serial) +{ + int i, cnt, r; + char str[256]; + + if (!serial) + return -1; + + cnt = rtlsdr_get_device_count(); + + if (!cnt) + return -2; + + for (i = 0; i < cnt; i++) { + r = rtlsdr_get_device_usb_strings(i, NULL, NULL, str); + if (!r && !strcmp(serial, str)) + return i; + } + + return -3; +} + +int rtlsdr_open(rtlsdr_dev_t **out_dev, uint32_t index) +{ + int r; + int i; + libusb_device **list; + rtlsdr_dev_t *dev = NULL; + libusb_device *device = NULL; + uint32_t device_count = 0; + struct libusb_device_descriptor dd; + uint8_t reg; + ssize_t cnt; + + dev = malloc(sizeof(rtlsdr_dev_t)); + if (NULL == dev) + return -ENOMEM; + + memset(dev, 0, sizeof(rtlsdr_dev_t)); + memcpy(dev->fir, fir_default, sizeof(fir_default)); + + r = libusb_init(&dev->ctx); + if(r < 0){ + free(dev); + return -1; + } + + dev->dev_lost = 1; + + cnt = libusb_get_device_list(dev->ctx, &list); + + for (i = 0; i < cnt; i++) { + device = list[i]; + + libusb_get_device_descriptor(list[i], &dd); + + if (find_known_device(dd.idVendor, dd.idProduct)) { + device_count++; + } + + if (index == device_count - 1) + break; + + device = NULL; + } + + if (!device) { + r = -1; + goto err; + } + + r = libusb_open(device, &dev->devh); + if (r < 0) { + libusb_free_device_list(list, 1); + fprintf(stderr, "usb_open error %d\n", r); + if(r == LIBUSB_ERROR_ACCESS) + fprintf(stderr, "Please fix the device permissions, e.g. " + "by installing the udev rules file rtl-sdr.rules\n"); + goto err; + } + + libusb_free_device_list(list, 1); + + if (libusb_kernel_driver_active(dev->devh, 0) == 1) { + dev->driver_active = 1; + +#ifdef DETACH_KERNEL_DRIVER + if (!libusb_detach_kernel_driver(dev->devh, 0)) { + fprintf(stderr, "Detached kernel driver\n"); + } else { + fprintf(stderr, "Detaching kernel driver failed!"); + goto err; + } +#else + fprintf(stderr, "\nKernel driver is active, or device is " + "claimed by second instance of librtlsdr." + "\nIn the first case, please either detach" + " or blacklist the kernel module\n" + "(dvb_usb_rtl28xxu), or enable automatic" + " detaching at compile time.\n\n"); +#endif + } + + r = libusb_claim_interface(dev->devh, 0); + if (r < 0) { + fprintf(stderr, "usb_claim_interface error %d\n", r); + goto err; + } + + dev->rtl_xtal = DEF_RTL_XTAL_FREQ; + + /* perform a dummy write, if it fails, reset the device */ + if (rtlsdr_write_reg(dev, USBB, USB_SYSCTL, 0x09, 1) < 0) { + fprintf(stderr, "Resetting device...\n"); + libusb_reset_device(dev->devh); + } + + rtlsdr_init_baseband(dev); + dev->dev_lost = 0; + + /* Probe tuners */ + rtlsdr_set_i2c_repeater(dev, 1); + + reg = rtlsdr_i2c_read_reg(dev, E4K_I2C_ADDR, E4K_CHECK_ADDR); + if (reg == E4K_CHECK_VAL) { + fprintf(stderr, "Found Elonics E4000 tuner\n"); + dev->tuner_type = RTLSDR_TUNER_E4000; + goto found; + } + + reg = rtlsdr_i2c_read_reg(dev, FC0013_I2C_ADDR, FC0013_CHECK_ADDR); + if (reg == FC0013_CHECK_VAL) { + fprintf(stderr, "Found Fitipower FC0013 tuner\n"); + dev->tuner_type = RTLSDR_TUNER_FC0013; + goto found; + } + + reg = rtlsdr_i2c_read_reg(dev, R820T_I2C_ADDR, R82XX_CHECK_ADDR); + if (reg == R82XX_CHECK_VAL) { + fprintf(stderr, "Found Rafael Micro R820T tuner\n"); + dev->tuner_type = RTLSDR_TUNER_R820T; + goto found; + } + + reg = rtlsdr_i2c_read_reg(dev, R828D_I2C_ADDR, R82XX_CHECK_ADDR); + if (reg == R82XX_CHECK_VAL) { + fprintf(stderr, "Found Rafael Micro R828D tuner\n"); + dev->tuner_type = RTLSDR_TUNER_R828D; + goto found; + } + + /* initialise GPIOs */ + rtlsdr_set_gpio_output(dev, 5); + + /* reset tuner before probing */ + rtlsdr_set_gpio_bit(dev, 5, 1); + rtlsdr_set_gpio_bit(dev, 5, 0); + + reg = rtlsdr_i2c_read_reg(dev, FC2580_I2C_ADDR, FC2580_CHECK_ADDR); + if ((reg & 0x7f) == FC2580_CHECK_VAL) { + fprintf(stderr, "Found FCI 2580 tuner\n"); + dev->tuner_type = RTLSDR_TUNER_FC2580; + goto found; + } + + reg = rtlsdr_i2c_read_reg(dev, FC0012_I2C_ADDR, FC0012_CHECK_ADDR); + if (reg == FC0012_CHECK_VAL) { + fprintf(stderr, "Found Fitipower FC0012 tuner\n"); + rtlsdr_set_gpio_output(dev, 6); + dev->tuner_type = RTLSDR_TUNER_FC0012; + goto found; + } + +found: + /* use the rtl clock value by default */ + dev->tun_xtal = dev->rtl_xtal; + dev->tuner = &tuners[dev->tuner_type]; + + switch (dev->tuner_type) { + case RTLSDR_TUNER_R828D: + dev->tun_xtal = R828D_XTAL_FREQ; + case RTLSDR_TUNER_R820T: + /* disable Zero-IF mode */ + rtlsdr_demod_write_reg(dev, 1, 0xb1, 0x1a, 1); + + /* only enable In-phase ADC input */ + rtlsdr_demod_write_reg(dev, 0, 0x08, 0x4d, 1); + + /* the R82XX use 3.57 MHz IF for the DVB-T 6 MHz mode, and + * 4.57 MHz for the 8 MHz mode */ + rtlsdr_set_if_freq(dev, R82XX_IF_FREQ); + + /* enable spectrum inversion */ + rtlsdr_demod_write_reg(dev, 1, 0x15, 0x01, 1); + break; + case RTLSDR_TUNER_UNKNOWN: + fprintf(stderr, "No supported tuner found\n"); + rtlsdr_set_direct_sampling(dev, 1); + break; + default: + break; + } + + if (dev->tuner->init) + r = dev->tuner->init(dev); + + rtlsdr_set_i2c_repeater(dev, 0); + + *out_dev = dev; + + return 0; +err: + if (dev) { + if (dev->ctx) + libusb_exit(dev->ctx); + + free(dev); + } + + return r; +} + +int rtlsdr_close(rtlsdr_dev_t *dev) +{ + if (!dev) + return -1; + + if(!dev->dev_lost) { + /* block until all async operations have been completed (if any) */ + while (RTLSDR_INACTIVE != dev->async_status) { +#ifdef _WIN32 + Sleep(1); +#else + usleep(1000); +#endif + } + + rtlsdr_deinit_baseband(dev); + } + + libusb_release_interface(dev->devh, 0); + +#ifdef DETACH_KERNEL_DRIVER + if (dev->driver_active) { + if (!libusb_attach_kernel_driver(dev->devh, 0)) + fprintf(stderr, "Reattached kernel driver\n"); + else + fprintf(stderr, "Reattaching kernel driver failed!\n"); + } +#endif + + libusb_close(dev->devh); + + libusb_exit(dev->ctx); + + free(dev); + + return 0; +} + +int rtlsdr_reset_buffer(rtlsdr_dev_t *dev) +{ + if (!dev) + return -1; + + rtlsdr_write_reg(dev, USBB, USB_EPA_CTL, 0x1002, 2); + rtlsdr_write_reg(dev, USBB, USB_EPA_CTL, 0x0000, 2); + + return 0; +} + +int rtlsdr_read_sync(rtlsdr_dev_t *dev, void *buf, int len, int *n_read) +{ + if (!dev) + return -1; + + return libusb_bulk_transfer(dev->devh, 0x81, buf, len, n_read, BULK_TIMEOUT); +} + +static void LIBUSB_CALL _libusb_callback(struct libusb_transfer *xfer) +{ + rtlsdr_dev_t *dev = (rtlsdr_dev_t *)xfer->user_data; + + if (LIBUSB_TRANSFER_COMPLETED == xfer->status) { + if (dev->cb) + dev->cb(xfer->buffer, xfer->actual_length, dev->cb_ctx); + + libusb_submit_transfer(xfer); /* resubmit transfer */ + dev->xfer_errors = 0; + } else if (LIBUSB_TRANSFER_CANCELLED != xfer->status) { +#ifndef _WIN32 + if (LIBUSB_TRANSFER_ERROR == xfer->status) + dev->xfer_errors++; + + if (dev->xfer_errors >= dev->xfer_buf_num || + LIBUSB_TRANSFER_NO_DEVICE == xfer->status) { +#endif + dev->dev_lost = 1; + rtlsdr_cancel_async(dev); + fprintf(stderr, "cb transfer status: %d, " + "canceling...\n", xfer->status); +#ifndef _WIN32 + } +#endif + } +} + +int rtlsdr_wait_async(rtlsdr_dev_t *dev, rtlsdr_read_async_cb_t cb, void *ctx) +{ + return rtlsdr_read_async(dev, cb, ctx, 0, 0); +} + +static int _rtlsdr_alloc_async_buffers(rtlsdr_dev_t *dev) +{ + unsigned int i; + + if (!dev) + return -1; + + if (!dev->xfer) { + dev->xfer = malloc(dev->xfer_buf_num * + sizeof(struct libusb_transfer *)); + + for(i = 0; i < dev->xfer_buf_num; ++i) + dev->xfer[i] = libusb_alloc_transfer(0); + } + + if (!dev->xfer_buf) { + dev->xfer_buf = malloc(dev->xfer_buf_num * + sizeof(unsigned char *)); + + for(i = 0; i < dev->xfer_buf_num; ++i) + dev->xfer_buf[i] = malloc(dev->xfer_buf_len); + } + + return 0; +} + +static int _rtlsdr_free_async_buffers(rtlsdr_dev_t *dev) +{ + unsigned int i; + + if (!dev) + return -1; + + if (dev->xfer) { + for(i = 0; i < dev->xfer_buf_num; ++i) { + if (dev->xfer[i]) { + libusb_free_transfer(dev->xfer[i]); + } + } + + free(dev->xfer); + dev->xfer = NULL; + } + + if (dev->xfer_buf) { + for(i = 0; i < dev->xfer_buf_num; ++i) { + if (dev->xfer_buf[i]) + free(dev->xfer_buf[i]); + } + + free(dev->xfer_buf); + dev->xfer_buf = NULL; + } + + return 0; +} + +int rtlsdr_read_async(rtlsdr_dev_t *dev, rtlsdr_read_async_cb_t cb, void *ctx, + uint32_t buf_num, uint32_t buf_len) +{ + unsigned int i; + int r = 0; + struct timeval tv = { 1, 0 }; + struct timeval zerotv = { 0, 0 }; + enum rtlsdr_async_status next_status = RTLSDR_INACTIVE; + + if (!dev) + return -1; + + if (RTLSDR_INACTIVE != dev->async_status) + return -2; + + dev->async_status = RTLSDR_RUNNING; + dev->async_cancel = 0; + + dev->cb = cb; + dev->cb_ctx = ctx; + + if (buf_num > 0) + dev->xfer_buf_num = buf_num; + else + dev->xfer_buf_num = DEFAULT_BUF_NUMBER; + + if (buf_len > 0 && buf_len % 512 == 0) /* len must be multiple of 512 */ + dev->xfer_buf_len = buf_len; + else + dev->xfer_buf_len = DEFAULT_BUF_LENGTH; + + _rtlsdr_alloc_async_buffers(dev); + + for(i = 0; i < dev->xfer_buf_num; ++i) { + libusb_fill_bulk_transfer(dev->xfer[i], + dev->devh, + 0x81, + dev->xfer_buf[i], + dev->xfer_buf_len, + _libusb_callback, + (void *)dev, + BULK_TIMEOUT); + + r = libusb_submit_transfer(dev->xfer[i]); + if (r < 0) { + fprintf(stderr, "Failed to submit transfer %i!\n", i); + dev->async_status = RTLSDR_CANCELING; + break; + } + } + + while (RTLSDR_INACTIVE != dev->async_status) { + r = libusb_handle_events_timeout_completed(dev->ctx, &tv, + &dev->async_cancel); + if (r < 0) { + /*fprintf(stderr, "handle_events returned: %d\n", r);*/ + if (r == LIBUSB_ERROR_INTERRUPTED) /* stray signal */ + continue; + break; + } + + if (RTLSDR_CANCELING == dev->async_status) { + next_status = RTLSDR_INACTIVE; + + if (!dev->xfer) + break; + + for(i = 0; i < dev->xfer_buf_num; ++i) { + if (!dev->xfer[i]) + continue; + + if (LIBUSB_TRANSFER_CANCELLED != + dev->xfer[i]->status) { + r = libusb_cancel_transfer(dev->xfer[i]); + /* handle events after canceling + * to allow transfer status to + * propagate */ + libusb_handle_events_timeout_completed(dev->ctx, + &zerotv, NULL); + if (r < 0) + continue; + + next_status = RTLSDR_CANCELING; + } + } + + if (dev->dev_lost || RTLSDR_INACTIVE == next_status) { + /* handle any events that still need to + * be handled before exiting after we + * just cancelled all transfers */ + libusb_handle_events_timeout_completed(dev->ctx, + &zerotv, NULL); + break; + } + } + } + + _rtlsdr_free_async_buffers(dev); + + dev->async_status = next_status; + + return r; +} + +int rtlsdr_cancel_async(rtlsdr_dev_t *dev) +{ + if (!dev) + return -1; + + /* if streaming, try to cancel gracefully */ + if (RTLSDR_RUNNING == dev->async_status) { + dev->async_status = RTLSDR_CANCELING; + dev->async_cancel = 1; + return 0; + } + + /* if called while in pending state, change the state forcefully */ +#if 0 + if (RTLSDR_INACTIVE != dev->async_status) { + dev->async_status = RTLSDR_INACTIVE; + return 0; + } +#endif + return -2; +} + +uint32_t rtlsdr_get_tuner_clock(void *dev) +{ + uint32_t tuner_freq; + + if (!dev) + return 0; + + /* read corrected clock value */ + if (rtlsdr_get_xtal_freq((rtlsdr_dev_t *)dev, NULL, &tuner_freq)) + return 0; + + return tuner_freq; +} + +int rtlsdr_i2c_write_fn(void *dev, uint8_t addr, uint8_t *buf, int len) +{ + if (dev) + return rtlsdr_i2c_write(((rtlsdr_dev_t *)dev), addr, buf, len); + + return -1; +} + +int rtlsdr_i2c_read_fn(void *dev, uint8_t addr, uint8_t *buf, int len) +{ + if (dev) + return rtlsdr_i2c_read(((rtlsdr_dev_t *)dev), addr, buf, len); + + return -1; +} diff --git a/src/make.mk b/src/make.mk new file mode 100644 index 0000000..57e1dbf --- /dev/null +++ b/src/make.mk @@ -0,0 +1,13 @@ +DIR_SRC=src +SRC_LIB += $(wildcard $(DIR_SRC)/*.c) +OBJ_LIB += $(SRC_LIB:.c=.o) +LDFLAGS_LIB=`pkg-config --libs libusb` -lc + +$(DIR_SRC)-lib-o: $(OBJ_LIB) + +$(DIR_SRC)-lib: $(DIR_SRC)-lib-o + gcc -shared -Wl,-soname,lib$(PROJECT).so.1 -o lib$(PROJECT).so.1 $(subst $(DIR_SRC)/,$(BUILD_DIR)$(DIR_SRC)/,$(OBJ_LIB)) $(LDFLAGS_LIB) + ar rcv lib$(PROJECT).a $(subst $(DIR_SRC)/,$(BUILD_DIR)$(DIR_SRC)/,$(OBJ_LIB)) + +$(DIR_SRC)/%.o: $(DIR_SRC)/%.c + $(CC) $(CFLAGS) -fPIC $(INCLUDE) -c $< -o $(BUILD_DIR)$@ diff --git a/src/tuner_e4k.c b/src/tuner_e4k.c new file mode 100644 index 0000000..400e745 --- /dev/null +++ b/src/tuner_e4k.c @@ -0,0 +1,1000 @@ +/* + * Elonics E4000 tuner driver + * + * (C) 2011-2012 by Harald Welte + * (C) 2012 by Sylvain Munaut + * (C) 2012 by Hoernchen + * + * All Rights Reserved + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include + +#include +#include +#include + +#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) + +/* If this is defined, the limits are somewhat relaxed compared to what the + * vendor claims is possible */ +#define OUT_OF_SPEC + +#define MHZ(x) ((x)*1000*1000) +#define KHZ(x) ((x)*1000) + +uint32_t unsigned_delta(uint32_t a, uint32_t b) +{ + if (a > b) + return a - b; + else + return b - a; +} + +/* look-up table bit-width -> mask */ +static const uint8_t width2mask[] = { + 0, 1, 3, 7, 0xf, 0x1f, 0x3f, 0x7f, 0xff +}; + +/*********************************************************************** + * Register Access */ + +/*! \brief Write a register of the tuner chip + * \param[in] e4k reference to the tuner + * \param[in] reg number of the register + * \param[in] val value to be written + * \returns 0 on success, negative in case of error + */ +static int e4k_reg_write(struct e4k_state *e4k, uint8_t reg, uint8_t val) +{ + int r; + uint8_t data[2]; + data[0] = reg; + data[1] = val; + + r = rtlsdr_i2c_write_fn(e4k->rtl_dev, e4k->i2c_addr, data, 2); + return r == 2 ? 0 : -1; +} + +/*! \brief Read a register of the tuner chip + * \param[in] e4k reference to the tuner + * \param[in] reg number of the register + * \returns positive 8bit register contents on success, negative in case of error + */ +static int e4k_reg_read(struct e4k_state *e4k, uint8_t reg) +{ + uint8_t data = reg; + + if (rtlsdr_i2c_write_fn(e4k->rtl_dev, e4k->i2c_addr, &data, 1) < 1) + return -1; + + if (rtlsdr_i2c_read_fn(e4k->rtl_dev, e4k->i2c_addr, &data, 1) < 1) + return -1; + + return data; +} + +/*! \brief Set or clear some (masked) bits inside a register + * \param[in] e4k reference to the tuner + * \param[in] reg number of the register + * \param[in] mask bit-mask of the value + * \param[in] val data value to be written to register + * \returns 0 on success, negative in case of error + */ +static int e4k_reg_set_mask(struct e4k_state *e4k, uint8_t reg, + uint8_t mask, uint8_t val) +{ + uint8_t tmp = e4k_reg_read(e4k, reg); + + if ((tmp & mask) == val) + return 0; + + return e4k_reg_write(e4k, reg, (tmp & ~mask) | (val & mask)); +} + +/*! \brief Write a given field inside a register + * \param[in] e4k reference to the tuner + * \param[in] field structure describing the field + * \param[in] val value to be written + * \returns 0 on success, negative in case of error + */ +static int e4k_field_write(struct e4k_state *e4k, const struct reg_field *field, uint8_t val) +{ + int rc; + uint8_t mask; + + rc = e4k_reg_read(e4k, field->reg); + if (rc < 0) + return rc; + + mask = width2mask[field->width] << field->shift; + + return e4k_reg_set_mask(e4k, field->reg, mask, val << field->shift); +} + +/*! \brief Read a given field inside a register + * \param[in] e4k reference to the tuner + * \param[in] field structure describing the field + * \returns positive value of the field, negative in case of error + */ +static int e4k_field_read(struct e4k_state *e4k, const struct reg_field *field) +{ + int rc; + + rc = e4k_reg_read(e4k, field->reg); + if (rc < 0) + return rc; + + rc = (rc >> field->shift) & width2mask[field->width]; + + return rc; +} + +/*********************************************************************** + * Filter Control */ + +static const uint32_t rf_filt_center_uhf[] = { + MHZ(360), MHZ(380), MHZ(405), MHZ(425), + MHZ(450), MHZ(475), MHZ(505), MHZ(540), + MHZ(575), MHZ(615), MHZ(670), MHZ(720), + MHZ(760), MHZ(840), MHZ(890), MHZ(970) +}; + +static const uint32_t rf_filt_center_l[] = { + MHZ(1300), MHZ(1320), MHZ(1360), MHZ(1410), + MHZ(1445), MHZ(1460), MHZ(1490), MHZ(1530), + MHZ(1560), MHZ(1590), MHZ(1640), MHZ(1660), + MHZ(1680), MHZ(1700), MHZ(1720), MHZ(1750) +}; + +static int closest_arr_idx(const uint32_t *arr, unsigned int arr_size, uint32_t freq) +{ + unsigned int i, bi = 0; + uint32_t best_delta = 0xffffffff; + + /* iterate over the array containing a list of the center + * frequencies, selecting the closest one */ + for (i = 0; i < arr_size; i++) { + uint32_t delta = unsigned_delta(freq, arr[i]); + if (delta < best_delta) { + best_delta = delta; + bi = i; + } + } + + return bi; +} + +/* return 4-bit index as to which RF filter to select */ +static int choose_rf_filter(enum e4k_band band, uint32_t freq) +{ + int rc; + + switch (band) { + case E4K_BAND_VHF2: + case E4K_BAND_VHF3: + rc = 0; + break; + case E4K_BAND_UHF: + rc = closest_arr_idx(rf_filt_center_uhf, + ARRAY_SIZE(rf_filt_center_uhf), + freq); + break; + case E4K_BAND_L: + rc = closest_arr_idx(rf_filt_center_l, + ARRAY_SIZE(rf_filt_center_l), + freq); + break; + default: + rc = -EINVAL; + break; + } + + return rc; +} + +/* \brief Automatically select apropriate RF filter based on e4k state */ +int e4k_rf_filter_set(struct e4k_state *e4k) +{ + int rc; + + rc = choose_rf_filter(e4k->band, e4k->vco.flo); + if (rc < 0) + return rc; + + return e4k_reg_set_mask(e4k, E4K_REG_FILT1, 0xF, rc); +} + +/* Mixer Filter */ +static const uint32_t mix_filter_bw[] = { + KHZ(27000), KHZ(27000), KHZ(27000), KHZ(27000), + KHZ(27000), KHZ(27000), KHZ(27000), KHZ(27000), + KHZ(4600), KHZ(4200), KHZ(3800), KHZ(3400), + KHZ(3300), KHZ(2700), KHZ(2300), KHZ(1900) +}; + +/* IF RC Filter */ +static const uint32_t ifrc_filter_bw[] = { + KHZ(21400), KHZ(21000), KHZ(17600), KHZ(14700), + KHZ(12400), KHZ(10600), KHZ(9000), KHZ(7700), + KHZ(6400), KHZ(5300), KHZ(4400), KHZ(3400), + KHZ(2600), KHZ(1800), KHZ(1200), KHZ(1000) +}; + +/* IF Channel Filter */ +static const uint32_t ifch_filter_bw[] = { + KHZ(5500), KHZ(5300), KHZ(5000), KHZ(4800), + KHZ(4600), KHZ(4400), KHZ(4300), KHZ(4100), + KHZ(3900), KHZ(3800), KHZ(3700), KHZ(3600), + KHZ(3400), KHZ(3300), KHZ(3200), KHZ(3100), + KHZ(3000), KHZ(2950), KHZ(2900), KHZ(2800), + KHZ(2750), KHZ(2700), KHZ(2600), KHZ(2550), + KHZ(2500), KHZ(2450), KHZ(2400), KHZ(2300), + KHZ(2280), KHZ(2240), KHZ(2200), KHZ(2150) +}; + +static const uint32_t *if_filter_bw[] = { + mix_filter_bw, + ifch_filter_bw, + ifrc_filter_bw, +}; + +static const uint32_t if_filter_bw_len[] = { + ARRAY_SIZE(mix_filter_bw), + ARRAY_SIZE(ifch_filter_bw), + ARRAY_SIZE(ifrc_filter_bw), +}; + +static const struct reg_field if_filter_fields[] = { + { + E4K_REG_FILT2, 4, 4, + }, + { + E4K_REG_FILT3, 0, 5, + }, + { + E4K_REG_FILT2, 0, 4, + } +}; + +static int find_if_bw(enum e4k_if_filter filter, uint32_t bw) +{ + if (filter >= ARRAY_SIZE(if_filter_bw)) + return -EINVAL; + + return closest_arr_idx(if_filter_bw[filter], + if_filter_bw_len[filter], bw); +} + +/*! \brief Set the filter band-width of any of the IF filters + * \param[in] e4k reference to the tuner chip + * \param[in] filter filter to be configured + * \param[in] bandwidth bandwidth to be configured + * \returns positive actual filter band-width, negative in case of error + */ +int e4k_if_filter_bw_set(struct e4k_state *e4k, enum e4k_if_filter filter, + uint32_t bandwidth) +{ + int bw_idx; + const struct reg_field *field; + + if (filter >= ARRAY_SIZE(if_filter_bw)) + return -EINVAL; + + bw_idx = find_if_bw(filter, bandwidth); + + field = &if_filter_fields[filter]; + + return e4k_field_write(e4k, field, bw_idx); +} + +/*! \brief Enables / Disables the channel filter + * \param[in] e4k reference to the tuner chip + * \param[in] on 1=filter enabled, 0=filter disabled + * \returns 0 success, negative errors + */ +int e4k_if_filter_chan_enable(struct e4k_state *e4k, int on) +{ + return e4k_reg_set_mask(e4k, E4K_REG_FILT3, E4K_FILT3_DISABLE, + on ? 0 : E4K_FILT3_DISABLE); +} + +int e4k_if_filter_bw_get(struct e4k_state *e4k, enum e4k_if_filter filter) +{ + const uint32_t *arr; + int rc; + const struct reg_field *field; + + if (filter >= ARRAY_SIZE(if_filter_bw)) + return -EINVAL; + + field = &if_filter_fields[filter]; + + rc = e4k_field_read(e4k, field); + if (rc < 0) + return rc; + + arr = if_filter_bw[filter]; + + return arr[rc]; +} + + +/*********************************************************************** + * Frequency Control */ + +#define E4K_FVCO_MIN_KHZ 2600000 /* 2.6 GHz */ +#define E4K_FVCO_MAX_KHZ 3900000 /* 3.9 GHz */ +#define E4K_PLL_Y 65536 + +#ifdef OUT_OF_SPEC +#define E4K_FLO_MIN_MHZ 50 +#define E4K_FLO_MAX_MHZ 2200UL +#else +#define E4K_FLO_MIN_MHZ 64 +#define E4K_FLO_MAX_MHZ 1700 +#endif + +struct pll_settings { + uint32_t freq; + uint8_t reg_synth7; + uint8_t mult; +}; + +static const struct pll_settings pll_vars[] = { + {KHZ(72400), (1 << 3) | 7, 48}, + {KHZ(81200), (1 << 3) | 6, 40}, + {KHZ(108300), (1 << 3) | 5, 32}, + {KHZ(162500), (1 << 3) | 4, 24}, + {KHZ(216600), (1 << 3) | 3, 16}, + {KHZ(325000), (1 << 3) | 2, 12}, + {KHZ(350000), (1 << 3) | 1, 8}, + {KHZ(432000), (0 << 3) | 3, 8}, + {KHZ(667000), (0 << 3) | 2, 6}, + {KHZ(1200000), (0 << 3) | 1, 4} +}; + +static int is_fvco_valid(uint32_t fvco_z) +{ + /* check if the resulting fosc is valid */ + if (fvco_z/1000 < E4K_FVCO_MIN_KHZ || + fvco_z/1000 > E4K_FVCO_MAX_KHZ) { + fprintf(stderr, "[E4K] Fvco %u invalid\n", fvco_z); + return 0; + } + + return 1; +} + +static int is_fosc_valid(uint32_t fosc) +{ + if (fosc < MHZ(16) || fosc > MHZ(30)) { + fprintf(stderr, "[E4K] Fosc %u invalid\n", fosc); + return 0; + } + + return 1; +} + +static int is_z_valid(uint32_t z) +{ + if (z > 255) { + fprintf(stderr, "[E4K] Z %u invalid\n", z); + return 0; + } + + return 1; +} + +/*! \brief Determine if 3-phase mixing shall be used or not */ +static int use_3ph_mixing(uint32_t flo) +{ + /* this is a magic number somewhre between VHF and UHF */ + if (flo < MHZ(350)) + return 1; + + return 0; +} + +/* \brief compute Fvco based on Fosc, Z and X + * \returns positive value (Fvco in Hz), 0 in case of error */ +static uint64_t compute_fvco(uint32_t f_osc, uint8_t z, uint16_t x) +{ + uint64_t fvco_z, fvco_x, fvco; + + /* We use the following transformation in order to + * handle the fractional part with integer arithmetic: + * Fvco = Fosc * (Z + X/Y) <=> Fvco = Fosc * Z + (Fosc * X)/Y + * This avoids X/Y = 0. However, then we would overflow a 32bit + * integer, as we cannot hold e.g. 26 MHz * 65536 either. + */ + fvco_z = (uint64_t)f_osc * z; + +#if 0 + if (!is_fvco_valid(fvco_z)) + return 0; +#endif + + fvco_x = ((uint64_t)f_osc * x) / E4K_PLL_Y; + + fvco = fvco_z + fvco_x; + + return fvco; +} + +static uint32_t compute_flo(uint32_t f_osc, uint8_t z, uint16_t x, uint8_t r) +{ + uint64_t fvco = compute_fvco(f_osc, z, x); + if (fvco == 0) + return -EINVAL; + + return fvco / r; +} + +static int e4k_band_set(struct e4k_state *e4k, enum e4k_band band) +{ + int rc; + + switch (band) { + case E4K_BAND_VHF2: + case E4K_BAND_VHF3: + case E4K_BAND_UHF: + e4k_reg_write(e4k, E4K_REG_BIAS, 3); + break; + case E4K_BAND_L: + e4k_reg_write(e4k, E4K_REG_BIAS, 0); + break; + } + + /* workaround: if we don't reset this register before writing to it, + * we get a gap between 325-350 MHz */ + rc = e4k_reg_set_mask(e4k, E4K_REG_SYNTH1, 0x06, 0); + rc = e4k_reg_set_mask(e4k, E4K_REG_SYNTH1, 0x06, band << 1); + if (rc >= 0) + e4k->band = band; + + return rc; +} + +/*! \brief Compute PLL parameters for givent target frequency + * \param[out] oscp Oscillator parameters, if computation successful + * \param[in] fosc Clock input frequency applied to the chip (Hz) + * \param[in] intended_flo target tuning frequency (Hz) + * \returns actual PLL frequency, as close as possible to intended_flo, + * 0 in case of error + */ +uint32_t e4k_compute_pll_params(struct e4k_pll_params *oscp, uint32_t fosc, uint32_t intended_flo) +{ + uint32_t i; + uint8_t r = 2; + uint64_t intended_fvco, remainder; + uint64_t z = 0; + uint32_t x; + int flo; + int three_phase_mixing = 0; + oscp->r_idx = 0; + + if (!is_fosc_valid(fosc)) + return 0; + + for(i = 0; i < ARRAY_SIZE(pll_vars); ++i) { + if(intended_flo < pll_vars[i].freq) { + three_phase_mixing = (pll_vars[i].reg_synth7 & 0x08) ? 1 : 0; + oscp->r_idx = pll_vars[i].reg_synth7; + r = pll_vars[i].mult; + break; + } + } + + //fprintf(stderr, "[E4K] Fint=%u, R=%u\n", intended_flo, r); + + /* flo(max) = 1700MHz, R(max) = 48, we need 64bit! */ + intended_fvco = (uint64_t)intended_flo * r; + + /* compute integral component of multiplier */ + z = intended_fvco / fosc; + + /* compute fractional part. this will not overflow, + * as fosc(max) = 30MHz and z(max) = 255 */ + remainder = intended_fvco - (fosc * z); + /* remainder(max) = 30MHz, E4K_PLL_Y = 65536 -> 64bit! */ + x = (remainder * E4K_PLL_Y) / fosc; + /* x(max) as result of this computation is 65536 */ + + flo = compute_flo(fosc, z, x, r); + + oscp->fosc = fosc; + oscp->flo = flo; + oscp->intended_flo = intended_flo; + oscp->r = r; +// oscp->r_idx = pll_vars[i].reg_synth7 & 0x0; + oscp->threephase = three_phase_mixing; + oscp->x = x; + oscp->z = z; + + return flo; +} + +int e4k_tune_params(struct e4k_state *e4k, struct e4k_pll_params *p) +{ + /* program R + 3phase/2phase */ + e4k_reg_write(e4k, E4K_REG_SYNTH7, p->r_idx); + /* program Z */ + e4k_reg_write(e4k, E4K_REG_SYNTH3, p->z); + /* program X */ + e4k_reg_write(e4k, E4K_REG_SYNTH4, p->x & 0xff); + e4k_reg_write(e4k, E4K_REG_SYNTH5, p->x >> 8); + + /* we're in auto calibration mode, so there's no need to trigger it */ + + memcpy(&e4k->vco, p, sizeof(e4k->vco)); + + /* set the band */ + if (e4k->vco.flo < MHZ(140)) + e4k_band_set(e4k, E4K_BAND_VHF2); + else if (e4k->vco.flo < MHZ(350)) + e4k_band_set(e4k, E4K_BAND_VHF3); + else if (e4k->vco.flo < MHZ(1135)) + e4k_band_set(e4k, E4K_BAND_UHF); + else + e4k_band_set(e4k, E4K_BAND_L); + + /* select and set proper RF filter */ + e4k_rf_filter_set(e4k); + + return e4k->vco.flo; +} + +/*! \brief High-level tuning API, just specify frquency + * + * This function will compute matching PLL parameters, program them into the + * hardware and set the band as well as RF filter. + * + * \param[in] e4k reference to tuner + * \param[in] freq frequency in Hz + * \returns actual tuned frequency, negative in case of error + */ +int e4k_tune_freq(struct e4k_state *e4k, uint32_t freq) +{ + uint32_t rc; + struct e4k_pll_params p; + + /* determine PLL parameters */ + rc = e4k_compute_pll_params(&p, e4k->vco.fosc, freq); + if (!rc) + return -EINVAL; + + /* actually tune to those parameters */ + rc = e4k_tune_params(e4k, &p); + + /* check PLL lock */ + rc = e4k_reg_read(e4k, E4K_REG_SYNTH1); + if (!(rc & 0x01)) { + fprintf(stderr, "[E4K] PLL not locked for %u Hz!\n", freq); + return -1; + } + + return 0; +} + +/*********************************************************************** + * Gain Control */ + +static const int8_t if_stage1_gain[] = { + -3, 6 +}; + +static const int8_t if_stage23_gain[] = { + 0, 3, 6, 9 +}; + +static const int8_t if_stage4_gain[] = { + 0, 1, 2, 2 +}; + +static const int8_t if_stage56_gain[] = { + 3, 6, 9, 12, 15, 15, 15, 15 +}; + +static const int8_t *if_stage_gain[] = { + 0, + if_stage1_gain, + if_stage23_gain, + if_stage23_gain, + if_stage4_gain, + if_stage56_gain, + if_stage56_gain +}; + +static const uint8_t if_stage_gain_len[] = { + 0, + ARRAY_SIZE(if_stage1_gain), + ARRAY_SIZE(if_stage23_gain), + ARRAY_SIZE(if_stage23_gain), + ARRAY_SIZE(if_stage4_gain), + ARRAY_SIZE(if_stage56_gain), + ARRAY_SIZE(if_stage56_gain) +}; + +static const struct reg_field if_stage_gain_regs[] = { + { 0, 0, 0 }, + { E4K_REG_GAIN3, 0, 1 }, + { E4K_REG_GAIN3, 1, 2 }, + { E4K_REG_GAIN3, 3, 2 }, + { E4K_REG_GAIN3, 5, 2 }, + { E4K_REG_GAIN4, 0, 3 }, + { E4K_REG_GAIN4, 3, 3 } +}; + +static const int32_t lnagain[] = { + -50, 0, + -25, 1, + 0, 4, + 25, 5, + 50, 6, + 75, 7, + 100, 8, + 125, 9, + 150, 10, + 175, 11, + 200, 12, + 250, 13, + 300, 14, +}; + +static const int32_t enhgain[] = { + 10, 30, 50, 70 +}; + +int e4k_set_lna_gain(struct e4k_state *e4k, int32_t gain) +{ + uint32_t i; + for(i = 0; i < ARRAY_SIZE(lnagain)/2; ++i) { + if(lnagain[i*2] == gain) { + e4k_reg_set_mask(e4k, E4K_REG_GAIN1, 0xf, lnagain[i*2+1]); + return gain; + } + } + return -EINVAL; +} + +int e4k_set_enh_gain(struct e4k_state *e4k, int32_t gain) +{ + uint32_t i; + for(i = 0; i < ARRAY_SIZE(enhgain); ++i) { + if(enhgain[i] == gain) { + e4k_reg_set_mask(e4k, E4K_REG_AGC11, 0x7, E4K_AGC11_LNA_GAIN_ENH | (i << 1)); + return gain; + } + } + e4k_reg_set_mask(e4k, E4K_REG_AGC11, 0x7, 0); + + /* special case: 0 = off*/ + if(0 == gain) + return 0; + else + return -EINVAL; +} + +int e4k_enable_manual_gain(struct e4k_state *e4k, uint8_t manual) +{ + if (manual) { + /* Set LNA mode to manual */ + e4k_reg_set_mask(e4k, E4K_REG_AGC1, E4K_AGC1_MOD_MASK, E4K_AGC_MOD_SERIAL); + + /* Set Mixer Gain Control to manual */ + e4k_reg_set_mask(e4k, E4K_REG_AGC7, E4K_AGC7_MIX_GAIN_AUTO, 0); + } else { + /* Set LNA mode to auto */ + e4k_reg_set_mask(e4k, E4K_REG_AGC1, E4K_AGC1_MOD_MASK, E4K_AGC_MOD_IF_SERIAL_LNA_AUTON); + /* Set Mixer Gain Control to auto */ + e4k_reg_set_mask(e4k, E4K_REG_AGC7, E4K_AGC7_MIX_GAIN_AUTO, 1); + + e4k_reg_set_mask(e4k, E4K_REG_AGC11, 0x7, 0); + } + + return 0; +} + +static int find_stage_gain(uint8_t stage, int8_t val) +{ + const int8_t *arr; + int i; + + if (stage >= ARRAY_SIZE(if_stage_gain)) + return -EINVAL; + + arr = if_stage_gain[stage]; + + for (i = 0; i < if_stage_gain_len[stage]; i++) { + if (arr[i] == val) + return i; + } + return -EINVAL; +} + +/*! \brief Set the gain of one of the IF gain stages + * \param [e4k] handle to the tuner chip + * \param [stage] number of the stage (1..6) + * \param [value] gain value in dB + * \returns 0 on success, negative in case of error + */ +int e4k_if_gain_set(struct e4k_state *e4k, uint8_t stage, int8_t value) +{ + int rc; + uint8_t mask; + const struct reg_field *field; + + rc = find_stage_gain(stage, value); + if (rc < 0) + return rc; + + /* compute the bit-mask for the given gain field */ + field = &if_stage_gain_regs[stage]; + mask = width2mask[field->width] << field->shift; + + return e4k_reg_set_mask(e4k, field->reg, mask, rc << field->shift); +} + +int e4k_mixer_gain_set(struct e4k_state *e4k, int8_t value) +{ + uint8_t bit; + + switch (value) { + case 4: + bit = 0; + break; + case 12: + bit = 1; + break; + default: + return -EINVAL; + } + + return e4k_reg_set_mask(e4k, E4K_REG_GAIN2, 1, bit); +} + +int e4k_commonmode_set(struct e4k_state *e4k, int8_t value) +{ + if(value < 0) + return -EINVAL; + else if(value > 7) + return -EINVAL; + + return e4k_reg_set_mask(e4k, E4K_REG_DC7, 7, value); +} + +/*********************************************************************** + * DC Offset */ + +int e4k_manual_dc_offset(struct e4k_state *e4k, int8_t iofs, int8_t irange, int8_t qofs, int8_t qrange) +{ + int res; + + if((iofs < 0x00) || (iofs > 0x3f)) + return -EINVAL; + if((irange < 0x00) || (irange > 0x03)) + return -EINVAL; + if((qofs < 0x00) || (qofs > 0x3f)) + return -EINVAL; + if((qrange < 0x00) || (qrange > 0x03)) + return -EINVAL; + + res = e4k_reg_set_mask(e4k, E4K_REG_DC2, 0x3f, iofs); + if(res < 0) + return res; + + res = e4k_reg_set_mask(e4k, E4K_REG_DC3, 0x3f, qofs); + if(res < 0) + return res; + + res = e4k_reg_set_mask(e4k, E4K_REG_DC4, 0x33, (qrange << 4) | irange); + return res; +} + +/*! \brief Perform a DC offset calibration right now + * \param [e4k] handle to the tuner chip + */ +int e4k_dc_offset_calibrate(struct e4k_state *e4k) +{ + /* make sure the DC range detector is enabled */ + e4k_reg_set_mask(e4k, E4K_REG_DC5, E4K_DC5_RANGE_DET_EN, E4K_DC5_RANGE_DET_EN); + + return e4k_reg_write(e4k, E4K_REG_DC1, 0x01); +} + + +static const int8_t if_gains_max[] = { + 0, 6, 9, 9, 2, 15, 15 +}; + +struct gain_comb { + int8_t mixer_gain; + int8_t if1_gain; + uint8_t reg; +}; + +static const struct gain_comb dc_gain_comb[] = { + { 4, -3, 0x50 }, + { 4, 6, 0x51 }, + { 12, -3, 0x52 }, + { 12, 6, 0x53 }, +}; + +#define TO_LUT(offset, range) (offset | (range << 6)) + +int e4k_dc_offset_gen_table(struct e4k_state *e4k) +{ + uint32_t i; + + /* FIXME: read ont current gain values and write them back + * before returning to the caller */ + + /* disable auto mixer gain */ + e4k_reg_set_mask(e4k, E4K_REG_AGC7, E4K_AGC7_MIX_GAIN_AUTO, 0); + + /* set LNA/IF gain to full manual */ + e4k_reg_set_mask(e4k, E4K_REG_AGC1, E4K_AGC1_MOD_MASK, + E4K_AGC_MOD_SERIAL); + + /* set all 'other' gains to maximum */ + for (i = 2; i <= 6; i++) + e4k_if_gain_set(e4k, i, if_gains_max[i]); + + /* iterate over all mixer + if_stage_1 gain combinations */ + for (i = 0; i < ARRAY_SIZE(dc_gain_comb); i++) { + uint8_t offs_i, offs_q, range, range_i, range_q; + + /* set the combination of mixer / if1 gain */ + e4k_mixer_gain_set(e4k, dc_gain_comb[i].mixer_gain); + e4k_if_gain_set(e4k, 1, dc_gain_comb[i].if1_gain); + + /* perform actual calibration */ + e4k_dc_offset_calibrate(e4k); + + /* extract I/Q offset and range values */ + offs_i = e4k_reg_read(e4k, E4K_REG_DC2) & 0x3f; + offs_q = e4k_reg_read(e4k, E4K_REG_DC3) & 0x3f; + range = e4k_reg_read(e4k, E4K_REG_DC4); + range_i = range & 0x3; + range_q = (range >> 4) & 0x3; + + fprintf(stderr, "[E4K] Table %u I=%u/%u, Q=%u/%u\n", + i, range_i, offs_i, range_q, offs_q); + + /* write into the table */ + e4k_reg_write(e4k, dc_gain_comb[i].reg, + TO_LUT(offs_q, range_q)); + e4k_reg_write(e4k, dc_gain_comb[i].reg + 0x10, + TO_LUT(offs_i, range_i)); + } + + return 0; +} + +/*********************************************************************** + * Standby */ + +/*! \brief Enable/disable standby mode + */ +int e4k_standby(struct e4k_state *e4k, int enable) +{ + e4k_reg_set_mask(e4k, E4K_REG_MASTER1, E4K_MASTER1_NORM_STBY, + enable ? 0 : E4K_MASTER1_NORM_STBY); + + return 0; +} + +/*********************************************************************** + * Initialization */ + +static int magic_init(struct e4k_state *e4k) +{ + e4k_reg_write(e4k, 0x7e, 0x01); + e4k_reg_write(e4k, 0x7f, 0xfe); + e4k_reg_write(e4k, 0x82, 0x00); + e4k_reg_write(e4k, 0x86, 0x50); /* polarity A */ + e4k_reg_write(e4k, 0x87, 0x20); + e4k_reg_write(e4k, 0x88, 0x01); + e4k_reg_write(e4k, 0x9f, 0x7f); + e4k_reg_write(e4k, 0xa0, 0x07); + + return 0; +} + +/*! \brief Initialize the E4K tuner + */ +int e4k_init(struct e4k_state *e4k) +{ + /* make a dummy i2c read or write command, will not be ACKed! */ + e4k_reg_read(e4k, 0); + + /* Make sure we reset everything and clear POR indicator */ + e4k_reg_write(e4k, E4K_REG_MASTER1, + E4K_MASTER1_RESET | + E4K_MASTER1_NORM_STBY | + E4K_MASTER1_POR_DET + ); + + /* Configure clock input */ + e4k_reg_write(e4k, E4K_REG_CLK_INP, 0x00); + + /* Disable clock output */ + e4k_reg_write(e4k, E4K_REG_REF_CLK, 0x00); + e4k_reg_write(e4k, E4K_REG_CLKOUT_PWDN, 0x96); + + /* Write some magic values into registers */ + magic_init(e4k); +#if 0 + /* Set common mode voltage a bit higher for more margin 850 mv */ + e4k_commonmode_set(e4k, 4); + + /* Initialize DC offset lookup tables */ + e4k_dc_offset_gen_table(e4k); + + /* Enable time variant DC correction */ + e4k_reg_write(e4k, E4K_REG_DCTIME1, 0x01); + e4k_reg_write(e4k, E4K_REG_DCTIME2, 0x01); +#endif + + /* Set LNA mode to manual */ + e4k_reg_write(e4k, E4K_REG_AGC4, 0x10); /* High threshold */ + e4k_reg_write(e4k, E4K_REG_AGC5, 0x04); /* Low threshold */ + e4k_reg_write(e4k, E4K_REG_AGC6, 0x1a); /* LNA calib + loop rate */ + + e4k_reg_set_mask(e4k, E4K_REG_AGC1, E4K_AGC1_MOD_MASK, + E4K_AGC_MOD_SERIAL); + + /* Set Mixer Gain Control to manual */ + e4k_reg_set_mask(e4k, E4K_REG_AGC7, E4K_AGC7_MIX_GAIN_AUTO, 0); + +#if 0 + /* Enable LNA Gain enhancement */ + e4k_reg_set_mask(e4k, E4K_REG_AGC11, 0x7, + E4K_AGC11_LNA_GAIN_ENH | (2 << 1)); + + /* Enable automatic IF gain mode switching */ + e4k_reg_set_mask(e4k, E4K_REG_AGC8, 0x1, E4K_AGC8_SENS_LIN_AUTO); +#endif + + /* Use auto-gain as default */ + e4k_enable_manual_gain(e4k, 0); + + /* Select moderate gain levels */ + e4k_if_gain_set(e4k, 1, 6); + e4k_if_gain_set(e4k, 2, 0); + e4k_if_gain_set(e4k, 3, 0); + e4k_if_gain_set(e4k, 4, 0); + e4k_if_gain_set(e4k, 5, 9); + e4k_if_gain_set(e4k, 6, 9); + + /* Set the most narrow filter we can possibly use */ + e4k_if_filter_bw_set(e4k, E4K_IF_FILTER_MIX, KHZ(1900)); + e4k_if_filter_bw_set(e4k, E4K_IF_FILTER_RC, KHZ(1000)); + e4k_if_filter_bw_set(e4k, E4K_IF_FILTER_CHAN, KHZ(2150)); + e4k_if_filter_chan_enable(e4k, 1); + + /* Disable time variant DC correction and LUT */ + e4k_reg_set_mask(e4k, E4K_REG_DC5, 0x03, 0); + e4k_reg_set_mask(e4k, E4K_REG_DCTIME1, 0x03, 0); + e4k_reg_set_mask(e4k, E4K_REG_DCTIME2, 0x03, 0); + + return 0; +} diff --git a/src/tuner_fc0012.c b/src/tuner_fc0012.c new file mode 100644 index 0000000..768cf1c --- /dev/null +++ b/src/tuner_fc0012.c @@ -0,0 +1,345 @@ +/* + * Fitipower FC0012 tuner driver + * + * Copyright (C) 2012 Hans-Frieder Vogt + * + * modified for use in librtlsdr + * Copyright (C) 2012 Steve Markgraf + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include + +#include "rtlsdr_i2c.h" +#include "tuner_fc0012.h" + +static int fc0012_writereg(void *dev, uint8_t reg, uint8_t val) +{ + uint8_t data[2]; + data[0] = reg; + data[1] = val; + + if (rtlsdr_i2c_write_fn(dev, FC0012_I2C_ADDR, data, 2) < 0) + return -1; + + return 0; +} + +static int fc0012_readreg(void *dev, uint8_t reg, uint8_t *val) +{ + uint8_t data = reg; + + if (rtlsdr_i2c_write_fn(dev, FC0012_I2C_ADDR, &data, 1) < 0) + return -1; + + if (rtlsdr_i2c_read_fn(dev, FC0012_I2C_ADDR, &data, 1) < 0) + return -1; + + *val = data; + + return 0; +} + +/* Incomplete list of register settings: + * + * Name Reg Bits Desc + * CHIP_ID 0x00 0-7 Chip ID (constant 0xA1) + * RF_A 0x01 0-3 Number of count-to-9 cycles in RF + * divider (suggested: 2..9) + * RF_M 0x02 0-7 Total number of cycles (to-8 and to-9) + * in RF divider + * RF_K_HIGH 0x03 0-6 Bits 8..14 of fractional divider + * RF_K_LOW 0x04 0-7 Bits 0..7 of fractional RF divider + * RF_OUTDIV_A 0x05 3-7 Power of two required? + * LNA_POWER_DOWN 0x06 0 Set to 1 to switch off low noise amp + * RF_OUTDIV_B 0x06 1 Set to select 3 instead of 2 for the + * RF output divider + * VCO_SPEED 0x06 3 Select tuning range of VCO: + * 0 = Low range, (ca. 1.1 - 1.5GHz) + * 1 = High range (ca. 1.4 - 1.8GHz) + * BANDWIDTH 0x06 6-7 Set bandwidth. 6MHz = 0x80, 7MHz=0x40 + * 8MHz=0x00 + * XTAL_SPEED 0x07 5 Set to 1 for 28.8MHz Crystal input + * or 0 for 36MHz + * 0x08 0-7 + * EN_CAL_RSSI 0x09 4 Enable calibrate RSSI + * (Receive Signal Strength Indicator) + * LNA_FORCE 0x0d 0 + * AGC_FORCE 0x0d ? + * LNA_GAIN 0x13 3-4 Low noise amp gain + * LNA_COMPS 0x15 3 ? + * VCO_CALIB 0x0e 7 Set high then low to calibrate VCO + * (fast lock?) + * VCO_VOLTAGE 0x0e 0-6 Read Control voltage of VCO + * (big value -> low freq) + */ + +int fc0012_init(void *dev) +{ + int ret = 0; + unsigned int i; + uint8_t reg[] = { + 0x00, /* dummy reg. 0 */ + 0x05, /* reg. 0x01 */ + 0x10, /* reg. 0x02 */ + 0x00, /* reg. 0x03 */ + 0x00, /* reg. 0x04 */ + 0x0f, /* reg. 0x05: may also be 0x0a */ + 0x00, /* reg. 0x06: divider 2, VCO slow */ + 0x00, /* reg. 0x07: may also be 0x0f */ + 0xff, /* reg. 0x08: AGC Clock divide by 256, AGC gain 1/256, + Loop Bw 1/8 */ + 0x6e, /* reg. 0x09: Disable LoopThrough, Enable LoopThrough: 0x6f */ + 0xb8, /* reg. 0x0a: Disable LO Test Buffer */ + 0x82, /* reg. 0x0b: Output Clock is same as clock frequency, + may also be 0x83 */ + 0xfc, /* reg. 0x0c: depending on AGC Up-Down mode, may need 0xf8 */ + 0x02, /* reg. 0x0d: AGC Not Forcing & LNA Forcing, 0x02 for DVB-T */ + 0x00, /* reg. 0x0e */ + 0x00, /* reg. 0x0f */ + 0x00, /* reg. 0x10: may also be 0x0d */ + 0x00, /* reg. 0x11 */ + 0x1f, /* reg. 0x12: Set to maximum gain */ + 0x08, /* reg. 0x13: Set to Middle Gain: 0x08, + Low Gain: 0x00, High Gain: 0x10, enable IX2: 0x80 */ + 0x00, /* reg. 0x14 */ + 0x04, /* reg. 0x15: Enable LNA COMPS */ + }; + +#if 0 + switch (rtlsdr_get_tuner_clock(dev)) { + case FC_XTAL_27_MHZ: + case FC_XTAL_28_8_MHZ: + reg[0x07] |= 0x20; + break; + case FC_XTAL_36_MHZ: + default: + break; + } +#endif + reg[0x07] |= 0x20; + +// if (priv->dual_master) + reg[0x0c] |= 0x02; + + for (i = 1; i < sizeof(reg); i++) { + ret = fc0012_writereg(dev, i, reg[i]); + if (ret) + break; + } + + return ret; +} + +int fc0012_set_params(void *dev, uint32_t freq, uint32_t bandwidth) +{ + int i, ret = 0; + uint8_t reg[7], am, pm, multi, tmp; + uint64_t f_vco; + uint32_t xtal_freq_div_2; + uint16_t xin, xdiv; + int vco_select = 0; + + xtal_freq_div_2 = rtlsdr_get_tuner_clock(dev) / 2; + + /* select frequency divider and the frequency of VCO */ + if (freq < 37084000) { /* freq * 96 < 3560000000 */ + multi = 96; + reg[5] = 0x82; + reg[6] = 0x00; + } else if (freq < 55625000) { /* freq * 64 < 3560000000 */ + multi = 64; + reg[5] = 0x82; + reg[6] = 0x02; + } else if (freq < 74167000) { /* freq * 48 < 3560000000 */ + multi = 48; + reg[5] = 0x42; + reg[6] = 0x00; + } else if (freq < 111250000) { /* freq * 32 < 3560000000 */ + multi = 32; + reg[5] = 0x42; + reg[6] = 0x02; + } else if (freq < 148334000) { /* freq * 24 < 3560000000 */ + multi = 24; + reg[5] = 0x22; + reg[6] = 0x00; + } else if (freq < 222500000) { /* freq * 16 < 3560000000 */ + multi = 16; + reg[5] = 0x22; + reg[6] = 0x02; + } else if (freq < 296667000) { /* freq * 12 < 3560000000 */ + multi = 12; + reg[5] = 0x12; + reg[6] = 0x00; + } else if (freq < 445000000) { /* freq * 8 < 3560000000 */ + multi = 8; + reg[5] = 0x12; + reg[6] = 0x02; + } else if (freq < 593334000) { /* freq * 6 < 3560000000 */ + multi = 6; + reg[5] = 0x0a; + reg[6] = 0x00; + } else { + multi = 4; + reg[5] = 0x0a; + reg[6] = 0x02; + } + + f_vco = freq * multi; + + if (f_vco >= 3060000000U) { + reg[6] |= 0x08; + vco_select = 1; + } + + /* From divided value (XDIV) determined the FA and FP value */ + xdiv = (uint16_t)(f_vco / xtal_freq_div_2); + if ((f_vco - xdiv * xtal_freq_div_2) >= (xtal_freq_div_2 / 2)) + xdiv++; + + pm = (uint8_t)(xdiv / 8); + am = (uint8_t)(xdiv - (8 * pm)); + + if (am < 2) { + am += 8; + pm--; + } + + if (pm > 31) { + reg[1] = am + (8 * (pm - 31)); + reg[2] = 31; + } else { + reg[1] = am; + reg[2] = pm; + } + + if ((reg[1] > 15) || (reg[2] < 0x0b)) { + fprintf(stderr, "[FC0012] no valid PLL combination " + "found for %u Hz!\n", freq); + return -1; + } + + /* fix clock out */ + reg[6] |= 0x20; + + /* From VCO frequency determines the XIN ( fractional part of Delta + Sigma PLL) and divided value (XDIV) */ + xin = (uint16_t)((f_vco - (f_vco / xtal_freq_div_2) * xtal_freq_div_2) / 1000); + xin = (xin << 15) / (xtal_freq_div_2 / 1000); + if (xin >= 16384) + xin += 32768; + + reg[3] = xin >> 8; /* xin with 9 bit resolution */ + reg[4] = xin & 0xff; + + reg[6] &= 0x3f; /* bits 6 and 7 describe the bandwidth */ + switch (bandwidth) { + case 6000000: + reg[6] |= 0x80; + break; + case 7000000: + reg[6] |= 0x40; + break; + case 8000000: + default: + break; + } + + /* modified for Realtek demod */ + reg[5] |= 0x07; + + for (i = 1; i <= 6; i++) { + ret = fc0012_writereg(dev, i, reg[i]); + if (ret) + goto exit; + } + + /* VCO Calibration */ + ret = fc0012_writereg(dev, 0x0e, 0x80); + if (!ret) + ret = fc0012_writereg(dev, 0x0e, 0x00); + + /* VCO Re-Calibration if needed */ + if (!ret) + ret = fc0012_writereg(dev, 0x0e, 0x00); + + if (!ret) { +// msleep(10); + ret = fc0012_readreg(dev, 0x0e, &tmp); + } + if (ret) + goto exit; + + /* vco selection */ + tmp &= 0x3f; + + if (vco_select) { + if (tmp > 0x3c) { + reg[6] &= ~0x08; + ret = fc0012_writereg(dev, 0x06, reg[6]); + if (!ret) + ret = fc0012_writereg(dev, 0x0e, 0x80); + if (!ret) + ret = fc0012_writereg(dev, 0x0e, 0x00); + } + } else { + if (tmp < 0x02) { + reg[6] |= 0x08; + ret = fc0012_writereg(dev, 0x06, reg[6]); + if (!ret) + ret = fc0012_writereg(dev, 0x0e, 0x80); + if (!ret) + ret = fc0012_writereg(dev, 0x0e, 0x00); + } + } + +exit: + return ret; +} + +int fc0012_set_gain(void *dev, int gain) +{ + int ret; + uint8_t tmp = 0; + + ret = fc0012_readreg(dev, 0x13, &tmp); + + /* mask bits off */ + tmp &= 0xe0; + + switch (gain) { + case -99: /* -9.9 dB */ + tmp |= 0x02; + break; + case -40: /* -4 dB */ + break; + case 71: + tmp |= 0x08; /* 7.1 dB */ + break; + case 179: + tmp |= 0x17; /* 17.9 dB */ + break; + case 192: + default: + tmp |= 0x10; /* 19.2 dB */ + break; + } + + ret = fc0012_writereg(dev, 0x13, tmp); + + return ret; +} diff --git a/src/tuner_fc0013.c b/src/tuner_fc0013.c new file mode 100644 index 0000000..78b696e --- /dev/null +++ b/src/tuner_fc0013.c @@ -0,0 +1,500 @@ +/* + * Fitipower FC0013 tuner driver + * + * Copyright (C) 2012 Hans-Frieder Vogt + * partially based on driver code from Fitipower + * Copyright (C) 2010 Fitipower Integrated Technology Inc + * + * modified for use in librtlsdr + * Copyright (C) 2012 Steve Markgraf + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + */ + +#include +#include + +#include "rtlsdr_i2c.h" +#include "tuner_fc0013.h" + +static int fc0013_writereg(void *dev, uint8_t reg, uint8_t val) +{ + uint8_t data[2]; + data[0] = reg; + data[1] = val; + + if (rtlsdr_i2c_write_fn(dev, FC0013_I2C_ADDR, data, 2) < 0) + return -1; + + return 0; +} + +static int fc0013_readreg(void *dev, uint8_t reg, uint8_t *val) +{ + uint8_t data = reg; + + if (rtlsdr_i2c_write_fn(dev, FC0013_I2C_ADDR, &data, 1) < 0) + return -1; + + if (rtlsdr_i2c_read_fn(dev, FC0013_I2C_ADDR, &data, 1) < 0) + return -1; + + *val = data; + + return 0; +} + +int fc0013_init(void *dev) +{ + int ret = 0; + unsigned int i; + uint8_t reg[] = { + 0x00, /* reg. 0x00: dummy */ + 0x09, /* reg. 0x01 */ + 0x16, /* reg. 0x02 */ + 0x00, /* reg. 0x03 */ + 0x00, /* reg. 0x04 */ + 0x17, /* reg. 0x05 */ + 0x02, /* reg. 0x06: LPF bandwidth */ + 0x0a, /* reg. 0x07: CHECK */ + 0xff, /* reg. 0x08: AGC Clock divide by 256, AGC gain 1/256, + Loop Bw 1/8 */ + 0x6e, /* reg. 0x09: Disable LoopThrough, Enable LoopThrough: 0x6f */ + 0xb8, /* reg. 0x0a: Disable LO Test Buffer */ + 0x82, /* reg. 0x0b: CHECK */ + 0xfc, /* reg. 0x0c: depending on AGC Up-Down mode, may need 0xf8 */ + 0x01, /* reg. 0x0d: AGC Not Forcing & LNA Forcing, may need 0x02 */ + 0x00, /* reg. 0x0e */ + 0x00, /* reg. 0x0f */ + 0x00, /* reg. 0x10 */ + 0x00, /* reg. 0x11 */ + 0x00, /* reg. 0x12 */ + 0x00, /* reg. 0x13 */ + 0x50, /* reg. 0x14: DVB-t High Gain, UHF. + Middle Gain: 0x48, Low Gain: 0x40 */ + 0x01, /* reg. 0x15 */ + }; +#if 0 + switch (rtlsdr_get_tuner_clock(dev)) { + case FC_XTAL_27_MHZ: + case FC_XTAL_28_8_MHZ: + reg[0x07] |= 0x20; + break; + case FC_XTAL_36_MHZ: + default: + break; + } +#endif + reg[0x07] |= 0x20; + +// if (dev->dual_master) + reg[0x0c] |= 0x02; + + for (i = 1; i < sizeof(reg); i++) { + ret = fc0013_writereg(dev, i, reg[i]); + if (ret < 0) + break; + } + + return ret; +} + +int fc0013_rc_cal_add(void *dev, int rc_val) +{ + int ret; + uint8_t rc_cal; + int val; + + /* push rc_cal value, get rc_cal value */ + ret = fc0013_writereg(dev, 0x10, 0x00); + if (ret) + goto error_out; + + /* get rc_cal value */ + ret = fc0013_readreg(dev, 0x10, &rc_cal); + if (ret) + goto error_out; + + rc_cal &= 0x0f; + + val = (int)rc_cal + rc_val; + + /* forcing rc_cal */ + ret = fc0013_writereg(dev, 0x0d, 0x11); + if (ret) + goto error_out; + + /* modify rc_cal value */ + if (val > 15) + ret = fc0013_writereg(dev, 0x10, 0x0f); + else if (val < 0) + ret = fc0013_writereg(dev, 0x10, 0x00); + else + ret = fc0013_writereg(dev, 0x10, (uint8_t)val); + +error_out: + return ret; +} + +int fc0013_rc_cal_reset(void *dev) +{ + int ret; + + ret = fc0013_writereg(dev, 0x0d, 0x01); + if (!ret) + ret = fc0013_writereg(dev, 0x10, 0x00); + + return ret; +} + +static int fc0013_set_vhf_track(void *dev, uint32_t freq) +{ + int ret; + uint8_t tmp; + + ret = fc0013_readreg(dev, 0x1d, &tmp); + if (ret) + goto error_out; + tmp &= 0xe3; + if (freq <= 177500000) { /* VHF Track: 7 */ + ret = fc0013_writereg(dev, 0x1d, tmp | 0x1c); + } else if (freq <= 184500000) { /* VHF Track: 6 */ + ret = fc0013_writereg(dev, 0x1d, tmp | 0x18); + } else if (freq <= 191500000) { /* VHF Track: 5 */ + ret = fc0013_writereg(dev, 0x1d, tmp | 0x14); + } else if (freq <= 198500000) { /* VHF Track: 4 */ + ret = fc0013_writereg(dev, 0x1d, tmp | 0x10); + } else if (freq <= 205500000) { /* VHF Track: 3 */ + ret = fc0013_writereg(dev, 0x1d, tmp | 0x0c); + } else if (freq <= 219500000) { /* VHF Track: 2 */ + ret = fc0013_writereg(dev, 0x1d, tmp | 0x08); + } else if (freq < 300000000) { /* VHF Track: 1 */ + ret = fc0013_writereg(dev, 0x1d, tmp | 0x04); + } else { /* UHF and GPS */ + ret = fc0013_writereg(dev, 0x1d, tmp | 0x1c); + } + +error_out: + return ret; +} + +int fc0013_set_params(void *dev, uint32_t freq, uint32_t bandwidth) +{ + int i, ret = 0; + uint8_t reg[7], am, pm, multi, tmp; + uint64_t f_vco; + uint32_t xtal_freq_div_2; + uint16_t xin, xdiv; + int vco_select = 0; + + xtal_freq_div_2 = rtlsdr_get_tuner_clock(dev) / 2; + + /* set VHF track */ + ret = fc0013_set_vhf_track(dev, freq); + if (ret) + goto exit; + + if (freq < 300000000) { + /* enable VHF filter */ + ret = fc0013_readreg(dev, 0x07, &tmp); + if (ret) + goto exit; + ret = fc0013_writereg(dev, 0x07, tmp | 0x10); + if (ret) + goto exit; + + /* disable UHF & disable GPS */ + ret = fc0013_readreg(dev, 0x14, &tmp); + if (ret) + goto exit; + ret = fc0013_writereg(dev, 0x14, tmp & 0x1f); + if (ret) + goto exit; + } else if (freq <= 862000000) { + /* disable VHF filter */ + ret = fc0013_readreg(dev, 0x07, &tmp); + if (ret) + goto exit; + ret = fc0013_writereg(dev, 0x07, tmp & 0xef); + if (ret) + goto exit; + + /* enable UHF & disable GPS */ + ret = fc0013_readreg(dev, 0x14, &tmp); + if (ret) + goto exit; + ret = fc0013_writereg(dev, 0x14, (tmp & 0x1f) | 0x40); + if (ret) + goto exit; + } else { + /* disable VHF filter */ + ret = fc0013_readreg(dev, 0x07, &tmp); + if (ret) + goto exit; + ret = fc0013_writereg(dev, 0x07, tmp & 0xef); + if (ret) + goto exit; + + /* disable UHF & enable GPS */ + ret = fc0013_readreg(dev, 0x14, &tmp); + if (ret) + goto exit; + ret = fc0013_writereg(dev, 0x14, (tmp & 0x1f) | 0x20); + if (ret) + goto exit; + } + + /* select frequency divider and the frequency of VCO */ + if (freq < 37084000) { /* freq * 96 < 3560000000 */ + multi = 96; + reg[5] = 0x82; + reg[6] = 0x00; + } else if (freq < 55625000) { /* freq * 64 < 3560000000 */ + multi = 64; + reg[5] = 0x02; + reg[6] = 0x02; + } else if (freq < 74167000) { /* freq * 48 < 3560000000 */ + multi = 48; + reg[5] = 0x42; + reg[6] = 0x00; + } else if (freq < 111250000) { /* freq * 32 < 3560000000 */ + multi = 32; + reg[5] = 0x82; + reg[6] = 0x02; + } else if (freq < 148334000) { /* freq * 24 < 3560000000 */ + multi = 24; + reg[5] = 0x22; + reg[6] = 0x00; + } else if (freq < 222500000) { /* freq * 16 < 3560000000 */ + multi = 16; + reg[5] = 0x42; + reg[6] = 0x02; + } else if (freq < 296667000) { /* freq * 12 < 3560000000 */ + multi = 12; + reg[5] = 0x12; + reg[6] = 0x00; + } else if (freq < 445000000) { /* freq * 8 < 3560000000 */ + multi = 8; + reg[5] = 0x22; + reg[6] = 0x02; + } else if (freq < 593334000) { /* freq * 6 < 3560000000 */ + multi = 6; + reg[5] = 0x0a; + reg[6] = 0x00; + } else if (freq < 950000000) { /* freq * 4 < 3800000000 */ + multi = 4; + reg[5] = 0x12; + reg[6] = 0x02; + } else { + multi = 2; + reg[5] = 0x0a; + reg[6] = 0x02; + } + + f_vco = freq * multi; + + if (f_vco >= 3060000000U) { + reg[6] |= 0x08; + vco_select = 1; + } + + /* From divided value (XDIV) determined the FA and FP value */ + xdiv = (uint16_t)(f_vco / xtal_freq_div_2); + if ((f_vco - xdiv * xtal_freq_div_2) >= (xtal_freq_div_2 / 2)) + xdiv++; + + pm = (uint8_t)(xdiv / 8); + am = (uint8_t)(xdiv - (8 * pm)); + + if (am < 2) { + am += 8; + pm--; + } + + if (pm > 31) { + reg[1] = am + (8 * (pm - 31)); + reg[2] = 31; + } else { + reg[1] = am; + reg[2] = pm; + } + + if ((reg[1] > 15) || (reg[2] < 0x0b)) { + fprintf(stderr, "[FC0013] no valid PLL combination " + "found for %u Hz!\n", freq); + return -1; + } + + /* fix clock out */ + reg[6] |= 0x20; + + /* From VCO frequency determines the XIN ( fractional part of Delta + Sigma PLL) and divided value (XDIV) */ + xin = (uint16_t)((f_vco - (f_vco / xtal_freq_div_2) * xtal_freq_div_2) / 1000); + xin = (xin << 15) / (xtal_freq_div_2 / 1000); + if (xin >= 16384) + xin += 32768; + + reg[3] = xin >> 8; + reg[4] = xin & 0xff; + + reg[6] &= 0x3f; /* bits 6 and 7 describe the bandwidth */ + switch (bandwidth) { + case 6000000: + reg[6] |= 0x80; + break; + case 7000000: + reg[6] |= 0x40; + break; + case 8000000: + default: + break; + } + + /* modified for Realtek demod */ + reg[5] |= 0x07; + + for (i = 1; i <= 6; i++) { + ret = fc0013_writereg(dev, i, reg[i]); + if (ret) + goto exit; + } + + ret = fc0013_readreg(dev, 0x11, &tmp); + if (ret) + goto exit; + if (multi == 64) + ret = fc0013_writereg(dev, 0x11, tmp | 0x04); + else + ret = fc0013_writereg(dev, 0x11, tmp & 0xfb); + if (ret) + goto exit; + + /* VCO Calibration */ + ret = fc0013_writereg(dev, 0x0e, 0x80); + if (!ret) + ret = fc0013_writereg(dev, 0x0e, 0x00); + + /* VCO Re-Calibration if needed */ + if (!ret) + ret = fc0013_writereg(dev, 0x0e, 0x00); + + if (!ret) { +// msleep(10); + ret = fc0013_readreg(dev, 0x0e, &tmp); + } + if (ret) + goto exit; + + /* vco selection */ + tmp &= 0x3f; + + if (vco_select) { + if (tmp > 0x3c) { + reg[6] &= ~0x08; + ret = fc0013_writereg(dev, 0x06, reg[6]); + if (!ret) + ret = fc0013_writereg(dev, 0x0e, 0x80); + if (!ret) + ret = fc0013_writereg(dev, 0x0e, 0x00); + } + } else { + if (tmp < 0x02) { + reg[6] |= 0x08; + ret = fc0013_writereg(dev, 0x06, reg[6]); + if (!ret) + ret = fc0013_writereg(dev, 0x0e, 0x80); + if (!ret) + ret = fc0013_writereg(dev, 0x0e, 0x00); + } + } + +exit: + return ret; +} + +int fc0013_set_gain_mode(void *dev, int manual) +{ + int ret = 0; + uint8_t tmp = 0; + + ret |= fc0013_readreg(dev, 0x0d, &tmp); + + if (manual) + tmp |= (1 << 3); + else + tmp &= ~(1 << 3); + + ret |= fc0013_writereg(dev, 0x0d, tmp); + + /* set a fixed IF-gain for now */ + ret |= fc0013_writereg(dev, 0x13, 0x0a); + + return ret; +} + +int fc0013_lna_gains[] ={ + -99, 0x02, + -73, 0x03, + -65, 0x05, + -63, 0x04, + -63, 0x00, + -60, 0x07, + -58, 0x01, + -54, 0x06, + 58, 0x0f, + 61, 0x0e, + 63, 0x0d, + 65, 0x0c, + 67, 0x0b, + 68, 0x0a, + 70, 0x09, + 71, 0x08, + 179, 0x17, + 181, 0x16, + 182, 0x15, + 184, 0x14, + 186, 0x13, + 188, 0x12, + 191, 0x11, + 197, 0x10 +}; + +#define GAIN_CNT (sizeof(fc0013_lna_gains) / sizeof(int) / 2) + +int fc0013_set_lna_gain(void *dev, int gain) +{ + int ret = 0; + unsigned int i; + uint8_t tmp = 0; + + ret |= fc0013_readreg(dev, 0x14, &tmp); + + /* mask bits off */ + tmp &= 0xe0; + + for (i = 0; i < GAIN_CNT; i++) { + if ((fc0013_lna_gains[i*2] >= gain) || (i+1 == GAIN_CNT)) { + tmp |= fc0013_lna_gains[i*2 + 1]; + break; + } + } + + /* set gain */ + ret |= fc0013_writereg(dev, 0x14, tmp); + + return ret; +} diff --git a/src/tuner_fc2580.c b/src/tuner_fc2580.c new file mode 100644 index 0000000..d2eeba5 --- /dev/null +++ b/src/tuner_fc2580.c @@ -0,0 +1,494 @@ +/* + * FCI FC2580 tuner driver, taken from the kernel driver that can be found + * on http://linux.terratec.de/tv_en.html + * + * This driver is a mess, and should be cleaned up/rewritten. + * + */ + +#include + +#include "rtlsdr_i2c.h" +#include "tuner_fc2580.h" + +/* 16.384 MHz (at least on the Logilink VG0002A) */ +#define CRYSTAL_FREQ 16384000 + +/* glue functions to rtl-sdr code */ + +fc2580_fci_result_type fc2580_i2c_write(void *pTuner, unsigned char reg, unsigned char val) +{ + uint8_t data[2]; + + data[0] = reg; + data[1] = val; + + if (rtlsdr_i2c_write_fn(pTuner, FC2580_I2C_ADDR, data, 2) < 0) + return FC2580_FCI_FAIL; + + return FC2580_FCI_SUCCESS; +} + +fc2580_fci_result_type fc2580_i2c_read(void *pTuner, unsigned char reg, unsigned char *read_data) +{ + uint8_t data = reg; + + if (rtlsdr_i2c_write_fn(pTuner, FC2580_I2C_ADDR, &data, 1) < 0) + return FC2580_FCI_FAIL; + + if (rtlsdr_i2c_read_fn(pTuner, FC2580_I2C_ADDR, &data, 1) < 0) + return FC2580_FCI_FAIL; + + *read_data = data; + + return FC2580_FCI_SUCCESS; +} + +int +fc2580_Initialize( + void *pTuner + ) +{ + int AgcMode; + unsigned int CrystalFreqKhz; + + //TODO set AGC mode + AgcMode = FC2580_AGC_EXTERNAL; + + // Initialize tuner with AGC mode. + // Note: CrystalFreqKhz = round(CrystalFreqHz / 1000) + CrystalFreqKhz = (unsigned int)((CRYSTAL_FREQ + 500) / 1000); + + if(fc2580_set_init(pTuner, AgcMode, CrystalFreqKhz) != FC2580_FCI_SUCCESS) + goto error_status_initialize_tuner; + + + return FUNCTION_SUCCESS; + + +error_status_initialize_tuner: + return FUNCTION_ERROR; +} + +int +fc2580_SetRfFreqHz( + void *pTuner, + unsigned long RfFreqHz + ) +{ + unsigned int RfFreqKhz; + unsigned int CrystalFreqKhz; + + // Set tuner RF frequency in KHz. + // Note: RfFreqKhz = round(RfFreqHz / 1000) + // CrystalFreqKhz = round(CrystalFreqHz / 1000) + RfFreqKhz = (unsigned int)((RfFreqHz + 500) / 1000); + CrystalFreqKhz = (unsigned int)((CRYSTAL_FREQ + 500) / 1000); + + if(fc2580_set_freq(pTuner, RfFreqKhz, CrystalFreqKhz) != FC2580_FCI_SUCCESS) + goto error_status_set_tuner_rf_frequency; + + return FUNCTION_SUCCESS; + +error_status_set_tuner_rf_frequency: + return FUNCTION_ERROR; +} + +/** + +@brief Set FC2580 tuner bandwidth mode. + +*/ +int +fc2580_SetBandwidthMode( + void *pTuner, + int BandwidthMode + ) +{ + unsigned int CrystalFreqKhz; + + // Set tuner bandwidth mode. + // Note: CrystalFreqKhz = round(CrystalFreqHz / 1000) + CrystalFreqKhz = (unsigned int)((CRYSTAL_FREQ + 500) / 1000); + + if(fc2580_set_filter(pTuner, (unsigned char)BandwidthMode, CrystalFreqKhz) != FC2580_FCI_SUCCESS) + goto error_status_set_tuner_bandwidth_mode; + + return FUNCTION_SUCCESS; + + +error_status_set_tuner_bandwidth_mode: + return FUNCTION_ERROR; +} + +void fc2580_wait_msec(void *pTuner, int a) +{ + /* USB latency is enough for now ;) */ +// usleep(a * 1000); + return; +} + +/*============================================================================== + fc2580 initial setting + + This function is a generic function which gets called to initialize + + fc2580 in DVB-H mode or L-Band TDMB mode + + + + ifagc_mode + type : integer + 1 : Internal AGC + 2 : Voltage Control Mode + +==============================================================================*/ +fc2580_fci_result_type fc2580_set_init( void *pTuner, int ifagc_mode, unsigned int freq_xtal ) +{ + fc2580_fci_result_type result = FC2580_FCI_SUCCESS; + + result &= fc2580_i2c_write(pTuner, 0x00, 0x00); /*** Confidential ***/ + result &= fc2580_i2c_write(pTuner, 0x12, 0x86); + result &= fc2580_i2c_write(pTuner, 0x14, 0x5C); + result &= fc2580_i2c_write(pTuner, 0x16, 0x3C); + result &= fc2580_i2c_write(pTuner, 0x1F, 0xD2); + result &= fc2580_i2c_write(pTuner, 0x09, 0xD7); + result &= fc2580_i2c_write(pTuner, 0x0B, 0xD5); + result &= fc2580_i2c_write(pTuner, 0x0C, 0x32); + result &= fc2580_i2c_write(pTuner, 0x0E, 0x43); + result &= fc2580_i2c_write(pTuner, 0x21, 0x0A); + result &= fc2580_i2c_write(pTuner, 0x22, 0x82); + if( ifagc_mode == 1 ) + { + result &= fc2580_i2c_write(pTuner, 0x45, 0x10); //internal AGC + result &= fc2580_i2c_write(pTuner, 0x4C, 0x00); //HOLD_AGC polarity + } + else if( ifagc_mode == 2 ) + { + result &= fc2580_i2c_write(pTuner, 0x45, 0x20); //Voltage Control Mode + result &= fc2580_i2c_write(pTuner, 0x4C, 0x02); //HOLD_AGC polarity + } + result &= fc2580_i2c_write(pTuner, 0x3F, 0x88); + result &= fc2580_i2c_write(pTuner, 0x02, 0x0E); + result &= fc2580_i2c_write(pTuner, 0x58, 0x14); + result &= fc2580_set_filter(pTuner, 8, freq_xtal); //BW = 7.8MHz + + return result; +} + + +/*============================================================================== + fc2580 frequency setting + + This function is a generic function which gets called to change LO Frequency + + of fc2580 in DVB-H mode or L-Band TDMB mode + + + freq_xtal: kHz + + f_lo + Value of target LO Frequency in 'kHz' unit + ex) 2.6GHz = 2600000 + +==============================================================================*/ +fc2580_fci_result_type fc2580_set_freq( void *pTuner, unsigned int f_lo, unsigned int freq_xtal ) +{ + unsigned int f_diff, f_diff_shifted, n_val, k_val; + unsigned int f_vco, r_val, f_comp; + unsigned char pre_shift_bits = 4;// number of preshift to prevent overflow in shifting f_diff to f_diff_shifted + unsigned char data_0x18; + unsigned char data_0x02 = (USE_EXT_CLK<<5)|0x0E; + + fc2580_band_type band = ( f_lo > 1000000 )? FC2580_L_BAND : ( f_lo > 400000 )? FC2580_UHF_BAND : FC2580_VHF_BAND; + + fc2580_fci_result_type result = FC2580_FCI_SUCCESS; + + f_vco = ( band == FC2580_UHF_BAND )? f_lo * 4 : (( band == FC2580_L_BAND )? f_lo * 2 : f_lo * 12); + r_val = ( f_vco >= 2*76*freq_xtal )? 1 : ( f_vco >= 76*freq_xtal )? 2 : 4; + f_comp = freq_xtal/r_val; + n_val = ( f_vco / 2 ) / f_comp; + + f_diff = f_vco - 2* f_comp * n_val; + f_diff_shifted = f_diff << ( 20 - pre_shift_bits ); + k_val = f_diff_shifted / ( ( 2* f_comp ) >> pre_shift_bits ); + + if( f_diff_shifted - k_val * ( ( 2* f_comp ) >> pre_shift_bits ) >= ( f_comp >> pre_shift_bits ) ) + k_val = k_val + 1; + + if( f_vco >= BORDER_FREQ ) //Select VCO Band + data_0x02 = data_0x02 | 0x08; //0x02[3] = 1; + else + data_0x02 = data_0x02 & 0xF7; //0x02[3] = 0; + +// if( band != curr_band ) { + switch(band) + { + case FC2580_UHF_BAND: + data_0x02 = (data_0x02 & 0x3F); + + result &= fc2580_i2c_write(pTuner, 0x25, 0xF0); + result &= fc2580_i2c_write(pTuner, 0x27, 0x77); + result &= fc2580_i2c_write(pTuner, 0x28, 0x53); + result &= fc2580_i2c_write(pTuner, 0x29, 0x60); + result &= fc2580_i2c_write(pTuner, 0x30, 0x09); + result &= fc2580_i2c_write(pTuner, 0x50, 0x8C); + result &= fc2580_i2c_write(pTuner, 0x53, 0x50); + + if( f_lo < 538000 ) + result &= fc2580_i2c_write(pTuner, 0x5F, 0x13); + else + result &= fc2580_i2c_write(pTuner, 0x5F, 0x15); + + if( f_lo < 538000 ) + { + result &= fc2580_i2c_write(pTuner, 0x61, 0x07); + result &= fc2580_i2c_write(pTuner, 0x62, 0x06); + result &= fc2580_i2c_write(pTuner, 0x67, 0x06); + result &= fc2580_i2c_write(pTuner, 0x68, 0x08); + result &= fc2580_i2c_write(pTuner, 0x69, 0x10); + result &= fc2580_i2c_write(pTuner, 0x6A, 0x12); + } + else if( f_lo < 794000 ) + { + result &= fc2580_i2c_write(pTuner, 0x61, 0x03); + result &= fc2580_i2c_write(pTuner, 0x62, 0x03); + result &= fc2580_i2c_write(pTuner, 0x67, 0x03); //ACI improve + result &= fc2580_i2c_write(pTuner, 0x68, 0x05); //ACI improve + result &= fc2580_i2c_write(pTuner, 0x69, 0x0C); + result &= fc2580_i2c_write(pTuner, 0x6A, 0x0E); + } + else + { + result &= fc2580_i2c_write(pTuner, 0x61, 0x07); + result &= fc2580_i2c_write(pTuner, 0x62, 0x06); + result &= fc2580_i2c_write(pTuner, 0x67, 0x07); + result &= fc2580_i2c_write(pTuner, 0x68, 0x09); + result &= fc2580_i2c_write(pTuner, 0x69, 0x10); + result &= fc2580_i2c_write(pTuner, 0x6A, 0x12); + } + + result &= fc2580_i2c_write(pTuner, 0x63, 0x15); + + result &= fc2580_i2c_write(pTuner, 0x6B, 0x0B); + result &= fc2580_i2c_write(pTuner, 0x6C, 0x0C); + result &= fc2580_i2c_write(pTuner, 0x6D, 0x78); + result &= fc2580_i2c_write(pTuner, 0x6E, 0x32); + result &= fc2580_i2c_write(pTuner, 0x6F, 0x14); + result &= fc2580_set_filter(pTuner, 8, freq_xtal); //BW = 7.8MHz + break; + case FC2580_VHF_BAND: + data_0x02 = (data_0x02 & 0x3F) | 0x80; + result &= fc2580_i2c_write(pTuner, 0x27, 0x77); + result &= fc2580_i2c_write(pTuner, 0x28, 0x33); + result &= fc2580_i2c_write(pTuner, 0x29, 0x40); + result &= fc2580_i2c_write(pTuner, 0x30, 0x09); + result &= fc2580_i2c_write(pTuner, 0x50, 0x8C); + result &= fc2580_i2c_write(pTuner, 0x53, 0x50); + result &= fc2580_i2c_write(pTuner, 0x5F, 0x0F); + result &= fc2580_i2c_write(pTuner, 0x61, 0x07); + result &= fc2580_i2c_write(pTuner, 0x62, 0x00); + result &= fc2580_i2c_write(pTuner, 0x63, 0x15); + result &= fc2580_i2c_write(pTuner, 0x67, 0x03); + result &= fc2580_i2c_write(pTuner, 0x68, 0x05); + result &= fc2580_i2c_write(pTuner, 0x69, 0x10); + result &= fc2580_i2c_write(pTuner, 0x6A, 0x12); + result &= fc2580_i2c_write(pTuner, 0x6B, 0x08); + result &= fc2580_i2c_write(pTuner, 0x6C, 0x0A); + result &= fc2580_i2c_write(pTuner, 0x6D, 0x78); + result &= fc2580_i2c_write(pTuner, 0x6E, 0x32); + result &= fc2580_i2c_write(pTuner, 0x6F, 0x54); + result &= fc2580_set_filter(pTuner, 7, freq_xtal); //BW = 6.8MHz + break; + case FC2580_L_BAND: + data_0x02 = (data_0x02 & 0x3F) | 0x40; + result &= fc2580_i2c_write(pTuner, 0x2B, 0x70); + result &= fc2580_i2c_write(pTuner, 0x2C, 0x37); + result &= fc2580_i2c_write(pTuner, 0x2D, 0xE7); + result &= fc2580_i2c_write(pTuner, 0x30, 0x09); + result &= fc2580_i2c_write(pTuner, 0x44, 0x20); + result &= fc2580_i2c_write(pTuner, 0x50, 0x8C); + result &= fc2580_i2c_write(pTuner, 0x53, 0x50); + result &= fc2580_i2c_write(pTuner, 0x5F, 0x0F); + result &= fc2580_i2c_write(pTuner, 0x61, 0x0F); + result &= fc2580_i2c_write(pTuner, 0x62, 0x00); + result &= fc2580_i2c_write(pTuner, 0x63, 0x13); + result &= fc2580_i2c_write(pTuner, 0x67, 0x00); + result &= fc2580_i2c_write(pTuner, 0x68, 0x02); + result &= fc2580_i2c_write(pTuner, 0x69, 0x0C); + result &= fc2580_i2c_write(pTuner, 0x6A, 0x0E); + result &= fc2580_i2c_write(pTuner, 0x6B, 0x08); + result &= fc2580_i2c_write(pTuner, 0x6C, 0x0A); + result &= fc2580_i2c_write(pTuner, 0x6D, 0xA0); + result &= fc2580_i2c_write(pTuner, 0x6E, 0x50); + result &= fc2580_i2c_write(pTuner, 0x6F, 0x14); + result &= fc2580_set_filter(pTuner, 1, freq_xtal); //BW = 1.53MHz + break; + default: + break; + } +// curr_band = band; +// } + + //A command about AGC clock's pre-divide ratio + if( freq_xtal >= 28000 ) + result &= fc2580_i2c_write(pTuner, 0x4B, 0x22 ); + + //Commands about VCO Band and PLL setting. + result &= fc2580_i2c_write(pTuner, 0x02, data_0x02); + data_0x18 = ( ( r_val == 1 )? 0x00 : ( ( r_val == 2 )? 0x10 : 0x20 ) ) + (unsigned char)(k_val >> 16); + result &= fc2580_i2c_write(pTuner, 0x18, data_0x18); //Load 'R' value and high part of 'K' values + result &= fc2580_i2c_write(pTuner, 0x1A, (unsigned char)( k_val >> 8 ) ); //Load middle part of 'K' value + result &= fc2580_i2c_write(pTuner, 0x1B, (unsigned char)( k_val ) ); //Load lower part of 'K' value + result &= fc2580_i2c_write(pTuner, 0x1C, (unsigned char)( n_val ) ); //Load 'N' value + + //A command about UHF LNA Load Cap + if( band == FC2580_UHF_BAND ) + result &= fc2580_i2c_write(pTuner, 0x2D, ( f_lo <= (unsigned int)794000 )? 0x9F : 0x8F ); //LNA_OUT_CAP + + + return result; +} + + +/*============================================================================== + fc2580 filter BW setting + + This function is a generic function which gets called to change Bandwidth + + frequency of fc2580's channel selection filter + + + freq_xtal: kHz + + filter_bw + 1 : 1.53MHz(TDMB) + 6 : 6MHz (Bandwidth 6MHz) + 7 : 6.8MHz (Bandwidth 7MHz) + 8 : 7.8MHz (Bandwidth 8MHz) + + +==============================================================================*/ +fc2580_fci_result_type fc2580_set_filter( void *pTuner, unsigned char filter_bw, unsigned int freq_xtal ) +{ + unsigned char cal_mon = 0, i; + fc2580_fci_result_type result = FC2580_FCI_SUCCESS; + + if(filter_bw == 1) + { + result &= fc2580_i2c_write(pTuner, 0x36, 0x1C); + result &= fc2580_i2c_write(pTuner, 0x37, (unsigned char)(4151*freq_xtal/1000000) ); + result &= fc2580_i2c_write(pTuner, 0x39, 0x00); + result &= fc2580_i2c_write(pTuner, 0x2E, 0x09); + } + if(filter_bw == 6) + { + result &= fc2580_i2c_write(pTuner, 0x36, 0x18); + result &= fc2580_i2c_write(pTuner, 0x37, (unsigned char)(4400*freq_xtal/1000000) ); + result &= fc2580_i2c_write(pTuner, 0x39, 0x00); + result &= fc2580_i2c_write(pTuner, 0x2E, 0x09); + } + else if(filter_bw == 7) + { + result &= fc2580_i2c_write(pTuner, 0x36, 0x18); + result &= fc2580_i2c_write(pTuner, 0x37, (unsigned char)(3910*freq_xtal/1000000) ); + result &= fc2580_i2c_write(pTuner, 0x39, 0x80); + result &= fc2580_i2c_write(pTuner, 0x2E, 0x09); + } + else if(filter_bw == 8) + { + result &= fc2580_i2c_write(pTuner, 0x36, 0x18); + result &= fc2580_i2c_write(pTuner, 0x37, (unsigned char)(3300*freq_xtal/1000000) ); + result &= fc2580_i2c_write(pTuner, 0x39, 0x80); + result &= fc2580_i2c_write(pTuner, 0x2E, 0x09); + } + + + for(i=0; i<5; i++) + { + fc2580_wait_msec(pTuner, 5);//wait 5ms + result &= fc2580_i2c_read(pTuner, 0x2F, &cal_mon); + if( (cal_mon & 0xC0) != 0xC0) + { + result &= fc2580_i2c_write(pTuner, 0x2E, 0x01); + result &= fc2580_i2c_write(pTuner, 0x2E, 0x09); + } + else + break; + } + + result &= fc2580_i2c_write(pTuner, 0x2E, 0x01); + + return result; +} + +/*============================================================================== + fc2580 RSSI function + + This function is a generic function which returns fc2580's + + current RSSI value. + + + none + + + int + rssi : estimated input power. + +==============================================================================*/ +//int fc2580_get_rssi(void) { +// +// unsigned char s_lna, s_rfvga, s_cfs, s_ifvga; +// int ofs_lna, ofs_rfvga, ofs_csf, ofs_ifvga, rssi; +// +// fc2580_i2c_read(0x71, &s_lna ); +// fc2580_i2c_read(0x72, &s_rfvga ); +// fc2580_i2c_read(0x73, &s_cfs ); +// fc2580_i2c_read(0x74, &s_ifvga ); +// +// +// ofs_lna = +// (curr_band==FC2580_UHF_BAND)? +// (s_lna==0)? 0 : +// (s_lna==1)? -6 : +// (s_lna==2)? -17 : +// (s_lna==3)? -22 : -30 : +// (curr_band==FC2580_VHF_BAND)? +// (s_lna==0)? 0 : +// (s_lna==1)? -6 : +// (s_lna==2)? -19 : +// (s_lna==3)? -24 : -32 : +// (curr_band==FC2580_L_BAND)? +// (s_lna==0)? 0 : +// (s_lna==1)? -6 : +// (s_lna==2)? -11 : +// (s_lna==3)? -16 : -34 : +// 0;//FC2580_NO_BAND +// ofs_rfvga = -s_rfvga+((s_rfvga>=11)? 1 : 0) + ((s_rfvga>=18)? 1 : 0); +// ofs_csf = -6*s_cfs; +// ofs_ifvga = s_ifvga/4; +// +// return rssi = ofs_lna+ofs_rfvga+ofs_csf+ofs_ifvga+OFS_RSSI; +// +//} + +/*============================================================================== + fc2580 Xtal frequency Setting + + This function is a generic function which sets + + the frequency of xtal. + + + + frequency + frequency value of internal(external) Xtal(clock) in kHz unit. + +==============================================================================*/ +//void fc2580_set_freq_xtal(unsigned int frequency) { +// +// freq_xtal = frequency; +// +//} + diff --git a/src/tuner_r82xx.c b/src/tuner_r82xx.c new file mode 100644 index 0000000..f620238 --- /dev/null +++ b/src/tuner_r82xx.c @@ -0,0 +1,1328 @@ +/* + * Rafael Micro R820T/R828D driver + * + * Copyright (C) 2013 Mauro Carvalho Chehab + * Copyright (C) 2013 Steve Markgraf + * + * This driver is a heavily modified version of the driver found in the + * Linux kernel: + * http://git.linuxtv.org/linux-2.6.git/history/HEAD:/drivers/media/tuners/r820t.c + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include + +#include "rtlsdr_i2c.h" +#include "tuner_r82xx.h" + +#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) +#define MHZ(x) ((x)*1000*1000) +#define KHZ(x) ((x)*1000) + +/* + * Static constants + */ + +/* Those initial values start from REG_SHADOW_START */ +static const uint8_t r82xx_init_array[NUM_REGS] = { + 0x83, 0x32, 0x75, /* 05 to 07 */ + 0xc0, 0x40, 0xd6, 0x6c, /* 08 to 0b */ + 0xf5, 0x63, 0x75, 0x68, /* 0c to 0f */ + 0x6c, 0x83, 0x80, 0x00, /* 10 to 13 */ + 0x0f, 0x00, 0xc0, 0x30, /* 14 to 17 */ + 0x48, 0xcc, 0x60, 0x00, /* 18 to 1b */ + 0x54, 0xae, 0x4a, 0xc0 /* 1c to 1f */ +}; + +/* Tuner frequency ranges */ +static const struct r82xx_freq_range freq_ranges[] = { + { + /* .freq = */ 0, /* Start freq, in MHz */ + /* .open_d = */ 0x08, /* low */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0xdf, /* R27[7:0] band2,band0 */ + /* .xtal_cap20p = */ 0x02, /* R16[1:0] 20pF (10) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 50, /* Start freq, in MHz */ + /* .open_d = */ 0x08, /* low */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0xbe, /* R27[7:0] band4,band1 */ + /* .xtal_cap20p = */ 0x02, /* R16[1:0] 20pF (10) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 55, /* Start freq, in MHz */ + /* .open_d = */ 0x08, /* low */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x8b, /* R27[7:0] band7,band4 */ + /* .xtal_cap20p = */ 0x02, /* R16[1:0] 20pF (10) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 60, /* Start freq, in MHz */ + /* .open_d = */ 0x08, /* low */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x7b, /* R27[7:0] band8,band4 */ + /* .xtal_cap20p = */ 0x02, /* R16[1:0] 20pF (10) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 65, /* Start freq, in MHz */ + /* .open_d = */ 0x08, /* low */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x69, /* R27[7:0] band9,band6 */ + /* .xtal_cap20p = */ 0x02, /* R16[1:0] 20pF (10) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 70, /* Start freq, in MHz */ + /* .open_d = */ 0x08, /* low */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x58, /* R27[7:0] band10,band7 */ + /* .xtal_cap20p = */ 0x02, /* R16[1:0] 20pF (10) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 75, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x44, /* R27[7:0] band11,band11 */ + /* .xtal_cap20p = */ 0x02, /* R16[1:0] 20pF (10) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 80, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x44, /* R27[7:0] band11,band11 */ + /* .xtal_cap20p = */ 0x02, /* R16[1:0] 20pF (10) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 90, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x34, /* R27[7:0] band12,band11 */ + /* .xtal_cap20p = */ 0x01, /* R16[1:0] 10pF (01) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 100, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x34, /* R27[7:0] band12,band11 */ + /* .xtal_cap20p = */ 0x01, /* R16[1:0] 10pF (01) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 110, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x24, /* R27[7:0] band13,band11 */ + /* .xtal_cap20p = */ 0x01, /* R16[1:0] 10pF (01) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 120, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x24, /* R27[7:0] band13,band11 */ + /* .xtal_cap20p = */ 0x01, /* R16[1:0] 10pF (01) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 140, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x14, /* R27[7:0] band14,band11 */ + /* .xtal_cap20p = */ 0x01, /* R16[1:0] 10pF (01) */ + /* .xtal_cap10p = */ 0x01, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 180, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x13, /* R27[7:0] band14,band12 */ + /* .xtal_cap20p = */ 0x00, /* R16[1:0] 0pF (00) */ + /* .xtal_cap10p = */ 0x00, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 220, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x13, /* R27[7:0] band14,band12 */ + /* .xtal_cap20p = */ 0x00, /* R16[1:0] 0pF (00) */ + /* .xtal_cap10p = */ 0x00, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 250, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x11, /* R27[7:0] highest,highest */ + /* .xtal_cap20p = */ 0x00, /* R16[1:0] 0pF (00) */ + /* .xtal_cap10p = */ 0x00, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 280, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x02, /* R26[7:6]=0 (LPF) R26[1:0]=2 (low) */ + /* .tf_c = */ 0x00, /* R27[7:0] highest,highest */ + /* .xtal_cap20p = */ 0x00, /* R16[1:0] 0pF (00) */ + /* .xtal_cap10p = */ 0x00, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 310, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x41, /* R26[7:6]=1 (bypass) R26[1:0]=1 (middle) */ + /* .tf_c = */ 0x00, /* R27[7:0] highest,highest */ + /* .xtal_cap20p = */ 0x00, /* R16[1:0] 0pF (00) */ + /* .xtal_cap10p = */ 0x00, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 450, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x41, /* R26[7:6]=1 (bypass) R26[1:0]=1 (middle) */ + /* .tf_c = */ 0x00, /* R27[7:0] highest,highest */ + /* .xtal_cap20p = */ 0x00, /* R16[1:0] 0pF (00) */ + /* .xtal_cap10p = */ 0x00, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 588, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x40, /* R26[7:6]=1 (bypass) R26[1:0]=0 (highest) */ + /* .tf_c = */ 0x00, /* R27[7:0] highest,highest */ + /* .xtal_cap20p = */ 0x00, /* R16[1:0] 0pF (00) */ + /* .xtal_cap10p = */ 0x00, + /* .xtal_cap0p = */ 0x00, + }, { + /* .freq = */ 650, /* Start freq, in MHz */ + /* .open_d = */ 0x00, /* high */ + /* .rf_mux_ploy = */ 0x40, /* R26[7:6]=1 (bypass) R26[1:0]=0 (highest) */ + /* .tf_c = */ 0x00, /* R27[7:0] highest,highest */ + /* .xtal_cap20p = */ 0x00, /* R16[1:0] 0pF (00) */ + /* .xtal_cap10p = */ 0x00, + /* .xtal_cap0p = */ 0x00, + } +}; + +static int r82xx_xtal_capacitor[][2] = { + { 0x0b, XTAL_LOW_CAP_30P }, + { 0x02, XTAL_LOW_CAP_20P }, + { 0x01, XTAL_LOW_CAP_10P }, + { 0x00, XTAL_LOW_CAP_0P }, + { 0x10, XTAL_HIGH_CAP_0P }, +}; + +/* + * I2C read/write code and shadow registers logic + */ +static void shadow_store(struct r82xx_priv *priv, uint8_t reg, const uint8_t *val, + int len) +{ + int r = reg - REG_SHADOW_START; + + if (r < 0) { + len += r; + r = 0; + } + if (len <= 0) + return; + if (len > NUM_REGS - r) + len = NUM_REGS - r; + + memcpy(&priv->regs[r], val, len); +} + +static int r82xx_write(struct r82xx_priv *priv, uint8_t reg, const uint8_t *val, + unsigned int len) +{ + int rc, size, pos = 0; + + /* Store the shadow registers */ + shadow_store(priv, reg, val, len); + + do { + if (len > priv->cfg->max_i2c_msg_len - 1) + size = priv->cfg->max_i2c_msg_len - 1; + else + size = len; + + /* Fill I2C buffer */ + priv->buf[0] = reg; + memcpy(&priv->buf[1], &val[pos], size); + + rc = rtlsdr_i2c_write_fn(priv->rtl_dev, priv->cfg->i2c_addr, + priv->buf, size + 1); + + if (rc != size + 1) { + fprintf(stderr, "%s: i2c wr failed=%d reg=%02x len=%d\n", + __FUNCTION__, rc, reg, size); + if (rc < 0) + return rc; + return -1; + } + + reg += size; + len -= size; + pos += size; + } while (len > 0); + + return 0; +} + +static int r82xx_write_reg(struct r82xx_priv *priv, uint8_t reg, uint8_t val) +{ + return r82xx_write(priv, reg, &val, 1); +} + +static int r82xx_read_cache_reg(struct r82xx_priv *priv, int reg) +{ + reg -= REG_SHADOW_START; + + if (reg >= 0 && reg < NUM_REGS) + return priv->regs[reg]; + else + return -1; +} + +static int r82xx_write_reg_mask(struct r82xx_priv *priv, uint8_t reg, uint8_t val, + uint8_t bit_mask) +{ + int rc = r82xx_read_cache_reg(priv, reg); + + if (rc < 0) + return rc; + + val = (rc & ~bit_mask) | (val & bit_mask); + + return r82xx_write(priv, reg, &val, 1); +} + +static uint8_t r82xx_bitrev(uint8_t byte) +{ + const uint8_t lut[16] = { 0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, + 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf }; + + return (lut[byte & 0xf] << 4) | lut[byte >> 4]; +} + +static int r82xx_read(struct r82xx_priv *priv, uint8_t reg, uint8_t *val, int len) +{ + int rc, i; + uint8_t *p = &priv->buf[1]; + + priv->buf[0] = reg; + + rc = rtlsdr_i2c_write_fn(priv->rtl_dev, priv->cfg->i2c_addr, priv->buf, 1); + if (rc < 1) + return rc; + + rc = rtlsdr_i2c_read_fn(priv->rtl_dev, priv->cfg->i2c_addr, p, len); + + if (rc != len) { + fprintf(stderr, "%s: i2c rd failed=%d reg=%02x len=%d\n", + __FUNCTION__, rc, reg, len); + if (rc < 0) + return rc; + return -1; + } + + /* Copy data to the output buffer */ + for (i = 0; i < len; i++) + val[i] = r82xx_bitrev(p[i]); + + return 0; +} + +/* + * r82xx tuning logic + */ + +static int r82xx_set_mux(struct r82xx_priv *priv, uint32_t freq) +{ + const struct r82xx_freq_range *range; + int rc; + unsigned int i; + uint8_t val; + + /* Get the proper frequency range */ + freq = freq / 1000000; + for (i = 0; i < ARRAY_SIZE(freq_ranges) - 1; i++) { + if (freq < freq_ranges[i + 1].freq) + break; + } + range = &freq_ranges[i]; + + /* Open Drain */ + rc = r82xx_write_reg_mask(priv, 0x17, range->open_d, 0x08); + if (rc < 0) + return rc; + + /* RF_MUX,Polymux */ + rc = r82xx_write_reg_mask(priv, 0x1a, range->rf_mux_ploy, 0xc3); + if (rc < 0) + return rc; + + /* TF BAND */ + rc = r82xx_write_reg(priv, 0x1b, range->tf_c); + if (rc < 0) + return rc; + + /* XTAL CAP & Drive */ + switch (priv->xtal_cap_sel) { + case XTAL_LOW_CAP_30P: + case XTAL_LOW_CAP_20P: + val = range->xtal_cap20p | 0x08; + break; + case XTAL_LOW_CAP_10P: + val = range->xtal_cap10p | 0x08; + break; + case XTAL_HIGH_CAP_0P: + val = range->xtal_cap0p | 0x00; + break; + default: + case XTAL_LOW_CAP_0P: + val = range->xtal_cap0p | 0x08; + break; + } + rc = r82xx_write_reg_mask(priv, 0x10, val, 0x0b); + if (rc < 0) + return rc; + + rc = r82xx_write_reg_mask(priv, 0x08, 0x00, 0x3f); + if (rc < 0) + return rc; + + rc = r82xx_write_reg_mask(priv, 0x09, 0x00, 0x3f); + + return rc; +} + +static int r82xx_set_pll(struct r82xx_priv *priv, uint32_t freq) +{ + int rc, i; + unsigned sleep_time = 10000; + uint64_t vco_freq; + uint32_t vco_fra; /* VCO contribution by SDM (kHz) */ + uint32_t vco_min = 1770000; + uint32_t vco_max = vco_min * 2; + uint32_t freq_khz, pll_ref, pll_ref_khz; + uint16_t n_sdm = 2; + uint16_t sdm = 0; + uint8_t mix_div = 2; + uint8_t div_buf = 0; + uint8_t div_num = 0; + uint8_t vco_power_ref = 2; + uint8_t refdiv2 = 0; + uint8_t ni, si, nint, vco_fine_tune, val; + uint8_t data[5]; + + /* Frequency in kHz */ + freq_khz = (freq + 500) / 1000; + pll_ref = priv->cfg->xtal; + pll_ref_khz = (priv->cfg->xtal + 500) / 1000; + + rc = r82xx_write_reg_mask(priv, 0x10, refdiv2, 0x10); + if (rc < 0) + return rc; + + /* set pll autotune = 128kHz */ + rc = r82xx_write_reg_mask(priv, 0x1a, 0x00, 0x0c); + if (rc < 0) + return rc; + + /* set VCO current = 100 */ + rc = r82xx_write_reg_mask(priv, 0x12, 0x80, 0xe0); + if (rc < 0) + return rc; + + /* Calculate divider */ + while (mix_div <= 64) { + if (((freq_khz * mix_div) >= vco_min) && + ((freq_khz * mix_div) < vco_max)) { + div_buf = mix_div; + while (div_buf > 2) { + div_buf = div_buf >> 1; + div_num++; + } + break; + } + mix_div = mix_div << 1; + } + + rc = r82xx_read(priv, 0x00, data, sizeof(data)); + if (rc < 0) + return rc; + + if (priv->cfg->rafael_chip == CHIP_R828D) + vco_power_ref = 1; + + vco_fine_tune = (data[4] & 0x30) >> 4; + + if (vco_fine_tune > vco_power_ref) + div_num = div_num - 1; + else if (vco_fine_tune < vco_power_ref) + div_num = div_num + 1; + + rc = r82xx_write_reg_mask(priv, 0x10, div_num << 5, 0xe0); + if (rc < 0) + return rc; + + vco_freq = (uint64_t)freq * (uint64_t)mix_div; + nint = vco_freq / (2 * pll_ref); + vco_fra = (vco_freq - 2 * pll_ref * nint) / 1000; + + if (nint > ((128 / vco_power_ref) - 1)) { + fprintf(stderr, "[R82XX] No valid PLL values for %u Hz!\n", freq); + return -1; + } + + ni = (nint - 13) / 4; + si = nint - 4 * ni - 13; + + rc = r82xx_write_reg(priv, 0x14, ni + (si << 6)); + if (rc < 0) + return rc; + + /* pw_sdm */ + if (!vco_fra) + val = 0x08; + else + val = 0x00; + + rc = r82xx_write_reg_mask(priv, 0x12, val, 0x08); + if (rc < 0) + return rc; + + /* sdm calculator */ + while (vco_fra > 1) { + if (vco_fra > (2 * pll_ref_khz / n_sdm)) { + sdm = sdm + 32768 / (n_sdm / 2); + vco_fra = vco_fra - 2 * pll_ref_khz / n_sdm; + if (n_sdm >= 0x8000) + break; + } + n_sdm <<= 1; + } + + rc = r82xx_write_reg(priv, 0x16, sdm >> 8); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x15, sdm & 0xff); + if (rc < 0) + return rc; + + for (i = 0; i < 2; i++) { +// usleep_range(sleep_time, sleep_time + 1000); + + /* Check if PLL has locked */ + rc = r82xx_read(priv, 0x00, data, 3); + if (rc < 0) + return rc; + if (data[2] & 0x40) + break; + + if (!i) { + /* Didn't lock. Increase VCO current */ + rc = r82xx_write_reg_mask(priv, 0x12, 0x60, 0xe0); + if (rc < 0) + return rc; + } + } + + if (!(data[2] & 0x40)) { + fprintf(stderr, "[R82XX] PLL not locked!\n"); + priv->has_lock = 0; + return 0; + } + + priv->has_lock = 1; + + /* set pll autotune = 8kHz */ + rc = r82xx_write_reg_mask(priv, 0x1a, 0x08, 0x08); + + return rc; +} + +static int r82xx_sysfreq_sel(struct r82xx_priv *priv, uint32_t freq, + enum r82xx_tuner_type type, + uint32_t delsys) +{ + int rc; + uint8_t mixer_top, lna_top, cp_cur, div_buf_cur, lna_vth_l, mixer_vth_l; + uint8_t air_cable1_in, cable2_in, pre_dect, lna_discharge, filter_cur; + + switch (delsys) { + case SYS_DVBT: + if ((freq == 506000000) || (freq == 666000000) || + (freq == 818000000)) { + mixer_top = 0x14; /* mixer top:14 , top-1, low-discharge */ + lna_top = 0xe5; /* detect bw 3, lna top:4, predet top:2 */ + cp_cur = 0x28; /* 101, 0.2 */ + div_buf_cur = 0x20; /* 10, 200u */ + } else { + mixer_top = 0x24; /* mixer top:13 , top-1, low-discharge */ + lna_top = 0xe5; /* detect bw 3, lna top:4, predet top:2 */ + cp_cur = 0x38; /* 111, auto */ + div_buf_cur = 0x30; /* 11, 150u */ + } + lna_vth_l = 0x53; /* lna vth 0.84 , vtl 0.64 */ + mixer_vth_l = 0x75; /* mixer vth 1.04, vtl 0.84 */ + air_cable1_in = 0x00; + cable2_in = 0x00; + pre_dect = 0x40; + lna_discharge = 14; + filter_cur = 0x40; /* 10, low */ + break; + case SYS_DVBT2: + mixer_top = 0x24; /* mixer top:13 , top-1, low-discharge */ + lna_top = 0xe5; /* detect bw 3, lna top:4, predet top:2 */ + lna_vth_l = 0x53; /* lna vth 0.84 , vtl 0.64 */ + mixer_vth_l = 0x75; /* mixer vth 1.04, vtl 0.84 */ + air_cable1_in = 0x00; + cable2_in = 0x00; + pre_dect = 0x40; + lna_discharge = 14; + cp_cur = 0x38; /* 111, auto */ + div_buf_cur = 0x30; /* 11, 150u */ + filter_cur = 0x40; /* 10, low */ + break; + case SYS_ISDBT: + mixer_top = 0x24; /* mixer top:13 , top-1, low-discharge */ + lna_top = 0xe5; /* detect bw 3, lna top:4, predet top:2 */ + lna_vth_l = 0x75; /* lna vth 1.04 , vtl 0.84 */ + mixer_vth_l = 0x75; /* mixer vth 1.04, vtl 0.84 */ + air_cable1_in = 0x00; + cable2_in = 0x00; + pre_dect = 0x40; + lna_discharge = 14; + cp_cur = 0x38; /* 111, auto */ + div_buf_cur = 0x30; /* 11, 150u */ + filter_cur = 0x40; /* 10, low */ + break; + default: /* DVB-T 8M */ + mixer_top = 0x24; /* mixer top:13 , top-1, low-discharge */ + lna_top = 0xe5; /* detect bw 3, lna top:4, predet top:2 */ + lna_vth_l = 0x53; /* lna vth 0.84 , vtl 0.64 */ + mixer_vth_l = 0x75; /* mixer vth 1.04, vtl 0.84 */ + air_cable1_in = 0x00; + cable2_in = 0x00; + pre_dect = 0x40; + lna_discharge = 14; + cp_cur = 0x38; /* 111, auto */ + div_buf_cur = 0x30; /* 11, 150u */ + filter_cur = 0x40; /* 10, low */ + break; + } + + if (priv->cfg->use_predetect) { + rc = r82xx_write_reg_mask(priv, 0x06, pre_dect, 0x40); + if (rc < 0) + return rc; + } + + rc = r82xx_write_reg_mask(priv, 0x1d, lna_top, 0xc7); + if (rc < 0) + return rc; + rc = r82xx_write_reg_mask(priv, 0x1c, mixer_top, 0xf8); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x0d, lna_vth_l); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x0e, mixer_vth_l); + if (rc < 0) + return rc; + + priv->input = air_cable1_in; + + /* Air-IN only for Astrometa */ + rc = r82xx_write_reg_mask(priv, 0x05, air_cable1_in, 0x60); + if (rc < 0) + return rc; + rc = r82xx_write_reg_mask(priv, 0x06, cable2_in, 0x08); + if (rc < 0) + return rc; + + rc = r82xx_write_reg_mask(priv, 0x11, cp_cur, 0x38); + if (rc < 0) + return rc; + rc = r82xx_write_reg_mask(priv, 0x17, div_buf_cur, 0x30); + if (rc < 0) + return rc; + rc = r82xx_write_reg_mask(priv, 0x0a, filter_cur, 0x60); + if (rc < 0) + return rc; + + /* + * Set LNA + */ + + if (type != TUNER_ANALOG_TV) { + /* LNA TOP: lowest */ + rc = r82xx_write_reg_mask(priv, 0x1d, 0, 0x38); + if (rc < 0) + return rc; + + /* 0: normal mode */ + rc = r82xx_write_reg_mask(priv, 0x1c, 0, 0x04); + if (rc < 0) + return rc; + + /* 0: PRE_DECT off */ + rc = r82xx_write_reg_mask(priv, 0x06, 0, 0x40); + if (rc < 0) + return rc; + + /* agc clk 250hz */ + rc = r82xx_write_reg_mask(priv, 0x1a, 0x30, 0x30); + if (rc < 0) + return rc; + +// msleep(250); + + /* write LNA TOP = 3 */ + rc = r82xx_write_reg_mask(priv, 0x1d, 0x18, 0x38); + if (rc < 0) + return rc; + + /* + * write discharge mode + * FIXME: IMHO, the mask here is wrong, but it matches + * what's there at the original driver + */ + rc = r82xx_write_reg_mask(priv, 0x1c, mixer_top, 0x04); + if (rc < 0) + return rc; + + /* LNA discharge current */ + rc = r82xx_write_reg_mask(priv, 0x1e, lna_discharge, 0x1f); + if (rc < 0) + return rc; + + /* agc clk 60hz */ + rc = r82xx_write_reg_mask(priv, 0x1a, 0x20, 0x30); + if (rc < 0) + return rc; + } else { + /* PRE_DECT off */ + rc = r82xx_write_reg_mask(priv, 0x06, 0, 0x40); + if (rc < 0) + return rc; + + /* write LNA TOP */ + rc = r82xx_write_reg_mask(priv, 0x1d, lna_top, 0x38); + if (rc < 0) + return rc; + + /* + * write discharge mode + * FIXME: IMHO, the mask here is wrong, but it matches + * what's there at the original driver + */ + rc = r82xx_write_reg_mask(priv, 0x1c, mixer_top, 0x04); + if (rc < 0) + return rc; + + /* LNA discharge current */ + rc = r82xx_write_reg_mask(priv, 0x1e, lna_discharge, 0x1f); + if (rc < 0) + return rc; + + /* agc clk 1Khz, external det1 cap 1u */ + rc = r82xx_write_reg_mask(priv, 0x1a, 0x00, 0x30); + if (rc < 0) + return rc; + + rc = r82xx_write_reg_mask(priv, 0x10, 0x00, 0x04); + if (rc < 0) + return rc; + } + return 0; +} + +static int r82xx_set_tv_standard(struct r82xx_priv *priv, + unsigned bw, + enum r82xx_tuner_type type, + uint32_t delsys) + +{ + int rc, i; + uint32_t if_khz, filt_cal_lo; + uint8_t data[5]; + uint8_t filt_gain, img_r, filt_q, hp_cor, ext_enable, loop_through; + uint8_t lt_att, flt_ext_widest, polyfil_cur; + int need_calibration; + + if (delsys == SYS_ISDBT) { + if_khz = 4063; + filt_cal_lo = 59000; + filt_gain = 0x10; /* +3db, 6mhz on */ + img_r = 0x00; /* image negative */ + filt_q = 0x10; /* r10[4]:low q(1'b1) */ + hp_cor = 0x6a; /* 1.7m disable, +2cap, 1.25mhz */ + ext_enable = 0x40; /* r30[6], ext enable; r30[5]:0 ext at lna max */ + loop_through = 0x00; /* r5[7], lt on */ + lt_att = 0x00; /* r31[7], lt att enable */ + flt_ext_widest = 0x00; /* r15[7]: flt_ext_wide off */ + polyfil_cur = 0x60; /* r25[6:5]:min */ + } else { + if (bw <= 6) { + if_khz = 3570; + filt_cal_lo = 56000; /* 52000->56000 */ + filt_gain = 0x10; /* +3db, 6mhz on */ + img_r = 0x00; /* image negative */ + filt_q = 0x10; /* r10[4]:low q(1'b1) */ + hp_cor = 0x6b; /* 1.7m disable, +2cap, 1.0mhz */ + ext_enable = 0x60; /* r30[6]=1 ext enable; r30[5]:1 ext at lna max-1 */ + loop_through = 0x00; /* r5[7], lt on */ + lt_att = 0x00; /* r31[7], lt att enable */ + flt_ext_widest = 0x00; /* r15[7]: flt_ext_wide off */ + polyfil_cur = 0x60; /* r25[6:5]:min */ + } else if (bw == 7) { +#if 0 + /* + * There are two 7 MHz tables defined on the original + * driver, but just the second one seems to be visible + * by rtl2832. Keep this one here commented, as it + * might be needed in the future + */ + + if_khz = 4070; + filt_cal_lo = 60000; + filt_gain = 0x10; /* +3db, 6mhz on */ + img_r = 0x00; /* image negative */ + filt_q = 0x10; /* r10[4]:low q(1'b1) */ + hp_cor = 0x2b; /* 1.7m disable, +1cap, 1.0mhz */ + ext_enable = 0x60; /* r30[6]=1 ext enable; r30[5]:1 ext at lna max-1 */ + loop_through = 0x00; /* r5[7], lt on */ + lt_att = 0x00; /* r31[7], lt att enable */ + flt_ext_widest = 0x00; /* r15[7]: flt_ext_wide off */ + polyfil_cur = 0x60; /* r25[6:5]:min */ +#endif + /* 7 MHz, second table */ + if_khz = 4570; + filt_cal_lo = 63000; + filt_gain = 0x10; /* +3db, 6mhz on */ + img_r = 0x00; /* image negative */ + filt_q = 0x10; /* r10[4]:low q(1'b1) */ + hp_cor = 0x2a; /* 1.7m disable, +1cap, 1.25mhz */ + ext_enable = 0x60; /* r30[6]=1 ext enable; r30[5]:1 ext at lna max-1 */ + loop_through = 0x00; /* r5[7], lt on */ + lt_att = 0x00; /* r31[7], lt att enable */ + flt_ext_widest = 0x00; /* r15[7]: flt_ext_wide off */ + polyfil_cur = 0x60; /* r25[6:5]:min */ + } else { + if_khz = 4570; + filt_cal_lo = 68500; + filt_gain = 0x10; /* +3db, 6mhz on */ + img_r = 0x00; /* image negative */ + filt_q = 0x10; /* r10[4]:low q(1'b1) */ + hp_cor = 0x0b; /* 1.7m disable, +0cap, 1.0mhz */ + ext_enable = 0x60; /* r30[6]=1 ext enable; r30[5]:1 ext at lna max-1 */ + loop_through = 0x00; /* r5[7], lt on */ + lt_att = 0x00; /* r31[7], lt att enable */ + flt_ext_widest = 0x00; /* r15[7]: flt_ext_wide off */ + polyfil_cur = 0x60; /* r25[6:5]:min */ + } + } + + /* Initialize the shadow registers */ + memcpy(priv->regs, r82xx_init_array, sizeof(r82xx_init_array)); + + /* Init Flag & Xtal_check Result (inits VGA gain, needed?)*/ + rc = r82xx_write_reg_mask(priv, 0x0c, 0x00, 0x0f); + if (rc < 0) + return rc; + + /* version */ + rc = r82xx_write_reg_mask(priv, 0x13, VER_NUM, 0x3f); + if (rc < 0) + return rc; + + /* for LT Gain test */ + if (type != TUNER_ANALOG_TV) { + rc = r82xx_write_reg_mask(priv, 0x1d, 0x00, 0x38); + if (rc < 0) + return rc; +// usleep_range(1000, 2000); + } + priv->int_freq = if_khz * 1000; + + /* Check if standard changed. If so, filter calibration is needed */ + /* as we call this function only once in rtlsdr, force calibration */ + need_calibration = 1; + + if (need_calibration) { + for (i = 0; i < 2; i++) { + /* Set filt_cap */ + rc = r82xx_write_reg_mask(priv, 0x0b, hp_cor, 0x60); + if (rc < 0) + return rc; + + /* set cali clk =on */ + rc = r82xx_write_reg_mask(priv, 0x0f, 0x04, 0x04); + if (rc < 0) + return rc; + + /* X'tal cap 0pF for PLL */ + rc = r82xx_write_reg_mask(priv, 0x10, 0x00, 0x03); + if (rc < 0) + return rc; + + rc = r82xx_set_pll(priv, filt_cal_lo * 1000); + if (rc < 0 || !priv->has_lock) + return rc; + + /* Start Trigger */ + rc = r82xx_write_reg_mask(priv, 0x0b, 0x10, 0x10); + if (rc < 0) + return rc; + +// usleep_range(1000, 2000); + + /* Stop Trigger */ + rc = r82xx_write_reg_mask(priv, 0x0b, 0x00, 0x10); + if (rc < 0) + return rc; + + /* set cali clk =off */ + rc = r82xx_write_reg_mask(priv, 0x0f, 0x00, 0x04); + if (rc < 0) + return rc; + + /* Check if calibration worked */ + rc = r82xx_read(priv, 0x00, data, sizeof(data)); + if (rc < 0) + return rc; + + priv->fil_cal_code = data[4] & 0x0f; + if (priv->fil_cal_code && priv->fil_cal_code != 0x0f) + break; + } + /* narrowest */ + if (priv->fil_cal_code == 0x0f) + priv->fil_cal_code = 0; + } + + rc = r82xx_write_reg_mask(priv, 0x0a, + filt_q | priv->fil_cal_code, 0x1f); + if (rc < 0) + return rc; + + /* Set BW, Filter_gain, & HP corner */ + rc = r82xx_write_reg_mask(priv, 0x0b, hp_cor, 0xef); + if (rc < 0) + return rc; + + /* Set Img_R */ + rc = r82xx_write_reg_mask(priv, 0x07, img_r, 0x80); + if (rc < 0) + return rc; + + /* Set filt_3dB, V6MHz */ + rc = r82xx_write_reg_mask(priv, 0x06, filt_gain, 0x30); + if (rc < 0) + return rc; + + /* channel filter extension */ + rc = r82xx_write_reg_mask(priv, 0x1e, ext_enable, 0x60); + if (rc < 0) + return rc; + + /* Loop through */ + rc = r82xx_write_reg_mask(priv, 0x05, loop_through, 0x80); + if (rc < 0) + return rc; + + /* Loop through attenuation */ + rc = r82xx_write_reg_mask(priv, 0x1f, lt_att, 0x80); + if (rc < 0) + return rc; + + /* filter extension widest */ + rc = r82xx_write_reg_mask(priv, 0x0f, flt_ext_widest, 0x80); + if (rc < 0) + return rc; + + /* RF poly filter current */ + rc = r82xx_write_reg_mask(priv, 0x19, polyfil_cur, 0x60); + if (rc < 0) + return rc; + + /* Store current standard. If it changes, re-calibrate the tuner */ + priv->delsys = delsys; + priv->type = type; + priv->bw = bw; + + return 0; +} + +static int r82xx_read_gain(struct r82xx_priv *priv) +{ + uint8_t data[4]; + int rc; + + rc = r82xx_read(priv, 0x00, data, sizeof(data)); + if (rc < 0) + return rc; + + return ((data[3] & 0x0f) << 1) + ((data[3] & 0xf0) >> 4); +} + +/* measured with a Racal 6103E GSM test set at 928 MHz with -60 dBm + * input power, for raw results see: + * http://steve-m.de/projects/rtl-sdr/gain_measurement/r820t/ + */ + +#define VGA_BASE_GAIN -47 +static const int r82xx_vga_gain_steps[] = { + 0, 26, 26, 30, 42, 35, 24, 13, 14, 32, 36, 34, 35, 37, 35, 36 +}; + +static const int r82xx_lna_gain_steps[] = { + 0, 9, 13, 40, 38, 13, 31, 22, 26, 31, 26, 14, 19, 5, 35, 13 +}; + +static const int r82xx_mixer_gain_steps[] = { + 0, 5, 10, 10, 19, 9, 10, 25, 17, 10, 8, 16, 13, 6, 3, -8 +}; + +int r82xx_set_gain(struct r82xx_priv *priv, int set_manual_gain, int gain) +{ + int rc; + + if (set_manual_gain) { + int i, total_gain = 0; + uint8_t mix_index = 0, lna_index = 0; + uint8_t data[4]; + + /* LNA auto off */ + rc = r82xx_write_reg_mask(priv, 0x05, 0x10, 0x10); + if (rc < 0) + return rc; + + /* Mixer auto off */ + rc = r82xx_write_reg_mask(priv, 0x07, 0, 0x10); + if (rc < 0) + return rc; + + rc = r82xx_read(priv, 0x00, data, sizeof(data)); + if (rc < 0) + return rc; + + /* set fixed VGA gain for now (16.3 dB) */ + rc = r82xx_write_reg_mask(priv, 0x0c, 0x08, 0x9f); + if (rc < 0) + return rc; + + for (i = 0; i < 15; i++) { + if (total_gain >= gain) + break; + + total_gain += r82xx_lna_gain_steps[++lna_index]; + + if (total_gain >= gain) + break; + + total_gain += r82xx_mixer_gain_steps[++mix_index]; + } + + /* set LNA gain */ + rc = r82xx_write_reg_mask(priv, 0x05, lna_index, 0x0f); + if (rc < 0) + return rc; + + /* set Mixer gain */ + rc = r82xx_write_reg_mask(priv, 0x07, mix_index, 0x0f); + if (rc < 0) + return rc; + } else { + /* LNA */ + rc = r82xx_write_reg_mask(priv, 0x05, 0, 0x10); + if (rc < 0) + return rc; + + /* Mixer */ + rc = r82xx_write_reg_mask(priv, 0x07, 0x10, 0x10); + if (rc < 0) + return rc; + + /* set fixed VGA gain for now (26.5 dB) */ + rc = r82xx_write_reg_mask(priv, 0x0c, 0x0b, 0x9f); + if (rc < 0) + return rc; + } + + return 0; +} + +/* Bandwidth contribution by low-pass filter. */ +static const int r82xx_if_low_pass_bw_table[] = { + 1700000, 1600000, 1550000, 1450000, 1200000, 900000, 700000, 550000, 450000, 350000 +}; + +#define FILT_HP_BW1 350000 +#define FILT_HP_BW2 380000 +int r82xx_set_bandwidth(struct r82xx_priv *priv, int bw, uint32_t rate) +{ + int rc; + unsigned int i; + int real_bw = 0; + uint8_t reg_0a; + uint8_t reg_0b; + + if (bw > 7000000) { + // BW: 8 MHz + reg_0a = 0x10; + reg_0b = 0x0b; + priv->int_freq = 4570000; + } else if (bw > 6000000) { + // BW: 7 MHz + reg_0a = 0x10; + reg_0b = 0x2a; + priv->int_freq = 4570000; + } else if (bw > r82xx_if_low_pass_bw_table[0] + FILT_HP_BW1 + FILT_HP_BW2) { + // BW: 6 MHz + reg_0a = 0x10; + reg_0b = 0x6b; + priv->int_freq = 3570000; + } else { + reg_0a = 0x00; + reg_0b = 0x80; + priv->int_freq = 2300000; + + if (bw > r82xx_if_low_pass_bw_table[0] + FILT_HP_BW1) { + bw -= FILT_HP_BW2; + priv->int_freq += FILT_HP_BW2; + real_bw += FILT_HP_BW2; + } else { + reg_0b |= 0x20; + } + + if (bw > r82xx_if_low_pass_bw_table[0]) { + bw -= FILT_HP_BW1; + priv->int_freq += FILT_HP_BW1; + real_bw += FILT_HP_BW1; + } else { + reg_0b |= 0x40; + } + + // find low-pass filter + for(i = 0; i < ARRAY_SIZE(r82xx_if_low_pass_bw_table); ++i) { + if (bw > r82xx_if_low_pass_bw_table[i]) + break; + } + --i; + reg_0b |= 15 - i; + real_bw += r82xx_if_low_pass_bw_table[i]; + + priv->int_freq -= real_bw / 2; + } + + rc = r82xx_write_reg_mask(priv, 0x0a, reg_0a, 0x10); + if (rc < 0) + return rc; + + rc = r82xx_write_reg_mask(priv, 0x0b, reg_0b, 0xef); + if (rc < 0) + return rc; + + return priv->int_freq; +} +#undef FILT_HP_BW1 +#undef FILT_HP_BW2 + +int r82xx_set_freq(struct r82xx_priv *priv, uint32_t freq) +{ + int rc = -1; + uint32_t lo_freq = freq + priv->int_freq; + uint8_t air_cable1_in; + + rc = r82xx_set_mux(priv, lo_freq); + if (rc < 0) + goto err; + + rc = r82xx_set_pll(priv, lo_freq); + if (rc < 0 || !priv->has_lock) + goto err; + + /* switch between 'Cable1' and 'Air-In' inputs on sticks with + * R828D tuner. We switch at 345 MHz, because that's where the + * noise-floor has about the same level with identical LNA + * settings. The original driver used 320 MHz. */ + air_cable1_in = (freq > MHZ(345)) ? 0x00 : 0x60; + + if ((priv->cfg->rafael_chip == CHIP_R828D) && + (air_cable1_in != priv->input)) { + priv->input = air_cable1_in; + rc = r82xx_write_reg_mask(priv, 0x05, air_cable1_in, 0x60); + } + +err: + if (rc < 0) + fprintf(stderr, "%s: failed=%d\n", __FUNCTION__, rc); + return rc; +} + +/* + * r82xx standby logic + */ + +int r82xx_standby(struct r82xx_priv *priv) +{ + int rc; + + /* If device was not initialized yet, don't need to standby */ + if (!priv->init_done) + return 0; + + rc = r82xx_write_reg(priv, 0x06, 0xb1); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x05, 0x03); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x07, 0x3a); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x08, 0x40); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x09, 0xc0); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x0a, 0x36); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x0c, 0x35); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x0f, 0x68); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x11, 0x03); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x17, 0xf4); + if (rc < 0) + return rc; + rc = r82xx_write_reg(priv, 0x19, 0x0c); + + /* Force initial calibration */ + priv->type = -1; + + return rc; +} + +/* + * r82xx device init logic + */ + +static int r82xx_xtal_check(struct r82xx_priv *priv) +{ + int rc; + unsigned int i; + uint8_t data[3], val; + + /* Initialize the shadow registers */ + memcpy(priv->regs, r82xx_init_array, sizeof(r82xx_init_array)); + + /* cap 30pF & Drive Low */ + rc = r82xx_write_reg_mask(priv, 0x10, 0x0b, 0x0b); + if (rc < 0) + return rc; + + /* set pll autotune = 128kHz */ + rc = r82xx_write_reg_mask(priv, 0x1a, 0x00, 0x0c); + if (rc < 0) + return rc; + + /* set manual initial reg = 111111; */ + rc = r82xx_write_reg_mask(priv, 0x13, 0x7f, 0x7f); + if (rc < 0) + return rc; + + /* set auto */ + rc = r82xx_write_reg_mask(priv, 0x13, 0x00, 0x40); + if (rc < 0) + return rc; + + /* Try several xtal capacitor alternatives */ + for (i = 0; i < ARRAY_SIZE(r82xx_xtal_capacitor); i++) { + rc = r82xx_write_reg_mask(priv, 0x10, + r82xx_xtal_capacitor[i][0], 0x1b); + if (rc < 0) + return rc; + +// usleep_range(5000, 6000); + + rc = r82xx_read(priv, 0x00, data, sizeof(data)); + if (rc < 0) + return rc; + if (!(data[2] & 0x40)) + continue; + + val = data[2] & 0x3f; + + if (priv->cfg->xtal == 16000000 && (val > 29 || val < 23)) + break; + + if (val != 0x3f) + break; + } + + if (i == ARRAY_SIZE(r82xx_xtal_capacitor)) + return -1; + + return r82xx_xtal_capacitor[i][1]; +} + +int r82xx_init(struct r82xx_priv *priv) +{ + int rc; + + /* TODO: R828D might need r82xx_xtal_check() */ + priv->xtal_cap_sel = XTAL_HIGH_CAP_0P; + + /* Initialize registers */ + rc = r82xx_write(priv, 0x05, + r82xx_init_array, sizeof(r82xx_init_array)); + + rc = r82xx_set_tv_standard(priv, 3, TUNER_DIGITAL_TV, 0); + if (rc < 0) + goto err; + + rc = r82xx_sysfreq_sel(priv, 0, TUNER_DIGITAL_TV, SYS_DVBT); + + priv->init_done = 1; + +err: + if (rc < 0) + fprintf(stderr, "%s: failed=%d\n", __FUNCTION__, rc); + return rc; +} + +#if 0 +/* Not used, for now */ +static int r82xx_gpio(struct r82xx_priv *priv, int enable) +{ + return r82xx_write_reg_mask(priv, 0x0f, enable ? 1 : 0, 0x01); +} +#endif diff --git a/utils/convenience/convenience.c b/utils/convenience/convenience.c new file mode 100644 index 0000000..517dc4e --- /dev/null +++ b/utils/convenience/convenience.c @@ -0,0 +1,304 @@ +/* + * Copyright (C) 2014 by Kyle Keen + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/* a collection of user friendly tools + * todo: use strtol for more flexible int parsing + * */ + +#include +#include +#include + +#ifndef _WIN32 +#include +#else +#include +#include +#include +#define _USE_MATH_DEFINES +#endif + +#include + +#include "rtl-sdr.h" + +double atofs(char *s) +/* standard suffixes */ +{ + char last; + int len; + double suff = 1.0; + len = strlen(s); + last = s[len-1]; + s[len-1] = '\0'; + switch (last) { + case 'g': + case 'G': + suff *= 1e3; + case 'm': + case 'M': + suff *= 1e3; + case 'k': + case 'K': + suff *= 1e3; + suff *= atof(s); + s[len-1] = last; + return suff; + } + s[len-1] = last; + return atof(s); +} + +double atoft(char *s) +/* time suffixes, returns seconds */ +{ + char last; + int len; + double suff = 1.0; + len = strlen(s); + last = s[len-1]; + s[len-1] = '\0'; + switch (last) { + case 'h': + case 'H': + suff *= 60; + case 'm': + case 'M': + suff *= 60; + case 's': + case 'S': + suff *= atof(s); + s[len-1] = last; + return suff; + } + s[len-1] = last; + return atof(s); +} + +double atofp(char *s) +/* percent suffixes */ +{ + char last; + int len; + double suff = 1.0; + len = strlen(s); + last = s[len-1]; + s[len-1] = '\0'; + switch (last) { + case '%': + suff *= 0.01; + suff *= atof(s); + s[len-1] = last; + return suff; + } + s[len-1] = last; + return atof(s); +} + +int nearest_gain(rtlsdr_dev_t *dev, int target_gain) +{ + int i, r, err1, err2, count, nearest; + int* gains; + r = rtlsdr_set_tuner_gain_mode(dev, 1); + if (r < 0) { + fprintf(stderr, "WARNING: Failed to enable manual gain.\n"); + return r; + } + count = rtlsdr_get_tuner_gains(dev, NULL); + if (count <= 0) { + return 0; + } + gains = malloc(sizeof(int) * count); + count = rtlsdr_get_tuner_gains(dev, gains); + nearest = gains[0]; + for (i=0; i= 0 && device < device_count) { + fprintf(stderr, "Using device %d: %s\n", + device, rtlsdr_get_device_name((uint32_t)device)); + return device; + } + /* does string exact match a serial */ + for (i = 0; i < device_count; i++) { + rtlsdr_get_device_usb_strings(i, vendor, product, serial); + if (strcmp(s, serial) != 0) { + continue;} + device = i; + fprintf(stderr, "Using device %d: %s\n", + device, rtlsdr_get_device_name((uint32_t)device)); + return device; + } + /* does string prefix match a serial */ + for (i = 0; i < device_count; i++) { + rtlsdr_get_device_usb_strings(i, vendor, product, serial); + if (strncmp(s, serial, strlen(s)) != 0) { + continue;} + device = i; + fprintf(stderr, "Using device %d: %s\n", + device, rtlsdr_get_device_name((uint32_t)device)); + return device; + } + /* does string suffix match a serial */ + for (i = 0; i < device_count; i++) { + rtlsdr_get_device_usb_strings(i, vendor, product, serial); + offset = strlen(serial) - strlen(s); + if (offset < 0) { + continue;} + if (strncmp(s, serial+offset, strlen(s)) != 0) { + continue;} + device = i; + fprintf(stderr, "Using device %d: %s\n", + device, rtlsdr_get_device_name((uint32_t)device)); + return device; + } + fprintf(stderr, "No matching devices found.\n"); + return -1; +} + +// vim: tabstop=8:softtabstop=8:shiftwidth=8:noexpandtab diff --git a/utils/convenience/convenience.h b/utils/convenience/convenience.h new file mode 100644 index 0000000..1faa2af --- /dev/null +++ b/utils/convenience/convenience.h @@ -0,0 +1,142 @@ +/* + * Copyright (C) 2014 by Kyle Keen + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/* a collection of user friendly tools */ + +/*! + * Convert standard suffixes (k, M, G) to double + * + * \param s a string to be parsed + * \return double + */ + +double atofs(char *s); + +/*! + * Convert time suffixes (s, m, h) to double + * + * \param s a string to be parsed + * \return seconds as double + */ + +double atoft(char *s); + +/*! + * Convert percent suffixe (%) to double + * + * \param s a string to be parsed + * \return double + */ + +double atofp(char *s); + +/*! + * Find nearest supported gain + * + * \param dev the device handle given by rtlsdr_open() + * \param target_gain in tenths of a dB + * \return 0 on success + */ + +int nearest_gain(rtlsdr_dev_t *dev, int target_gain); + +/*! + * Set device frequency and report status on stderr + * + * \param dev the device handle given by rtlsdr_open() + * \param frequency in Hz + * \return 0 on success + */ + +int verbose_set_frequency(rtlsdr_dev_t *dev, uint32_t frequency); + +/*! + * Set device sample rate and report status on stderr + * + * \param dev the device handle given by rtlsdr_open() + * \param samp_rate in samples/second + * \return 0 on success + */ + +int verbose_set_sample_rate(rtlsdr_dev_t *dev, uint32_t samp_rate); + +/*! + * Enable or disable the direct sampling mode and report status on stderr + * + * \param dev the device handle given by rtlsdr_open() + * \param on 0 means disabled, 1 I-ADC input enabled, 2 Q-ADC input enabled + * \return 0 on success + */ + +int verbose_direct_sampling(rtlsdr_dev_t *dev, int on); + +/*! + * Enable offset tuning and report status on stderr + * + * \param dev the device handle given by rtlsdr_open() + * \return 0 on success + */ + +int verbose_offset_tuning(rtlsdr_dev_t *dev); + +/*! + * Enable auto gain and report status on stderr + * + * \param dev the device handle given by rtlsdr_open() + * \return 0 on success + */ + +int verbose_auto_gain(rtlsdr_dev_t *dev); + +/*! + * Set tuner gain and report status on stderr + * + * \param dev the device handle given by rtlsdr_open() + * \param gain in tenths of a dB + * \return 0 on success + */ + +int verbose_gain_set(rtlsdr_dev_t *dev, int gain); + +/*! + * Set the frequency correction value for the device and report status on stderr. + * + * \param dev the device handle given by rtlsdr_open() + * \param ppm_error correction value in parts per million (ppm) + * \return 0 on success + */ + +int verbose_ppm_set(rtlsdr_dev_t *dev, int ppm_error); + +/*! + * Reset buffer + * + * \param dev the device handle given by rtlsdr_open() + * \return 0 on success + */ + +int verbose_reset_buffer(rtlsdr_dev_t *dev); + +/*! + * Find the closest matching device. + * + * \param s a string to be parsed + * \return dev_index int, -1 on error + */ + +int verbose_device_search(char *s); + diff --git a/utils/getopt/getopt.c b/utils/getopt/getopt.c new file mode 100644 index 0000000..f1d461a --- /dev/null +++ b/utils/getopt/getopt.c @@ -0,0 +1,1059 @@ +/* Getopt for GNU. + NOTE: getopt is now part of the C library, so if you don't know what + "Keep this file name-space clean" means, talk to drepper@gnu.org + before changing it! + Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ +/* This tells Alpha OSF/1 not to define a getopt prototype in . + Ditto for AIX 3.2 and . */ +#ifndef _NO_PROTO +# define _NO_PROTO +#endif + +#ifdef HAVE_CONFIG_H +# include +#endif + +#if !defined __STDC__ || !__STDC__ +/* This is a separate conditional since some stdc systems + reject `defined (const)'. */ +# ifndef const +# define const +# endif +#endif + +#include + +/* Comment out all this code if we are using the GNU C Library, and are not + actually compiling the library itself. This code is part of the GNU C + Library, but also included in many other GNU distributions. Compiling + and linking in this code is a waste when using the GNU C library + (especially if it is a shared library). Rather than having every GNU + program understand `configure --with-gnu-libc' and omit the object files, + it is simpler to just do this in the source for each such file. */ + +#define GETOPT_INTERFACE_VERSION 2 +#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 +# include +# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION +# define ELIDE_CODE +# endif +#endif + +#ifndef ELIDE_CODE + + +/* This needs to come after some library #include + to get __GNU_LIBRARY__ defined. */ +#ifdef __GNU_LIBRARY__ +/* Don't include stdlib.h for non-GNU C libraries because some of them + contain conflicting prototypes for getopt. */ +# include +# include +#endif /* GNU C library. */ + +#ifdef VMS +# include +# if HAVE_STRING_H - 0 +# include +# endif +#endif + +#ifndef _ +/* This is for other GNU distributions with internationalized messages. */ +# if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC +# include +# ifndef _ +# define _(msgid) gettext (msgid) +# endif +# else +# define _(msgid) (msgid) +# endif +#endif + +/* This version of `getopt' appears to the caller like standard Unix `getopt' + but it behaves differently for the user, since it allows the user + to intersperse the options with the other arguments. + + As `getopt' works, it permutes the elements of ARGV so that, + when it is done, all the options precede everything else. Thus + all application programs are extended to handle flexible argument order. + + Setting the environment variable POSIXLY_CORRECT disables permutation. + Then the behavior is completely standard. + + GNU application programs can use a third alternative mode in which + they can distinguish the relative order of options and other arguments. */ + +#include "getopt.h" + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +/* 1003.2 says this must be 1 before any call. */ +int optind = 1; + +/* Formerly, initialization of getopt depended on optind==0, which + causes problems with re-calling getopt as programs generally don't + know that. */ + +int __getopt_initialized; + +/* The next char to be scanned in the option-element + in which the last option character we returned was found. + This allows us to pick up the scan where we left off. + + If this is zero, or a null string, it means resume the scan + by advancing to the next ARGV-element. */ + +static char *nextchar; + +/* Callers store zero here to inhibit the error message + for unrecognized options. */ + +int opterr = 1; + +/* Set to an option character which was unrecognized. + This must be initialized on some systems to avoid linking in the + system's own getopt implementation. */ + +int optopt = '?'; + +/* Describe how to deal with options that follow non-option ARGV-elements. + + If the caller did not specify anything, + the default is REQUIRE_ORDER if the environment variable + POSIXLY_CORRECT is defined, PERMUTE otherwise. + + REQUIRE_ORDER means don't recognize them as options; + stop option processing when the first non-option is seen. + This is what Unix does. + This mode of operation is selected by either setting the environment + variable POSIXLY_CORRECT, or using `+' as the first character + of the list of option characters. + + PERMUTE is the default. We permute the contents of ARGV as we scan, + so that eventually all the non-options are at the end. This allows options + to be given in any order, even with programs that were not written to + expect this. + + RETURN_IN_ORDER is an option available to programs that were written + to expect options and other ARGV-elements in any order and that care about + the ordering of the two. We describe each non-option ARGV-element + as if it were the argument of an option with character code 1. + Using `-' as the first character of the list of option characters + selects this mode of operation. + + The special argument `--' forces an end of option-scanning regardless + of the value of `ordering'. In the case of RETURN_IN_ORDER, only + `--' can cause `getopt' to return -1 with `optind' != ARGC. */ + +static enum +{ + REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER +} ordering; + +/* Value of POSIXLY_CORRECT environment variable. */ +static char *posixly_correct; + +#ifdef __GNU_LIBRARY__ +/* We want to avoid inclusion of string.h with non-GNU libraries + because there are many ways it can cause trouble. + On some systems, it contains special magic macros that don't work + in GCC. */ +# include +# define my_index strchr +#else + +# if 1 //HAVE_STRING_H +# include +# else +# include +# endif + +/* Avoid depending on library functions or files + whose names are inconsistent. */ + +#ifndef getenv +#ifdef _MSC_VER +// DDK will complain if you don't use the stdlib defined getenv +#include +#else +extern char *getenv (); +#endif +#endif + +static char * +my_index (str, chr) + const char *str; + int chr; +{ + while (*str) + { + if (*str == chr) + return (char *) str; + str++; + } + return 0; +} + +/* If using GCC, we can safely declare strlen this way. + If not using GCC, it is ok not to declare it. */ +#ifdef __GNUC__ +/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. + That was relevant to code that was here before. */ +# if (!defined __STDC__ || !__STDC__) && !defined strlen +/* gcc with -traditional declares the built-in strlen to return int, + and has done so at least since version 2.4.5. -- rms. */ +extern int strlen (const char *); +# endif /* not __STDC__ */ +#endif /* __GNUC__ */ + +#endif /* not __GNU_LIBRARY__ */ + +/* Handle permutation of arguments. */ + +/* Describe the part of ARGV that contains non-options that have + been skipped. `first_nonopt' is the index in ARGV of the first of them; + `last_nonopt' is the index after the last of them. */ + +static int first_nonopt; +static int last_nonopt; + +#ifdef _LIBC +/* Stored original parameters. + XXX This is no good solution. We should rather copy the args so + that we can compare them later. But we must not use malloc(3). */ +extern int __libc_argc; +extern char **__libc_argv; + +/* Bash 2.0 gives us an environment variable containing flags + indicating ARGV elements that should not be considered arguments. */ + +# ifdef USE_NONOPTION_FLAGS +/* Defined in getopt_init.c */ +extern char *__getopt_nonoption_flags; + +static int nonoption_flags_max_len; +static int nonoption_flags_len; +# endif + +# ifdef USE_NONOPTION_FLAGS +# define SWAP_FLAGS(ch1, ch2) \ + if (nonoption_flags_len > 0) \ + { \ + char __tmp = __getopt_nonoption_flags[ch1]; \ + __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ + __getopt_nonoption_flags[ch2] = __tmp; \ + } +# else +# define SWAP_FLAGS(ch1, ch2) +# endif +#else /* !_LIBC */ +# define SWAP_FLAGS(ch1, ch2) +#endif /* _LIBC */ + +/* Exchange two adjacent subsequences of ARGV. + One subsequence is elements [first_nonopt,last_nonopt) + which contains all the non-options that have been skipped so far. + The other is elements [last_nonopt,optind), which contains all + the options processed since those non-options were skipped. + + `first_nonopt' and `last_nonopt' are relocated so that they describe + the new indices of the non-options in ARGV after they are moved. */ + +#if defined __STDC__ && __STDC__ +static void exchange (char **); +#endif + +static void +exchange (argv) + char **argv; +{ + int bottom = first_nonopt; + int middle = last_nonopt; + int top = optind; + char *tem; + + /* Exchange the shorter segment with the far end of the longer segment. + That puts the shorter segment into the right place. + It leaves the longer segment in the right place overall, + but it consists of two parts that need to be swapped next. */ + +#if defined _LIBC && defined USE_NONOPTION_FLAGS + /* First make sure the handling of the `__getopt_nonoption_flags' + string can work normally. Our top argument must be in the range + of the string. */ + if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) + { + /* We must extend the array. The user plays games with us and + presents new arguments. */ + char *new_str = malloc (top + 1); + if (new_str == NULL) + nonoption_flags_len = nonoption_flags_max_len = 0; + else + { + memset (__mempcpy (new_str, __getopt_nonoption_flags, + nonoption_flags_max_len), + '\0', top + 1 - nonoption_flags_max_len); + nonoption_flags_max_len = top + 1; + __getopt_nonoption_flags = new_str; + } + } +#endif + + while (top > middle && middle > bottom) + { + if (top - middle > middle - bottom) + { + /* Bottom segment is the short one. */ + int len = middle - bottom; + register int i; + + /* Swap it with the top part of the top segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[top - (middle - bottom) + i]; + argv[top - (middle - bottom) + i] = tem; + SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); + } + /* Exclude the moved bottom segment from further swapping. */ + top -= len; + } + else + { + /* Top segment is the short one. */ + int len = top - middle; + register int i; + + /* Swap it with the bottom part of the bottom segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[middle + i]; + argv[middle + i] = tem; + SWAP_FLAGS (bottom + i, middle + i); + } + /* Exclude the moved top segment from further swapping. */ + bottom += len; + } + } + + /* Update records for the slots the non-options now occupy. */ + + first_nonopt += (optind - last_nonopt); + last_nonopt = optind; +} + +/* Initialize the internal data when the first call is made. */ + +#if defined __STDC__ && __STDC__ +static const char *_getopt_initialize (int, char *const *, const char *); +#endif +static const char * +_getopt_initialize (argc, argv, optstring) + int argc; + char *const *argv; + const char *optstring; +{ + /* Start processing options with ARGV-element 1 (since ARGV-element 0 + is the program name); the sequence of previously skipped + non-option ARGV-elements is empty. */ + + first_nonopt = last_nonopt = optind; + + nextchar = NULL; + + posixly_correct = getenv ("POSIXLY_CORRECT"); + + /* Determine how to handle the ordering of options and nonoptions. */ + + if (optstring[0] == '-') + { + ordering = RETURN_IN_ORDER; + ++optstring; + } + else if (optstring[0] == '+') + { + ordering = REQUIRE_ORDER; + ++optstring; + } + else if (posixly_correct != NULL) + ordering = REQUIRE_ORDER; + else + ordering = PERMUTE; + +#if defined _LIBC && defined USE_NONOPTION_FLAGS + if (posixly_correct == NULL + && argc == __libc_argc && argv == __libc_argv) + { + if (nonoption_flags_max_len == 0) + { + if (__getopt_nonoption_flags == NULL + || __getopt_nonoption_flags[0] == '\0') + nonoption_flags_max_len = -1; + else + { + const char *orig_str = __getopt_nonoption_flags; + int len = nonoption_flags_max_len = strlen (orig_str); + if (nonoption_flags_max_len < argc) + nonoption_flags_max_len = argc; + __getopt_nonoption_flags = + (char *) malloc (nonoption_flags_max_len); + if (__getopt_nonoption_flags == NULL) + nonoption_flags_max_len = -1; + else + memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), + '\0', nonoption_flags_max_len - len); + } + } + nonoption_flags_len = nonoption_flags_max_len; + } + else + nonoption_flags_len = 0; +#endif + + return optstring; +} + +/* Scan elements of ARGV (whose length is ARGC) for option characters + given in OPTSTRING. + + If an element of ARGV starts with '-', and is not exactly "-" or "--", + then it is an option element. The characters of this element + (aside from the initial '-') are option characters. If `getopt' + is called repeatedly, it returns successively each of the option characters + from each of the option elements. + + If `getopt' finds another option character, it returns that character, + updating `optind' and `nextchar' so that the next call to `getopt' can + resume the scan with the following option character or ARGV-element. + + If there are no more option characters, `getopt' returns -1. + Then `optind' is the index in ARGV of the first ARGV-element + that is not an option. (The ARGV-elements have been permuted + so that those that are not options now come last.) + + OPTSTRING is a string containing the legitimate option characters. + If an option character is seen that is not listed in OPTSTRING, + return '?' after printing an error message. If you set `opterr' to + zero, the error message is suppressed but we still return '?'. + + If a char in OPTSTRING is followed by a colon, that means it wants an arg, + so the following text in the same ARGV-element, or the text of the following + ARGV-element, is returned in `optarg'. Two colons mean an option that + wants an optional arg; if there is text in the current ARGV-element, + it is returned in `optarg', otherwise `optarg' is set to zero. + + If OPTSTRING starts with `-' or `+', it requests different methods of + handling the non-option ARGV-elements. + See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. + + Long-named options begin with `--' instead of `-'. + Their names may be abbreviated as long as the abbreviation is unique + or is an exact match for some defined option. If they have an + argument, it follows the option name in the same ARGV-element, separated + from the option name by a `=', or else the in next ARGV-element. + When `getopt' finds a long-named option, it returns 0 if that option's + `flag' field is nonzero, the value of the option's `val' field + if the `flag' field is zero. + + The elements of ARGV aren't really const, because we permute them. + But we pretend they're const in the prototype to be compatible + with other systems. + + LONGOPTS is a vector of `struct option' terminated by an + element containing a name which is zero. + + LONGIND returns the index in LONGOPT of the long-named option found. + It is only valid when a long-named option has been found by the most + recent call. + + If LONG_ONLY is nonzero, '-' as well as '--' can introduce + long-named options. */ + +int +_getopt_internal (argc, argv, optstring, longopts, longind, long_only) + int argc; + char *const *argv; + const char *optstring; + const struct option *longopts; + int *longind; + int long_only; +{ + int print_errors = opterr; + if (optstring[0] == ':') + print_errors = 0; + + if (argc < 1) + return -1; + + optarg = NULL; + + if (optind == 0 || !__getopt_initialized) + { + if (optind == 0) + optind = 1; /* Don't scan ARGV[0], the program name. */ + optstring = _getopt_initialize (argc, argv, optstring); + __getopt_initialized = 1; + } + + /* Test whether ARGV[optind] points to a non-option argument. + Either it does not have option syntax, or there is an environment flag + from the shell indicating it is not an option. The later information + is only used when the used in the GNU libc. */ +#if defined _LIBC && defined USE_NONOPTION_FLAGS +# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ + || (optind < nonoption_flags_len \ + && __getopt_nonoption_flags[optind] == '1')) +#else +# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') +#endif + + if (nextchar == NULL || *nextchar == '\0') + { + /* Advance to the next ARGV-element. */ + + /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been + moved back by the user (who may also have changed the arguments). */ + if (last_nonopt > optind) + last_nonopt = optind; + if (first_nonopt > optind) + first_nonopt = optind; + + if (ordering == PERMUTE) + { + /* If we have just processed some options following some non-options, + exchange them so that the options come first. */ + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange ((char **) argv); + else if (last_nonopt != optind) + first_nonopt = optind; + + /* Skip any additional non-options + and extend the range of non-options previously skipped. */ + + while (optind < argc && NONOPTION_P) + optind++; + last_nonopt = optind; + } + + /* The special ARGV-element `--' means premature end of options. + Skip it like a null option, + then exchange with previous non-options as if it were an option, + then skip everything else like a non-option. */ + + if (optind != argc && !strcmp (argv[optind], "--")) + { + optind++; + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange ((char **) argv); + else if (first_nonopt == last_nonopt) + first_nonopt = optind; + last_nonopt = argc; + + optind = argc; + } + + /* If we have done all the ARGV-elements, stop the scan + and back over any non-options that we skipped and permuted. */ + + if (optind == argc) + { + /* Set the next-arg-index to point at the non-options + that we previously skipped, so the caller will digest them. */ + if (first_nonopt != last_nonopt) + optind = first_nonopt; + return -1; + } + + /* If we have come to a non-option and did not permute it, + either stop the scan or describe it to the caller and pass it by. */ + + if (NONOPTION_P) + { + if (ordering == REQUIRE_ORDER) + return -1; + optarg = argv[optind++]; + return 1; + } + + /* We have found another option-ARGV-element. + Skip the initial punctuation. */ + + nextchar = (argv[optind] + 1 + + (longopts != NULL && argv[optind][1] == '-')); + } + + /* Decode the current option-ARGV-element. */ + + /* Check whether the ARGV-element is a long option. + + If long_only and the ARGV-element has the form "-f", where f is + a valid short option, don't consider it an abbreviated form of + a long option that starts with f. Otherwise there would be no + way to give the -f short option. + + On the other hand, if there's a long option "fubar" and + the ARGV-element is "-fu", do consider that an abbreviation of + the long option, just like "--fu", and not "-f" with arg "u". + + This distinction seems to be the most useful approach. */ + + if (longopts != NULL + && (argv[optind][1] == '-' + || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = -1; + int option_index; + + for (nameend = nextchar; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) + == (unsigned int) strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else if (long_only + || pfound->has_arg != p->has_arg + || pfound->flag != p->flag + || pfound->val != p->val) + /* Second or later nonexact match found. */ + ambig = 1; + } + + if (ambig && !exact) + { + if (print_errors) + fprintf (stderr, _("%s: option `%s' is ambiguous\n"), + argv[0], argv[optind]); + nextchar += strlen (nextchar); + optind++; + optopt = 0; + return '?'; + } + + if (pfound != NULL) + { + option_index = indfound; + optind++; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + optarg = nameend + 1; + else + { + if (print_errors) + { + if (argv[optind - 1][1] == '-') + /* --option */ + fprintf (stderr, + _("%s: option `--%s' doesn't allow an argument\n"), + argv[0], pfound->name); + else + /* +option or -option */ + fprintf (stderr, + _("%s: option `%c%s' doesn't allow an argument\n"), + argv[0], argv[optind - 1][0], pfound->name); + } + + nextchar += strlen (nextchar); + + optopt = pfound->val; + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (optind < argc) + optarg = argv[optind++]; + else + { + if (print_errors) + fprintf (stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[optind - 1]); + nextchar += strlen (nextchar); + optopt = pfound->val; + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + + /* Can't find it as a long option. If this is not getopt_long_only, + or the option starts with '--' or is not a valid short + option, then it's an error. + Otherwise interpret it as a short option. */ + if (!long_only || argv[optind][1] == '-' + || my_index (optstring, *nextchar) == NULL) + { + if (print_errors) + { + if (argv[optind][1] == '-') + /* --option */ + fprintf (stderr, _("%s: unrecognized option `--%s'\n"), + argv[0], nextchar); + else + /* +option or -option */ + fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), + argv[0], argv[optind][0], nextchar); + } + nextchar = (char *) ""; + optind++; + optopt = 0; + return '?'; + } + } + + /* Look at and handle the next short option-character. */ + + { + char c = *nextchar++; + char *temp = my_index (optstring, c); + + /* Increment `optind' when we start to process its last character. */ + if (*nextchar == '\0') + ++optind; + + if (temp == NULL || c == ':') + { + if (print_errors) + { + if (posixly_correct) + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, _("%s: illegal option -- %c\n"), + argv[0], c); + else + fprintf (stderr, _("%s: invalid option -- %c\n"), + argv[0], c); + } + optopt = c; + return '?'; + } + /* Convenience. Treat POSIX -W foo same as long option --foo */ + if (temp[0] == 'W' && temp[1] == ';') + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = 0; + int option_index; + + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (print_errors) + { + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, _("%s: option requires an argument -- %c\n"), + argv[0], c); + } + optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + return c; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + + /* optarg is now the argument, see if it's in the + table of longopts. */ + + for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) == strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + if (ambig && !exact) + { + if (print_errors) + fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"), + argv[0], argv[optind]); + nextchar += strlen (nextchar); + optind++; + return '?'; + } + if (pfound != NULL) + { + option_index = indfound; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + optarg = nameend + 1; + else + { + if (print_errors) + fprintf (stderr, _("\ + %s: option `-W %s' doesn't allow an argument\n"), + argv[0], pfound->name); + + nextchar += strlen (nextchar); + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (optind < argc) + optarg = argv[optind++]; + else + { + if (print_errors) + fprintf (stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[optind - 1]); + nextchar += strlen (nextchar); + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + nextchar = NULL; + return 'W'; /* Let the application handle it. */ + } + if (temp[1] == ':') + { + if (temp[2] == ':') + { + /* This is an option that accepts an argument optionally. */ + if (*nextchar != '\0') + { + optarg = nextchar; + optind++; + } + else + optarg = NULL; + nextchar = NULL; + } + else + { + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (print_errors) + { + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, + _("%s: option requires an argument -- %c\n"), + argv[0], c); + } + optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + nextchar = NULL; + } + } + return c; + } +} + +int +getopt (argc, argv, optstring) + int argc; + char *const *argv; + const char *optstring; +{ + return _getopt_internal (argc, argv, optstring, + (const struct option *) 0, + (int *) 0, + 0); +} + +#endif /* Not ELIDE_CODE. */ + +#ifdef TEST + +/* Compile with -DTEST to make an executable for use in testing + the above definition of `getopt'. */ + +int +main (argc, argv) + int argc; + char **argv; +{ + int c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = optind ? optind : 1; + + c = getopt (argc, argv, "abc:d:0123456789"); + if (c == -1) + break; + + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf ("digits occur in two different argv-elements.\n"); + digit_optind = this_option_optind; + printf ("option %c\n", c); + break; + + case 'a': + printf ("option a\n"); + break; + + case 'b': + printf ("option b\n"); + break; + + case 'c': + printf ("option c with value `%s'\n", optarg); + break; + + case '?': + break; + + default: + printf ("?? getopt returned character code 0%o ??\n", c); + } + } + + if (optind < argc) + { + printf ("non-option ARGV-elements: "); + while (optind < argc) + printf ("%s ", argv[optind++]); + printf ("\n"); + } + + exit (0); +} + +#endif /* TEST */ diff --git a/utils/getopt/getopt.h b/utils/getopt/getopt.h new file mode 100644 index 0000000..a1b8dd6 --- /dev/null +++ b/utils/getopt/getopt.h @@ -0,0 +1,180 @@ +/* Declarations for getopt. + Copyright (C) 1989-1994, 1996-1999, 2001 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#ifndef _GETOPT_H + +#ifndef __need_getopt +# define _GETOPT_H 1 +#endif + +/* If __GNU_LIBRARY__ is not already defined, either we are being used + standalone, or this is the first header included in the source file. + If we are being used with glibc, we need to include , but + that does not exist if we are standalone. So: if __GNU_LIBRARY__ is + not defined, include , which will pull in for us + if it's from glibc. (Why ctype.h? It's guaranteed to exist and it + doesn't flood the namespace with stuff the way some other headers do.) */ +#if !defined __GNU_LIBRARY__ +# include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +extern char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +extern int optind; + +/* Callers store zero here to inhibit the error message `getopt' prints + for unrecognized options. */ + +extern int opterr; + +/* Set to an option character which was unrecognized. */ + +extern int optopt; + +#ifndef __need_getopt +/* Describe the long-named options requested by the application. + The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector + of `struct option' terminated by an element containing a name which is + zero. + + The field `has_arg' is: + no_argument (or 0) if the option does not take an argument, + required_argument (or 1) if the option requires an argument, + optional_argument (or 2) if the option takes an optional argument. + + If the field `flag' is not NULL, it points to a variable that is set + to the value given in the field `val' when the option is found, but + left unchanged if the option is not found. + + To have a long-named option do something other than set an `int' to + a compiled-in constant, such as set a value from `optarg', set the + option's `flag' field to zero and its `val' field to a nonzero + value (the equivalent single-letter option character, if there is + one). For long options that have a zero `flag' field, `getopt' + returns the contents of the `val' field. */ + +struct option +{ +# if (defined __STDC__ && __STDC__) || defined __cplusplus + const char *name; +# else + char *name; +# endif + /* has_arg can't be an enum because some compilers complain about + type mismatches in all the code that assumes it is an int. */ + int has_arg; + int *flag; + int val; +}; + +/* Names for the values of the `has_arg' field of `struct option'. */ + +# define no_argument 0 +# define required_argument 1 +# define optional_argument 2 +#endif /* need getopt */ + + +/* Get definitions and prototypes for functions to process the + arguments in ARGV (ARGC of them, minus the program name) for + options given in OPTS. + + Return the option character from OPTS just read. Return -1 when + there are no more options. For unrecognized options, or options + missing arguments, `optopt' is set to the option letter, and '?' is + returned. + + The OPTS string is a list of characters which are recognized option + letters, optionally followed by colons, specifying that that letter + takes an argument, to be placed in `optarg'. + + If a letter in OPTS is followed by two colons, its argument is + optional. This behavior is specific to the GNU `getopt'. + + The argument `--' causes premature termination of argument + scanning, explicitly telling `getopt' that there are no more + options. + + If OPTS begins with `--', then non-option arguments are treated as + arguments to the option '\0'. This behavior is specific to the GNU + `getopt'. */ + +#if (defined __STDC__ && __STDC__) || defined __cplusplus +# ifdef __GNU_LIBRARY__ +/* Many other libraries have conflicting prototypes for getopt, with + differences in the consts, in stdlib.h. To avoid compilation + errors, only prototype getopt for the GNU C library. */ +extern int getopt (int __argc, char *const *__argv, const char *__shortopts); +# else /* not __GNU_LIBRARY__ */ +extern int getopt (); +# endif /* __GNU_LIBRARY__ */ + +# ifndef __need_getopt +extern int getopt_long (int __argc, char *const *__argv, const char *__shortopts, + const struct option *__longopts, int *__longind); +extern int getopt_long_only (int __argc, char *const *__argv, + const char *__shortopts, + const struct option *__longopts, int *__longind); + +/* Internal only. Users should not call this directly. */ +extern int _getopt_internal (int __argc, char *const *__argv, + const char *__shortopts, + const struct option *__longopts, int *__longind, + int __long_only); +# endif +#else /* not __STDC__ */ +extern int getopt (); +# ifndef __need_getopt +extern int getopt_long (); +extern int getopt_long_only (); + +extern int _getopt_internal (); +# endif +#endif /* __STDC__ */ + +#ifdef __cplusplus +} +#endif + +/* Make sure we later can get all the definitions and declarations. */ +#undef __need_getopt + +#endif /* getopt.h */ diff --git a/utils/make.mk b/utils/make.mk new file mode 100644 index 0000000..645ee7a --- /dev/null +++ b/utils/make.mk @@ -0,0 +1,15 @@ +DIR=utils + +SRC_UTILS += $(wildcard $(DIR)/*.c) +SRC_UTILS_PRE += $(wildcard $(DIR)/convenience/*.c) +OBJ_UTILS += $(SRC_UTILS:.c=) +OBJ_UTILS_PRE += $(SRC_UTILS_PRE:.c=.o) +LDFLAGS_UTILS = -pthread -L/tmp -lr820t -lm + +$(DIR)-pre: $(OBJ_UTILS_PRE) + +$(DIR)/convenience/%.o: $(DIR)/convenience/%.c + $(CC) $(CFLAGS) $(INCLUDE) -c $< -o $(BUILD_DIR)$@ + +$(DIR)/%: $(DIR)/%.c + $(CC) $(CFLAGS) $(INCLUDE) $(BUILD_DIR)$(OBJ_UTILS_PRE) $< -o $(BUILD_DIR)$@ $(LDFLAGS_UTILS) \ No newline at end of file diff --git a/utils/rtl_adsb.c b/utils/rtl_adsb.c new file mode 100644 index 0000000..7de9204 --- /dev/null +++ b/utils/rtl_adsb.c @@ -0,0 +1,496 @@ +/* + * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver + * Copyright (C) 2012 by Steve Markgraf + * Copyright (C) 2012 by Hoernchen + * Copyright (C) 2012 by Kyle Keen + * Copyright (C) 2012 by Youssef Touil + * Copyright (C) 2012 by Ian Gilmour + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#else +#include +#include +#include +#include "getopt/getopt.h" +#endif + +#include +#include + +#include "rtl-sdr.h" +#include "convenience/convenience.h" + +#ifdef _WIN32 +#define sleep Sleep +#if defined(_MSC_VER) && (_MSC_VER < 1800) +#define round(x) (x > 0.0 ? floor(x + 0.5): ceil(x - 0.5)) +#endif +#endif + +#define ADSB_RATE 2000000 +#define ADSB_FREQ 1090000000 +#define DEFAULT_ASYNC_BUF_NUMBER 12 +#define DEFAULT_BUF_LENGTH (16 * 16384) +#define AUTO_GAIN -100 + +#define MESSAGEGO 253 +#define OVERWRITE 254 +#define BADSAMPLE 255 + +static pthread_t demod_thread; +static pthread_cond_t ready; +static pthread_mutex_t ready_m; +static volatile int do_exit = 0; +static rtlsdr_dev_t *dev = NULL; + +uint16_t squares[256]; + +/* todo, bundle these up in a struct */ +uint8_t *buffer; /* also abused for uint16_t */ +int verbose_output = 0; +int short_output = 0; +int quality = 10; +int allowed_errors = 5; +FILE *file; +int adsb_frame[14]; +#define preamble_len 16 +#define long_frame 112 +#define short_frame 56 + +/* signals are not threadsafe by default */ +#define safe_cond_signal(n, m) pthread_mutex_lock(m); pthread_cond_signal(n); pthread_mutex_unlock(m) +#define safe_cond_wait(n, m) pthread_mutex_lock(m); pthread_cond_wait(n, m); pthread_mutex_unlock(m) + +void usage(void) +{ + fprintf(stderr, + "rtl_adsb, a simple ADS-B decoder\n\n" + "Use:\trtl_adsb [-R] [-g gain] [-p ppm] [output file]\n" + "\t[-d device_index (default: 0)]\n" + "\t[-V verbove output (default: off)]\n" + "\t[-S show short frames (default: off)]\n" + "\t[-Q quality (0: no sanity checks, 0.5: half bit, 1: one bit (default), 2: two bits)]\n" + "\t[-e allowed_errors (default: 5)]\n" + "\t[-g tuner_gain (default: automatic)]\n" + "\t[-p ppm_error (default: 0)]\n" + "\tfilename (a '-' dumps samples to stdout)\n" + "\t (omitting the filename also uses stdout)\n\n" + "Streaming with netcat:\n" + "\trtl_adsb | netcat -lp 8080\n" + "\twhile true; do rtl_adsb | nc -lp 8080; done\n" + "Streaming with socat:\n" + "\trtl_adsb | socat -u - TCP4:sdrsharp.com:47806\n" + "\n"); + exit(1); +} + +#ifdef _WIN32 +BOOL WINAPI +sighandler(int signum) +{ + if (CTRL_C_EVENT == signum) { + fprintf(stderr, "Signal caught, exiting!\n"); + do_exit = 1; + rtlsdr_cancel_async(dev); + return TRUE; + } + return FALSE; +} +#else +static void sighandler(int signum) +{ + fprintf(stderr, "Signal caught, exiting!\n"); + do_exit = 1; + rtlsdr_cancel_async(dev); +} +#endif + +void display(int *frame, int len) +{ + int i, df; + if (!short_output && len <= short_frame) { + return;} + df = (frame[0] >> 3) & 0x1f; + if (quality == 0 && !(df==11 || df==17 || df==18 || df==19)) { + return;} + fprintf(file, "*"); + for (i=0; i<((len+7)/8); i++) { + fprintf(file, "%02x", frame[i]);} + fprintf(file, ";\r\n"); + if (!verbose_output) { + return;} + fprintf(file, "DF=%i CA=%i\n", df, frame[0] & 0x07); + fprintf(file, "ICAO Address=%06x\n", frame[1] << 16 | frame[2] << 8 | frame[3]); + if (len <= short_frame) { + return;} + fprintf(file, "PI=0x%06x\n", frame[11] << 16 | frame[12] << 8 | frame[13]); + fprintf(file, "Type Code=%i S.Type/Ant.=%x\n", (frame[4] >> 3) & 0x1f, frame[4] & 0x07); + fprintf(file, "--------------\n"); +} + +int abs8(int x) +/* do not subtract 127 from the raw iq, this handles it */ +{ + if (x >= 127) { + return x - 127;} + return 127 - x; +} + +void squares_precompute(void) +/* equiv to abs(x-128) ^ 2 */ +{ + int i, j; + // todo, check if this LUT is actually any faster + for (i=0; i<256; i++) { + j = abs8(i); + squares[i] = (uint16_t)(j*j); + } +} + +int magnitute(uint8_t *buf, int len) +/* takes i/q, changes buf in place (16 bit), returns new len (16 bit) */ +{ + int i; + uint16_t *m; + for (i=0; i b; + bit = c > d; + + if (quality == 0) { + return bit;} + + if (quality == 5) { + if ( bit && bit_p && b > c) { + return BADSAMPLE;} + if (!bit && !bit_p && b < c) { + return BADSAMPLE;} + return bit; + } + + if (quality == 10) { + if ( bit && bit_p && c > b) { + return 1;} + if ( bit && !bit_p && d < b) { + return 1;} + if (!bit && bit_p && d > b) { + return 0;} + if (!bit && !bit_p && c < b) { + return 0;} + return BADSAMPLE; + } + + if ( bit && bit_p && c > b && d < a) { + return 1;} + if ( bit && !bit_p && c > a && d < b) { + return 1;} + if (!bit && bit_p && c < a && d > b) { + return 0;} + if (!bit && !bit_p && c < b && d > a) { + return 0;} + return BADSAMPLE; +} + +inline uint16_t min16(uint16_t a, uint16_t b) +{ + return ab ? a : b; +} + +int preamble(uint16_t *buf, int i) +/* returns 0/1 for preamble at index i */ +{ + int i2; + uint16_t low = 0; + uint16_t high = 65535; + for (i2=0; i2 allowed_errors) { + buf[i2] = BADSAMPLE; + break; + } else { + bit = a > b; + /* these don't have to match the bit */ + a = 0; + b = 65535; + } + } + buf[i] = buf[i+1] = OVERWRITE; + buf[i2] = bit; + } + } +} + +void messages(uint16_t *buf, int len) +{ + int i, data_i, index, shift, frame_len; + // todo, allow wrap across buffers + for (i=0; i 1) { + continue;} + frame_len = long_frame; + data_i = 0; + for (index=0; index<14; index++) { + adsb_frame[index] = 0;} + for(; i= 0 ? r : -r; +} + diff --git a/utils/rtl_eeprom.c b/utils/rtl_eeprom.c new file mode 100644 index 0000000..5259820 --- /dev/null +++ b/utils/rtl_eeprom.c @@ -0,0 +1,425 @@ +/* + * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver + * rtl_eeprom, EEPROM modification tool + * Copyright (C) 2012 by Steve Markgraf + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include + +#ifndef _WIN32 +#include +#else +#include +#include "getopt/getopt.h" +#endif + +#include "rtl-sdr.h" + +#define EEPROM_SIZE 256 +#define MAX_STR_SIZE 256 +#define STR_OFFSET 0x09 + +static rtlsdr_dev_t *dev = NULL; + +typedef struct rtlsdr_config { + uint16_t vendor_id; + uint16_t product_id; + char manufacturer[MAX_STR_SIZE]; + char product[MAX_STR_SIZE]; + char serial[MAX_STR_SIZE]; + int have_serial; + int enable_ir; + int remote_wakeup; +} rtlsdr_config_t; + +void dump_config(rtlsdr_config_t *conf) +{ + fprintf(stderr, "__________________________________________\n"); + fprintf(stderr, "Vendor ID:\t\t0x%04x\n", conf->vendor_id); + fprintf(stderr, "Product ID:\t\t0x%04x\n", conf->product_id); + fprintf(stderr, "Manufacturer:\t\t%s\n", conf->manufacturer); + fprintf(stderr, "Product:\t\t%s\n", conf->product); + fprintf(stderr, "Serial number:\t\t%s\n", conf->serial); + fprintf(stderr, "Serial number enabled:\t"); + fprintf(stderr, conf->have_serial ? "yes\n": "no\n"); + fprintf(stderr, "IR endpoint enabled:\t"); + fprintf(stderr, conf->enable_ir ? "yes\n": "no\n"); + fprintf(stderr, "Remote wakeup enabled:\t"); + fprintf(stderr, conf->remote_wakeup ? "yes\n": "no\n"); + fprintf(stderr, "__________________________________________\n"); +} + +void usage(void) +{ + fprintf(stderr, + "rtl_eeprom, an EEPROM programming tool for " + "RTL2832 based DVB-T receivers\n\n" + "Usage:\n" + "\t[-d device_index (default: 0)]\n" + "\t[-m set manufacturer string]\n" + "\t[-p set product string]\n" + "\t[-s set serial number string]\n" + "\t[-i <0,1> disable/enable IR-endpoint]\n" + "\t[-g generate default config and write to device]\n" + "\t[ can be one of:]\n" + "\t[ realtek\t\tRealtek default (as without EEPROM)]\n" + "\t[ realtek_oem\t\tRealtek default OEM with EEPROM]\n" + "\t[ noxon\t\tTerratec NOXON DAB Stick]\n" + "\t[ terratec_black\tTerratec T Stick Black]\n" + "\t[ terratec_plus\tTerratec T Stick+ (DVB-T/DAB)]\n" + "\t[-w write dumped file to device]\n" + "\t[-r dump EEPROM to file]\n" + "\t[-h display this help text]\n" + "\nUse on your own risk, especially -w!\n"); + exit(1); +} + +int get_string_descriptor(int pos, uint8_t *data, char *str) +{ + int len, i, j = 0; + + len = data[pos]; + + if (data[pos + 1] != 0x03) + fprintf(stderr, "Error: invalid string descriptor!\n"); + + for (i = 2; i < len; i += 2) + str[j++] = data[pos + i]; + + str[j] = 0x00; + + return pos + i; +} + +int set_string_descriptor(int pos, uint8_t *data, char *str) +{ + int i = 0, j = 2; + + if (pos < 0) + return -1; + + data[pos + 1] = 0x03; + + while (str[i] != 0x00) { + if ((pos + j) >= 78) { + fprintf(stderr, "Error: string too long, truncated!\n"); + return -1; + } + data[pos + j++] = str[i++]; + data[pos + j++] = 0x00; + } + + data[pos] = j; + + return pos + j; +} + +int parse_eeprom_to_conf(rtlsdr_config_t *conf, uint8_t *dat) +{ + int pos; + + if ((dat[0] != 0x28) || (dat[1] != 0x32)) + fprintf(stderr, "Error: invalid RTL2832 EEPROM header!\n"); + + conf->vendor_id = dat[2] | (dat[3] << 8); + conf->product_id = dat[4] | (dat[5] << 8); + conf->have_serial = (dat[6] == 0xa5) ? 1 : 0; + conf->remote_wakeup = (dat[7] & 0x01) ? 1 : 0; + conf->enable_ir = (dat[7] & 0x02) ? 1 : 0; + + pos = get_string_descriptor(STR_OFFSET, dat, conf->manufacturer); + pos = get_string_descriptor(pos, dat, conf->product); + get_string_descriptor(pos, dat, conf->serial); + + return 0; +} + +int gen_eeprom_from_conf(rtlsdr_config_t *conf, uint8_t *dat) +{ + int pos; + + dat[0] = 0x28; + dat[1] = 0x32; + dat[2] = conf->vendor_id & 0xff; + dat[3] = (conf->vendor_id >> 8) & 0xff ; + dat[4] = conf->product_id & 0xff; + dat[5] = (conf->product_id >> 8) & 0xff; + dat[6] = conf->have_serial ? 0xa5 : 0x00; + dat[7] = 0x14; + dat[7] |= conf->remote_wakeup ? 0x01 : 0x00; + dat[7] |= conf->enable_ir ? 0x02 : 0x00; + dat[8] = 0x02; + + pos = set_string_descriptor(STR_OFFSET, dat, conf->manufacturer); + pos = set_string_descriptor(pos, dat, conf->product); + pos = set_string_descriptor(pos, dat, conf->serial); + + dat[78] = 0x00; /* length of IR config */ + + return pos; +} + +enum configs { + CONF_NONE = 0, + REALTEK, + REALTEK_EEPROM, + TERRATEC_NOXON, + TERRATEC_T_BLACK, + TERRATEC_T_PLUS, +}; + +void gen_default_conf(rtlsdr_config_t *conf, int config) +{ + switch (config) { + case REALTEK: + fprintf(stderr, "Realtek default (as without EEPROM)\n"); + conf->vendor_id = 0x0bda; + conf->product_id = 0x2832; + strcpy(conf->manufacturer, "Generic"); + strcpy(conf->product, "RTL2832U DVB-T"); + strcpy(conf->serial, "0"); + conf->have_serial = 1; + conf->enable_ir = 0; + conf->remote_wakeup = 1; + break; + case REALTEK_EEPROM: + fprintf(stderr, "Realtek default OEM with EEPROM\n"); + conf->vendor_id = 0x0bda; + conf->product_id = 0x2838; + strcpy(conf->manufacturer, "Realtek"); + strcpy(conf->product, "RTL2838UHIDIR"); + strcpy(conf->serial, "00000001"); + conf->have_serial = 1; + conf->enable_ir = 1; + conf->remote_wakeup = 0; + break; + case TERRATEC_NOXON: + fprintf(stderr, "Terratec NOXON DAB Stick\n"); + conf->vendor_id = 0x0ccd; + conf->product_id = 0x00b3; + strcpy(conf->manufacturer, "NOXON"); + strcpy(conf->product, "DAB Stick"); + strcpy(conf->serial, "0"); + conf->have_serial = 1; + conf->enable_ir = 0; + conf->remote_wakeup = 1; + break; + case TERRATEC_T_BLACK: + fprintf(stderr, "Terratec T Stick Black\n"); + conf->vendor_id = 0x0ccd; + conf->product_id = 0x00a9; + strcpy(conf->manufacturer, "Realtek"); + strcpy(conf->product, "RTL2838UHIDIR"); + strcpy(conf->serial, "00000001"); + conf->have_serial = 1; + conf->enable_ir = 1; + conf->remote_wakeup = 0; + break; + case TERRATEC_T_PLUS: + fprintf(stderr, "Terratec ran T Stick+\n"); + conf->vendor_id = 0x0ccd; + conf->product_id = 0x00d7; + strcpy(conf->manufacturer, "Realtek"); + strcpy(conf->product, "RTL2838UHIDIR"); + strcpy(conf->serial, "00000001"); + conf->have_serial = 1; + conf->enable_ir = 1; + conf->remote_wakeup = 0; + break; + default: + break; + }; +} + +int main(int argc, char **argv) +{ + int i, r, opt; + uint32_t dev_index = 0; + int device_count; + char *filename = NULL; + FILE *file = NULL; + char *manuf_str = NULL; + char *product_str = NULL; + char *serial_str = NULL; + uint8_t buf[EEPROM_SIZE]; + rtlsdr_config_t conf; + int flash_file = 0; + int default_config = 0; + int change = 0; + int ir_endpoint = 0; + char ch; + + while ((opt = getopt(argc, argv, "d:m:p:s:i:g:w:r:h?")) != -1) { + switch (opt) { + case 'd': + dev_index = atoi(optarg); + break; + case 'm': + manuf_str = optarg; + change = 1; + break; + case 'p': + product_str = optarg; + change = 1; + break; + case 's': + serial_str = optarg; + change = 1; + break; + case 'i': + ir_endpoint = (atoi(optarg) > 0) ? 1 : -1; + change = 1; + break; + case 'g': + if (!strcmp(optarg, "realtek")) + default_config = REALTEK; + else if (!strcmp(optarg, "realtek_oem")) + default_config = REALTEK_EEPROM; + else if (!strcmp(optarg, "noxon")) + default_config = TERRATEC_NOXON; + else if (!strcmp(optarg, "terratec_black")) + default_config = TERRATEC_T_BLACK; + else if (!strcmp(optarg, "terratec_plus")) + default_config = TERRATEC_T_PLUS; + + if (default_config != CONF_NONE) + change = 1; + break; + case 'w': + flash_file = 1; + change = 1; + case 'r': + filename = optarg; + break; + default: + usage(); + break; + } + } + + device_count = rtlsdr_get_device_count(); + if (!device_count) { + fprintf(stderr, "No supported devices found.\n"); + exit(1); + } + + fprintf(stderr, "Found %d device(s):\n", device_count); + for (i = 0; i < device_count; i++) + fprintf(stderr, " %d: %s\n", i, rtlsdr_get_device_name(i)); + fprintf(stderr, "\n"); + + fprintf(stderr, "Using device %d: %s\n", + dev_index, + rtlsdr_get_device_name(dev_index)); + + r = rtlsdr_open(&dev, dev_index); + if (r < 0) { + fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index); + exit(1); + } + + fprintf(stderr, "\n"); + + r = rtlsdr_read_eeprom(dev, buf, 0, EEPROM_SIZE); + if (r < 0) { + if (r == -3) + fprintf(stderr, "No EEPROM has been found.\n"); + else + fprintf(stderr, "Failed to read EEPROM, err %i.\n", r); + goto exit; + } + + if (r < 0) + return -1; + + fprintf(stderr, "Current configuration:\n"); + parse_eeprom_to_conf(&conf, buf); + dump_config(&conf); + + if (filename) { + file = fopen(filename, flash_file ? "rb" : "wb"); + if (!file) { + fprintf(stderr, "Error opening file!\n"); + goto exit; + } + if (flash_file) { + if (fread(buf, 1, sizeof(buf), file) != sizeof(buf)) + fprintf(stderr, "Error reading file!\n"); + } else { + if (fwrite(buf, 1, sizeof(buf), file) != sizeof(buf)) + fprintf(stderr, "Short write, exiting!\n"); + else + fprintf(stderr, "\nDump to %s successful.\n", filename); + } + } + + if (manuf_str) + strncpy((char*)&conf.manufacturer, manuf_str, MAX_STR_SIZE); + + if (product_str) + strncpy((char*)&conf.product, product_str, MAX_STR_SIZE); + + if (serial_str) { + conf.have_serial = 1; + strncpy((char*)&conf.serial, serial_str, MAX_STR_SIZE); + } + + if (ir_endpoint != 0) + conf.enable_ir = (ir_endpoint > 0) ? 1 : 0; + + if (!change) + goto exit; + + fprintf(stderr, "\nNew configuration:\n"); + + if (default_config != CONF_NONE) + gen_default_conf(&conf, default_config); + + if (!flash_file) { + if (gen_eeprom_from_conf(&conf, buf) < 0) + goto exit; + } + + parse_eeprom_to_conf(&conf, buf); + dump_config(&conf); + + fprintf(stderr, "Write new configuration to device [y/n]? "); + + while ((ch = getchar())) { + if (ch != 'y') + goto exit; + else + break; + } + + r = rtlsdr_write_eeprom(dev, buf, 0, flash_file ? EEPROM_SIZE : 128); + if (r < 0) + fprintf(stderr, "Error while writing EEPROM: %i\n", r); + else + fprintf(stderr, "\nConfiguration successfully written.\n" + "Please replug the device for changes" + " to take effect.\n"); + +exit: + if (file) + fclose(file); + + rtlsdr_close(dev); + + return r >= 0 ? r : -r; +} diff --git a/utils/rtl_fm.c b/utils/rtl_fm.c new file mode 100644 index 0000000..e89e42d --- /dev/null +++ b/utils/rtl_fm.c @@ -0,0 +1,1264 @@ +/* + * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver + * Copyright (C) 2012 by Steve Markgraf + * Copyright (C) 2012 by Hoernchen + * Copyright (C) 2012 by Kyle Keen + * Copyright (C) 2013 by Elias Oenal + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +/* + * written because people could not do real time + * FM demod on Atom hardware with GNU radio + * based on rtl_sdr.c and rtl_tcp.c + * + * lots of locks, but that is okay + * (no many-to-many locks) + * + * todo: + * sanity checks + * scale squelch to other input parameters + * test all the demodulations + * pad output on hop + * frequency ranges could be stored better + * scaled AM demod amplification + * auto-hop after time limit + * peak detector to tune onto stronger signals + * fifo for active hop frequency + * clips + * noise squelch + * merge stereo patch + * merge soft agc patch + * merge udp patch + * testmode to detect overruns + * watchdog to reset bad dongle + * fix oversampling + */ + +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#else +#include +#include +#include +#include "getopt/getopt.h" +#define usleep(x) Sleep(x/1000) +#if defined(_MSC_VER) && (_MSC_VER < 1800) +#define round(x) (x > 0.0 ? floor(x + 0.5): ceil(x - 0.5)) +#endif +#define _USE_MATH_DEFINES +#endif + +#include +#include +#include + +#include "rtl-sdr.h" +#include "convenience/convenience.h" + +#define DEFAULT_SAMPLE_RATE 24000 +#define DEFAULT_BUF_LENGTH (1 * 16384) +#define MAXIMUM_OVERSAMPLE 16 +#define MAXIMUM_BUF_LENGTH (MAXIMUM_OVERSAMPLE * DEFAULT_BUF_LENGTH) +#define AUTO_GAIN -100 +#define BUFFER_DUMP 4096 + +#define FREQUENCIES_LIMIT 1000 + +static volatile int do_exit = 0; +static int lcm_post[17] = {1,1,1,3,1,5,3,7,1,9,5,11,3,13,7,15,1}; +static int ACTUAL_BUF_LENGTH; + +static int *atan_lut = NULL; +static int atan_lut_size = 131072; /* 512 KB */ +static int atan_lut_coef = 8; + +struct dongle_state +{ + int exit_flag; + pthread_t thread; + rtlsdr_dev_t *dev; + int dev_index; + uint32_t freq; + uint32_t rate; + int gain; + uint16_t buf16[MAXIMUM_BUF_LENGTH]; + uint32_t buf_len; + int ppm_error; + int offset_tuning; + int direct_sampling; + int mute; + struct demod_state *demod_target; +}; + +struct demod_state +{ + int exit_flag; + pthread_t thread; + int16_t lowpassed[MAXIMUM_BUF_LENGTH]; + int lp_len; + int16_t lp_i_hist[10][6]; + int16_t lp_q_hist[10][6]; + int16_t result[MAXIMUM_BUF_LENGTH]; + int16_t droop_i_hist[9]; + int16_t droop_q_hist[9]; + int result_len; + int rate_in; + int rate_out; + int rate_out2; + int now_r, now_j; + int pre_r, pre_j; + int prev_index; + int downsample; /* min 1, max 256 */ + int post_downsample; + int output_scale; + int squelch_level, conseq_squelch, squelch_hits, terminate_on_squelch; + int downsample_passes; + int comp_fir_size; + int custom_atan; + int deemph, deemph_a; + int now_lpr; + int prev_lpr_index; + int dc_block, dc_avg; + void (*mode_demod)(struct demod_state*); + pthread_rwlock_t rw; + pthread_cond_t ready; + pthread_mutex_t ready_m; + struct output_state *output_target; +}; + +struct output_state +{ + int exit_flag; + pthread_t thread; + FILE *file; + char *filename; + int16_t result[MAXIMUM_BUF_LENGTH]; + int result_len; + int rate; + pthread_rwlock_t rw; + pthread_cond_t ready; + pthread_mutex_t ready_m; +}; + +struct controller_state +{ + int exit_flag; + pthread_t thread; + uint32_t freqs[FREQUENCIES_LIMIT]; + int freq_len; + int freq_now; + int edge; + int wb_mode; + pthread_cond_t hop; + pthread_mutex_t hop_m; +}; + +// multiple of these, eventually +struct dongle_state dongle; +struct demod_state demod; +struct output_state output; +struct controller_state controller; + +void usage(void) +{ + fprintf(stderr, + "rtl_fm, a simple narrow band FM demodulator for RTL2832 based DVB-T receivers\n\n" + "Use:\trtl_fm -f freq [-options] [filename]\n" + "\t-f frequency_to_tune_to [Hz]\n" + "\t use multiple -f for scanning (requires squelch)\n" + "\t ranges supported, -f 118M:137M:25k\n" + "\t[-M modulation (default: fm)]\n" + "\t fm, wbfm, raw, am, usb, lsb\n" + "\t wbfm == -M fm -s 170k -o 4 -A fast -r 32k -l 0 -E deemp\n" + "\t raw mode outputs 2x16 bit IQ pairs\n" + "\t[-s sample_rate (default: 24k)]\n" + "\t[-d device_index (default: 0)]\n" + "\t[-g tuner_gain (default: automatic)]\n" + "\t[-l squelch_level (default: 0/off)]\n" + //"\t for fm squelch is inverted\n" + //"\t[-o oversampling (default: 1, 4 recommended)]\n" + "\t[-p ppm_error (default: 0)]\n" + "\t[-E enable_option (default: none)]\n" + "\t use multiple -E to enable multiple options\n" + "\t edge: enable lower edge tuning\n" + "\t dc: enable dc blocking filter\n" + "\t deemp: enable de-emphasis filter\n" + "\t direct: enable direct sampling\n" + "\t offset: enable offset tuning\n" + "\tfilename ('-' means stdout)\n" + "\t omitting the filename also uses stdout\n\n" + "Experimental options:\n" + "\t[-r resample_rate (default: none / same as -s)]\n" + "\t[-t squelch_delay (default: 10)]\n" + "\t +values will mute/scan, -values will exit\n" + "\t[-F fir_size (default: off)]\n" + "\t enables low-leakage downsample filter\n" + "\t size can be 0 or 9. 0 has bad roll off\n" + "\t[-A std/fast/lut choose atan math (default: std)]\n" + //"\t[-C clip_path (default: off)\n" + //"\t (create time stamped raw clips, requires squelch)\n" + //"\t (path must have '\%s' and will expand to date_time_freq)\n" + //"\t[-H hop_fifo (default: off)\n" + //"\t (fifo will contain the active frequency)\n" + "\n" + "Produces signed 16 bit ints, use Sox or aplay to hear them.\n" + "\trtl_fm ... | play -t raw -r 24k -es -b 16 -c 1 -V1 -\n" + "\t | aplay -r 24k -f S16_LE -t raw -c 1\n" + "\t -M wbfm | play -r 32k ... \n" + "\t -s 22050 | multimon -t raw /dev/stdin\n\n"); + exit(1); +} + +#ifdef _WIN32 +BOOL WINAPI +sighandler(int signum) +{ + if (CTRL_C_EVENT == signum) { + fprintf(stderr, "Signal caught, exiting!\n"); + do_exit = 1; + rtlsdr_cancel_async(dongle.dev); + return TRUE; + } + return FALSE; +} +#else +static void sighandler(int signum) +{ + fprintf(stderr, "Signal caught, exiting!\n"); + do_exit = 1; + rtlsdr_cancel_async(dongle.dev); +} +#endif + +/* more cond dumbness */ +#define safe_cond_signal(n, m) pthread_mutex_lock(m); pthread_cond_signal(n); pthread_mutex_unlock(m) +#define safe_cond_wait(n, m) pthread_mutex_lock(m); pthread_cond_wait(n, m); pthread_mutex_unlock(m) + +/* {length, coef, coef, coef} and scaled by 2^15 + for now, only length 9, optimal way to get +85% bandwidth */ +#define CIC_TABLE_MAX 10 +int cic_9_tables[][10] = { + {0,}, + {9, -156, -97, 2798, -15489, 61019, -15489, 2798, -97, -156}, + {9, -128, -568, 5593, -24125, 74126, -24125, 5593, -568, -128}, + {9, -129, -639, 6187, -26281, 77511, -26281, 6187, -639, -129}, + {9, -122, -612, 6082, -26353, 77818, -26353, 6082, -612, -122}, + {9, -120, -602, 6015, -26269, 77757, -26269, 6015, -602, -120}, + {9, -120, -582, 5951, -26128, 77542, -26128, 5951, -582, -120}, + {9, -119, -580, 5931, -26094, 77505, -26094, 5931, -580, -119}, + {9, -119, -578, 5921, -26077, 77484, -26077, 5921, -578, -119}, + {9, -119, -577, 5917, -26067, 77473, -26067, 5917, -577, -119}, + {9, -199, -362, 5303, -25505, 77489, -25505, 5303, -362, -199}, +}; + +#if defined(_MSC_VER) && (_MSC_VER < 1800) +double log2(double n) +{ + return log(n) / log(2.0); +} +#endif + +void rotate_90(unsigned char *buf, uint32_t len) +/* 90 rotation is 1+0j, 0+1j, -1+0j, 0-1j + or [0, 1, -3, 2, -4, -5, 7, -6] */ +{ + uint32_t i; + unsigned char tmp; + for (i=0; ilp_len) { + d->now_r += d->lowpassed[i]; + d->now_j += d->lowpassed[i+1]; + i += 2; + d->prev_index++; + if (d->prev_index < d->downsample) { + continue; + } + d->lowpassed[i2] = d->now_r; // * d->output_scale; + d->lowpassed[i2+1] = d->now_j; // * d->output_scale; + d->prev_index = 0; + d->now_r = 0; + d->now_j = 0; + i2 += 2; + } + d->lp_len = i2; +} + +int low_pass_simple(int16_t *signal2, int len, int step) +// no wrap around, length must be multiple of step +{ + int i, i2, sum; + for(i=0; i < len; i+=step) { + sum = 0; + for(i2=0; i2rate_out; + int slow = s->rate_out2; + while (i < s->result_len) { + s->now_lpr += s->result[i]; + i++; + s->prev_lpr_index += slow; + if (s->prev_lpr_index < fast) { + continue; + } + s->result[i2] = (int16_t)(s->now_lpr / (fast/slow)); + s->prev_lpr_index -= fast; + s->now_lpr = 0; + i2 += 1; + } + s->result_len = i2; +} + +void fifth_order(int16_t *data, int length, int16_t *hist) +/* for half of interleaved data */ +{ + int i; + int16_t a, b, c, d, e, f; + a = hist[1]; + b = hist[2]; + c = hist[3]; + d = hist[4]; + e = hist[5]; + f = data[0]; + /* a downsample should improve resolution, so don't fully shift */ + data[0] = (a + (b+e)*5 + (c+d)*10 + f) >> 4; + for (i=4; i> 4; + } + /* archive */ + hist[0] = a; + hist[1] = b; + hist[2] = c; + hist[3] = d; + hist[4] = e; + hist[5] = f; +} + +void generic_fir(int16_t *data, int length, int *fir, int16_t *hist) +/* Okay, not at all generic. Assumes length 9, fix that eventually. */ +{ + int d, temp, sum; + for (d=0; d> 15 ; + hist[0] = hist[1]; + hist[1] = hist[2]; + hist[2] = hist[3]; + hist[3] = hist[4]; + hist[4] = hist[5]; + hist[5] = hist[6]; + hist[6] = hist[7]; + hist[7] = hist[8]; + hist[8] = temp; + } +} + +/* define our own complex math ops + because ARMv5 has no hardware float */ + +void multiply(int ar, int aj, int br, int bj, int *cr, int *cj) +{ + *cr = ar*br - aj*bj; + *cj = aj*br + ar*bj; +} + +int polar_discriminant(int ar, int aj, int br, int bj) +{ + int cr, cj; + double angle; + multiply(ar, aj, br, -bj, &cr, &cj); + angle = atan2((double)cj, (double)cr); + return (int)(angle / 3.14159 * (1<<14)); +} + +int fast_atan2(int y, int x) +/* pre scaled for int16 */ +{ + int yabs, angle; + int pi4=(1<<12), pi34=3*(1<<12); // note pi = 1<<14 + if (x==0 && y==0) { + return 0; + } + yabs = y; + if (yabs < 0) { + yabs = -yabs; + } + if (x >= 0) { + angle = pi4 - pi4 * (x-yabs) / (x+yabs); + } else { + angle = pi34 - pi4 * (x+yabs) / (yabs-x); + } + if (y < 0) { + return -angle; + } + return angle; +} + +int polar_disc_fast(int ar, int aj, int br, int bj) +{ + int cr, cj; + multiply(ar, aj, br, -bj, &cr, &cj); + return fast_atan2(cj, cr); +} + +int atan_lut_init(void) +{ + int i = 0; + + atan_lut = malloc(atan_lut_size * sizeof(int)); + + for (i = 0; i < atan_lut_size; i++) { + atan_lut[i] = (int) (atan((double) i / (1< 0) + {return 1 << 13;} + if (cr == 0 && cj < 0) + {return -(1 << 13);} + if (cj == 0 && cr > 0) + {return 0;} + if (cj == 0 && cr < 0) + {return 1 << 14;} + } + + /* real range -32768 - 32768 use 64x range -> absolute maximum: 2097152 */ + x = (cj << atan_lut_coef) / cr; + x_abs = abs(x); + + if (x_abs >= atan_lut_size) { + /* we can use linear range, but it is not necessary */ + return (cj > 0) ? 1<<13 : -1<<13; + } + + if (x > 0) { + return (cj > 0) ? atan_lut[x] : atan_lut[x] - (1<<14); + } else { + return (cj > 0) ? (1<<14) - atan_lut[-x] : -atan_lut[-x]; + } + + return 0; +} + +void fm_demod(struct demod_state *fm) +{ + int i, pcm; + int16_t *lp = fm->lowpassed; + pcm = polar_discriminant(lp[0], lp[1], + fm->pre_r, fm->pre_j); + fm->result[0] = (int16_t)pcm; + for (i = 2; i < (fm->lp_len-1); i += 2) { + switch (fm->custom_atan) { + case 0: + pcm = polar_discriminant(lp[i], lp[i+1], + lp[i-2], lp[i-1]); + break; + case 1: + pcm = polar_disc_fast(lp[i], lp[i+1], + lp[i-2], lp[i-1]); + break; + case 2: + pcm = polar_disc_lut(lp[i], lp[i+1], + lp[i-2], lp[i-1]); + break; + } + fm->result[i/2] = (int16_t)pcm; + } + fm->pre_r = lp[fm->lp_len - 2]; + fm->pre_j = lp[fm->lp_len - 1]; + fm->result_len = fm->lp_len/2; +} + +void am_demod(struct demod_state *fm) +// todo, fix this extreme laziness +{ + int i, pcm; + int16_t *lp = fm->lowpassed; + int16_t *r = fm->result; + for (i = 0; i < fm->lp_len; i += 2) { + // hypot uses floats but won't overflow + //r[i/2] = (int16_t)hypot(lp[i], lp[i+1]); + pcm = lp[i] * lp[i]; + pcm += lp[i+1] * lp[i+1]; + r[i/2] = (int16_t)sqrt(pcm) * fm->output_scale; + } + fm->result_len = fm->lp_len/2; + // lowpass? (3khz) highpass? (dc) +} + +void usb_demod(struct demod_state *fm) +{ + int i, pcm; + int16_t *lp = fm->lowpassed; + int16_t *r = fm->result; + for (i = 0; i < fm->lp_len; i += 2) { + pcm = lp[i] + lp[i+1]; + r[i/2] = (int16_t)pcm * fm->output_scale; + } + fm->result_len = fm->lp_len/2; +} + +void lsb_demod(struct demod_state *fm) +{ + int i, pcm; + int16_t *lp = fm->lowpassed; + int16_t *r = fm->result; + for (i = 0; i < fm->lp_len; i += 2) { + pcm = lp[i] - lp[i+1]; + r[i/2] = (int16_t)pcm * fm->output_scale; + } + fm->result_len = fm->lp_len/2; +} + +void raw_demod(struct demod_state *fm) +{ + int i; + for (i = 0; i < fm->lp_len; i++) { + fm->result[i] = (int16_t)fm->lowpassed[i]; + } + fm->result_len = fm->lp_len; +} + +void deemph_filter(struct demod_state *fm) +{ + static int avg; // cheating... + int i, d; + // de-emph IIR + // avg = avg * (1 - alpha) + sample * alpha; + for (i = 0; i < fm->result_len; i++) { + d = fm->result[i] - avg; + if (d > 0) { + avg += (d + fm->deemph_a/2) / fm->deemph_a; + } else { + avg += (d - fm->deemph_a/2) / fm->deemph_a; + } + fm->result[i] = (int16_t)avg; + } +} + +void dc_block_filter(struct demod_state *fm) +{ + int i, avg; + int64_t sum = 0; + for (i=0; i < fm->result_len; i++) { + sum += fm->result[i]; + } + avg = sum / fm->result_len; + avg = (avg + fm->dc_avg * 9) / 10; + for (i=0; i < fm->result_len; i++) { + fm->result[i] -= avg; + } + fm->dc_avg = avg; +} + +int mad(int16_t *samples, int len, int step) +/* mean average deviation */ +{ + int i=0, sum=0, ave=0; + if (len == 0) + {return 0;} + for (i=0; i len2) { + tick -= len2; + i++; + } + if (i >= len1) { + i = len1 - 1; + tick = len2; + } + } +} + +void arbitrary_downsample(int16_t *buf1, int16_t *buf2, int len1, int len2) +/* fractional boxcar lowpass, len1 > len2 */ +{ + int i = 1; + int j = 0; + int tick = 0; + double remainder = 0; + double frac; // use integers... + buf2[0] = 0; + while (j < len2) { + frac = 1.0; + if ((tick + len2) > len1) { + frac = (double)(len1 - tick) / (double)len2;} + buf2[j] += (int16_t)((double)buf1[i] * frac + remainder); + remainder = (double)buf1[i] * (1.0-frac); + tick += len2; + i++; + if (tick > len1) { + j++; + buf2[j] = 0; + tick -= len1; + } + if (i >= len1) { + i = len1 - 1; + tick = len1; + } + } + for (j=0; jdownsample_passes; + if (ds_p) { + for (i=0; i < ds_p; i++) { + fifth_order(d->lowpassed, (d->lp_len >> i), d->lp_i_hist[i]); + fifth_order(d->lowpassed+1, (d->lp_len >> i) - 1, d->lp_q_hist[i]); + } + d->lp_len = d->lp_len >> ds_p; + /* droop compensation */ + if (d->comp_fir_size == 9 && ds_p <= CIC_TABLE_MAX) { + generic_fir(d->lowpassed, d->lp_len, + cic_9_tables[ds_p], d->droop_i_hist); + generic_fir(d->lowpassed+1, d->lp_len-1, + cic_9_tables[ds_p], d->droop_q_hist); + } + } else { + low_pass(d); + } + /* power squelch */ + if (d->squelch_level) { + sr = rms(d->lowpassed, d->lp_len, 1); + if (sr < d->squelch_level) { + d->squelch_hits++; + for (i=0; ilp_len; i++) { + d->lowpassed[i] = 0; + } + } else { + d->squelch_hits = 0;} + } + d->mode_demod(d); /* lowpassed -> result */ + if (d->mode_demod == &raw_demod) { + return; + } + /* todo, fm noise squelch */ + // use nicer filter here too? + if (d->post_downsample > 1) { + d->result_len = low_pass_simple(d->result, d->result_len, d->post_downsample);} + if (d->deemph) { + deemph_filter(d);} + if (d->dc_block) { + dc_block_filter(d);} + if (d->rate_out2 > 0) { + low_pass_real(d); + //arbitrary_resample(d->result, d->result, d->result_len, d->result_len * d->rate_out2 / d->rate_out); + } +} + +static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx) +{ + int i; + struct dongle_state *s = ctx; + struct demod_state *d = s->demod_target; + + if (do_exit) { + return;} + if (!ctx) { + return;} + if (s->mute) { + for (i=0; imute; i++) { + buf[i] = 127;} + s->mute = 0; + } + if (!s->offset_tuning) { + rotate_90(buf, len);} + for (i=0; i<(int)len; i++) { + s->buf16[i] = (int16_t)buf[i] - 127;} + pthread_rwlock_wrlock(&d->rw); + memcpy(d->lowpassed, s->buf16, 2*len); + d->lp_len = len; + pthread_rwlock_unlock(&d->rw); + safe_cond_signal(&d->ready, &d->ready_m); +} + +static void *dongle_thread_fn(void *arg) +{ + struct dongle_state *s = arg; + rtlsdr_read_async(s->dev, rtlsdr_callback, s, 0, s->buf_len); + return 0; +} + +static void *demod_thread_fn(void *arg) +{ + struct demod_state *d = arg; + struct output_state *o = d->output_target; + while (!do_exit) { + safe_cond_wait(&d->ready, &d->ready_m); + pthread_rwlock_wrlock(&d->rw); + full_demod(d); + pthread_rwlock_unlock(&d->rw); + if (d->exit_flag) { + do_exit = 1; + } + if (d->squelch_level && d->squelch_hits > d->conseq_squelch) { + d->squelch_hits = d->conseq_squelch + 1; /* hair trigger */ + safe_cond_signal(&controller.hop, &controller.hop_m); + continue; + } + pthread_rwlock_wrlock(&o->rw); + memcpy(o->result, d->result, 2*d->result_len); + o->result_len = d->result_len; + pthread_rwlock_unlock(&o->rw); + safe_cond_signal(&o->ready, &o->ready_m); + } + return 0; +} + +static void *output_thread_fn(void *arg) +{ + struct output_state *s = arg; + while (!do_exit) { + // use timedwait and pad out under runs + safe_cond_wait(&s->ready, &s->ready_m); + pthread_rwlock_rdlock(&s->rw); + fwrite(s->result, 2, s->result_len, s->file); + pthread_rwlock_unlock(&s->rw); + } + return 0; +} + +static void optimal_settings(int freq, int rate) +{ + // giant ball of hacks + // seems unable to do a single pass, 2:1 + int capture_freq, capture_rate; + struct dongle_state *d = &dongle; + struct demod_state *dm = &demod; + struct controller_state *cs = &controller; + dm->downsample = (1000000 / dm->rate_in) + 1; + if (dm->downsample_passes) { + dm->downsample_passes = (int)log2(dm->downsample) + 1; + dm->downsample = 1 << dm->downsample_passes; + } + capture_freq = freq; + capture_rate = dm->downsample * dm->rate_in; + if (!d->offset_tuning) { + capture_freq = freq + capture_rate/4;} + capture_freq += cs->edge * dm->rate_in / 2; + dm->output_scale = (1<<15) / (128 * dm->downsample); + if (dm->output_scale < 1) { + dm->output_scale = 1;} + if (dm->mode_demod == &fm_demod) { + dm->output_scale = 1;} + d->freq = (uint32_t)capture_freq; + d->rate = (uint32_t)capture_rate; +} + +static void *controller_thread_fn(void *arg) +{ + // thoughts for multiple dongles + // might be no good using a controller thread if retune/rate blocks + int i; + struct controller_state *s = arg; + + if (s->wb_mode) { + for (i=0; i < s->freq_len; i++) { + s->freqs[i] += 16000;} + } + + /* set up primary channel */ + optimal_settings(s->freqs[0], demod.rate_in); + if (dongle.direct_sampling) { + verbose_direct_sampling(dongle.dev, 1);} + if (dongle.offset_tuning) { + verbose_offset_tuning(dongle.dev);} + + /* Set the frequency */ + verbose_set_frequency(dongle.dev, dongle.freq); + fprintf(stderr, "Oversampling input by: %ix.\n", demod.downsample); + fprintf(stderr, "Oversampling output by: %ix.\n", demod.post_downsample); + fprintf(stderr, "Buffer size: %0.2fms\n", + 1000 * 0.5 * (float)ACTUAL_BUF_LENGTH / (float)dongle.rate); + + /* Set the sample rate */ + verbose_set_sample_rate(dongle.dev, dongle.rate); + fprintf(stderr, "Output at %u Hz.\n", demod.rate_in/demod.post_downsample); + + while (!do_exit) { + safe_cond_wait(&s->hop, &s->hop_m); + if (s->freq_len <= 1) { + continue;} + /* hacky hopping */ + s->freq_now = (s->freq_now + 1) % s->freq_len; + optimal_settings(s->freqs[s->freq_now], demod.rate_in); + rtlsdr_set_center_freq(dongle.dev, dongle.freq); + dongle.mute = BUFFER_DUMP; + } + return 0; +} + +void frequency_range(struct controller_state *s, char *arg) +{ + char *start, *stop, *step; + int i; + start = arg; + stop = strchr(start, ':') + 1; + stop[-1] = '\0'; + step = strchr(stop, ':') + 1; + step[-1] = '\0'; + for(i=(int)atofs(start); i<=(int)atofs(stop); i+=(int)atofs(step)) + { + s->freqs[s->freq_len] = (uint32_t)i; + s->freq_len++; + if (s->freq_len >= FREQUENCIES_LIMIT) { + break;} + } + stop[-1] = ':'; + step[-1] = ':'; +} + +void dongle_init(struct dongle_state *s) +{ + s->rate = DEFAULT_SAMPLE_RATE; + s->gain = AUTO_GAIN; // tenths of a dB + s->mute = 0; + s->direct_sampling = 0; + s->offset_tuning = 0; + s->demod_target = &demod; +} + +void demod_init(struct demod_state *s) +{ + s->rate_in = DEFAULT_SAMPLE_RATE; + s->rate_out = DEFAULT_SAMPLE_RATE; + s->squelch_level = 0; + s->conseq_squelch = 10; + s->terminate_on_squelch = 0; + s->squelch_hits = 11; + s->downsample_passes = 0; + s->comp_fir_size = 0; + s->prev_index = 0; + s->post_downsample = 1; // once this works, default = 4 + s->custom_atan = 0; + s->deemph = 0; + s->rate_out2 = -1; // flag for disabled + s->mode_demod = &fm_demod; + s->pre_j = s->pre_r = s->now_r = s->now_j = 0; + s->prev_lpr_index = 0; + s->deemph_a = 0; + s->now_lpr = 0; + s->dc_block = 0; + s->dc_avg = 0; + pthread_rwlock_init(&s->rw, NULL); + pthread_cond_init(&s->ready, NULL); + pthread_mutex_init(&s->ready_m, NULL); + s->output_target = &output; +} + +void demod_cleanup(struct demod_state *s) +{ + pthread_rwlock_destroy(&s->rw); + pthread_cond_destroy(&s->ready); + pthread_mutex_destroy(&s->ready_m); +} + +void output_init(struct output_state *s) +{ + s->rate = DEFAULT_SAMPLE_RATE; + pthread_rwlock_init(&s->rw, NULL); + pthread_cond_init(&s->ready, NULL); + pthread_mutex_init(&s->ready_m, NULL); +} + +void output_cleanup(struct output_state *s) +{ + pthread_rwlock_destroy(&s->rw); + pthread_cond_destroy(&s->ready); + pthread_mutex_destroy(&s->ready_m); +} + +void controller_init(struct controller_state *s) +{ + s->freqs[0] = 100000000; + s->freq_len = 0; + s->edge = 0; + s->wb_mode = 0; + pthread_cond_init(&s->hop, NULL); + pthread_mutex_init(&s->hop_m, NULL); +} + +void controller_cleanup(struct controller_state *s) +{ + pthread_cond_destroy(&s->hop); + pthread_mutex_destroy(&s->hop_m); +} + +void sanity_checks(void) +{ + if (controller.freq_len == 0) { + fprintf(stderr, "Please specify a frequency.\n"); + exit(1); + } + + if (controller.freq_len >= FREQUENCIES_LIMIT) { + fprintf(stderr, "Too many channels, maximum %i.\n", FREQUENCIES_LIMIT); + exit(1); + } + + if (controller.freq_len > 1 && demod.squelch_level == 0) { + fprintf(stderr, "Please specify a squelch level. Required for scanning multiple frequencies.\n"); + exit(1); + } + +} + +int main(int argc, char **argv) +{ +#ifndef _WIN32 + struct sigaction sigact; +#endif + int r, opt; + int dev_given = 0; + int custom_ppm = 0; + dongle_init(&dongle); + demod_init(&demod); + output_init(&output); + controller_init(&controller); + + while ((opt = getopt(argc, argv, "d:f:g:s:b:l:o:t:r:p:E:F:A:M:h")) != -1) { + switch (opt) { + case 'd': + dongle.dev_index = verbose_device_search(optarg); + dev_given = 1; + break; + case 'f': + if (controller.freq_len >= FREQUENCIES_LIMIT) { + break;} + if (strchr(optarg, ':')) + {frequency_range(&controller, optarg);} + else + { + controller.freqs[controller.freq_len] = (uint32_t)atofs(optarg); + controller.freq_len++; + } + break; + case 'g': + dongle.gain = (int)(atof(optarg) * 10); + break; + case 'l': + demod.squelch_level = (int)atof(optarg); + break; + case 's': + demod.rate_in = (uint32_t)atofs(optarg); + demod.rate_out = (uint32_t)atofs(optarg); + break; + case 'r': + output.rate = (int)atofs(optarg); + demod.rate_out2 = (int)atofs(optarg); + break; + case 'o': + fprintf(stderr, "Warning: -o is very buggy\n"); + demod.post_downsample = (int)atof(optarg); + if (demod.post_downsample < 1 || demod.post_downsample > MAXIMUM_OVERSAMPLE) { + fprintf(stderr, "Oversample must be between 1 and %i\n", MAXIMUM_OVERSAMPLE);} + break; + case 't': + demod.conseq_squelch = (int)atof(optarg); + if (demod.conseq_squelch < 0) { + demod.conseq_squelch = -demod.conseq_squelch; + demod.terminate_on_squelch = 1; + } + break; + case 'p': + dongle.ppm_error = atoi(optarg); + custom_ppm = 1; + break; + case 'E': + if (strcmp("edge", optarg) == 0) { + controller.edge = 1;} + if (strcmp("dc", optarg) == 0) { + demod.dc_block = 1;} + if (strcmp("deemp", optarg) == 0) { + demod.deemph = 1;} + if (strcmp("direct", optarg) == 0) { + dongle.direct_sampling = 1;} + if (strcmp("offset", optarg) == 0) { + dongle.offset_tuning = 1;} + break; + case 'F': + demod.downsample_passes = 1; /* truthy placeholder */ + demod.comp_fir_size = atoi(optarg); + break; + case 'A': + if (strcmp("std", optarg) == 0) { + demod.custom_atan = 0;} + if (strcmp("fast", optarg) == 0) { + demod.custom_atan = 1;} + if (strcmp("lut", optarg) == 0) { + atan_lut_init(); + demod.custom_atan = 2;} + break; + case 'M': + if (strcmp("fm", optarg) == 0) { + demod.mode_demod = &fm_demod;} + if (strcmp("raw", optarg) == 0) { + demod.mode_demod = &raw_demod;} + if (strcmp("am", optarg) == 0) { + demod.mode_demod = &am_demod;} + if (strcmp("usb", optarg) == 0) { + demod.mode_demod = &usb_demod;} + if (strcmp("lsb", optarg) == 0) { + demod.mode_demod = &lsb_demod;} + if (strcmp("wbfm", optarg) == 0) { + controller.wb_mode = 1; + demod.mode_demod = &fm_demod; + demod.rate_in = 170000; + demod.rate_out = 170000; + demod.rate_out2 = 32000; + demod.custom_atan = 1; + //demod.post_downsample = 4; + demod.deemph = 1; + demod.squelch_level = 0;} + break; + case 'h': + default: + usage(); + break; + } + } + + /* quadruple sample_rate to limit to Δθ to ±π/2 */ + demod.rate_in *= demod.post_downsample; + + if (!output.rate) { + output.rate = demod.rate_out;} + + sanity_checks(); + + if (controller.freq_len > 1) { + demod.terminate_on_squelch = 0;} + + if (argc <= optind) { + output.filename = "-"; + } else { + output.filename = argv[optind]; + } + + ACTUAL_BUF_LENGTH = lcm_post[demod.post_downsample] * DEFAULT_BUF_LENGTH; + + if (!dev_given) { + dongle.dev_index = verbose_device_search("0"); + } + + if (dongle.dev_index < 0) { + exit(1); + } + + r = rtlsdr_open(&dongle.dev, (uint32_t)dongle.dev_index); + if (r < 0) { + fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dongle.dev_index); + exit(1); + } +#ifndef _WIN32 + sigact.sa_handler = sighandler; + sigemptyset(&sigact.sa_mask); + sigact.sa_flags = 0; + sigaction(SIGINT, &sigact, NULL); + sigaction(SIGTERM, &sigact, NULL); + sigaction(SIGQUIT, &sigact, NULL); + sigaction(SIGPIPE, &sigact, NULL); +#else + SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE ); +#endif + + if (demod.deemph) { + demod.deemph_a = (int)round(1.0/((1.0-exp(-1.0/(demod.rate_out * 75e-6))))); + } + + /* Set the tuner gain */ + if (dongle.gain == AUTO_GAIN) { + verbose_auto_gain(dongle.dev); + } else { + dongle.gain = nearest_gain(dongle.dev, dongle.gain); + verbose_gain_set(dongle.dev, dongle.gain); + } + + verbose_ppm_set(dongle.dev, dongle.ppm_error); + + if (strcmp(output.filename, "-") == 0) { /* Write samples to stdout */ + output.file = stdout; +#ifdef _WIN32 + _setmode(_fileno(output.file), _O_BINARY); +#endif + } else { + output.file = fopen(output.filename, "wb"); + if (!output.file) { + fprintf(stderr, "Failed to open %s\n", output.filename); + exit(1); + } + } + + //r = rtlsdr_set_testmode(dongle.dev, 1); + + /* Reset endpoint before we start reading from it (mandatory) */ + verbose_reset_buffer(dongle.dev); + + pthread_create(&controller.thread, NULL, controller_thread_fn, (void *)(&controller)); + usleep(100000); + pthread_create(&output.thread, NULL, output_thread_fn, (void *)(&output)); + pthread_create(&demod.thread, NULL, demod_thread_fn, (void *)(&demod)); + pthread_create(&dongle.thread, NULL, dongle_thread_fn, (void *)(&dongle)); + + while (!do_exit) { + usleep(100000); + } + + if (do_exit) { + fprintf(stderr, "\nUser cancel, exiting...\n");} + else { + fprintf(stderr, "\nLibrary error %d, exiting...\n", r);} + + rtlsdr_cancel_async(dongle.dev); + pthread_join(dongle.thread, NULL); + safe_cond_signal(&demod.ready, &demod.ready_m); + pthread_join(demod.thread, NULL); + safe_cond_signal(&output.ready, &output.ready_m); + pthread_join(output.thread, NULL); + safe_cond_signal(&controller.hop, &controller.hop_m); + pthread_join(controller.thread, NULL); + + //dongle_cleanup(&dongle); + demod_cleanup(&demod); + output_cleanup(&output); + controller_cleanup(&controller); + + if (output.file != stdout) { + fclose(output.file);} + + rtlsdr_close(dongle.dev); + return r >= 0 ? r : -r; +} + +// vim: tabstop=8:softtabstop=8:shiftwidth=8:noexpandtab diff --git a/utils/rtl_power.c b/utils/rtl_power.c new file mode 100644 index 0000000..23b516c --- /dev/null +++ b/utils/rtl_power.c @@ -0,0 +1,998 @@ +/* + * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver + * Copyright (C) 2012 by Steve Markgraf + * Copyright (C) 2012 by Hoernchen + * Copyright (C) 2012 by Kyle Keen + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +/* + * rtl_power: general purpose FFT integrator + * -f low_freq:high_freq:max_bin_size + * -i seconds + * outputs CSV + * time, low, high, step, db, db, db ... + * db optional? raw output might be better for noise correction + * todo: + * threading + * randomized hopping + * noise correction + * continuous IIR + * general astronomy usefulness + * multiple dongles + * multiple FFT workers + * check edge cropping for off-by-one and rounding errors + * 1.8MS/s for hiding xtal harmonics + */ + +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#else +#include +#include +#include +#include "getopt/getopt.h" +#define usleep(x) Sleep(x/1000) +#if defined(_MSC_VER) && (_MSC_VER < 1800) +#define round(x) (x > 0.0 ? floor(x + 0.5): ceil(x - 0.5)) +#endif +#define _USE_MATH_DEFINES +#endif + +#include +#include +#include + +#include "rtl-sdr.h" +#include "convenience/convenience.h" + +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) + +#define DEFAULT_BUF_LENGTH (1 * 16384) +#define AUTO_GAIN -100 +#define BUFFER_DUMP (1<<12) + +#define MAXIMUM_RATE 2800000 +#define MINIMUM_RATE 1000000 + +static volatile int do_exit = 0; +static rtlsdr_dev_t *dev = NULL; +FILE *file; + +int16_t* Sinewave; +double* power_table; +int N_WAVE, LOG2_N_WAVE; +int next_power; +int16_t *fft_buf; +int *window_coefs; + +struct tuning_state +/* one per tuning range */ +{ + int freq; + int rate; + int bin_e; + long *avg; /* length == 2^bin_e */ + int samples; + int downsample; + int downsample_passes; /* for the recursive filter */ + double crop; + //pthread_rwlock_t avg_lock; + //pthread_mutex_t avg_mutex; + /* having the iq buffer here is wasteful, but will avoid contention */ + uint8_t *buf8; + int buf_len; + //int *comp_fir; + //pthread_rwlock_t buf_lock; + //pthread_mutex_t buf_mutex; +}; + +/* 3000 is enough for 3GHz b/w worst case */ +#define MAX_TUNES 3000 +struct tuning_state tunes[MAX_TUNES]; +int tune_count = 0; + +int boxcar = 1; +int comp_fir_size = 0; +int peak_hold = 0; + +void usage(void) +{ + fprintf(stderr, + "rtl_power, a simple FFT logger for RTL2832 based DVB-T receivers\n\n" + "Use:\trtl_power -f freq_range [-options] [filename]\n" + "\t-f lower:upper:bin_size [Hz]\n" + "\t (bin size is a maximum, smaller more convenient bins\n" + "\t will be used. valid range 1Hz - 2.8MHz)\n" + "\t[-i integration_interval (default: 10 seconds)]\n" + "\t (buggy if a full sweep takes longer than the interval)\n" + "\t[-1 enables single-shot mode (default: off)]\n" + "\t[-e exit_timer (default: off/0)]\n" + //"\t[-s avg/iir smoothing (default: avg)]\n" + //"\t[-t threads (default: 1)]\n" + "\t[-d device_index (default: 0)]\n" + "\t[-g tuner_gain (default: automatic)]\n" + "\t[-p ppm_error (default: 0)]\n" + "\tfilename (a '-' dumps samples to stdout)\n" + "\t (omitting the filename also uses stdout)\n" + "\n" + "Experimental options:\n" + "\t[-w window (default: rectangle)]\n" + "\t (hamming, blackman, blackman-harris, hann-poisson, bartlett, youssef)\n" + // kaiser + "\t[-c crop_percent (default: 0%%, recommended: 20%%-50%%)]\n" + "\t (discards data at the edges, 100%% discards everything)\n" + "\t (has no effect for bins larger than 1MHz)\n" + "\t[-F fir_size (default: disabled)]\n" + "\t (enables low-leakage downsample filter,\n" + "\t fir_size can be 0 or 9. 0 has bad roll off,\n" + "\t try with '-c 50%%')\n" + "\t[-P enables peak hold (default: off)]\n" + "\t[-D enable direct sampling (default: off)]\n" + "\t[-O enable offset tuning (default: off)]\n" + "\n" + "CSV FFT output columns:\n" + "\tdate, time, Hz low, Hz high, Hz step, samples, dbm, dbm, ...\n\n" + "Examples:\n" + "\trtl_power -f 88M:108M:125k fm_stations.csv\n" + "\t (creates 160 bins across the FM band,\n" + "\t individual stations should be visible)\n" + "\trtl_power -f 100M:1G:1M -i 5m -1 survey.csv\n" + "\t (a five minute low res scan of nearly everything)\n" + "\trtl_power -f ... -i 15m -1 log.csv\n" + "\t (integrate for 15 minutes and exit afterwards)\n" + "\trtl_power -f ... -e 1h | gzip > log.csv.gz\n" + "\t (collect data for one hour and compress it on the fly)\n\n" + "Convert CSV to a waterfall graphic with:\n" + "\t http://kmkeen.com/tmp/heatmap.py.txt \n"); + exit(1); +} + +void multi_bail(void) +{ + if (do_exit == 1) + { + fprintf(stderr, "Signal caught, finishing scan pass.\n"); + } + if (do_exit >= 2) + { + fprintf(stderr, "Signal caught, aborting immediately.\n"); + } +} + +#ifdef _WIN32 +BOOL WINAPI +sighandler(int signum) +{ + if (CTRL_C_EVENT == signum) { + do_exit++; + multi_bail(); + return TRUE; + } + return FALSE; +} +#else +static void sighandler(int signum) +{ + do_exit++; + multi_bail(); +} +#endif + +/* more cond dumbness */ +#define safe_cond_signal(n, m) pthread_mutex_lock(m); pthread_cond_signal(n); pthread_mutex_unlock(m) +#define safe_cond_wait(n, m) pthread_mutex_lock(m); pthread_cond_wait(n, m); pthread_mutex_unlock(m) + +/* {length, coef, coef, coef} and scaled by 2^15 + for now, only length 9, optimal way to get +85% bandwidth */ +#define CIC_TABLE_MAX 10 +int cic_9_tables[][10] = { + {0,}, + {9, -156, -97, 2798, -15489, 61019, -15489, 2798, -97, -156}, + {9, -128, -568, 5593, -24125, 74126, -24125, 5593, -568, -128}, + {9, -129, -639, 6187, -26281, 77511, -26281, 6187, -639, -129}, + {9, -122, -612, 6082, -26353, 77818, -26353, 6082, -612, -122}, + {9, -120, -602, 6015, -26269, 77757, -26269, 6015, -602, -120}, + {9, -120, -582, 5951, -26128, 77542, -26128, 5951, -582, -120}, + {9, -119, -580, 5931, -26094, 77505, -26094, 5931, -580, -119}, + {9, -119, -578, 5921, -26077, 77484, -26077, 5921, -578, -119}, + {9, -119, -577, 5917, -26067, 77473, -26067, 5917, -577, -119}, + {9, -199, -362, 5303, -25505, 77489, -25505, 5303, -362, -199}, +}; + +#if defined(_MSC_VER) && (_MSC_VER < 1800) +double log2(double n) +{ + return log(n) / log(2.0); +} +#endif + +/* FFT based on fix_fft.c by Roberts, Slaney and Bouras + http://www.jjj.de/fft/fftpage.html + 16 bit ints for everything + -32768..+32768 maps to -1.0..+1.0 +*/ + +void sine_table(int size) +{ + int i; + double d; + LOG2_N_WAVE = size; + N_WAVE = 1 << LOG2_N_WAVE; + Sinewave = malloc(sizeof(int16_t) * N_WAVE*3/4); + power_table = malloc(sizeof(double) * N_WAVE); + for (i=0; i> 14; + b = c & 0x01; + return (c >> 1) + b; +} + +int fix_fft(int16_t iq[], int m) +/* interleaved iq[], 0 <= n < 2**m, changes in place */ +{ + int mr, nn, i, j, l, k, istep, n, shift; + int16_t qr, qi, tr, ti, wr, wi; + n = 1 << m; + if (n > N_WAVE) + {return -1;} + mr = 0; + nn = n - 1; + /* decimation in time - re-order data */ + for (m=1; m<=nn; ++m) { + l = n; + do + {l >>= 1;} + while (mr+l > nn); + mr = (mr & (l-1)) + l; + if (mr <= m) + {continue;} + // real = 2*m, imag = 2*m+1 + tr = iq[2*m]; + iq[2*m] = iq[2*mr]; + iq[2*mr] = tr; + ti = iq[2*m+1]; + iq[2*m+1] = iq[2*mr+1]; + iq[2*mr+1] = ti; + } + l = 1; + k = LOG2_N_WAVE-1; + while (l < n) { + shift = 1; + istep = l << 1; + for (m=0; m>= 1; wi >>= 1;} + for (i=m; i>= 1; qi >>= 1;} + iq[2*j] = qr - tr; + iq[2*j+1] = qi - ti; + iq[2*i] = qr + tr; + iq[2*i+1] = qi + ti; + } + } + --k; + l = istep; + } + return 0; +} + +double rectangle(int i, int length) +{ + return 1.0; +} + +double hamming(int i, int length) +{ + double a, b, w, N1; + a = 25.0/46.0; + b = 21.0/46.0; + N1 = (double)(length-1); + w = a - b*cos(2*i*M_PI/N1); + return w; +} + +double blackman(int i, int length) +{ + double a0, a1, a2, w, N1; + a0 = 7938.0/18608.0; + a1 = 9240.0/18608.0; + a2 = 1430.0/18608.0; + N1 = (double)(length-1); + w = a0 - a1*cos(2*i*M_PI/N1) + a2*cos(4*i*M_PI/N1); + return w; +} + +double blackman_harris(int i, int length) +{ + double a0, a1, a2, a3, w, N1; + a0 = 0.35875; + a1 = 0.48829; + a2 = 0.14128; + a3 = 0.01168; + N1 = (double)(length-1); + w = a0 - a1*cos(2*i*M_PI/N1) + a2*cos(4*i*M_PI/N1) - a3*cos(6*i*M_PI/N1); + return w; +} + +double hann_poisson(int i, int length) +{ + double a, N1, w; + a = 2.0; + N1 = (double)(length-1); + w = 0.5 * (1 - cos(2*M_PI*i/N1)) * \ + pow(M_E, (-a*(double)abs((int)(N1-1-2*i)))/N1); + return w; +} + +double youssef(int i, int length) +/* really a blackman-harris-poisson window, but that is a mouthful */ +{ + double a, a0, a1, a2, a3, w, N1; + a0 = 0.35875; + a1 = 0.48829; + a2 = 0.14128; + a3 = 0.01168; + N1 = (double)(length-1); + w = a0 - a1*cos(2*i*M_PI/N1) + a2*cos(4*i*M_PI/N1) - a3*cos(6*i*M_PI/N1); + a = 0.0025; + w *= pow(M_E, (-a*(double)abs((int)(N1-1-2*i)))/N1); + return w; +} + +double kaiser(int i, int length) +// todo, become more smart +{ + return 1.0; +} + +double bartlett(int i, int length) +{ + double N1, L, w; + L = (double)length; + N1 = L - 1; + w = (i - N1/2) / (L/2); + if (w < 0) { + w = -w;} + w = 1 - w; + return w; +} + +void rms_power(struct tuning_state *ts) +/* for bins between 1MHz and 2MHz */ +{ + int i, s; + uint8_t *buf = ts->buf8; + int buf_len = ts->buf_len; + long p, t; + double dc, err; + + p = t = 0L; + for (i=0; iavg[0] += p; + } else { + ts->avg[0] = MAX(ts->avg[0], p); + } + ts->samples += 1; +} + +void frequency_range(char *arg, double crop) +/* flesh out the tunes[] for scanning */ +// do we want the fewest ranges (easy) or the fewest bins (harder)? +{ + char *start, *stop, *step; + int i, j, upper, lower, max_size, bw_seen, bw_used, bin_e, buf_len; + int downsample, downsample_passes; + double bin_size; + struct tuning_state *ts; + /* hacky string parsing */ + start = arg; + stop = strchr(start, ':') + 1; + stop[-1] = '\0'; + step = strchr(stop, ':') + 1; + step[-1] = '\0'; + lower = (int)atofs(start); + upper = (int)atofs(stop); + max_size = (int)atofs(step); + stop[-1] = ':'; + step[-1] = ':'; + downsample = 1; + downsample_passes = 0; + /* evenly sized ranges, as close to MAXIMUM_RATE as possible */ + // todo, replace loop with algebra + for (i=1; i<1500; i++) { + bw_seen = (upper - lower) / i; + bw_used = (int)((double)(bw_seen) / (1.0 - crop)); + if (bw_used > MAXIMUM_RATE) { + continue;} + tune_count = i; + break; + } + /* unless small bandwidth */ + if (bw_used < MINIMUM_RATE) { + tune_count = 1; + downsample = MAXIMUM_RATE / bw_used; + bw_used = bw_used * downsample; + } + if (!boxcar && downsample > 1) { + downsample_passes = (int)log2(downsample); + downsample = 1 << downsample_passes; + bw_used = (int)((double)(bw_seen * downsample) / (1.0 - crop)); + } + /* number of bins is power-of-two, bin size is under limit */ + // todo, replace loop with log2 + for (i=1; i<=21; i++) { + bin_e = i; + bin_size = (double)bw_used / (double)((1<= MINIMUM_RATE) { + bw_seen = max_size; + bw_used = max_size; + tune_count = (upper - lower) / bw_seen; + bin_e = 0; + crop = 0; + } + if (tune_count > MAX_TUNES) { + fprintf(stderr, "Error: bandwidth too wide.\n"); + exit(1); + } + buf_len = 2 * (1<freq = lower + i*bw_seen + bw_seen/2; + ts->rate = bw_used; + ts->bin_e = bin_e; + ts->samples = 0; + ts->crop = crop; + ts->downsample = downsample; + ts->downsample_passes = downsample_passes; + ts->avg = (long*)malloc((1<avg) { + fprintf(stderr, "Error: malloc.\n"); + exit(1); + } + for (j=0; j<(1<avg[j] = 0L; + } + ts->buf8 = (uint8_t*)malloc(buf_len * sizeof(uint8_t)); + if (!ts->buf8) { + fprintf(stderr, "Error: malloc.\n"); + exit(1); + } + ts->buf_len = buf_len; + } + /* report */ + fprintf(stderr, "Number of frequency hops: %i\n", tune_count); + fprintf(stderr, "Dongle bandwidth: %iHz\n", bw_used); + fprintf(stderr, "Downsampling by: %ix\n", downsample); + fprintf(stderr, "Cropping by: %0.2f%%\n", crop*100); + fprintf(stderr, "Total FFT bins: %i\n", tune_count * (1<> 4; + data[2] = ((b+c)*10 + (a+d)*5 + e + f) >> 4; + data[4] = (a + (b+e)*5 + (c+d)*10 + f) >> 4; + for (i=12; i> 4; + } +} + +void remove_dc(int16_t *data, int length) +/* works on interleaved data */ +{ + int i; + int16_t ave; + long sum = 0L; + for (i=0; i < length; i+=2) { + sum += data[i]; + } + ave = (int16_t)(sum / (long)(length)); + if (ave == 0) { + return;} + for (i=0; i < length; i+=2) { + data[i] -= ave; + } +} + +void generic_fir(int16_t *data, int length, int *fir) +/* Okay, not at all generic. Assumes length 9, fix that eventually. */ +{ + int d, temp, sum; + int hist[9] = {0,}; + /* cheat on the beginning, let it go unfiltered */ + for (d=0; d<18; d+=2) { + hist[d/2] = data[d]; + } + for (d=18; d> 15) ; + hist[0] = hist[1]; + hist[1] = hist[2]; + hist[2] = hist[3]; + hist[3] = hist[4]; + hist[4] = hist[5]; + hist[5] = hist[6]; + hist[6] = hist[7]; + hist[7] = hist[8]; + hist[8] = temp; + } +} + +void downsample_iq(int16_t *data, int length) +{ + fifth_order(data, length); + //remove_dc(data, length); + fifth_order(data+1, length-1); + //remove_dc(data+1, length-1); +} + +long real_conj(int16_t real, int16_t imag) +/* real(n * conj(n)) */ +{ + return ((long)real*(long)real + (long)imag*(long)imag); +} + +void scanner(void) +{ + int i, j, j2, f, n_read, offset, bin_e, bin_len, buf_len, ds, ds_p; + int32_t w; + struct tuning_state *ts; + bin_e = tunes[0].bin_e; + bin_len = 1 << bin_e; + buf_len = tunes[0].buf_len; + for (i=0; i= 2) + {return;} + ts = &tunes[i]; + f = (int)rtlsdr_get_center_freq(dev); + if (f != ts->freq) { + retune(dev, ts->freq);} + rtlsdr_read_sync(dev, ts->buf8, buf_len, &n_read); + if (n_read != buf_len) { + fprintf(stderr, "Error: dropped samples.\n");} + /* rms */ + if (bin_len == 1) { + rms_power(ts); + continue; + } + /* prep for fft */ + for (j=0; jbuf8[j] - 127; + } + ds = ts->downsample; + ds_p = ts->downsample_passes; + if (boxcar && ds > 1) { + j=2, j2=0; + while (j < buf_len) { + fft_buf[j2] += fft_buf[j]; + fft_buf[j2+1] += fft_buf[j+1]; + fft_buf[j] = 0; + fft_buf[j+1] = 0; + j += 2; + if (j % (ds*2) == 0) { + j2 += 2;} + } + } else if (ds_p) { /* recursive */ + for (j=0; j < ds_p; j++) { + downsample_iq(fft_buf, buf_len >> j); + } + /* droop compensation */ + if (comp_fir_size == 9 && ds_p <= CIC_TABLE_MAX) { + generic_fir(fft_buf, buf_len >> j, cic_9_tables[ds_p]); + generic_fir(fft_buf+1, (buf_len >> j)-1, cic_9_tables[ds_p]); + } + } + remove_dc(fft_buf, buf_len / ds); + remove_dc(fft_buf+1, (buf_len / ds) - 1); + /* window function and fft */ + for (offset=0; offset<(buf_len/ds); offset+=(2*bin_len)) { + // todo, let rect skip this + for (j=0; javg[j] += real_conj(fft_buf[offset+j*2], fft_buf[offset+j*2+1]); + } + } else { + for (j=0; javg[j] = MAX(real_conj(fft_buf[offset+j*2], fft_buf[offset+j*2+1]), ts->avg[j]); + } + } + ts->samples += ds; + } + } +} + +void csv_dbm(struct tuning_state *ts) +{ + int i, len, ds, i1, i2, bw2, bin_count; + long tmp; + double dbm; + len = 1 << ts->bin_e; + ds = ts->downsample; + /* fix FFT stuff quirks */ + if (ts->bin_e > 0) { + /* nuke DC component (not effective for all windows) */ + ts->avg[0] = ts->avg[1]; + /* FFT is translated by 180 degrees */ + for (i=0; iavg[i]; + ts->avg[i] = ts->avg[i+len/2]; + ts->avg[i+len/2] = tmp; + } + } + /* Hz low, Hz high, Hz step, samples, dbm, dbm, ... */ + bin_count = (int)((double)len * (1.0 - ts->crop)); + bw2 = (int)(((double)ts->rate * (double)bin_count) / (len * 2 * ds)); + fprintf(file, "%i, %i, %.2f, %i, ", ts->freq - bw2, ts->freq + bw2, + (double)ts->rate / (double)(len*ds), ts->samples); + // something seems off with the dbm math + i1 = 0 + (int)((double)len * ts->crop * 0.5); + i2 = (len-1) - (int)((double)len * ts->crop * 0.5); + for (i=i1; i<=i2; i++) { + dbm = (double)ts->avg[i]; + dbm /= (double)ts->rate; + dbm /= (double)ts->samples; + dbm = 10 * log10(dbm); + fprintf(file, "%.2f, ", dbm); + } + dbm = (double)ts->avg[i2] / ((double)ts->rate * (double)ts->samples); + if (ts->bin_e == 0) { + dbm = ((double)ts->avg[0] / \ + ((double)ts->rate * (double)ts->samples));} + dbm = 10 * log10(dbm); + fprintf(file, "%.2f\n", dbm); + for (i=0; iavg[i] = 0L; + } + ts->samples = 0; +} + +int main(int argc, char **argv) +{ +#ifndef _WIN32 + struct sigaction sigact; +#endif + char *filename = NULL; + int i, length, r, opt, wb_mode = 0; + int f_set = 0; + int gain = AUTO_GAIN; // tenths of a dB + int dev_index = 0; + int dev_given = 0; + int ppm_error = 0; + int interval = 10; + int fft_threads = 1; + int smoothing = 0; + int single = 0; + int direct_sampling = 0; + int offset_tuning = 0; + double crop = 0.0; + char *freq_optarg; + time_t next_tick; + time_t time_now; + time_t exit_time = 0; + char t_str[50]; + struct tm *cal_time; + double (*window_fn)(int, int) = rectangle; + freq_optarg = ""; + + while ((opt = getopt(argc, argv, "f:i:s:t:d:g:p:e:w:c:F:1PDOh")) != -1) { + switch (opt) { + case 'f': // lower:upper:bin_size + freq_optarg = strdup(optarg); + f_set = 1; + break; + case 'd': + dev_index = verbose_device_search(optarg); + dev_given = 1; + break; + case 'g': + gain = (int)(atof(optarg) * 10); + break; + case 'c': + crop = atofp(optarg); + break; + case 'i': + interval = (int)round(atoft(optarg)); + break; + case 'e': + exit_time = (time_t)((int)round(atoft(optarg))); + break; + case 's': + if (strcmp("avg", optarg) == 0) { + smoothing = 0;} + if (strcmp("iir", optarg) == 0) { + smoothing = 1;} + break; + case 'w': + if (strcmp("rectangle", optarg) == 0) { + window_fn = rectangle;} + if (strcmp("hamming", optarg) == 0) { + window_fn = hamming;} + if (strcmp("blackman", optarg) == 0) { + window_fn = blackman;} + if (strcmp("blackman-harris", optarg) == 0) { + window_fn = blackman_harris;} + if (strcmp("hann-poisson", optarg) == 0) { + window_fn = hann_poisson;} + if (strcmp("youssef", optarg) == 0) { + window_fn = youssef;} + if (strcmp("kaiser", optarg) == 0) { + window_fn = kaiser;} + if (strcmp("bartlett", optarg) == 0) { + window_fn = bartlett;} + break; + case 't': + fft_threads = atoi(optarg); + break; + case 'p': + ppm_error = atoi(optarg); + break; + case '1': + single = 1; + break; + case 'P': + peak_hold = 1; + break; + case 'D': + direct_sampling = 1; + break; + case 'O': + offset_tuning = 1; + break; + case 'F': + boxcar = 0; + comp_fir_size = atoi(optarg); + break; + case 'h': + default: + usage(); + break; + } + } + + if (!f_set) { + fprintf(stderr, "No frequency range provided.\n"); + exit(1); + } + + if ((crop < 0.0) || (crop > 1.0)) { + fprintf(stderr, "Crop value outside of 0 to 1.\n"); + exit(1); + } + + frequency_range(freq_optarg, crop); + + if (tune_count == 0) { + usage();} + + if (argc <= optind) { + filename = "-"; + } else { + filename = argv[optind]; + } + + if (interval < 1) { + interval = 1;} + + fprintf(stderr, "Reporting every %i seconds\n", interval); + + if (!dev_given) { + dev_index = verbose_device_search("0"); + } + + if (dev_index < 0) { + exit(1); + } + + r = rtlsdr_open(&dev, (uint32_t)dev_index); + if (r < 0) { + fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index); + exit(1); + } +#ifndef _WIN32 + sigact.sa_handler = sighandler; + sigemptyset(&sigact.sa_mask); + sigact.sa_flags = 0; + sigaction(SIGINT, &sigact, NULL); + sigaction(SIGTERM, &sigact, NULL); + sigaction(SIGQUIT, &sigact, NULL); + sigaction(SIGPIPE, &sigact, NULL); +#else + SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE ); +#endif + + if (direct_sampling) { + verbose_direct_sampling(dev, 1); + } + + if (offset_tuning) { + verbose_offset_tuning(dev); + } + + /* Set the tuner gain */ + if (gain == AUTO_GAIN) { + verbose_auto_gain(dev); + } else { + gain = nearest_gain(dev, gain); + verbose_gain_set(dev, gain); + } + + verbose_ppm_set(dev, ppm_error); + + if (strcmp(filename, "-") == 0) { /* Write log to stdout */ + file = stdout; +#ifdef _WIN32 + // Is this necessary? Output is ascii. + _setmode(_fileno(file), _O_BINARY); +#endif + } else { + file = fopen(filename, "wb"); + if (!file) { + fprintf(stderr, "Failed to open %s\n", filename); + exit(1); + } + } + + /* Reset endpoint before we start reading from it (mandatory) */ + verbose_reset_buffer(dev); + + /* actually do stuff */ + rtlsdr_set_sample_rate(dev, (uint32_t)tunes[0].rate); + sine_table(tunes[0].bin_e); + next_tick = time(NULL) + interval; + if (exit_time) { + exit_time = time(NULL) + exit_time;} + fft_buf = malloc(tunes[0].buf_len * sizeof(int16_t)); + length = 1 << tunes[0].bin_e; + window_coefs = malloc(length * sizeof(int)); + for (i=0; i= next_tick) { + next_tick += interval;} + if (single) { + do_exit = 1;} + if (exit_time && time(NULL) >= exit_time) { + do_exit = 1;} + } + + /* clean up */ + + if (do_exit) { + fprintf(stderr, "\nUser cancel, exiting...\n");} + else { + fprintf(stderr, "\nLibrary error %d, exiting...\n", r);} + + if (file != stdout) { + fclose(file);} + + rtlsdr_close(dev); + free(fft_buf); + free(window_coefs); + //for (i=0; i= 0 ? r : -r; +} + +// vim: tabstop=8:softtabstop=8:shiftwidth=8:noexpandtab diff --git a/utils/rtl_sdr.c b/utils/rtl_sdr.c new file mode 100644 index 0000000..e6537ca --- /dev/null +++ b/utils/rtl_sdr.c @@ -0,0 +1,278 @@ +/* + * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver + * Copyright (C) 2012 by Steve Markgraf + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#else +#include +#include +#include +#include "getopt/getopt.h" +#endif + +#include "rtl-sdr.h" +#include "convenience/convenience.h" + +#define DEFAULT_SAMPLE_RATE 2048000 +#define DEFAULT_BUF_LENGTH (16 * 16384) +#define MINIMAL_BUF_LENGTH 512 +#define MAXIMAL_BUF_LENGTH (256 * 16384) + +static int do_exit = 0; +static uint32_t bytes_to_read = 0; +static rtlsdr_dev_t *dev = NULL; + +void usage(void) +{ + fprintf(stderr, + "rtl_sdr, an I/Q recorder for RTL2832 based DVB-T receivers\n\n" + "Usage:\t -f frequency_to_tune_to [Hz]\n" + "\t[-s samplerate (default: 2048000 Hz)]\n" + "\t[-d device_index (default: 0)]\n" + "\t[-g gain (default: 0 for auto)]\n" + "\t[-p ppm_error (default: 0)]\n" + "\t[-b output_block_size (default: 16 * 16384)]\n" + "\t[-n number of samples to read (default: 0, infinite)]\n" + "\t[-S force sync output (default: async)]\n" + "\tfilename (a '-' dumps samples to stdout)\n\n"); + exit(1); +} + +#ifdef _WIN32 +BOOL WINAPI +sighandler(int signum) +{ + if (CTRL_C_EVENT == signum) { + fprintf(stderr, "Signal caught, exiting!\n"); + do_exit = 1; + rtlsdr_cancel_async(dev); + return TRUE; + } + return FALSE; +} +#else +static void sighandler(int signum) +{ + fprintf(stderr, "Signal caught, exiting!\n"); + do_exit = 1; + rtlsdr_cancel_async(dev); +} +#endif + +static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx) +{ + if (ctx) { + if (do_exit) + return; + + if ((bytes_to_read > 0) && (bytes_to_read < len)) { + len = bytes_to_read; + do_exit = 1; + rtlsdr_cancel_async(dev); + } + + if (fwrite(buf, 1, len, (FILE*)ctx) != len) { + fprintf(stderr, "Short write, samples lost, exiting!\n"); + rtlsdr_cancel_async(dev); + } + + if (bytes_to_read > 0) + bytes_to_read -= len; + } +} + +int main(int argc, char **argv) +{ +#ifndef _WIN32 + struct sigaction sigact; +#endif + char *filename = NULL; + int n_read; + int r, opt; + int gain = 0; + int ppm_error = 0; + int sync_mode = 0; + FILE *file; + uint8_t *buffer; + int dev_index = 0; + int dev_given = 0; + uint32_t frequency = 100000000; + uint32_t samp_rate = DEFAULT_SAMPLE_RATE; + uint32_t out_block_size = DEFAULT_BUF_LENGTH; + + while ((opt = getopt(argc, argv, "d:f:g:s:b:n:p:S")) != -1) { + switch (opt) { + case 'd': + dev_index = verbose_device_search(optarg); + dev_given = 1; + break; + case 'f': + frequency = (uint32_t)atofs(optarg); + break; + case 'g': + gain = (int)(atof(optarg) * 10); /* tenths of a dB */ + break; + case 's': + samp_rate = (uint32_t)atofs(optarg); + break; + case 'p': + ppm_error = atoi(optarg); + break; + case 'b': + out_block_size = (uint32_t)atof(optarg); + break; + case 'n': + bytes_to_read = (uint32_t)atof(optarg) * 2; + break; + case 'S': + sync_mode = 1; + break; + default: + usage(); + break; + } + } + + if (argc <= optind) { + usage(); + } else { + filename = argv[optind]; + } + + if(out_block_size < MINIMAL_BUF_LENGTH || + out_block_size > MAXIMAL_BUF_LENGTH ){ + fprintf(stderr, + "Output block size wrong value, falling back to default\n"); + fprintf(stderr, + "Minimal length: %u\n", MINIMAL_BUF_LENGTH); + fprintf(stderr, + "Maximal length: %u\n", MAXIMAL_BUF_LENGTH); + out_block_size = DEFAULT_BUF_LENGTH; + } + + buffer = malloc(out_block_size * sizeof(uint8_t)); + + if (!dev_given) { + dev_index = verbose_device_search("0"); + } + + if (dev_index < 0) { + exit(1); + } + + r = rtlsdr_open(&dev, (uint32_t)dev_index); + if (r < 0) { + fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index); + exit(1); + } +#ifndef _WIN32 + sigact.sa_handler = sighandler; + sigemptyset(&sigact.sa_mask); + sigact.sa_flags = 0; + sigaction(SIGINT, &sigact, NULL); + sigaction(SIGTERM, &sigact, NULL); + sigaction(SIGQUIT, &sigact, NULL); + sigaction(SIGPIPE, &sigact, NULL); +#else + SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE ); +#endif + /* Set the sample rate */ + verbose_set_sample_rate(dev, samp_rate); + + /* Set the frequency */ + verbose_set_frequency(dev, frequency); + + if (0 == gain) { + /* Enable automatic gain */ + verbose_auto_gain(dev); + } else { + /* Enable manual gain */ + gain = nearest_gain(dev, gain); + verbose_gain_set(dev, gain); + } + + verbose_ppm_set(dev, ppm_error); + + if(strcmp(filename, "-") == 0) { /* Write samples to stdout */ + file = stdout; +#ifdef _WIN32 + _setmode(_fileno(stdin), _O_BINARY); +#endif + } else { + file = fopen(filename, "wb"); + if (!file) { + fprintf(stderr, "Failed to open %s\n", filename); + goto out; + } + } + + /* Reset endpoint before we start reading from it (mandatory) */ + verbose_reset_buffer(dev); + + if (sync_mode) { + fprintf(stderr, "Reading samples in sync mode...\n"); + while (!do_exit) { + r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read); + if (r < 0) { + fprintf(stderr, "WARNING: sync read failed.\n"); + break; + } + + if ((bytes_to_read > 0) && (bytes_to_read < (uint32_t)n_read)) { + n_read = bytes_to_read; + do_exit = 1; + } + + if (fwrite(buffer, 1, n_read, file) != (size_t)n_read) { + fprintf(stderr, "Short write, samples lost, exiting!\n"); + break; + } + + if ((uint32_t)n_read < out_block_size) { + fprintf(stderr, "Short read, samples lost, exiting!\n"); + break; + } + + if (bytes_to_read > 0) + bytes_to_read -= n_read; + } + } else { + fprintf(stderr, "Reading samples in async mode...\n"); + r = rtlsdr_read_async(dev, rtlsdr_callback, (void *)file, + 0, out_block_size); + } + + if (do_exit) + fprintf(stderr, "\nUser cancel, exiting...\n"); + else + fprintf(stderr, "\nLibrary error %d, exiting...\n", r); + + if (file != stdout) + fclose(file); + + rtlsdr_close(dev); + free (buffer); +out: + return r >= 0 ? r : -r; +} diff --git a/utils/rtl_tcp.c b/utils/rtl_tcp.c new file mode 100644 index 0000000..317e0f3 --- /dev/null +++ b/utils/rtl_tcp.c @@ -0,0 +1,603 @@ +/* + * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver + * Copyright (C) 2012 by Steve Markgraf + * Copyright (C) 2012-2013 by Hoernchen + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#include +#include +#include +#include +#else +#include +#include "getopt/getopt.h" +#endif + +#include + +#include "rtl-sdr.h" +#include "convenience/convenience.h" + +#ifdef _WIN32 +#pragma comment(lib, "ws2_32.lib") + +typedef int socklen_t; + +#else +#define closesocket close +#define SOCKADDR struct sockaddr +#define SOCKET int +#define SOCKET_ERROR -1 +#endif + +static SOCKET s; + +static pthread_t tcp_worker_thread; +static pthread_t command_thread; +static pthread_cond_t exit_cond; +static pthread_mutex_t exit_cond_lock; + +static pthread_mutex_t ll_mutex; +static pthread_cond_t cond; + +struct llist { + char *data; + size_t len; + struct llist *next; +}; + +typedef struct { /* structure size must be multiple of 2 bytes */ + char magic[4]; + uint32_t tuner_type; + uint32_t tuner_gain_count; +} dongle_info_t; + +static rtlsdr_dev_t *dev = NULL; + +static int global_numq = 0; +static struct llist *ll_buffers = 0; +static int llbuf_num = 500; + +static volatile int do_exit = 0; + +void usage(void) +{ + printf("rtl_tcp, an I/Q spectrum server for RTL2832 based DVB-T receivers\n\n" + "Usage:\t[-a listen address]\n" + "\t[-p listen port (default: 1234)]\n" + "\t[-f frequency to tune to [Hz]]\n" + "\t[-g gain (default: 0 for auto)]\n" + "\t[-s samplerate in Hz (default: 2048000 Hz)]\n" + "\t[-b number of buffers (default: 15, set by library)]\n" + "\t[-n max number of linked list buffers to keep (default: 500)]\n" + "\t[-d device index (default: 0)]\n" + "\t[-P ppm_error (default: 0)]\n"); + exit(1); +} + +#ifdef _WIN32 +int gettimeofday(struct timeval *tv, void* ignored) +{ + FILETIME ft; + unsigned __int64 tmp = 0; + if (NULL != tv) { + GetSystemTimeAsFileTime(&ft); + tmp |= ft.dwHighDateTime; + tmp <<= 32; + tmp |= ft.dwLowDateTime; + tmp /= 10; +#ifdef _MSC_VER + tmp -= 11644473600000000Ui64; +#else + tmp -= 11644473600000000ULL; +#endif + tv->tv_sec = (long)(tmp / 1000000UL); + tv->tv_usec = (long)(tmp % 1000000UL); + } + return 0; +} + +BOOL WINAPI +sighandler(int signum) +{ + if (CTRL_C_EVENT == signum) { + fprintf(stderr, "Signal caught, exiting!\n"); + do_exit = 1; + rtlsdr_cancel_async(dev); + return TRUE; + } + return FALSE; +} +#else +static void sighandler(int signum) +{ + fprintf(stderr, "Signal caught, exiting!\n"); + rtlsdr_cancel_async(dev); + do_exit = 1; +} +#endif + +void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx) +{ + if(!do_exit) { + struct llist *rpt = (struct llist*)malloc(sizeof(struct llist)); + rpt->data = (char*)malloc(len); + memcpy(rpt->data, buf, len); + rpt->len = len; + rpt->next = NULL; + + pthread_mutex_lock(&ll_mutex); + + if (ll_buffers == NULL) { + ll_buffers = rpt; + } else { + struct llist *cur = ll_buffers; + int num_queued = 0; + + while (cur->next != NULL) { + cur = cur->next; + num_queued++; + } + + if(llbuf_num && llbuf_num == num_queued-2){ + struct llist *curelem; + + free(ll_buffers->data); + curelem = ll_buffers->next; + free(ll_buffers); + ll_buffers = curelem; + } + + cur->next = rpt; + + if (num_queued > global_numq) + printf("ll+, now %d\n", num_queued); + else if (num_queued < global_numq) + printf("ll-, now %d\n", num_queued); + + global_numq = num_queued; + } + pthread_cond_signal(&cond); + pthread_mutex_unlock(&ll_mutex); + } +} + +static void *tcp_worker(void *arg) +{ + struct llist *curelem,*prev; + int bytesleft,bytessent, index; + struct timeval tv= {1,0}; + struct timespec ts; + struct timeval tp; + fd_set writefds; + int r = 0; + + while(1) { + if(do_exit) + pthread_exit(0); + + pthread_mutex_lock(&ll_mutex); + gettimeofday(&tp, NULL); + ts.tv_sec = tp.tv_sec+5; + ts.tv_nsec = tp.tv_usec * 1000; + r = pthread_cond_timedwait(&cond, &ll_mutex, &ts); + if(r == ETIMEDOUT) { + pthread_mutex_unlock(&ll_mutex); + printf("worker cond timeout\n"); + sighandler(0); + pthread_exit(NULL); + } + + curelem = ll_buffers; + ll_buffers = 0; + pthread_mutex_unlock(&ll_mutex); + + while(curelem != 0) { + bytesleft = curelem->len; + index = 0; + bytessent = 0; + while(bytesleft > 0) { + FD_ZERO(&writefds); + FD_SET(s, &writefds); + tv.tv_sec = 1; + tv.tv_usec = 0; + r = select(s+1, NULL, &writefds, NULL, &tv); + if(r) { + bytessent = send(s, &curelem->data[index], bytesleft, 0); + bytesleft -= bytessent; + index += bytessent; + } + if(bytessent == SOCKET_ERROR || do_exit) { + printf("worker socket bye\n"); + sighandler(0); + pthread_exit(NULL); + } + } + prev = curelem; + curelem = curelem->next; + free(prev->data); + free(prev); + } + } +} + +static int set_gain_by_index(rtlsdr_dev_t *_dev, unsigned int index) +{ + int res = 0; + int* gains; + int count = rtlsdr_get_tuner_gains(_dev, NULL); + + if (count > 0 && (unsigned int)count > index) { + gains = malloc(sizeof(int) * count); + count = rtlsdr_get_tuner_gains(_dev, gains); + + res = rtlsdr_set_tuner_gain(_dev, gains[index]); + + free(gains); + } + + return res; +} + +#ifdef _WIN32 +#define __attribute__(x) +#pragma pack(push, 1) +#endif +struct command{ + unsigned char cmd; + unsigned int param; +}__attribute__((packed)); +#ifdef _WIN32 +#pragma pack(pop) +#endif +static void *command_worker(void *arg) +{ + int left, received = 0; + fd_set readfds; + struct command cmd={0, 0}; + struct timeval tv= {1, 0}; + int r = 0; + uint32_t tmp; + + while(1) { + left=sizeof(cmd); + while(left >0) { + FD_ZERO(&readfds); + FD_SET(s, &readfds); + tv.tv_sec = 1; + tv.tv_usec = 0; + r = select(s+1, &readfds, NULL, NULL, &tv); + if(r) { + received = recv(s, (char*)&cmd+(sizeof(cmd)-left), left, 0); + left -= received; + } + if(received == SOCKET_ERROR || do_exit) { + printf("comm recv bye\n"); + sighandler(0); + pthread_exit(NULL); + } + } + switch(cmd.cmd) { + case 0x01: + printf("set freq %d\n", ntohl(cmd.param)); + rtlsdr_set_center_freq(dev,ntohl(cmd.param)); + break; + case 0x02: + printf("set sample rate %d\n", ntohl(cmd.param)); + rtlsdr_set_sample_rate(dev, ntohl(cmd.param)); + break; + case 0x03: + printf("set gain mode %d\n", ntohl(cmd.param)); + rtlsdr_set_tuner_gain_mode(dev, ntohl(cmd.param)); + break; + case 0x04: + printf("set gain %d\n", ntohl(cmd.param)); + rtlsdr_set_tuner_gain(dev, ntohl(cmd.param)); + break; + case 0x05: + printf("set freq correction %d\n", ntohl(cmd.param)); + rtlsdr_set_freq_correction(dev, ntohl(cmd.param)); + break; + case 0x06: + tmp = ntohl(cmd.param); + printf("set if stage %d gain %d\n", tmp >> 16, (short)(tmp & 0xffff)); + rtlsdr_set_tuner_if_gain(dev, tmp >> 16, (short)(tmp & 0xffff)); + break; + case 0x07: + printf("set test mode %d\n", ntohl(cmd.param)); + rtlsdr_set_testmode(dev, ntohl(cmd.param)); + break; + case 0x08: + printf("set agc mode %d\n", ntohl(cmd.param)); + rtlsdr_set_agc_mode(dev, ntohl(cmd.param)); + break; + case 0x09: + printf("set direct sampling %d\n", ntohl(cmd.param)); + rtlsdr_set_direct_sampling(dev, ntohl(cmd.param)); + break; + case 0x0a: + printf("set offset tuning %d\n", ntohl(cmd.param)); + rtlsdr_set_offset_tuning(dev, ntohl(cmd.param)); + break; + case 0x0b: + printf("set rtl xtal %d\n", ntohl(cmd.param)); + rtlsdr_set_xtal_freq(dev, ntohl(cmd.param), 0); + break; + case 0x0c: + printf("set tuner xtal %d\n", ntohl(cmd.param)); + rtlsdr_set_xtal_freq(dev, 0, ntohl(cmd.param)); + break; + case 0x0d: + printf("set tuner gain by index %d\n", ntohl(cmd.param)); + set_gain_by_index(dev, ntohl(cmd.param)); + break; + default: + break; + } + cmd.cmd = 0xff; + } +} + +int main(int argc, char **argv) +{ + int r, opt, i; + char* addr = "127.0.0.1"; + int port = 1234; + uint32_t frequency = 100000000, samp_rate = 2048000; + struct sockaddr_in local, remote; + uint32_t buf_num = 0; + int dev_index = 0; + int dev_given = 0; + int gain = 0; + int ppm_error = 0; + struct llist *curelem,*prev; + pthread_attr_t attr; + void *status; + struct timeval tv = {1,0}; + struct linger ling = {1,0}; + SOCKET listensocket; + socklen_t rlen; + fd_set readfds; + u_long blockmode = 1; + dongle_info_t dongle_info; +#ifdef _WIN32 + WSADATA wsd; + i = WSAStartup(MAKEWORD(2,2), &wsd); +#else + struct sigaction sigact, sigign; +#endif + + while ((opt = getopt(argc, argv, "a:p:f:g:s:b:n:d:P:")) != -1) { + switch (opt) { + case 'd': + dev_index = verbose_device_search(optarg); + dev_given = 1; + break; + case 'f': + frequency = (uint32_t)atofs(optarg); + break; + case 'g': + gain = (int)(atof(optarg) * 10); /* tenths of a dB */ + break; + case 's': + samp_rate = (uint32_t)atofs(optarg); + break; + case 'a': + addr = optarg; + break; + case 'p': + port = atoi(optarg); + break; + case 'b': + buf_num = atoi(optarg); + break; + case 'n': + llbuf_num = atoi(optarg); + break; + case 'P': + ppm_error = atoi(optarg); + break; + default: + usage(); + break; + } + } + + if (argc < optind) + usage(); + + if (!dev_given) { + dev_index = verbose_device_search("0"); + } + + if (dev_index < 0) { + exit(1); + } + + rtlsdr_open(&dev, (uint32_t)dev_index); + if (NULL == dev) { + fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index); + exit(1); + } + +#ifndef _WIN32 + sigact.sa_handler = sighandler; + sigemptyset(&sigact.sa_mask); + sigact.sa_flags = 0; + sigign.sa_handler = SIG_IGN; + sigaction(SIGINT, &sigact, NULL); + sigaction(SIGTERM, &sigact, NULL); + sigaction(SIGQUIT, &sigact, NULL); + sigaction(SIGPIPE, &sigign, NULL); +#else + SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE ); +#endif + + /* Set the tuner error */ + verbose_ppm_set(dev, ppm_error); + + /* Set the sample rate */ + r = rtlsdr_set_sample_rate(dev, samp_rate); + if (r < 0) + fprintf(stderr, "WARNING: Failed to set sample rate.\n"); + + /* Set the frequency */ + r = rtlsdr_set_center_freq(dev, frequency); + if (r < 0) + fprintf(stderr, "WARNING: Failed to set center freq.\n"); + else + fprintf(stderr, "Tuned to %i Hz.\n", frequency); + + if (0 == gain) { + /* Enable automatic gain */ + r = rtlsdr_set_tuner_gain_mode(dev, 0); + if (r < 0) + fprintf(stderr, "WARNING: Failed to enable automatic gain.\n"); + } else { + /* Enable manual gain */ + r = rtlsdr_set_tuner_gain_mode(dev, 1); + if (r < 0) + fprintf(stderr, "WARNING: Failed to enable manual gain.\n"); + + /* Set the tuner gain */ + r = rtlsdr_set_tuner_gain(dev, gain); + if (r < 0) + fprintf(stderr, "WARNING: Failed to set tuner gain.\n"); + else + fprintf(stderr, "Tuner gain set to %f dB.\n", gain/10.0); + } + + /* Reset endpoint before we start reading from it (mandatory) */ + r = rtlsdr_reset_buffer(dev); + if (r < 0) + fprintf(stderr, "WARNING: Failed to reset buffers.\n"); + + pthread_mutex_init(&exit_cond_lock, NULL); + pthread_mutex_init(&ll_mutex, NULL); + pthread_mutex_init(&exit_cond_lock, NULL); + pthread_cond_init(&cond, NULL); + pthread_cond_init(&exit_cond, NULL); + + memset(&local,0,sizeof(local)); + local.sin_family = AF_INET; + local.sin_port = htons(port); + local.sin_addr.s_addr = inet_addr(addr); + + listensocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + r = 1; + setsockopt(listensocket, SOL_SOCKET, SO_REUSEADDR, (char *)&r, sizeof(int)); + setsockopt(listensocket, SOL_SOCKET, SO_LINGER, (char *)&ling, sizeof(ling)); + bind(listensocket,(struct sockaddr *)&local,sizeof(local)); + +#ifdef _WIN32 + ioctlsocket(listensocket, FIONBIO, &blockmode); +#else + r = fcntl(listensocket, F_GETFL, 0); + r = fcntl(listensocket, F_SETFL, r | O_NONBLOCK); +#endif + + while(1) { + printf("listening...\n"); + printf("Use the device argument 'rtl_tcp=%s:%d' in OsmoSDR " + "(gr-osmosdr) source\n" + "to receive samples in GRC and control " + "rtl_tcp parameters (frequency, gain, ...).\n", + addr, port); + listen(listensocket,1); + + while(1) { + FD_ZERO(&readfds); + FD_SET(listensocket, &readfds); + tv.tv_sec = 1; + tv.tv_usec = 0; + r = select(listensocket+1, &readfds, NULL, NULL, &tv); + if(do_exit) { + goto out; + } else if(r) { + rlen = sizeof(remote); + s = accept(listensocket,(struct sockaddr *)&remote, &rlen); + break; + } + } + + setsockopt(s, SOL_SOCKET, SO_LINGER, (char *)&ling, sizeof(ling)); + + printf("client accepted!\n"); + + memset(&dongle_info, 0, sizeof(dongle_info)); + memcpy(&dongle_info.magic, "RTL0", 4); + + r = rtlsdr_get_tuner_type(dev); + if (r >= 0) + dongle_info.tuner_type = htonl(r); + + r = rtlsdr_get_tuner_gains(dev, NULL); + if (r >= 0) + dongle_info.tuner_gain_count = htonl(r); + + r = send(s, (const char *)&dongle_info, sizeof(dongle_info), 0); + if (sizeof(dongle_info) != r) + printf("failed to send dongle information\n"); + + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); + r = pthread_create(&tcp_worker_thread, &attr, tcp_worker, NULL); + r = pthread_create(&command_thread, &attr, command_worker, NULL); + pthread_attr_destroy(&attr); + + r = rtlsdr_read_async(dev, rtlsdr_callback, NULL, buf_num, 0); + + pthread_join(tcp_worker_thread, &status); + pthread_join(command_thread, &status); + + closesocket(s); + + printf("all threads dead..\n"); + curelem = ll_buffers; + ll_buffers = 0; + + while(curelem != 0) { + prev = curelem; + curelem = curelem->next; + free(prev->data); + free(prev); + } + + do_exit = 0; + global_numq = 0; + } + +out: + rtlsdr_close(dev); + closesocket(listensocket); + closesocket(s); +#ifdef _WIN32 + WSACleanup(); +#endif + printf("bye!\n"); + return r >= 0 ? r : -r; +} diff --git a/utils/rtl_test.c b/utils/rtl_test.c new file mode 100644 index 0000000..9a6cfda --- /dev/null +++ b/utils/rtl_test.c @@ -0,0 +1,423 @@ +/* + * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver + * rtl_test, test and benchmark tool + * + * Copyright (C) 2012-2014 by Steve Markgraf + * Copyright (C) 2012-2014 by Kyle Keen + * Copyright (C) 2014 by Michael Tatarinov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include + +#ifdef __APPLE__ +#include +#else +#include +#endif + +#ifndef _WIN32 +#include +#else +#include +#include "getopt/getopt.h" +#endif + +#include "rtl-sdr.h" +#include "convenience/convenience.h" + +#define DEFAULT_SAMPLE_RATE 2048000 +#define DEFAULT_BUF_LENGTH (16 * 16384) +#define MINIMAL_BUF_LENGTH 512 +#define MAXIMAL_BUF_LENGTH (256 * 16384) + +#define MHZ(x) ((x)*1000*1000) + +#define PPM_DURATION 10 +#define PPM_DUMP_TIME 5 + +static enum { + NO_BENCHMARK, + TUNER_BENCHMARK, + PPM_BENCHMARK +} test_mode = NO_BENCHMARK; + +static int do_exit = 0; +static rtlsdr_dev_t *dev = NULL; + +static uint32_t samp_rate = DEFAULT_SAMPLE_RATE; + +static uint32_t total_samples = 0; +static uint32_t dropped_samples = 0; + +static unsigned int ppm_duration = PPM_DURATION; + +void usage(void) +{ + fprintf(stderr, + "rtl_test, a benchmark tool for RTL2832 based DVB-T receivers\n\n" + "Usage:\n" + "\t[-s samplerate (default: 2048000 Hz)]\n" + "\t[-d device_index (default: 0)]\n" + "\t[-t enable Elonics E4000 tuner benchmark]\n" +#ifndef _WIN32 + "\t[-p[seconds] enable PPM error measurement (default: 10 seconds)]\n" +#endif + "\t[-b output_block_size (default: 16 * 16384)]\n" + "\t[-S force sync output (default: async)]\n"); + exit(1); +} + +#ifdef _WIN32 +BOOL WINAPI +sighandler(int signum) +{ + if (CTRL_C_EVENT == signum) { + fprintf(stderr, "Signal caught, exiting!\n"); + do_exit = 1; + rtlsdr_cancel_async(dev); + return TRUE; + } + return FALSE; +} +#else +static void sighandler(int signum) +{ + fprintf(stderr, "Signal caught, exiting!\n"); + do_exit = 1; + rtlsdr_cancel_async(dev); +} +#endif + +static void underrun_test(unsigned char *buf, uint32_t len, int mute) +{ + uint32_t i, lost = 0; + static uint8_t bcnt, uninit = 1; + + if (uninit) { + bcnt = buf[0]; + uninit = 0; + } + for (i = 0; i < len; i++) { + if(bcnt != buf[i]) { + lost += (buf[i] > bcnt) ? (buf[i] - bcnt) : (bcnt - buf[i]); + bcnt = buf[i]; + } + + bcnt++; + } + + total_samples += len; + dropped_samples += lost; + if (mute) + return; + if (lost) + printf("lost at least %d bytes\n", lost); + +} + +#ifndef _WIN32 +static int ppm_gettime(struct timespec *ts) +{ + int rv = ENOSYS; + +#ifdef __unix__ + rv = clock_gettime(CLOCK_MONOTONIC, ts); +#elif __APPLE__ + struct timeval tv; + + rv = gettimeofday(&tv, NULL); + ts->tv_sec = tv.tv_sec; + ts->tv_nsec = tv.tv_usec * 1000; +#endif + return rv; +} + +static int ppm_report(uint64_t nsamples, uint64_t interval) +{ + double real_rate, ppm; + + real_rate = nsamples * 1e9 / interval; + ppm = 1e6 * (real_rate / (double)samp_rate - 1.); + return (int)round(ppm); +} + +static void ppm_test(uint32_t len) +{ + static uint64_t nsamples = 0; + static uint64_t interval = 0; + static uint64_t nsamples_total = 0; + static uint64_t interval_total = 0; + struct timespec ppm_now; + static struct timespec ppm_recent; + static enum { + PPM_INIT_NO, + PPM_INIT_DUMP, + PPM_INIT_RUN + } ppm_init = PPM_INIT_NO; + + ppm_gettime(&ppm_now); + if (ppm_init != PPM_INIT_RUN) { + /* + * Kyle Keen wrote: + * PPM_DUMP_TIME throws out the first N seconds of data. + * The dongle's PPM is usually very bad when first starting up, + * typically incorrect by more than twice the final value. + * Discarding the first few seconds allows the value to stabilize much faster. + */ + if (ppm_init == PPM_INIT_NO) { + ppm_recent.tv_sec = ppm_now.tv_sec + PPM_DUMP_TIME; + ppm_init = PPM_INIT_DUMP; + return; + } + if (ppm_init == PPM_INIT_DUMP && ppm_recent.tv_sec < ppm_now.tv_sec) + return; + ppm_recent.tv_sec = ppm_now.tv_sec; + ppm_recent.tv_nsec = ppm_now.tv_nsec; + ppm_init = PPM_INIT_RUN; + return; + } + nsamples += (uint64_t)(len / 2UL); + interval = (uint64_t)(ppm_now.tv_sec - ppm_recent.tv_sec); + if (interval < ppm_duration) + return; + interval *= 1000000000UL; + interval += (int64_t)(ppm_now.tv_nsec - ppm_recent.tv_nsec); + nsamples_total += nsamples; + interval_total += interval; + printf("real sample rate: %i current PPM: %i cumulative PPM: %i\n", + (int)((1000000000UL * nsamples) / interval), + ppm_report(nsamples, interval), + ppm_report(nsamples_total, interval_total)); + ppm_recent.tv_sec = ppm_now.tv_sec; + ppm_recent.tv_nsec = ppm_now.tv_nsec; + nsamples = 0; +} +#endif + +static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx) +{ + underrun_test(buf, len, 0); +#ifndef _WIN32 + if (test_mode == PPM_BENCHMARK) + ppm_test(len); +#endif +} + +void e4k_benchmark(void) +{ + uint32_t freq, gap_start = 0, gap_end = 0; + uint32_t range_start = 0, range_end = 0; + + fprintf(stderr, "Benchmarking E4000 PLL...\n"); + + /* find tuner range start */ + for (freq = MHZ(70); freq > MHZ(1); freq -= MHZ(1)) { + if (rtlsdr_set_center_freq(dev, freq) < 0) { + range_start = freq; + break; + } + } + + /* find tuner range end */ + for (freq = MHZ(2000); freq < MHZ(2300UL); freq += MHZ(1)) { + if (rtlsdr_set_center_freq(dev, freq) < 0) { + range_end = freq; + break; + } + } + + /* find start of L-band gap */ + for (freq = MHZ(1000); freq < MHZ(1300); freq += MHZ(1)) { + if (rtlsdr_set_center_freq(dev, freq) < 0) { + gap_start = freq; + break; + } + } + + /* find end of L-band gap */ + for (freq = MHZ(1300); freq > MHZ(1000); freq -= MHZ(1)) { + if (rtlsdr_set_center_freq(dev, freq) < 0) { + gap_end = freq; + break; + } + } + + fprintf(stderr, "E4K range: %i to %i MHz\n", + range_start/MHZ(1) + 1, range_end/MHZ(1) - 1); + + fprintf(stderr, "E4K L-band gap: %i to %i MHz\n", + gap_start/MHZ(1), gap_end/MHZ(1)); +} + +int main(int argc, char **argv) +{ +#ifndef _WIN32 + struct sigaction sigact; +#endif + int n_read, r, opt, i; + int sync_mode = 0; + uint8_t *buffer; + int dev_index = 0; + int dev_given = 0; + uint32_t out_block_size = DEFAULT_BUF_LENGTH; + int count; + int gains[100]; + + while ((opt = getopt(argc, argv, "d:s:b:tp::Sh")) != -1) { + switch (opt) { + case 'd': + dev_index = verbose_device_search(optarg); + dev_given = 1; + break; + case 's': + samp_rate = (uint32_t)atof(optarg); + break; + case 'b': + out_block_size = (uint32_t)atof(optarg); + break; + case 't': + test_mode = TUNER_BENCHMARK; + break; + case 'p': + test_mode = PPM_BENCHMARK; + if (optarg) + ppm_duration = atoi(optarg); + break; + case 'S': + sync_mode = 1; + break; + case 'h': + default: + usage(); + break; + } + } + + if(out_block_size < MINIMAL_BUF_LENGTH || + out_block_size > MAXIMAL_BUF_LENGTH ){ + fprintf(stderr, + "Output block size wrong value, falling back to default\n"); + fprintf(stderr, + "Minimal length: %u\n", MINIMAL_BUF_LENGTH); + fprintf(stderr, + "Maximal length: %u\n", MAXIMAL_BUF_LENGTH); + out_block_size = DEFAULT_BUF_LENGTH; + } + + buffer = malloc(out_block_size * sizeof(uint8_t)); + + if (!dev_given) { + dev_index = verbose_device_search("0"); + } + + if (dev_index < 0) { + exit(1); + } + + r = rtlsdr_open(&dev, (uint32_t)dev_index); + if (r < 0) { + fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index); + exit(1); + } +#ifndef _WIN32 + sigact.sa_handler = sighandler; + sigemptyset(&sigact.sa_mask); + sigact.sa_flags = 0; + sigaction(SIGINT, &sigact, NULL); + sigaction(SIGTERM, &sigact, NULL); + sigaction(SIGQUIT, &sigact, NULL); + sigaction(SIGPIPE, &sigact, NULL); +#else + SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE ); +#endif + count = rtlsdr_get_tuner_gains(dev, NULL); + fprintf(stderr, "Supported gain values (%d): ", count); + + count = rtlsdr_get_tuner_gains(dev, gains); + for (i = 0; i < count; i++) + fprintf(stderr, "%.1f ", gains[i] / 10.0); + fprintf(stderr, "\n"); + + /* Set the sample rate */ + verbose_set_sample_rate(dev, samp_rate); + + if (test_mode == TUNER_BENCHMARK) { + if (rtlsdr_get_tuner_type(dev) == RTLSDR_TUNER_E4000) + e4k_benchmark(); + else + fprintf(stderr, "No E4000 tuner found, aborting.\n"); + + goto exit; + } + + /* Enable test mode */ + r = rtlsdr_set_testmode(dev, 1); + + /* Reset endpoint before we start reading from it (mandatory) */ + verbose_reset_buffer(dev); + + if ((test_mode == PPM_BENCHMARK) && !sync_mode) { + fprintf(stderr, "Reporting PPM error measurement every %i seconds...\n", ppm_duration); + fprintf(stderr, "Press ^C after a few minutes.\n"); + } + + if (test_mode == NO_BENCHMARK) { + fprintf(stderr, "\nInfo: This tool will continuously" + " read from the device, and report if\n" + "samples get lost. If you observe no " + "further output, everything is fine.\n\n"); + } + + if (sync_mode) { + fprintf(stderr, "Reading samples in sync mode...\n"); + fprintf(stderr, "(Samples are being lost but not reported.)\n"); + while (!do_exit) { + r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read); + if (r < 0) { + fprintf(stderr, "WARNING: sync read failed.\n"); + break; + } + + if ((uint32_t)n_read < out_block_size) { + fprintf(stderr, "Short read, samples lost, exiting!\n"); + break; + } + underrun_test(buffer, n_read, 1); + } + } else { + fprintf(stderr, "Reading samples in async mode...\n"); + r = rtlsdr_read_async(dev, rtlsdr_callback, NULL, + 0, out_block_size); + } + + if (do_exit) { + fprintf(stderr, "\nUser cancel, exiting...\n"); + fprintf(stderr, "Samples per million lost (minimum): %i\n", (int)(1000000L * dropped_samples / total_samples)); + } + else + fprintf(stderr, "\nLibrary error %d, exiting...\n", r); + +exit: + rtlsdr_close(dev); + free (buffer); + + return r >= 0 ? r : -r; +} -- cgit v1.2.3