diff options
Diffstat (limited to 'utils')
-rw-r--r-- | utils/convenience/convenience.c | 308 | ||||
-rw-r--r-- | utils/convenience/convenience.h | 142 | ||||
-rw-r--r-- | utils/getopt/getopt.c | 1059 | ||||
-rw-r--r-- | utils/getopt/getopt.h | 180 | ||||
-rw-r--r-- | utils/make.mk | 15 | ||||
-rw-r--r-- | utils/rtl_adsb.c | 507 | ||||
-rw-r--r-- | utils/rtl_biast.c | 101 | ||||
-rw-r--r-- | utils/rtl_eeprom.c | 426 | ||||
-rw-r--r-- | utils/rtl_fm.c | 1289 | ||||
-rw-r--r-- | utils/rtl_power.c | 1015 | ||||
-rw-r--r-- | utils/rtl_sdr.c | 278 | ||||
-rw-r--r-- | utils/rtl_tcp.c | 660 | ||||
-rw-r--r-- | utils/rtl_test.c | 457 |
13 files changed, 0 insertions, 6437 deletions
diff --git a/utils/convenience/convenience.c b/utils/convenience/convenience.c deleted file mode 100644 index 00cc2cc..0000000 --- a/utils/convenience/convenience.c +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright (C) 2014 by Kyle Keen <keenerd@gmail.com> - * - * 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 <http://www.gnu.org/licenses/>. - */ - -/* a collection of user friendly tools - * todo: use strtol for more flexible int parsing - * */ - -#include <string.h> -#include <stdio.h> -#include <stdlib.h> - -#ifndef _WIN32 -#include <unistd.h> -#else -#include <windows.h> -#include <fcntl.h> -#include <io.h> -#define _USE_MATH_DEFINES -#endif - -#include <math.h> - -#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; - /* fall-through */ - case 'm': - case 'M': - suff *= 1e3; - /* fall-through */ - 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; - /* fall-through */ - case 'm': - case 'M': - suff *= 60; - /* fall-through */ - 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<count; i++) { - err1 = abs(target_gain - nearest); - err2 = abs(target_gain - gains[i]); - if (err2 < err1) { - nearest = gains[i]; - } - } - free(gains); - return nearest; -} - -int verbose_set_frequency(rtlsdr_dev_t *dev, uint32_t frequency) -{ - int r; - r = rtlsdr_set_center_freq(dev, frequency); - if (r < 0) { - fprintf(stderr, "WARNING: Failed to set center freq.\n"); - } else { - fprintf(stderr, "Tuned to %u Hz.\n", frequency); - } - return r; -} - -int verbose_set_sample_rate(rtlsdr_dev_t *dev, uint32_t samp_rate) -{ - int r; - r = rtlsdr_set_sample_rate(dev, samp_rate); - if (r < 0) { - fprintf(stderr, "WARNING: Failed to set sample rate.\n"); - } else { - fprintf(stderr, "Sampling at %u S/s.\n", samp_rate); - } - return r; -} - -int verbose_direct_sampling(rtlsdr_dev_t *dev, int on) -{ - int r; - r = rtlsdr_set_direct_sampling(dev, on); - if (r != 0) { - fprintf(stderr, "WARNING: Failed to set direct sampling mode.\n"); - return r; - } - if (on == 0) { - fprintf(stderr, "Direct sampling mode disabled.\n");} - if (on == 1) { - fprintf(stderr, "Enabled direct sampling mode, input 1/I.\n");} - if (on == 2) { - fprintf(stderr, "Enabled direct sampling mode, input 2/Q.\n");} - return r; -} - -int verbose_offset_tuning(rtlsdr_dev_t *dev) -{ - int r; - r = rtlsdr_set_offset_tuning(dev, 1); - if (r != 0) { - fprintf(stderr, "WARNING: Failed to set offset tuning.\n"); - } else { - fprintf(stderr, "Offset tuning mode enabled.\n"); - } - return r; -} - -int verbose_auto_gain(rtlsdr_dev_t *dev) -{ - int r; - r = rtlsdr_set_tuner_gain_mode(dev, 0); - if (r != 0) { - fprintf(stderr, "WARNING: Failed to set tuner gain.\n"); - } else { - fprintf(stderr, "Tuner gain set to automatic.\n"); - } - return r; -} - -int verbose_gain_set(rtlsdr_dev_t *dev, int gain) -{ - int r; - r = rtlsdr_set_tuner_gain_mode(dev, 1); - if (r < 0) { - fprintf(stderr, "WARNING: Failed to enable manual gain.\n"); - return r; - } - 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 %0.2f dB.\n", gain/10.0); - } - return r; -} - -int verbose_ppm_set(rtlsdr_dev_t *dev, int ppm_error) -{ - int r; - if (ppm_error == 0) { - return 0;} - r = rtlsdr_set_freq_correction(dev, ppm_error); - if (r < 0) { - fprintf(stderr, "WARNING: Failed to set ppm error.\n"); - } else { - fprintf(stderr, "Tuner error set to %i ppm.\n", ppm_error); - } - return r; -} - -int verbose_reset_buffer(rtlsdr_dev_t *dev) -{ - int r; - r = rtlsdr_reset_buffer(dev); - if (r < 0) { - fprintf(stderr, "WARNING: Failed to reset buffers.\n");} - return r; -} - -int verbose_device_search(char *s) -{ - int i, device_count, device, offset; - char *s2; - char vendor[256], product[256], serial[256]; - device_count = rtlsdr_get_device_count(); - if (!device_count) { - fprintf(stderr, "No supported devices found.\n"); - return -1; - } - fprintf(stderr, "Found %d device(s):\n", device_count); - for (i = 0; i < device_count; i++) { - rtlsdr_get_device_usb_strings(i, vendor, product, serial); - fprintf(stderr, " %d: %s, %s, SN: %s\n", i, vendor, product, serial); - } - fprintf(stderr, "\n"); - /* does string look like raw id number */ - device = (int)strtol(s, &s2, 0); - if (s2[0] == '\0' && device >= 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 deleted file mode 100644 index 1faa2af..0000000 --- a/utils/convenience/convenience.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2014 by Kyle Keen <keenerd@gmail.com> - * - * 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 <http://www.gnu.org/licenses/>. - */ - -/* 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 deleted file mode 100644 index f1d461a..0000000 --- a/utils/getopt/getopt.c +++ /dev/null @@ -1,1059 +0,0 @@ -/* 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 <stdio.h>. - Ditto for AIX 3.2 and <stdlib.h>. */ -#ifndef _NO_PROTO -# define _NO_PROTO -#endif - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#if !defined __STDC__ || !__STDC__ -/* This is a separate conditional since some stdc systems - reject `defined (const)'. */ -# ifndef const -# define const -# endif -#endif - -#include <stdio.h> - -/* 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 <gnu-versions.h> -# 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 <stdlib.h> -# include <unistd.h> -#endif /* GNU C library. */ - -#ifdef VMS -# include <unixlib.h> -# if HAVE_STRING_H - 0 -# include <string.h> -# endif -#endif - -#ifndef _ -/* This is for other GNU distributions with internationalized messages. */ -# if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC -# include <libintl.h> -# 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 <string.h> -# define my_index strchr -#else - -# if 1 //HAVE_STRING_H -# include <string.h> -# else -# include <strings.h> -# 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 <stdlib.h> -#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 deleted file mode 100644 index a1b8dd6..0000000 --- a/utils/getopt/getopt.h +++ /dev/null @@ -1,180 +0,0 @@ -/* 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 <features.h>, but - that does not exist if we are standalone. So: if __GNU_LIBRARY__ is - not defined, include <ctype.h>, which will pull in <features.h> 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 <ctype.h> -#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 deleted file mode 100644 index aef23d6..0000000 --- a/utils/make.mk +++ /dev/null @@ -1,15 +0,0 @@ -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 -lr820t -lm -L. - -$(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) diff --git a/utils/rtl_adsb.c b/utils/rtl_adsb.c deleted file mode 100644 index 7aea8dd..0000000 --- a/utils/rtl_adsb.c +++ /dev/null @@ -1,507 +0,0 @@ -/* - * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver - * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de> - * Copyright (C) 2012 by Hoernchen <la@tfc-server.de> - * Copyright (C) 2012 by Kyle Keen <keenerd@gmail.com> - * Copyright (C) 2012 by Youssef Touil <youssef@sdrsharp.com> - * Copyright (C) 2012 by Ian Gilmour <ian@sdrsharp.com> - * - * 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 <http://www.gnu.org/licenses/>. - */ - - -#include <errno.h> -#include <signal.h> -#include <string.h> -#include <stdio.h> -#include <stdlib.h> -#include <math.h> - -#ifndef _WIN32 -#include <unistd.h> -#else -#include <windows.h> -#include <fcntl.h> -#include <io.h> -#include "getopt/getopt.h" -#endif - -#include <pthread.h> -#include <libusb.h> - -#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" - "\t[-T enable bias-T on GPIO PIN 0 (works for rtl-sdr.com v3 dongles)]\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<len; i+=2) { - m = (uint16_t*)(&buf[i]); - *m = squares[buf[i]] + squares[buf[i+1]]; - } - return len/2; -} - -static inline uint16_t single_manchester(uint16_t a, uint16_t b, uint16_t c, uint16_t d) -/* takes 4 consecutive real samples, return 0 or 1, BADSAMPLE on error */ -{ - int bit, bit_p; - bit_p = a > 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; -} - -static inline uint16_t min16(uint16_t a, uint16_t b) -{ - return a<b ? a : b; -} - -static inline uint16_t max16(uint16_t a, uint16_t b) -{ - return a>b ? a : b; -} - -static inline 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<preamble_len; i2++) { - switch (i2) { - case 0: - case 2: - case 7: - case 9: - //high = min16(high, buf[i+i2]); - high = buf[i+i2]; - break; - default: - //low = max16(low, buf[i+i2]); - low = buf[i+i2]; - break; - } - if (high <= low) { - return 0;} - } - return 1; -} - -void manchester(uint16_t *buf, int len) -/* overwrites magnitude buffer with valid bits (BADSAMPLE on errors) */ -{ - /* a and b hold old values to verify local manchester */ - uint16_t a=0, b=0; - uint16_t bit; - int i, i2, start, errors; - int maximum_i = len - 1; // len-1 since we look at i and i+1 - // todo, allow wrap across buffers - i = 0; - while (i < maximum_i) { - /* find preamble */ - for ( ; i < (len - preamble_len); i++) { - if (!preamble(buf, i)) { - continue;} - a = buf[i]; - b = buf[i+1]; - for (i2=0; i2<preamble_len; i2++) { - buf[i+i2] = MESSAGEGO;} - i += preamble_len; - break; - } - i2 = start = i; - errors = 0; - /* mark bits until encoding breaks */ - for ( ; i < maximum_i; i+=2, i2++) { - bit = single_manchester(a, b, buf[i], buf[i+1]); - a = buf[i]; - b = buf[i+1]; - if (bit == BADSAMPLE) { - errors += 1; - if (errors > 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<len; i++) { - if (buf[i] > 1) { - continue;} - frame_len = long_frame; - data_i = 0; - for (index=0; index<14; index++) { - adsb_frame[index] = 0;} - for(; i<len && buf[i]<=1 && data_i<frame_len; i++, data_i++) { - if (buf[i]) { - index = data_i / 8; - shift = 7 - (data_i % 8); - adsb_frame[index] |= (uint8_t)(1<<shift); - } - if (data_i == 7) { - if (adsb_frame[0] == 0) { - break;} - if (adsb_frame[0] & 0x80) { - frame_len = long_frame;} - else { - frame_len = short_frame;} - } - } - if (data_i < (frame_len-1)) { - continue;} - display(adsb_frame, frame_len); - fflush(file); - } -} - -static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx) -{ - if (do_exit) { - return;} - memcpy(buffer, buf, len); - safe_cond_signal(&ready, &ready_m); -} - -static void *demod_thread_fn(void *arg) -{ - int len; - while (!do_exit) { - safe_cond_wait(&ready, &ready_m); - len = magnitute(buffer, DEFAULT_BUF_LENGTH); - manchester((uint16_t*)buffer, len); - messages((uint16_t*)buffer, len); - } - rtlsdr_cancel_async(dev); - return 0; -} - -int main(int argc, char **argv) -{ -#ifndef _WIN32 - struct sigaction sigact; -#endif - char *filename = NULL; - int r, opt; - int gain = AUTO_GAIN; /* tenths of a dB */ - int dev_index = 0; - int dev_given = 0; - int ppm_error = 0; - int enable_biastee = 0; - pthread_cond_init(&ready, NULL); - pthread_mutex_init(&ready_m, NULL); - squares_precompute(); - - while ((opt = getopt(argc, argv, "d:g:p:e:Q:VST")) != -1) - { - switch (opt) { - case 'd': - dev_index = verbose_device_search(optarg); - dev_given = 1; - break; - case 'g': - gain = (int)(atof(optarg) * 10); - break; - case 'p': - ppm_error = atoi(optarg); - break; - case 'V': - verbose_output = 1; - break; - case 'S': - short_output = 1; - break; - case 'e': - allowed_errors = atoi(optarg); - break; - case 'Q': - quality = (int)(atof(optarg) * 10); - break; - case 'T': - enable_biastee = 1; - break; - default: - usage(); - return 0; - } - } - - if (argc <= optind) { - filename = "-"; - } else { - filename = argv[optind]; - } - - buffer = malloc(DEFAULT_BUF_LENGTH * 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 - - if (strcmp(filename, "-") == 0) { /* Write samples to stdout */ - file = stdout; - setvbuf(stdout, NULL, _IONBF, 0); -#ifdef _WIN32 - _setmode(_fileno(file), _O_BINARY); -#endif - } else { - file = fopen(filename, "wb"); - if (!file) { - fprintf(stderr, "Failed to open %s\n", filename); - exit(1); - } - } - - /* 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); - r = rtlsdr_set_agc_mode(dev, 1); - - /* Set the tuner frequency */ - verbose_set_frequency(dev, ADSB_FREQ); - - /* Set the sample rate */ - verbose_set_sample_rate(dev, ADSB_RATE); - - rtlsdr_set_bias_tee(dev, enable_biastee); - if (enable_biastee) - fprintf(stderr, "activated bias-T on GPIO PIN 0\n"); - - /* Reset endpoint before we start reading from it (mandatory) */ - verbose_reset_buffer(dev); - - pthread_create(&demod_thread, NULL, demod_thread_fn, (void *)(NULL)); - rtlsdr_read_async(dev, rtlsdr_callback, (void *)(NULL), - DEFAULT_ASYNC_BUF_NUMBER, - DEFAULT_BUF_LENGTH); - - if (do_exit) { - fprintf(stderr, "\nUser cancel, exiting...\n");} - else { - fprintf(stderr, "\nLibrary error %d, exiting...\n", r);} - rtlsdr_cancel_async(dev); - pthread_cancel(demod_thread); - pthread_join(demod_thread, NULL); - pthread_cond_destroy(&ready); - pthread_mutex_destroy(&ready_m); - - if (file != stdout) { - fclose(file);} - - rtlsdr_close(dev); - free(buffer); - return r >= 0 ? r : -r; -} - diff --git a/utils/rtl_biast.c b/utils/rtl_biast.c deleted file mode 100644 index 185e838..0000000 --- a/utils/rtl_biast.c +++ /dev/null @@ -1,101 +0,0 @@ -/* - * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver - * rtl_biast, tool to set bias tee gpio output - * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de> - * - * 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 <http://www.gnu.org/licenses/>. - */ - -#include <string.h> -#include <stdio.h> -#include <stdlib.h> - -#ifndef _WIN32 -#include <unistd.h> -#else -#include <windows.h> -#include "getopt/getopt.h" -#endif - -#include "rtl-sdr.h" -#include "convenience/convenience.h" - -static rtlsdr_dev_t *dev = NULL; - -void usage(void) -{ - fprintf(stderr, - "rtl_biast, a tool for turning the RTL-SDR.com \n" - "bias tee or any GPIO ON and OFF. Example to turn on the \n" - "bias tee: rtl_biast -d 0 -b 1\n" - "Any GPIO: rtl_biast -d 0 -g 1 -b 1\n\n" - "Usage:\n" - "\t[-d device_index (default: 0)]\n" - "\t[-b bias_on (default: 0)]\n" - "\t[-g GPIO select (default: 0)]\n"); - exit(1); -} - -int main(int argc, char **argv) -{ - int i, r, opt; - int dev_index = 0; - int dev_given = 0; - uint32_t bias_on = 0; - uint32_t gpio_pin = 0; - int device_count; - - while ((opt = getopt(argc, argv, "d:b:g:h?")) != -1) { - switch (opt) { - case 'd': - dev_index = verbose_device_search(optarg); - dev_given = 1; - break; - case 'b': - bias_on = atoi(optarg); - break; - case 'g': - gpio_pin = atoi(optarg); - break; - default: - usage(); - break; - } - } - - if (!dev_given) { - dev_index = verbose_device_search("0"); - } - - if (dev_index < 0) { - exit(1); - } - - r = rtlsdr_open(&dev, dev_index); - rtlsdr_set_bias_tee_gpio(dev, gpio_pin, bias_on); - -exit: - /* - * Note - rtlsdr_close() in this tree does not clear the bias tee - * GPIO line, so it leaves the bias tee enabled if a client program - * doesn't explictly disable it. - * - * If that behaviour changes then another rtlsdr_close() will be - * needed that takes some extension flags, and one of them should - * be to either explicitly close the biast or leave it alone. - */ - rtlsdr_close(dev); - - return r >= 0 ? r : -r; -} diff --git a/utils/rtl_eeprom.c b/utils/rtl_eeprom.c deleted file mode 100644 index 24be900..0000000 --- a/utils/rtl_eeprom.c +++ /dev/null @@ -1,426 +0,0 @@ -/* - * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver - * rtl_eeprom, EEPROM modification tool - * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de> - * - * 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 <http://www.gnu.org/licenses/>. - */ - -#include <string.h> -#include <stdio.h> -#include <stdlib.h> - -#ifndef _WIN32 -#include <unistd.h> -#else -#include <windows.h> -#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 <str> set manufacturer string]\n" - "\t[-p <str> set product string]\n" - "\t[-s <str> set serial number string]\n" - "\t[-i <0,1> disable/enable IR-endpoint]\n" - "\t[-g <conf> generate default config and write to device]\n" - "\t[ <conf> 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 <filename> write dumped file to device]\n" - "\t[-r <filename> 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; - /* fall-through */ - 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 - 1); - - if (product_str) - strncpy((char*)&conf.product, product_str, MAX_STR_SIZE - 1); - - if (serial_str) { - conf.have_serial = 1; - strncpy((char*)&conf.serial, serial_str, MAX_STR_SIZE - 1); - } - - 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 deleted file mode 100644 index 7c84332..0000000 --- a/utils/rtl_fm.c +++ /dev/null @@ -1,1289 +0,0 @@ -/* - * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver - * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de> - * Copyright (C) 2012 by Hoernchen <la@tfc-server.de> - * Copyright (C) 2012 by Kyle Keen <keenerd@gmail.com> - * Copyright (C) 2013 by Elias Oenal <EliasOenal@gmail.com> - * - * 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 <http://www.gnu.org/licenses/>. - */ - - -/* - * 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 <errno.h> -#include <signal.h> -#include <string.h> -#include <stdio.h> -#include <stdlib.h> - -#ifndef _WIN32 -#include <unistd.h> -#else -#include <windows.h> -#include <fcntl.h> -#include <io.h> -#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 <math.h> -#include <pthread.h> -#include <libusb.h> - -#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[-T enable bias-T on GPIO PIN 0 (works for rtl-sdr.com v3 dongles)]\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 1 (usually I)\n" - "\t direct2: enable direct sampling 2 (usually Q)\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; i<len; i+=8) { - /* uint8_t negation = 255 - x */ - tmp = 255 - buf[i+3]; - buf[i+3] = buf[i+2]; - buf[i+2] = tmp; - - buf[i+4] = 255 - buf[i+4]; - buf[i+5] = 255 - buf[i+5]; - - tmp = 255 - buf[i+6]; - buf[i+6] = buf[i+7]; - buf[i+7] = tmp; - } -} - -void low_pass(struct demod_state *d) -/* simple square window FIR */ -{ - int i=0, i2=0; - while (i < d->lp_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; i2<step; i2++) { - sum += (int)signal2[i + i2]; - } - //signal2[i/step] = (int16_t)(sum / step); - signal2[i/step] = (int16_t)(sum); - } - signal2[i/step + 1] = signal2[i/step]; - return len / step; -} - -void low_pass_real(struct demod_state *s) -/* simple square window FIR */ -// add support for upsampling? -{ - int i=0, i2=0; - int fast = (int)s->rate_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<length; i+=4) { - a = c; - b = d; - c = e; - d = f; - e = data[i-2]; - f = data[i]; - data[i/2] = (a + (b+e)*5 + (c+d)*10 + f) >> 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<length; d+=2) { - temp = data[d]; - sum = 0; - sum += (hist[0] + hist[8]) * fir[1]; - sum += (hist[1] + hist[7]) * fir[2]; - sum += (hist[2] + hist[6]) * fir[3]; - sum += (hist[3] + hist[5]) * fir[4]; - sum += hist[4] * fir[5]; - data[d] = sum >> 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<<atan_lut_coef)) / 3.14159 * (1<<14)); - } - - return 0; -} - -int polar_disc_lut(int ar, int aj, int br, int bj) -{ - int cr, cj, x, x_abs; - - multiply(ar, aj, br, -bj, &cr, &cj); - - /* special cases */ - if (cr == 0 || cj == 0) { - if (cr == 0 && cj == 0) - {return 0;} - if (cr == 0 && cj > 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<len; i+=step) { - sum += samples[i]; - } - ave = sum / (len * step); - sum = 0; - for (i=0; i<len; i+=step) { - sum += abs(samples[i] - ave); - } - return sum / (len / step); -} - -int rms(int16_t *samples, int len, int step) -/* largely lifted from rtl_power */ -{ - int i; - long p, t, s; - double dc, err; - - p = t = 0L; - for (i=0; i<len; i+=step) { - s = (long)samples[i]; - t += s; - p += s * s; - } - /* correct for dc offset in squares */ - dc = (double)(t*step) / (double)len; - err = t * 2 * dc - dc * dc * len; - - return (int)sqrt((p-err) / len); -} - -void arbitrary_upsample(int16_t *buf1, int16_t *buf2, int len1, int len2) -/* linear interpolation, len1 < len2 */ -{ - int i = 1; - int j = 0; - int tick = 0; - double frac; // use integers... - while (j < len2) { - frac = (double)tick / (double)len2; - buf2[j] = (int16_t)(buf1[i-1]*(1-frac) + buf1[i]*frac); - j++; - tick += len1; - if (tick > 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; j<len2; j++) { - buf2[j] = buf2[j] * len2 / len1;} -} - -void arbitrary_resample(int16_t *buf1, int16_t *buf2, int len1, int len2) -/* up to you to calculate lengths and make sure it does not go OOB - * okay for buffers to overlap, if you are downsampling */ -{ - if (len1 < len2) { - arbitrary_upsample(buf1, buf2, len1, len2); - } else { - arbitrary_downsample(buf1, buf2, len1, len2); - } -} - -void full_demod(struct demod_state *d) -{ - int i, ds_p; - int sr = 0; - ds_p = d->downsample_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; i<d->lp_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; i<s->mute; 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, dongle.direct_sampling);} - 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; - if (stop == (char *)1) { // no stop or step given - s->freqs[s->freq_len] = (uint32_t) atofs(start); - s->freq_len++; - return; - } - stop[-1] = '\0'; - step = strchr(stop, ':') + 1; - if (step == (char *)1) { // no step given - s->freqs[s->freq_len] = (uint32_t) atofs(start); - s->freq_len++; - s->freqs[s->freq_len] = (uint32_t) atofs(stop); - s->freq_len++; - stop[-1] = ':'; - return; - } - 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; - int enable_biastee = 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:hT")) != -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("direct2", optarg) == 0) { - dongle.direct_sampling = 2;} - 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 'T': - enable_biastee = 1; - 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); - } - - rtlsdr_set_bias_tee(dongle.dev, enable_biastee); - if (enable_biastee) - fprintf(stderr, "activated bias-T on GPIO PIN 0\n"); - - 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 deleted file mode 100644 index 6204de2..0000000 --- a/utils/rtl_power.c +++ /dev/null @@ -1,1015 +0,0 @@ -/* - * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver - * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de> - * Copyright (C) 2012 by Hoernchen <la@tfc-server.de> - * Copyright (C) 2012 by Kyle Keen <keenerd@gmail.com> - * - * 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 <http://www.gnu.org/licenses/>. - */ - - -/* - * 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 <errno.h> -#include <signal.h> -#include <string.h> -#include <stdio.h> -#include <stdlib.h> -#include <time.h> - -#ifndef _WIN32 -#include <unistd.h> -#else -#include <windows.h> -#include <fcntl.h> -#include <io.h> -#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 <math.h> -#include <pthread.h> -#include <libusb.h> - -#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" - "\t[-T enable bias-T on GPIO PIN 0 (works for rtl-sdr.com v3 dongles)]\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<N_WAVE*3/4; i++) - { - d = (double)i * 2.0 * M_PI / N_WAVE; - Sinewave[i] = (int)round(32767*sin(d)); - //printf("%i\n", Sinewave[i]); - } -} - -static inline int16_t FIX_MPY(int16_t a, int16_t b) -/* fixed point multiply and scale */ -{ - int c = ((int)a * (int)b) >> 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<l; ++m) { - j = m << k; - wr = Sinewave[j+N_WAVE/4]; - wi = -Sinewave[j]; - if (shift) { - wr >>= 1; wi >>= 1;} - for (i=m; i<n; i+=istep) { - j = i + l; - tr = FIX_MPY(wr,iq[2*j]) - FIX_MPY(wi,iq[2*j+1]); - ti = FIX_MPY(wr,iq[2*j+1]) + FIX_MPY(wi,iq[2*j]); - qr = iq[2*i]; - qi = iq[2*i+1]; - if (shift) { - qr >>= 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; i<buf_len; i++) { - s = (int)buf[i] - 127; - t += (long)s; - p += (long)(s * s); - } - /* correct for dc offset in squares */ - dc = (double)t / (double)buf_len; - err = t * 2 * dc - dc * dc * buf_len; - p -= (long)round(err); - - if (!peak_hold) { - ts->avg[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; - if (stop == (char *)1) { - fprintf(stderr, "Bad frequency range specification: %s\n", arg); - exit(1); - } - stop[-1] = '\0'; - step = strchr(stop, ':') + 1; - if (step == (char *)1) { - fprintf(stderr, "Bad frequency range specification: %s\n", arg); - exit(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<<i) * downsample); - if (bin_size <= (double)max_size) { - break;} - } - /* unless giant bins */ - if (max_size >= 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<<bin_e) * downsample; - if (buf_len < DEFAULT_BUF_LENGTH) { - buf_len = DEFAULT_BUF_LENGTH; - } - /* build the array */ - for (i=0; i<tune_count; i++) { - ts = &tunes[i]; - ts->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<<bin_e) * sizeof(long)); - if (!ts->avg) { - fprintf(stderr, "Error: malloc.\n"); - exit(1); - } - for (j=0; j<(1<<bin_e); j++) { - ts->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<<bin_e)); - fprintf(stderr, "Logged FFT bins: %i\n", \ - (int)((double)(tune_count * (1<<bin_e)) * (1.0-crop))); - fprintf(stderr, "FFT bin size: %0.2fHz\n", bin_size); - fprintf(stderr, "Buffer size: %i bytes (%0.2fms)\n", buf_len, 1000 * 0.5 * (float)buf_len / (float)bw_used); -} - -void retune(rtlsdr_dev_t *d, int freq) -{ - uint8_t dump[BUFFER_DUMP]; - int n_read; - rtlsdr_set_center_freq(d, (uint32_t)freq); - /* wait for settling and flush buffer */ - usleep(5000); - rtlsdr_read_sync(d, &dump, BUFFER_DUMP, &n_read); - if (n_read != BUFFER_DUMP) { - fprintf(stderr, "Error: bad retune.\n");} -} - -void fifth_order(int16_t *data, int length) -/* for half of interleaved data */ -{ - int i; - int a, b, c, d, e, f; - a = data[0]; - b = data[2]; - c = data[4]; - d = data[6]; - e = data[8]; - f = data[10]; - /* a downsample should improve resolution, so don't fully shift */ - /* ease in instead of being stateful */ - data[0] = ((a+b)*10 + (c+d)*5 + d + f) >> 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<length; i+=4) { - a = c; - b = d; - c = e; - d = f; - e = data[i-2]; - f = data[i]; - data[i/2] = (a + (b+e)*5 + (c+d)*10 + f) >> 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<length; d+=2) { - temp = data[d]; - sum = 0; - sum += (hist[0] + hist[8]) * fir[1]; - sum += (hist[1] + hist[7]) * fir[2]; - sum += (hist[2] + hist[6]) * fir[3]; - sum += (hist[3] + hist[5]) * fir[4]; - sum += hist[4] * fir[5]; - data[d] = (int16_t)(sum >> 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<tune_count; i++) { - if (do_exit >= 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; j<buf_len; j++) { - fft_buf[j] = (int16_t)ts->buf8[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; j<bin_len; j++) { - w = (int32_t)fft_buf[offset+j*2]; - w *= (int32_t)(window_coefs[j]); - //w /= (int32_t)(ds); - fft_buf[offset+j*2] = (int16_t)w; - w = (int32_t)fft_buf[offset+j*2+1]; - w *= (int32_t)(window_coefs[j]); - //w /= (int32_t)(ds); - fft_buf[offset+j*2+1] = (int16_t)w; - } - fix_fft(fft_buf+offset, bin_e); - if (!peak_hold) { - for (j=0; j<bin_len; j++) { - ts->avg[j] += real_conj(fft_buf[offset+j*2], fft_buf[offset+j*2+1]); - } - } else { - for (j=0; j<bin_len; j++) { - ts->avg[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; i<len/2; i++) { - tmp = ts->avg[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; i<len; i++) { - ts->avg[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; - int enable_biastee = 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:1PDOhT")) != -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 'T': - enable_biastee = 1; - 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); - - rtlsdr_set_bias_tee(dev, enable_biastee); - if (enable_biastee) - fprintf(stderr, "activated bias-T on GPIO PIN 0\n"); - - 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<length; i++) { - window_coefs[i] = (int)(256*window_fn(i, length)); - } - while (!do_exit) { - scanner(); - time_now = time(NULL); - if (time_now < next_tick) { - continue;} - // time, Hz low, Hz high, Hz step, samples, dbm, dbm, ... - cal_time = localtime(&time_now); - strftime(t_str, 50, "%Y-%m-%d, %H:%M:%S", cal_time); - for (i=0; i<tune_count; i++) { - fprintf(file, "%s, ", t_str); - csv_dbm(&tunes[i]); - } - fflush(file); - while (time(NULL) >= 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<tune_count; i++) { - // free(tunes[i].avg); - // free(tunes[i].buf8); - //} - return r >= 0 ? r : -r; -} - -// vim: tabstop=8:softtabstop=8:shiftwidth=8:noexpandtab diff --git a/utils/rtl_sdr.c b/utils/rtl_sdr.c deleted file mode 100644 index e6537ca..0000000 --- a/utils/rtl_sdr.c +++ /dev/null @@ -1,278 +0,0 @@ -/* - * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver - * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de> - * - * 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 <http://www.gnu.org/licenses/>. - */ - -#include <errno.h> -#include <signal.h> -#include <string.h> -#include <stdio.h> -#include <stdlib.h> - -#ifndef _WIN32 -#include <unistd.h> -#else -#include <windows.h> -#include <io.h> -#include <fcntl.h> -#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 deleted file mode 100644 index 84f5591..0000000 --- a/utils/rtl_tcp.c +++ /dev/null @@ -1,660 +0,0 @@ -/* - * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver - * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de> - * Copyright (C) 2012-2013 by Hoernchen <la@tfc-server.de> - * - * 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 <http://www.gnu.org/licenses/>. - */ - -#include <errno.h> -#include <signal.h> -#include <string.h> -#include <stdio.h> -#include <stdlib.h> - -#ifndef _WIN32 -#include <unistd.h> -#include <arpa/inet.h> -#include <sys/socket.h> -#include <sys/types.h> -#include <sys/socket.h> -#include <sys/time.h> -#include <netdb.h> -#include <netinet/in.h> -#include <fcntl.h> -#else -#include <winsock2.h> -#include <ws2tcpip.h> -#include "getopt/getopt.h" -#endif - -#include <pthread.h> - -#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 - -#define DEFAULT_PORT_STR "1234" -#define DEFAULT_SAMPLE_RATE_HZ 2048000 -#define DEFAULT_MAX_NUM_BUFFERS 500 - -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 enable_biastee = 0; -static int global_numq = 0; -static struct llist *ll_buffers = 0; -static int llbuf_num = DEFAULT_MAX_NUM_BUFFERS; - -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"); - printf("Usage:\t[-a listen address]\n"); - printf("\t[-p listen port (default: %s)]\n", DEFAULT_PORT_STR); - printf("\t[-f frequency to tune to [Hz]]\n"); - printf("\t[-g gain (default: 0 for auto)]\n"); - printf("\t[-s samplerate in Hz (default: %d Hz)]\n", DEFAULT_SAMPLE_RATE_HZ); - printf("\t[-b number of buffers (default: 15, set by library)]\n"); - printf("\t[-n max number of linked list buffers to keep (default: %d)]\n", DEFAULT_MAX_NUM_BUFFERS); - printf("\t[-d device index (default: 0)]\n"); - printf("\t[-P ppm_error (default: 0)]\n"); - printf("\t[-T enable bias-T on GPIO PIN 0 (works for rtl-sdr.com v3 dongles)]\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; - case 0x0e: - printf("set bias tee %d\n", ntohl(cmd.param)); - rtlsdr_set_bias_tee(dev, (int)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"; - const char *port = DEFAULT_PORT_STR; - uint32_t frequency = 100000000, samp_rate = DEFAULT_SAMPLE_RATE_HZ; - struct sockaddr_storage local, remote; - struct addrinfo *ai; - struct addrinfo *aiHead; - struct addrinfo hints; - char hostinfo[NI_MAXHOST]; - char portinfo[NI_MAXSERV]; - char remhostinfo[NI_MAXHOST]; - char remportinfo[NI_MAXSERV]; - int aiErr; - 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 = 0; - 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:T")) != -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 = strdup(optarg); - break; - case 'p': - port = strdup(optarg); - break; - case 'b': - buf_num = atoi(optarg); - break; - case 'n': - llbuf_num = atoi(optarg); - break; - case 'P': - ppm_error = atoi(optarg); - break; - case 'T': - enable_biastee = 1; - 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); - } - - rtlsdr_set_bias_tee(dev, enable_biastee); - if (enable_biastee) - fprintf(stderr, "activated bias-T on GPIO PIN 0\n"); - - /* 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); - - hints.ai_flags = AI_PASSIVE; /* Server mode. */ - hints.ai_family = PF_UNSPEC; /* IPv4 or IPv6. */ - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - - if ((aiErr = getaddrinfo(addr, - port, - &hints, - &aiHead )) != 0) - { - fprintf(stderr, "local address %s ERROR - %s.\n", - addr, gai_strerror(aiErr)); - return(-1); - } - memcpy(&local, aiHead->ai_addr, aiHead->ai_addrlen); - - for (ai = aiHead; ai != NULL; ai = ai->ai_next) { - aiErr = getnameinfo((struct sockaddr *)ai->ai_addr, ai->ai_addrlen, - hostinfo, NI_MAXHOST, - portinfo, NI_MAXSERV, NI_NUMERICSERV | NI_NUMERICHOST); - if (aiErr) - fprintf( stderr, "getnameinfo ERROR - %s.\n",hostinfo); - - listensocket = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); - if (listensocket < 0) - continue; - - r = 1; - setsockopt(listensocket, SOL_SOCKET, SO_REUSEADDR, (char *)&r, sizeof(int)); - setsockopt(listensocket, SOL_SOCKET, SO_LINGER, (char *)&ling, sizeof(ling)); - - if (bind(listensocket, (struct sockaddr *)&local, sizeof(local))) - fprintf(stderr, "rtl_tcp bind error: %s", strerror(errno)); - else - break; - } - -#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:%s' in OsmoSDR " - "(gr-osmosdr) source\n" - "to receive samples in GRC and control " - "rtl_tcp parameters (frequency, gain, ...).\n", - hostinfo, portinfo); - 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)); - - getnameinfo((struct sockaddr *)&remote, rlen, - remhostinfo, NI_MAXHOST, - remportinfo, NI_MAXSERV, NI_NUMERICSERV); - printf("client accepted! %s %s\n", remhostinfo, remportinfo); - - 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 deleted file mode 100644 index 9b44097..0000000 --- a/utils/rtl_test.c +++ /dev/null @@ -1,457 +0,0 @@ -/* - * 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 <steve@steve-m.de> - * Copyright (C) 2012-2014 by Kyle Keen <keenerd@gmail.com> - * Copyright (C) 2014 by Michael Tatarinov <kukabu@gmail.com> - * - * 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 <http://www.gnu.org/licenses/>. - */ - -#include <errno.h> -#include <signal.h> -#include <string.h> -#include <stdio.h> -#include <stdlib.h> -#include <math.h> - -#ifdef __APPLE__ -#include <sys/time.h> -#else -#include <time.h> -#endif - -#ifndef _WIN32 -#include <unistd.h> -#else -#include <windows.h> -#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 - -struct time_generic -/* holds all the platform specific values */ -{ -#ifndef _WIN32 - time_t tv_sec; - long tv_nsec; -#else - long tv_sec; - long tv_nsec; - int init; - LARGE_INTEGER frequency; - LARGE_INTEGER ticks; -#endif -}; - -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 time_generic *tg) -{ - int rv = ENOSYS; - struct timespec ts; - -#ifdef __unix__ - rv = clock_gettime(CLOCK_MONOTONIC, &ts); - tg->tv_sec = ts.tv_sec; - tg->tv_nsec = ts.tv_nsec; -#elif __APPLE__ - struct timeval tv; - - rv = gettimeofday(&tv, NULL); - tg->tv_sec = tv.tv_sec; - tg->tv_nsec = tv.tv_usec * 1000; -#endif - return rv; -} -#endif - -#ifdef _WIN32 -static int ppm_gettime(struct time_generic *tg) -{ - int rv; - int64_t frac; - if (!tg->init) { - QueryPerformanceFrequency(&tg->frequency); - tg->init = 1; - } - rv = QueryPerformanceCounter(&tg->ticks); - tg->tv_sec = tg->ticks.QuadPart / tg->frequency.QuadPart; - frac = (int64_t)(tg->ticks.QuadPart - (tg->tv_sec * tg->frequency.QuadPart)); - tg->tv_nsec = (long)(frac * 1000000000L / (int64_t)tg->frequency.QuadPart); - return !rv; -} -#endif - -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 time_generic ppm_now; - static struct time_generic 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 = ppm_now; - 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 = ppm_now; - nsamples = 0; -} - -static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx) -{ - underrun_test(buf, len, 0); - - if (test_mode == PPM_BENCHMARK) - ppm_test(len); -} - -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 %u 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; -} |