1 /*
2  * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver
3  * rtl_test, test and benchmark tool
4  *
5  * Copyright (C) 2012-2014 by Steve Markgraf <steve@steve-m.de>
6  * Copyright (C) 2012-2014 by Kyle Keen <keenerd@gmail.com>
7  * Copyright (C) 2014 by Michael Tatarinov <kukabu@gmail.com>
8  *
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.
13  *
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.
18  *
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/>.
21  */
22 
23 #include <errno.h>
24 #include <signal.h>
25 #include <string.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <math.h>
29 
30 #ifdef __APPLE__
31 #include <sys/time.h>
32 #else
33 #include <time.h>
34 #endif
35 
36 #ifndef _WIN32
37 #include <unistd.h>
38 #else
39 #include <windows.h>
40 #include "getopt/getopt.h"
41 #endif
42 
43 #include "rtl-sdr.h"
44 #include "convenience/convenience.h"
45 
46 #define DEFAULT_SAMPLE_RATE		2048000
47 #define DEFAULT_BUF_LENGTH		(16 * 16384)
48 #define MINIMAL_BUF_LENGTH		512
49 #define MAXIMAL_BUF_LENGTH		(256 * 16384)
50 
51 #define MHZ(x)	((x)*1000*1000)
52 
53 #define PPM_DURATION			10
54 #define PPM_DUMP_TIME			5
55 
56 struct time_generic
57 /* holds all the platform specific values */
58 {
59 #ifndef _WIN32
60 	time_t tv_sec;
61 	long tv_nsec;
62 #else
63 	long tv_sec;
64 	long tv_nsec;
65 	int init;
66 	LARGE_INTEGER frequency;
67 	LARGE_INTEGER ticks;
68 #endif
69 };
70 
71 static enum {
72 	NO_BENCHMARK,
73 	TUNER_BENCHMARK,
74 	PPM_BENCHMARK
75 } test_mode = NO_BENCHMARK;
76 
77 static int do_exit = 0;
78 static rtlsdr_dev_t *dev = NULL;
79 
80 static uint32_t samp_rate = DEFAULT_SAMPLE_RATE;
81 
82 static uint32_t total_samples = 0;
83 static uint32_t dropped_samples = 0;
84 
85 static unsigned int ppm_duration = PPM_DURATION;
86 
usage(void)87 void usage(void)
88 {
89 	fprintf(stderr,
90 		"rtl_test, a benchmark tool for RTL2832 based DVB-T receivers\n\n"
91 		"Usage:\n"
92 		"\t[-s samplerate (default: 2048000 Hz)]\n"
93 		"\t[-d device_index (default: 0)]\n"
94 		"\t[-t enable Elonics E4000 tuner benchmark]\n"
95 #ifndef _WIN32
96 		"\t[-p[seconds] enable PPM error measurement (default: 10 seconds)]\n"
97 #endif
98 		"\t[-b output_block_size (default: 16 * 16384)]\n"
99 		"\t[-S force sync output (default: async)]\n");
100 	exit(1);
101 }
102 
103 #ifdef _WIN32
104 BOOL WINAPI
sighandler(int signum)105 sighandler(int signum)
106 {
107 	if (CTRL_C_EVENT == signum) {
108 		fprintf(stderr, "Signal caught, exiting!\n");
109 		do_exit = 1;
110 		rtlsdr_cancel_async(dev);
111 		return TRUE;
112 	}
113 	return FALSE;
114 }
115 #else
sighandler(int signum)116 static void sighandler(int signum)
117 {
118 	fprintf(stderr, "Signal caught, exiting!\n");
119 	do_exit = 1;
120 	rtlsdr_cancel_async(dev);
121 }
122 #endif
123 
underrun_test(unsigned char * buf,uint32_t len,int mute)124 static void underrun_test(unsigned char *buf, uint32_t len, int mute)
125 {
126 	uint32_t i, lost = 0;
127 	static uint8_t bcnt, uninit = 1;
128 
129 	if (uninit) {
130 		bcnt = buf[0];
131 		uninit = 0;
132 	}
133 	for (i = 0; i < len; i++) {
134 		if(bcnt != buf[i]) {
135 			lost += (buf[i] > bcnt) ? (buf[i] - bcnt) : (bcnt - buf[i]);
136 			bcnt = buf[i];
137 		}
138 
139 		bcnt++;
140 	}
141 
142 	total_samples += len;
143 	dropped_samples += lost;
144 	if (mute)
145 		return;
146 	if (lost)
147 		printf("lost at least %d bytes\n", lost);
148 
149 }
150 
151 #ifndef _WIN32
ppm_gettime(struct time_generic * tg)152 static int ppm_gettime(struct time_generic *tg)
153 {
154 	int rv = ENOSYS;
155 	struct timespec ts;
156 
157 #ifdef __unix__
158 	rv = clock_gettime(CLOCK_MONOTONIC, &ts);
159 	tg->tv_sec = ts.tv_sec;
160 	tg->tv_nsec = ts.tv_nsec;
161 #elif __APPLE__
162 	struct timeval tv;
163 
164 	rv = gettimeofday(&tv, NULL);
165 	tg->tv_sec = tv.tv_sec;
166 	tg->tv_nsec = tv.tv_usec * 1000;
167 #endif
168 	return rv;
169 }
170 #endif
171 
172 #ifdef _WIN32
ppm_gettime(struct time_generic * tg)173 static int ppm_gettime(struct time_generic *tg)
174 {
175 	int rv;
176 	int64_t frac;
177 	if (!tg->init) {
178 		QueryPerformanceFrequency(&tg->frequency);
179 		tg->init = 1;
180 	}
181 	rv = QueryPerformanceCounter(&tg->ticks);
182 	tg->tv_sec = tg->ticks.QuadPart / tg->frequency.QuadPart;
183 	frac = (int64_t)(tg->ticks.QuadPart - (tg->tv_sec * tg->frequency.QuadPart));
184 	tg->tv_nsec = (long)(frac * 1000000000L / (int64_t)tg->frequency.QuadPart);
185 	return !rv;
186 }
187 #endif
188 
ppm_report(uint64_t nsamples,uint64_t interval)189 static int ppm_report(uint64_t nsamples, uint64_t interval)
190 {
191 	double real_rate, ppm;
192 
193 	real_rate = nsamples * 1e9 / interval;
194 	ppm = 1e6 * (real_rate / (double)samp_rate - 1.);
195 	return (int)round(ppm);
196 }
197 
ppm_test(uint32_t len)198 static void ppm_test(uint32_t len)
199 {
200 	static uint64_t nsamples = 0;
201 	static uint64_t interval = 0;
202 	static uint64_t nsamples_total = 0;
203 	static uint64_t interval_total = 0;
204 	struct time_generic ppm_now;
205 	static struct time_generic ppm_recent;
206 	static enum {
207 		PPM_INIT_NO,
208 		PPM_INIT_DUMP,
209 		PPM_INIT_RUN
210 	} ppm_init = PPM_INIT_NO;
211 
212 	ppm_gettime(&ppm_now);
213 
214 	if (ppm_init != PPM_INIT_RUN) {
215 		/*
216 		 * Kyle Keen wrote:
217 		 * PPM_DUMP_TIME throws out the first N seconds of data.
218 		 * The dongle's PPM is usually very bad when first starting up,
219 		 * typically incorrect by more than twice the final value.
220 		 * Discarding the first few seconds allows the value to stabilize much faster.
221 		*/
222 		if (ppm_init == PPM_INIT_NO) {
223 			ppm_recent.tv_sec = ppm_now.tv_sec + PPM_DUMP_TIME;
224 			ppm_init = PPM_INIT_DUMP;
225 			return;
226 		}
227 		if (ppm_init == PPM_INIT_DUMP && ppm_recent.tv_sec < ppm_now.tv_sec)
228 			return;
229 		ppm_recent = ppm_now;
230 		ppm_init = PPM_INIT_RUN;
231 		return;
232 	}
233 
234 	nsamples += (uint64_t)(len / 2UL);
235 	interval = (uint64_t)(ppm_now.tv_sec - ppm_recent.tv_sec);
236 	if (interval < ppm_duration)
237 		return;
238 	interval *= 1000000000UL;
239 	interval += (int64_t)(ppm_now.tv_nsec - ppm_recent.tv_nsec);
240 	nsamples_total += nsamples;
241 	interval_total += interval;
242 	printf("real sample rate: %i current PPM: %i cumulative PPM: %i\n",
243 		(int)((1000000000UL * nsamples) / interval),
244 		ppm_report(nsamples, interval),
245 		ppm_report(nsamples_total, interval_total));
246 	ppm_recent = ppm_now;
247 	nsamples = 0;
248 }
249 
rtlsdr_callback(unsigned char * buf,uint32_t len,void * ctx)250 static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
251 {
252 	underrun_test(buf, len, 0);
253 
254 	if (test_mode == PPM_BENCHMARK)
255 		ppm_test(len);
256 }
257 
e4k_benchmark(void)258 void e4k_benchmark(void)
259 {
260 	uint32_t freq, gap_start = 0, gap_end = 0;
261 	uint32_t range_start = 0, range_end = 0;
262 
263 	fprintf(stderr, "Benchmarking E4000 PLL...\n");
264 
265 	/* find tuner range start */
266 	for (freq = MHZ(70); freq > MHZ(1); freq -= MHZ(1)) {
267 		if (rtlsdr_set_center_freq(dev, freq) < 0) {
268 			range_start = freq;
269 			break;
270 		}
271 	}
272 
273 	/* find tuner range end */
274 	for (freq = MHZ(2000); freq < MHZ(2300UL); freq += MHZ(1)) {
275 		if (rtlsdr_set_center_freq(dev, freq) < 0) {
276 			range_end = freq;
277 			break;
278 		}
279 	}
280 
281 	/* find start of L-band gap */
282 	for (freq = MHZ(1000); freq < MHZ(1300); freq += MHZ(1)) {
283 		if (rtlsdr_set_center_freq(dev, freq) < 0) {
284 			gap_start = freq;
285 			break;
286 		}
287 	}
288 
289 	/* find end of L-band gap */
290 	for (freq = MHZ(1300); freq > MHZ(1000); freq -= MHZ(1)) {
291 		if (rtlsdr_set_center_freq(dev, freq) < 0) {
292 			gap_end = freq;
293 			break;
294 		}
295 	}
296 
297 	fprintf(stderr, "E4K range: %i to %i MHz\n",
298 		range_start/MHZ(1) + 1, range_end/MHZ(1) - 1);
299 
300 	fprintf(stderr, "E4K L-band gap: %i to %i MHz\n",
301 		gap_start/MHZ(1), gap_end/MHZ(1));
302 }
303 
main(int argc,char ** argv)304 int main(int argc, char **argv)
305 {
306 #ifndef _WIN32
307 	struct sigaction sigact;
308 #endif
309 	int n_read, r, opt, i;
310 	int sync_mode = 0;
311 	uint8_t *buffer;
312 	int dev_index = 0;
313 	int dev_given = 0;
314 	uint32_t out_block_size = DEFAULT_BUF_LENGTH;
315 	int count;
316 	int gains[100];
317 
318 	while ((opt = getopt(argc, argv, "d:s:b:tp::Sh")) != -1) {
319 		switch (opt) {
320 		case 'd':
321 			dev_index = verbose_device_search(optarg);
322 			dev_given = 1;
323 			break;
324 		case 's':
325 			samp_rate = (uint32_t)atof(optarg);
326 			break;
327 		case 'b':
328 			out_block_size = (uint32_t)atof(optarg);
329 			break;
330 		case 't':
331 			test_mode = TUNER_BENCHMARK;
332 			break;
333 		case 'p':
334 			test_mode = PPM_BENCHMARK;
335 			if (optarg)
336 				ppm_duration = atoi(optarg);
337 			break;
338 		case 'S':
339 			sync_mode = 1;
340 			break;
341 		case 'h':
342 		default:
343 			usage();
344 			break;
345 		}
346 	}
347 
348 	if(out_block_size < MINIMAL_BUF_LENGTH ||
349 	   out_block_size > MAXIMAL_BUF_LENGTH ){
350 		fprintf(stderr,
351 			"Output block size wrong value, falling back to default\n");
352 		fprintf(stderr,
353 			"Minimal length: %u\n", MINIMAL_BUF_LENGTH);
354 		fprintf(stderr,
355 			"Maximal length: %u\n", MAXIMAL_BUF_LENGTH);
356 		out_block_size = DEFAULT_BUF_LENGTH;
357 	}
358 
359 	buffer = malloc(out_block_size * sizeof(uint8_t));
360 
361 	if (!dev_given) {
362 		dev_index = verbose_device_search("0");
363 	}
364 
365 	if (dev_index < 0) {
366 		exit(1);
367 	}
368 
369 	r = rtlsdr_open(&dev, (uint32_t)dev_index);
370 	if (r < 0) {
371 		fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
372 		exit(1);
373 	}
374 #ifndef _WIN32
375 	sigact.sa_handler = sighandler;
376 	sigemptyset(&sigact.sa_mask);
377 	sigact.sa_flags = 0;
378 	sigaction(SIGINT, &sigact, NULL);
379 	sigaction(SIGTERM, &sigact, NULL);
380 	sigaction(SIGQUIT, &sigact, NULL);
381 	sigaction(SIGPIPE, &sigact, NULL);
382 #else
383 	SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
384 #endif
385 	count = rtlsdr_get_tuner_gains(dev, NULL);
386 	fprintf(stderr, "Supported gain values (%d): ", count);
387 
388 	count = rtlsdr_get_tuner_gains(dev, gains);
389 	for (i = 0; i < count; i++)
390 		fprintf(stderr, "%.1f ", gains[i] / 10.0);
391 	fprintf(stderr, "\n");
392 
393 	/* Set the sample rate */
394 	verbose_set_sample_rate(dev, samp_rate);
395 
396 	if (test_mode == TUNER_BENCHMARK) {
397 		if (rtlsdr_get_tuner_type(dev) == RTLSDR_TUNER_E4000)
398 			e4k_benchmark();
399 		else
400 			fprintf(stderr, "No E4000 tuner found, aborting.\n");
401 
402 		goto exit;
403 	}
404 
405 	/* Enable test mode */
406 	r = rtlsdr_set_testmode(dev, 1);
407 
408 	/* Reset endpoint before we start reading from it (mandatory) */
409 	verbose_reset_buffer(dev);
410 
411 	if ((test_mode == PPM_BENCHMARK) && !sync_mode) {
412 		fprintf(stderr, "Reporting PPM error measurement every %u seconds...\n", ppm_duration);
413 		fprintf(stderr, "Press ^C after a few minutes.\n");
414 	}
415 
416 	if (test_mode == NO_BENCHMARK) {
417 		fprintf(stderr, "\nInfo: This tool will continuously"
418 				" read from the device, and report if\n"
419 				"samples get lost. If you observe no "
420 				"further output, everything is fine.\n\n");
421 	}
422 
423 	if (sync_mode) {
424 		fprintf(stderr, "Reading samples in sync mode...\n");
425 		fprintf(stderr, "(Samples are being lost but not reported.)\n");
426 		while (!do_exit) {
427 			r = rtlsdr_read_sync(dev, buffer, out_block_size, &n_read);
428 			if (r < 0) {
429 				fprintf(stderr, "WARNING: sync read failed.\n");
430 				break;
431 			}
432 
433 			if ((uint32_t)n_read < out_block_size) {
434 				fprintf(stderr, "Short read, samples lost, exiting!\n");
435 				break;
436 			}
437 			underrun_test(buffer, n_read, 1);
438 		}
439 	} else {
440 		fprintf(stderr, "Reading samples in async mode...\n");
441 		r = rtlsdr_read_async(dev, rtlsdr_callback, NULL,
442 				      0, out_block_size);
443 	}
444 
445 	if (do_exit) {
446 		fprintf(stderr, "\nUser cancel, exiting...\n");
447 		fprintf(stderr, "Samples per million lost (minimum): %i\n", (int)(1000000L * dropped_samples / total_samples));
448 	}
449 	else
450 		fprintf(stderr, "\nLibrary error %d, exiting...\n", r);
451 
452 exit:
453 	rtlsdr_close(dev);
454 	free (buffer);
455 
456 	return r >= 0 ? r : -r;
457 }
458