2 * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver
3 * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de>
4 * Copyright (C) 2012 by Hoernchen <la@tfc-server.de>
5 * Copyright (C) 2012 by Kyle Keen <keenerd@gmail.com>
6 * Copyright (C) 2012 by Youssef Touil <youssef@sdrsharp.com>
7 * Copyright (C) 2012 by Ian Gilmour <ian@sdrsharp.com>
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 #include "getopt/getopt.h"
40 #include <semaphore.h>
48 #define round(x) (x > 0.0 ? floor(x + 0.5): ceil(x - 0.5))
51 #define ADSB_RATE 2000000
52 #define ADSB_FREQ 1090000000
53 #define DEFAULT_ASYNC_BUF_NUMBER 12
54 #define DEFAULT_BUF_LENGTH (16 * 16384)
55 #define AUTO_GAIN -100
57 static pthread_t demod_thread;
58 static sem_t data_ready;
59 static volatile int do_exit = 0;
60 static rtlsdr_dev_t *dev = NULL;
62 /* look up table, could be made smaller */
63 uint8_t pyth[129][129];
65 /* todo, bundle these up in a struct */
67 int verbose_output = 0;
70 int allowed_errors = 5;
73 #define preamble_len 16
74 #define long_frame 112
75 #define short_frame 56
80 "rtl_adsb, a simple ADS-B decoder\n\n"
81 "Use:\trtl_adsb [-R] [-g gain] [-p ppm] [output file]\n"
82 "\t[-d device_index (default: 0)]\n"
83 "\t[-V verbove output (default: off)]\n"
84 "\t[-S show short frames (default: off)]\n"
85 "\t[-Q quality (0: no sanity checks, 0.5: half bit, 1: one bit (default), 2: two bits)]\n"
86 "\t[-e allowed_errors (default: 5)]\n"
87 "\t[-g tuner_gain (default: automatic)]\n"
88 "\t[-p ppm_error (default: 0)]\n"
89 "\tfilename (a '-' dumps samples to stdout)\n"
90 "\t (omitting the filename also uses stdout)\n\n"
91 "Streaming with netcat:\n"
92 "\trtl_adsb | netcat -lp 8080\n"
93 "\twhile true; do rtl_adsb | nc -lp 8080; done\n"
94 "Streaming with socat:\n"
95 "\trtl_adsb | socat -u - TCP4:sdrsharp.com:47806\n"
102 sighandler(int signum)
104 if (CTRL_C_EVENT == signum) {
105 fprintf(stderr, "Signal caught, exiting!\n");
107 rtlsdr_cancel_async(dev);
113 static void sighandler(int signum)
115 fprintf(stderr, "Signal caught, exiting!\n");
117 rtlsdr_cancel_async(dev);
121 void display(int *frame, int len)
124 if (!short_output && len <= short_frame) {
126 df = (frame[0] >> 3) & 0x1f;
127 if (quality == 0.0 && !(df==11 || df==17 || df==18 || df==19)) {
130 for (i=0; i<((len+7)/8); i++) {
131 fprintf(file, "%02x", frame[i]);}
132 fprintf(file, ";\r\n");
133 if (!verbose_output) {
135 fprintf(file, "DF=%i CA=%i\n", df, frame[0] & 0x07);
136 fprintf(file, "ICAO Address=%06x\n", frame[1] << 16 | frame[2] << 8 | frame[3]);
137 if (len <= short_frame) {
139 fprintf(file, "PI=0x%06x\n", frame[11] << 16 | frame[12] << 8 | frame[13]);
140 fprintf(file, "Type Code=%i S.Type/Ant.=%x\n", (frame[4] >> 3) & 0x1f, frame[4] & 0x07);
141 fprintf(file, "--------------\n");
144 void pyth_precompute(void)
147 double scale = 1.408 ; /* use the full 8 bits */
148 for (x=0; x<129; x++) {
149 for (y=0; y<129; y++) {
150 pyth[x][y] = (uint8_t)round(scale * sqrt(x*x + y*y));
154 inline uint8_t abs8(uint8_t x)
155 /* do not subtract 128 from the raw iq, this handles it */
162 int magnitute(uint8_t *buf, int len)
163 /* takes i/q, changes buf in place, returns new len */
166 for (i=0; i<len; i+=2) {
167 buf[i/2] = pyth[abs8(buf[i])][abs8(buf[i+1])];
172 inline uint8_t single_manchester(uint8_t a, uint8_t b, uint8_t c, uint8_t d)
173 /* takes 4 consecutive real samples, return 0 or 1, 255 on error */
179 if (quality == 0.0) {
182 if (quality == 0.5) {
183 if ( bit && bit_p && b > c) {
185 if (!bit && !bit_p && b < c) {
190 if (quality == 1.0) {
191 if ( bit && bit_p && c > b) {
193 if ( bit && !bit_p && d < b) {
195 if (!bit && bit_p && d > b) {
197 if (!bit && !bit_p && c < b) {
202 if ( bit && bit_p && c > b && d < a) {
204 if ( bit && !bit_p && c > a && d < b) {
206 if (!bit && bit_p && c < a && d > b) {
208 if (!bit && !bit_p && c < b && d > a) {
213 inline uint8_t min8(uint8_t a, uint8_t b)
218 inline uint8_t max8(uint8_t a, uint8_t b)
223 inline int preamble(uint8_t *buf, int len, int i)
224 /* returns 0/1 for preamble at index i */
229 for (i2=0; i2<preamble_len; i2++) {
235 //high = min8(high, buf[i+i2]);
239 //low = max8(low, buf[i+i2]);
249 void manchester(uint8_t *buf, int len)
250 /* overwrites magnitude buffer with valid bits (255 on errors) */
252 /* a and b hold old values to verify local manchester */
255 int i, i2, start, errors;
256 // todo, allow wrap across buffers
260 for ( ; i < (len - preamble_len); i++) {
261 if (!preamble(buf, len, i)) {
265 for (i2=0; i2<preamble_len; i2++) {
272 /* mark bits until encoding breaks */
273 for ( ; i < len; i+=2, i2++) {
274 bit = single_manchester(a, b, buf[i], buf[i+1]);
279 if (errors > allowed_errors) {
284 /* these don't have to match the bit */
289 buf[i] = buf[i+1] = 254; /* to be overwritten */
295 void messages(uint8_t *buf, int len)
297 int i, i2, start, preamble_found;
298 int data_i, index, shift, frame_len;
299 // todo, allow wrap across buffers
300 for (i=0; i<len; i++) {
303 frame_len = long_frame;
305 for (index=0; index<14; index++) {
306 adsb_frame[index] = 0;}
307 for(; i<len && buf[i]<=1 && data_i<frame_len; i++, data_i++) {
310 shift = 7 - (data_i % 8);
311 adsb_frame[index] |= (uint8_t)(1<<shift);
314 if (adsb_frame[0] == 0) {
316 if (adsb_frame[0] & 0x80) {
317 frame_len = long_frame;}
319 frame_len = short_frame;}
322 if (data_i < (frame_len-1)) {
324 display(adsb_frame, frame_len);
329 static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
334 memcpy(buffer, buf, len);
335 sem_getvalue(&data_ready, &dr_val);
337 sem_post(&data_ready);}
340 static void *demod_thread_fn(void *arg)
344 sem_wait(&data_ready);
345 len = magnitute(buffer, DEFAULT_BUF_LENGTH);
346 manchester(buffer, len);
347 messages(buffer, len);
349 rtlsdr_cancel_async(dev);
353 int main(int argc, char **argv)
356 struct sigaction sigact;
358 char *filename = NULL;
360 int i, gain = AUTO_GAIN; /* tenths of a dB */
361 uint32_t dev_index = 0;
364 char vendor[256], product[256], serial[256];
365 sem_init(&data_ready, 0, 0);
368 while ((opt = getopt(argc, argv, "d:g:p:e:Q:VS")) != -1)
372 dev_index = atoi(optarg);
375 gain = (int)(atof(optarg) * 10);
378 ppm_error = atoi(optarg);
387 allowed_errors = atoi(optarg);
390 quality = atof(optarg);
398 if (argc <= optind) {
401 filename = argv[optind];
404 buffer = malloc(DEFAULT_BUF_LENGTH * sizeof(uint8_t));
406 device_count = rtlsdr_get_device_count();
408 fprintf(stderr, "No supported devices found.\n");
412 fprintf(stderr, "Found %d device(s):\n", device_count);
413 for (i = 0; i < device_count; i++) {
414 rtlsdr_get_device_usb_strings(i, vendor, product, serial);
415 fprintf(stderr, " %d: %s, %s, SN: %s\n", i, vendor, product, serial);
417 fprintf(stderr, "\n");
419 fprintf(stderr, "Using device %d: %s\n",
420 dev_index, rtlsdr_get_device_name(dev_index));
422 r = rtlsdr_open(&dev, dev_index);
424 fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
428 sigact.sa_handler = sighandler;
429 sigemptyset(&sigact.sa_mask);
431 sigaction(SIGINT, &sigact, NULL);
432 sigaction(SIGTERM, &sigact, NULL);
433 sigaction(SIGQUIT, &sigact, NULL);
434 sigaction(SIGPIPE, &sigact, NULL);
436 SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
439 if (strcmp(filename, "-") == 0) { /* Write samples to stdout */
441 setvbuf(stdout, NULL, _IONBF, 0);
443 _setmode(_fileno(file), _O_BINARY);
446 file = fopen(filename, "wb");
448 fprintf(stderr, "Failed to open %s\n", filename);
453 /* Set the tuner gain */
454 if (gain == AUTO_GAIN) {
455 r = rtlsdr_set_tuner_gain_mode(dev, 0);
457 r = rtlsdr_set_tuner_gain_mode(dev, 1);
458 r = rtlsdr_set_tuner_gain(dev, gain);
461 fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
462 } else if (gain == AUTO_GAIN) {
463 fprintf(stderr, "Tuner gain set to automatic.\n");
465 fprintf(stderr, "Tuner gain set to %0.2f dB.\n", gain/10.0);
468 r = rtlsdr_set_freq_correction(dev, ppm_error);
469 r = rtlsdr_set_agc_mode(dev, 1);
471 /* Set the tuner frequency */
472 r = rtlsdr_set_center_freq(dev, ADSB_FREQ);
474 fprintf(stderr, "WARNING: Failed to set center freq.\n");}
476 fprintf(stderr, "Tuned to %u Hz.\n", ADSB_FREQ);}
478 /* Set the sample rate */
479 fprintf(stderr, "Sampling at %u Hz.\n", ADSB_RATE);
480 r = rtlsdr_set_sample_rate(dev, ADSB_RATE);
482 fprintf(stderr, "WARNING: Failed to set sample rate.\n");}
484 /* Reset endpoint before we start reading from it (mandatory) */
485 r = rtlsdr_reset_buffer(dev);
487 fprintf(stderr, "WARNING: Failed to reset buffers.\n");}
491 rtlsdr_read_sync(dev, NULL, 4096, NULL);
493 pthread_create(&demod_thread, NULL, demod_thread_fn, (void *)(NULL));
494 rtlsdr_read_async(dev, rtlsdr_callback, (void *)(NULL),
495 DEFAULT_ASYNC_BUF_NUMBER,
500 fprintf(stderr, "\nUser cancel, exiting...\n");}
502 fprintf(stderr, "\nLibrary error %d, exiting...\n", r);}
503 rtlsdr_cancel_async(dev);
505 if (file != stdout) {
510 return r >= 0 ? r : -r;