rtl_power.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. /*
  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. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /*
  21. * rtl_power: general purpose FFT integrator
  22. * -f low_freq:high_freq:max_bin_size
  23. * -i seconds
  24. * outputs CSV
  25. * time, low, high, step, db, db, db ...
  26. * db optional? raw output might be better for noise correction
  27. * todo:
  28. * threading
  29. * randomized hopping
  30. * noise correction
  31. * continuous IIR
  32. * general astronomy usefulness
  33. * multiple dongles
  34. * multiple FFT workers
  35. * check edge cropping for off-by-one and rounding errors
  36. * 1.8MS/s for hiding xtal harmonics
  37. */
  38. #include <errno.h>
  39. #include <signal.h>
  40. #include <string.h>
  41. #include <stdio.h>
  42. #include <stdlib.h>
  43. #include <time.h>
  44. #ifndef _WIN32
  45. #include <unistd.h>
  46. #else
  47. #include <windows.h>
  48. #include <fcntl.h>
  49. #include <io.h>
  50. #include "getopt/getopt.h"
  51. #define usleep(x) Sleep(x/1000)
  52. #if defined(_MSC_VER) && (_MSC_VER < 1800)
  53. #define round(x) (x > 0.0 ? floor(x + 0.5): ceil(x - 0.5))
  54. #endif
  55. #define _USE_MATH_DEFINES
  56. #endif
  57. #include <math.h>
  58. #include <pthread.h>
  59. #include <libusb.h>
  60. #include "rtl-sdr.h"
  61. #include "convenience/convenience.h"
  62. #define MAX(x, y) (((x) > (y)) ? (x) : (y))
  63. #define DEFAULT_BUF_LENGTH (1 * 16384)
  64. #define AUTO_GAIN -100
  65. #define BUFFER_DUMP (1<<12)
  66. #define MAXIMUM_RATE 2800000
  67. #define MINIMUM_RATE 1000000
  68. static volatile int do_exit = 0;
  69. static rtlsdr_dev_t *dev = NULL;
  70. FILE *file;
  71. int16_t* Sinewave;
  72. double* power_table;
  73. int N_WAVE, LOG2_N_WAVE;
  74. int next_power;
  75. int16_t *fft_buf;
  76. int *window_coefs;
  77. struct tuning_state
  78. /* one per tuning range */
  79. {
  80. int freq;
  81. int rate;
  82. int bin_e;
  83. long *avg; /* length == 2^bin_e */
  84. int samples;
  85. int downsample;
  86. int downsample_passes; /* for the recursive filter */
  87. double crop;
  88. //pthread_rwlock_t avg_lock;
  89. //pthread_mutex_t avg_mutex;
  90. /* having the iq buffer here is wasteful, but will avoid contention */
  91. uint8_t *buf8;
  92. int buf_len;
  93. //int *comp_fir;
  94. //pthread_rwlock_t buf_lock;
  95. //pthread_mutex_t buf_mutex;
  96. };
  97. /* 3000 is enough for 3GHz b/w worst case */
  98. #define MAX_TUNES 3000
  99. struct tuning_state tunes[MAX_TUNES];
  100. int tune_count = 0;
  101. int boxcar = 1;
  102. int comp_fir_size = 0;
  103. int peak_hold = 0;
  104. void usage(void)
  105. {
  106. fprintf(stderr,
  107. "rtl_power, a simple FFT logger for RTL2832 based DVB-T receivers\n\n"
  108. "Use:\trtl_power -f freq_range [-options] [filename]\n"
  109. "\t-f lower:upper:bin_size [Hz]\n"
  110. "\t (bin size is a maximum, smaller more convenient bins\n"
  111. "\t will be used. valid range 1Hz - 2.8MHz)\n"
  112. "\t[-i integration_interval (default: 10 seconds)]\n"
  113. "\t (buggy if a full sweep takes longer than the interval)\n"
  114. "\t[-1 enables single-shot mode (default: off)]\n"
  115. "\t[-e exit_timer (default: off/0)]\n"
  116. //"\t[-s avg/iir smoothing (default: avg)]\n"
  117. //"\t[-t threads (default: 1)]\n"
  118. "\t[-d device_index (default: 0)]\n"
  119. "\t[-g tuner_gain (default: automatic)]\n"
  120. "\t[-p ppm_error (default: 0)]\n"
  121. "\tfilename (a '-' dumps samples to stdout)\n"
  122. "\t (omitting the filename also uses stdout)\n"
  123. "\n"
  124. "Experimental options:\n"
  125. "\t[-w window (default: rectangle)]\n"
  126. "\t (hamming, blackman, blackman-harris, hann-poisson, bartlett, youssef)\n"
  127. // kaiser
  128. "\t[-c crop_percent (default: 0%%, recommended: 20%%-50%%)]\n"
  129. "\t (discards data at the edges, 100%% discards everything)\n"
  130. "\t (has no effect for bins larger than 1MHz)\n"
  131. "\t[-F fir_size (default: disabled)]\n"
  132. "\t (enables low-leakage downsample filter,\n"
  133. "\t fir_size can be 0 or 9. 0 has bad roll off,\n"
  134. "\t try with '-c 50%%')\n"
  135. "\t[-P enables peak hold (default: off)]\n"
  136. "\t[-D enable direct sampling (default: off)]\n"
  137. "\t[-O enable offset tuning (default: off)]\n"
  138. "\n"
  139. "CSV FFT output columns:\n"
  140. "\tdate, time, Hz low, Hz high, Hz step, samples, dbm, dbm, ...\n\n"
  141. "Examples:\n"
  142. "\trtl_power -f 88M:108M:125k fm_stations.csv\n"
  143. "\t (creates 160 bins across the FM band,\n"
  144. "\t individual stations should be visible)\n"
  145. "\trtl_power -f 100M:1G:1M -i 5m -1 survey.csv\n"
  146. "\t (a five minute low res scan of nearly everything)\n"
  147. "\trtl_power -f ... -i 15m -1 log.csv\n"
  148. "\t (integrate for 15 minutes and exit afterwards)\n"
  149. "\trtl_power -f ... -e 1h | gzip > log.csv.gz\n"
  150. "\t (collect data for one hour and compress it on the fly)\n\n"
  151. "Convert CSV to a waterfall graphic with:\n"
  152. "\t http://kmkeen.com/tmp/heatmap.py.txt \n");
  153. exit(1);
  154. }
  155. void multi_bail(void)
  156. {
  157. if (do_exit == 1)
  158. {
  159. fprintf(stderr, "Signal caught, finishing scan pass.\n");
  160. }
  161. if (do_exit >= 2)
  162. {
  163. fprintf(stderr, "Signal caught, aborting immediately.\n");
  164. }
  165. }
  166. #ifdef _WIN32
  167. BOOL WINAPI
  168. sighandler(int signum)
  169. {
  170. if (CTRL_C_EVENT == signum) {
  171. do_exit++;
  172. multi_bail();
  173. return TRUE;
  174. }
  175. return FALSE;
  176. }
  177. #else
  178. static void sighandler(int signum)
  179. {
  180. do_exit++;
  181. multi_bail();
  182. }
  183. #endif
  184. /* more cond dumbness */
  185. #define safe_cond_signal(n, m) pthread_mutex_lock(m); pthread_cond_signal(n); pthread_mutex_unlock(m)
  186. #define safe_cond_wait(n, m) pthread_mutex_lock(m); pthread_cond_wait(n, m); pthread_mutex_unlock(m)
  187. /* {length, coef, coef, coef} and scaled by 2^15
  188. for now, only length 9, optimal way to get +85% bandwidth */
  189. #define CIC_TABLE_MAX 10
  190. int cic_9_tables[][10] = {
  191. {0,},
  192. {9, -156, -97, 2798, -15489, 61019, -15489, 2798, -97, -156},
  193. {9, -128, -568, 5593, -24125, 74126, -24125, 5593, -568, -128},
  194. {9, -129, -639, 6187, -26281, 77511, -26281, 6187, -639, -129},
  195. {9, -122, -612, 6082, -26353, 77818, -26353, 6082, -612, -122},
  196. {9, -120, -602, 6015, -26269, 77757, -26269, 6015, -602, -120},
  197. {9, -120, -582, 5951, -26128, 77542, -26128, 5951, -582, -120},
  198. {9, -119, -580, 5931, -26094, 77505, -26094, 5931, -580, -119},
  199. {9, -119, -578, 5921, -26077, 77484, -26077, 5921, -578, -119},
  200. {9, -119, -577, 5917, -26067, 77473, -26067, 5917, -577, -119},
  201. {9, -199, -362, 5303, -25505, 77489, -25505, 5303, -362, -199},
  202. };
  203. #if defined(_MSC_VER) && (_MSC_VER < 1800)
  204. double log2(double n)
  205. {
  206. return log(n) / log(2.0);
  207. }
  208. #endif
  209. /* FFT based on fix_fft.c by Roberts, Slaney and Bouras
  210. http://www.jjj.de/fft/fftpage.html
  211. 16 bit ints for everything
  212. -32768..+32768 maps to -1.0..+1.0
  213. */
  214. void sine_table(int size)
  215. {
  216. int i;
  217. double d;
  218. LOG2_N_WAVE = size;
  219. N_WAVE = 1 << LOG2_N_WAVE;
  220. Sinewave = malloc(sizeof(int16_t) * N_WAVE*3/4);
  221. power_table = malloc(sizeof(double) * N_WAVE);
  222. for (i=0; i<N_WAVE*3/4; i++)
  223. {
  224. d = (double)i * 2.0 * M_PI / N_WAVE;
  225. Sinewave[i] = (int)round(32767*sin(d));
  226. //printf("%i\n", Sinewave[i]);
  227. }
  228. }
  229. inline int16_t FIX_MPY(int16_t a, int16_t b)
  230. /* fixed point multiply and scale */
  231. {
  232. int c = ((int)a * (int)b) >> 14;
  233. b = c & 0x01;
  234. return (c >> 1) + b;
  235. }
  236. int fix_fft(int16_t iq[], int m)
  237. /* interleaved iq[], 0 <= n < 2**m, changes in place */
  238. {
  239. int mr, nn, i, j, l, k, istep, n, shift;
  240. int16_t qr, qi, tr, ti, wr, wi;
  241. n = 1 << m;
  242. if (n > N_WAVE)
  243. {return -1;}
  244. mr = 0;
  245. nn = n - 1;
  246. /* decimation in time - re-order data */
  247. for (m=1; m<=nn; ++m) {
  248. l = n;
  249. do
  250. {l >>= 1;}
  251. while (mr+l > nn);
  252. mr = (mr & (l-1)) + l;
  253. if (mr <= m)
  254. {continue;}
  255. // real = 2*m, imag = 2*m+1
  256. tr = iq[2*m];
  257. iq[2*m] = iq[2*mr];
  258. iq[2*mr] = tr;
  259. ti = iq[2*m+1];
  260. iq[2*m+1] = iq[2*mr+1];
  261. iq[2*mr+1] = ti;
  262. }
  263. l = 1;
  264. k = LOG2_N_WAVE-1;
  265. while (l < n) {
  266. shift = 1;
  267. istep = l << 1;
  268. for (m=0; m<l; ++m) {
  269. j = m << k;
  270. wr = Sinewave[j+N_WAVE/4];
  271. wi = -Sinewave[j];
  272. if (shift) {
  273. wr >>= 1; wi >>= 1;}
  274. for (i=m; i<n; i+=istep) {
  275. j = i + l;
  276. tr = FIX_MPY(wr,iq[2*j]) - FIX_MPY(wi,iq[2*j+1]);
  277. ti = FIX_MPY(wr,iq[2*j+1]) + FIX_MPY(wi,iq[2*j]);
  278. qr = iq[2*i];
  279. qi = iq[2*i+1];
  280. if (shift) {
  281. qr >>= 1; qi >>= 1;}
  282. iq[2*j] = qr - tr;
  283. iq[2*j+1] = qi - ti;
  284. iq[2*i] = qr + tr;
  285. iq[2*i+1] = qi + ti;
  286. }
  287. }
  288. --k;
  289. l = istep;
  290. }
  291. return 0;
  292. }
  293. double rectangle(int i, int length)
  294. {
  295. return 1.0;
  296. }
  297. double hamming(int i, int length)
  298. {
  299. double a, b, w, N1;
  300. a = 25.0/46.0;
  301. b = 21.0/46.0;
  302. N1 = (double)(length-1);
  303. w = a - b*cos(2*i*M_PI/N1);
  304. return w;
  305. }
  306. double blackman(int i, int length)
  307. {
  308. double a0, a1, a2, w, N1;
  309. a0 = 7938.0/18608.0;
  310. a1 = 9240.0/18608.0;
  311. a2 = 1430.0/18608.0;
  312. N1 = (double)(length-1);
  313. w = a0 - a1*cos(2*i*M_PI/N1) + a2*cos(4*i*M_PI/N1);
  314. return w;
  315. }
  316. double blackman_harris(int i, int length)
  317. {
  318. double a0, a1, a2, a3, w, N1;
  319. a0 = 0.35875;
  320. a1 = 0.48829;
  321. a2 = 0.14128;
  322. a3 = 0.01168;
  323. N1 = (double)(length-1);
  324. w = a0 - a1*cos(2*i*M_PI/N1) + a2*cos(4*i*M_PI/N1) - a3*cos(6*i*M_PI/N1);
  325. return w;
  326. }
  327. double hann_poisson(int i, int length)
  328. {
  329. double a, N1, w;
  330. a = 2.0;
  331. N1 = (double)(length-1);
  332. w = 0.5 * (1 - cos(2*M_PI*i/N1)) * \
  333. pow(M_E, (-a*(double)abs((int)(N1-1-2*i)))/N1);
  334. return w;
  335. }
  336. double youssef(int i, int length)
  337. /* really a blackman-harris-poisson window, but that is a mouthful */
  338. {
  339. double a, a0, a1, a2, a3, w, N1;
  340. a0 = 0.35875;
  341. a1 = 0.48829;
  342. a2 = 0.14128;
  343. a3 = 0.01168;
  344. N1 = (double)(length-1);
  345. w = a0 - a1*cos(2*i*M_PI/N1) + a2*cos(4*i*M_PI/N1) - a3*cos(6*i*M_PI/N1);
  346. a = 0.0025;
  347. w *= pow(M_E, (-a*(double)abs((int)(N1-1-2*i)))/N1);
  348. return w;
  349. }
  350. double kaiser(int i, int length)
  351. // todo, become more smart
  352. {
  353. return 1.0;
  354. }
  355. double bartlett(int i, int length)
  356. {
  357. double N1, L, w;
  358. L = (double)length;
  359. N1 = L - 1;
  360. w = (i - N1/2) / (L/2);
  361. if (w < 0) {
  362. w = -w;}
  363. w = 1 - w;
  364. return w;
  365. }
  366. void rms_power(struct tuning_state *ts)
  367. /* for bins between 1MHz and 2MHz */
  368. {
  369. int i, s;
  370. uint8_t *buf = ts->buf8;
  371. int buf_len = ts->buf_len;
  372. long p, t;
  373. double dc, err;
  374. p = t = 0L;
  375. for (i=0; i<buf_len; i++) {
  376. s = (int)buf[i] - 127;
  377. t += (long)s;
  378. p += (long)(s * s);
  379. }
  380. /* correct for dc offset in squares */
  381. dc = (double)t / (double)buf_len;
  382. err = t * 2 * dc - dc * dc * buf_len;
  383. p -= (long)round(err);
  384. if (!peak_hold) {
  385. ts->avg[0] += p;
  386. } else {
  387. ts->avg[0] = MAX(ts->avg[0], p);
  388. }
  389. ts->samples += 1;
  390. }
  391. void frequency_range(char *arg, double crop)
  392. /* flesh out the tunes[] for scanning */
  393. // do we want the fewest ranges (easy) or the fewest bins (harder)?
  394. {
  395. char *start, *stop, *step;
  396. int i, j, upper, lower, max_size, bw_seen, bw_used, bin_e, buf_len;
  397. int downsample, downsample_passes;
  398. double bin_size;
  399. struct tuning_state *ts;
  400. /* hacky string parsing */
  401. start = arg;
  402. stop = strchr(start, ':') + 1;
  403. stop[-1] = '\0';
  404. step = strchr(stop, ':') + 1;
  405. step[-1] = '\0';
  406. lower = (int)atofs(start);
  407. upper = (int)atofs(stop);
  408. max_size = (int)atofs(step);
  409. stop[-1] = ':';
  410. step[-1] = ':';
  411. downsample = 1;
  412. downsample_passes = 0;
  413. /* evenly sized ranges, as close to MAXIMUM_RATE as possible */
  414. // todo, replace loop with algebra
  415. for (i=1; i<1500; i++) {
  416. bw_seen = (upper - lower) / i;
  417. bw_used = (int)((double)(bw_seen) / (1.0 - crop));
  418. if (bw_used > MAXIMUM_RATE) {
  419. continue;}
  420. tune_count = i;
  421. break;
  422. }
  423. /* unless small bandwidth */
  424. if (bw_used < MINIMUM_RATE) {
  425. tune_count = 1;
  426. downsample = MAXIMUM_RATE / bw_used;
  427. bw_used = bw_used * downsample;
  428. }
  429. if (!boxcar && downsample > 1) {
  430. downsample_passes = (int)log2(downsample);
  431. downsample = 1 << downsample_passes;
  432. bw_used = (int)((double)(bw_seen * downsample) / (1.0 - crop));
  433. }
  434. /* number of bins is power-of-two, bin size is under limit */
  435. // todo, replace loop with log2
  436. for (i=1; i<=21; i++) {
  437. bin_e = i;
  438. bin_size = (double)bw_used / (double)((1<<i) * downsample);
  439. if (bin_size <= (double)max_size) {
  440. break;}
  441. }
  442. /* unless giant bins */
  443. if (max_size >= MINIMUM_RATE) {
  444. bw_seen = max_size;
  445. bw_used = max_size;
  446. tune_count = (upper - lower) / bw_seen;
  447. bin_e = 0;
  448. crop = 0;
  449. }
  450. if (tune_count > MAX_TUNES) {
  451. fprintf(stderr, "Error: bandwidth too wide.\n");
  452. exit(1);
  453. }
  454. buf_len = 2 * (1<<bin_e) * downsample;
  455. if (buf_len < DEFAULT_BUF_LENGTH) {
  456. buf_len = DEFAULT_BUF_LENGTH;
  457. }
  458. /* build the array */
  459. for (i=0; i<tune_count; i++) {
  460. ts = &tunes[i];
  461. ts->freq = lower + i*bw_seen + bw_seen/2;
  462. ts->rate = bw_used;
  463. ts->bin_e = bin_e;
  464. ts->samples = 0;
  465. ts->crop = crop;
  466. ts->downsample = downsample;
  467. ts->downsample_passes = downsample_passes;
  468. ts->avg = (long*)malloc((1<<bin_e) * sizeof(long));
  469. if (!ts->avg) {
  470. fprintf(stderr, "Error: malloc.\n");
  471. exit(1);
  472. }
  473. for (j=0; j<(1<<bin_e); j++) {
  474. ts->avg[j] = 0L;
  475. }
  476. ts->buf8 = (uint8_t*)malloc(buf_len * sizeof(uint8_t));
  477. if (!ts->buf8) {
  478. fprintf(stderr, "Error: malloc.\n");
  479. exit(1);
  480. }
  481. ts->buf_len = buf_len;
  482. }
  483. /* report */
  484. fprintf(stderr, "Number of frequency hops: %i\n", tune_count);
  485. fprintf(stderr, "Dongle bandwidth: %iHz\n", bw_used);
  486. fprintf(stderr, "Downsampling by: %ix\n", downsample);
  487. fprintf(stderr, "Cropping by: %0.2f%%\n", crop*100);
  488. fprintf(stderr, "Total FFT bins: %i\n", tune_count * (1<<bin_e));
  489. fprintf(stderr, "Logged FFT bins: %i\n", \
  490. (int)((double)(tune_count * (1<<bin_e)) * (1.0-crop)));
  491. fprintf(stderr, "FFT bin size: %0.2fHz\n", bin_size);
  492. fprintf(stderr, "Buffer size: %i bytes (%0.2fms)\n", buf_len, 1000 * 0.5 * (float)buf_len / (float)bw_used);
  493. }
  494. void retune(rtlsdr_dev_t *d, int freq)
  495. {
  496. uint8_t dump[BUFFER_DUMP];
  497. int n_read;
  498. rtlsdr_set_center_freq(d, (uint32_t)freq);
  499. /* wait for settling and flush buffer */
  500. usleep(5000);
  501. rtlsdr_read_sync(d, &dump, BUFFER_DUMP, &n_read);
  502. if (n_read != BUFFER_DUMP) {
  503. fprintf(stderr, "Error: bad retune.\n");}
  504. }
  505. void fifth_order(int16_t *data, int length)
  506. /* for half of interleaved data */
  507. {
  508. int i;
  509. int a, b, c, d, e, f;
  510. a = data[0];
  511. b = data[2];
  512. c = data[4];
  513. d = data[6];
  514. e = data[8];
  515. f = data[10];
  516. /* a downsample should improve resolution, so don't fully shift */
  517. /* ease in instead of being stateful */
  518. data[0] = ((a+b)*10 + (c+d)*5 + d + f) >> 4;
  519. data[2] = ((b+c)*10 + (a+d)*5 + e + f) >> 4;
  520. data[4] = (a + (b+e)*5 + (c+d)*10 + f) >> 4;
  521. for (i=12; i<length; i+=4) {
  522. a = c;
  523. b = d;
  524. c = e;
  525. d = f;
  526. e = data[i-2];
  527. f = data[i];
  528. data[i/2] = (a + (b+e)*5 + (c+d)*10 + f) >> 4;
  529. }
  530. }
  531. void remove_dc(int16_t *data, int length)
  532. /* works on interleaved data */
  533. {
  534. int i;
  535. int16_t ave;
  536. long sum = 0L;
  537. for (i=0; i < length; i+=2) {
  538. sum += data[i];
  539. }
  540. ave = (int16_t)(sum / (long)(length));
  541. if (ave == 0) {
  542. return;}
  543. for (i=0; i < length; i+=2) {
  544. data[i] -= ave;
  545. }
  546. }
  547. void generic_fir(int16_t *data, int length, int *fir)
  548. /* Okay, not at all generic. Assumes length 9, fix that eventually. */
  549. {
  550. int d, temp, sum;
  551. int hist[9] = {0,};
  552. /* cheat on the beginning, let it go unfiltered */
  553. for (d=0; d<18; d+=2) {
  554. hist[d/2] = data[d];
  555. }
  556. for (d=18; d<length; d+=2) {
  557. temp = data[d];
  558. sum = 0;
  559. sum += (hist[0] + hist[8]) * fir[1];
  560. sum += (hist[1] + hist[7]) * fir[2];
  561. sum += (hist[2] + hist[6]) * fir[3];
  562. sum += (hist[3] + hist[5]) * fir[4];
  563. sum += hist[4] * fir[5];
  564. data[d] = (int16_t)(sum >> 15) ;
  565. hist[0] = hist[1];
  566. hist[1] = hist[2];
  567. hist[2] = hist[3];
  568. hist[3] = hist[4];
  569. hist[4] = hist[5];
  570. hist[5] = hist[6];
  571. hist[6] = hist[7];
  572. hist[7] = hist[8];
  573. hist[8] = temp;
  574. }
  575. }
  576. void downsample_iq(int16_t *data, int length)
  577. {
  578. fifth_order(data, length);
  579. //remove_dc(data, length);
  580. fifth_order(data+1, length-1);
  581. //remove_dc(data+1, length-1);
  582. }
  583. long real_conj(int16_t real, int16_t imag)
  584. /* real(n * conj(n)) */
  585. {
  586. return ((long)real*(long)real + (long)imag*(long)imag);
  587. }
  588. void scanner(void)
  589. {
  590. int i, j, j2, f, n_read, offset, bin_e, bin_len, buf_len, ds, ds_p;
  591. int32_t w;
  592. struct tuning_state *ts;
  593. bin_e = tunes[0].bin_e;
  594. bin_len = 1 << bin_e;
  595. buf_len = tunes[0].buf_len;
  596. for (i=0; i<tune_count; i++) {
  597. if (do_exit >= 2)
  598. {return;}
  599. ts = &tunes[i];
  600. f = (int)rtlsdr_get_center_freq(dev);
  601. if (f != ts->freq) {
  602. retune(dev, ts->freq);}
  603. rtlsdr_read_sync(dev, ts->buf8, buf_len, &n_read);
  604. if (n_read != buf_len) {
  605. fprintf(stderr, "Error: dropped samples.\n");}
  606. /* rms */
  607. if (bin_len == 1) {
  608. rms_power(ts);
  609. continue;
  610. }
  611. /* prep for fft */
  612. for (j=0; j<buf_len; j++) {
  613. fft_buf[j] = (int16_t)ts->buf8[j] - 127;
  614. }
  615. ds = ts->downsample;
  616. ds_p = ts->downsample_passes;
  617. if (boxcar && ds > 1) {
  618. j=2, j2=0;
  619. while (j < buf_len) {
  620. fft_buf[j2] += fft_buf[j];
  621. fft_buf[j2+1] += fft_buf[j+1];
  622. fft_buf[j] = 0;
  623. fft_buf[j+1] = 0;
  624. j += 2;
  625. if (j % (ds*2) == 0) {
  626. j2 += 2;}
  627. }
  628. } else if (ds_p) { /* recursive */
  629. for (j=0; j < ds_p; j++) {
  630. downsample_iq(fft_buf, buf_len >> j);
  631. }
  632. /* droop compensation */
  633. if (comp_fir_size == 9 && ds_p <= CIC_TABLE_MAX) {
  634. generic_fir(fft_buf, buf_len >> j, cic_9_tables[ds_p]);
  635. generic_fir(fft_buf+1, (buf_len >> j)-1, cic_9_tables[ds_p]);
  636. }
  637. }
  638. remove_dc(fft_buf, buf_len / ds);
  639. remove_dc(fft_buf+1, (buf_len / ds) - 1);
  640. /* window function and fft */
  641. for (offset=0; offset<(buf_len/ds); offset+=(2*bin_len)) {
  642. // todo, let rect skip this
  643. for (j=0; j<bin_len; j++) {
  644. w = (int32_t)fft_buf[offset+j*2];
  645. w *= (int32_t)(window_coefs[j]);
  646. //w /= (int32_t)(ds);
  647. fft_buf[offset+j*2] = (int16_t)w;
  648. w = (int32_t)fft_buf[offset+j*2+1];
  649. w *= (int32_t)(window_coefs[j]);
  650. //w /= (int32_t)(ds);
  651. fft_buf[offset+j*2+1] = (int16_t)w;
  652. }
  653. fix_fft(fft_buf+offset, bin_e);
  654. if (!peak_hold) {
  655. for (j=0; j<bin_len; j++) {
  656. ts->avg[j] += real_conj(fft_buf[offset+j*2], fft_buf[offset+j*2+1]);
  657. }
  658. } else {
  659. for (j=0; j<bin_len; j++) {
  660. ts->avg[j] = MAX(real_conj(fft_buf[offset+j*2], fft_buf[offset+j*2+1]), ts->avg[j]);
  661. }
  662. }
  663. ts->samples += ds;
  664. }
  665. }
  666. }
  667. void csv_dbm(struct tuning_state *ts)
  668. {
  669. int i, len, ds, i1, i2, bw2, bin_count;
  670. long tmp;
  671. double dbm;
  672. len = 1 << ts->bin_e;
  673. ds = ts->downsample;
  674. /* fix FFT stuff quirks */
  675. if (ts->bin_e > 0) {
  676. /* nuke DC component (not effective for all windows) */
  677. ts->avg[0] = ts->avg[1];
  678. /* FFT is translated by 180 degrees */
  679. for (i=0; i<len/2; i++) {
  680. tmp = ts->avg[i];
  681. ts->avg[i] = ts->avg[i+len/2];
  682. ts->avg[i+len/2] = tmp;
  683. }
  684. }
  685. /* Hz low, Hz high, Hz step, samples, dbm, dbm, ... */
  686. bin_count = (int)((double)len * (1.0 - ts->crop));
  687. bw2 = (int)(((double)ts->rate * (double)bin_count) / (len * 2 * ds));
  688. fprintf(file, "%i, %i, %.2f, %i, ", ts->freq - bw2, ts->freq + bw2,
  689. (double)ts->rate / (double)(len*ds), ts->samples);
  690. // something seems off with the dbm math
  691. i1 = 0 + (int)((double)len * ts->crop * 0.5);
  692. i2 = (len-1) - (int)((double)len * ts->crop * 0.5);
  693. for (i=i1; i<=i2; i++) {
  694. dbm = (double)ts->avg[i];
  695. dbm /= (double)ts->rate;
  696. dbm /= (double)ts->samples;
  697. dbm = 10 * log10(dbm);
  698. fprintf(file, "%.2f, ", dbm);
  699. }
  700. dbm = (double)ts->avg[i2] / ((double)ts->rate * (double)ts->samples);
  701. if (ts->bin_e == 0) {
  702. dbm = ((double)ts->avg[0] / \
  703. ((double)ts->rate * (double)ts->samples));}
  704. dbm = 10 * log10(dbm);
  705. fprintf(file, "%.2f\n", dbm);
  706. for (i=0; i<len; i++) {
  707. ts->avg[i] = 0L;
  708. }
  709. ts->samples = 0;
  710. }
  711. int main(int argc, char **argv)
  712. {
  713. #ifndef _WIN32
  714. struct sigaction sigact;
  715. #endif
  716. char *filename = NULL;
  717. int i, length, r, opt, wb_mode = 0;
  718. int f_set = 0;
  719. int gain = AUTO_GAIN; // tenths of a dB
  720. int dev_index = 0;
  721. int dev_given = 0;
  722. int ppm_error = 0;
  723. int interval = 10;
  724. int fft_threads = 1;
  725. int smoothing = 0;
  726. int single = 0;
  727. int direct_sampling = 0;
  728. int offset_tuning = 0;
  729. double crop = 0.0;
  730. char *freq_optarg;
  731. time_t next_tick;
  732. time_t time_now;
  733. time_t exit_time = 0;
  734. char t_str[50];
  735. struct tm *cal_time;
  736. double (*window_fn)(int, int) = rectangle;
  737. freq_optarg = "";
  738. while ((opt = getopt(argc, argv, "f:i:s:t:d:g:p:e:w:c:F:1PDOh")) != -1) {
  739. switch (opt) {
  740. case 'f': // lower:upper:bin_size
  741. freq_optarg = strdup(optarg);
  742. f_set = 1;
  743. break;
  744. case 'd':
  745. dev_index = verbose_device_search(optarg);
  746. dev_given = 1;
  747. break;
  748. case 'g':
  749. gain = (int)(atof(optarg) * 10);
  750. break;
  751. case 'c':
  752. crop = atofp(optarg);
  753. break;
  754. case 'i':
  755. interval = (int)round(atoft(optarg));
  756. break;
  757. case 'e':
  758. exit_time = (time_t)((int)round(atoft(optarg)));
  759. break;
  760. case 's':
  761. if (strcmp("avg", optarg) == 0) {
  762. smoothing = 0;}
  763. if (strcmp("iir", optarg) == 0) {
  764. smoothing = 1;}
  765. break;
  766. case 'w':
  767. if (strcmp("rectangle", optarg) == 0) {
  768. window_fn = rectangle;}
  769. if (strcmp("hamming", optarg) == 0) {
  770. window_fn = hamming;}
  771. if (strcmp("blackman", optarg) == 0) {
  772. window_fn = blackman;}
  773. if (strcmp("blackman-harris", optarg) == 0) {
  774. window_fn = blackman_harris;}
  775. if (strcmp("hann-poisson", optarg) == 0) {
  776. window_fn = hann_poisson;}
  777. if (strcmp("youssef", optarg) == 0) {
  778. window_fn = youssef;}
  779. if (strcmp("kaiser", optarg) == 0) {
  780. window_fn = kaiser;}
  781. if (strcmp("bartlett", optarg) == 0) {
  782. window_fn = bartlett;}
  783. break;
  784. case 't':
  785. fft_threads = atoi(optarg);
  786. break;
  787. case 'p':
  788. ppm_error = atoi(optarg);
  789. break;
  790. case '1':
  791. single = 1;
  792. break;
  793. case 'P':
  794. peak_hold = 1;
  795. break;
  796. case 'D':
  797. direct_sampling = 1;
  798. break;
  799. case 'O':
  800. offset_tuning = 1;
  801. break;
  802. case 'F':
  803. boxcar = 0;
  804. comp_fir_size = atoi(optarg);
  805. break;
  806. case 'h':
  807. default:
  808. usage();
  809. break;
  810. }
  811. }
  812. if (!f_set) {
  813. fprintf(stderr, "No frequency range provided.\n");
  814. exit(1);
  815. }
  816. if ((crop < 0.0) || (crop > 1.0)) {
  817. fprintf(stderr, "Crop value outside of 0 to 1.\n");
  818. exit(1);
  819. }
  820. frequency_range(freq_optarg, crop);
  821. if (tune_count == 0) {
  822. usage();}
  823. if (argc <= optind) {
  824. filename = "-";
  825. } else {
  826. filename = argv[optind];
  827. }
  828. if (interval < 1) {
  829. interval = 1;}
  830. fprintf(stderr, "Reporting every %i seconds\n", interval);
  831. if (!dev_given) {
  832. dev_index = verbose_device_search("0");
  833. }
  834. if (dev_index < 0) {
  835. exit(1);
  836. }
  837. r = rtlsdr_open(&dev, (uint32_t)dev_index);
  838. if (r < 0) {
  839. fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
  840. exit(1);
  841. }
  842. #ifndef _WIN32
  843. sigact.sa_handler = sighandler;
  844. sigemptyset(&sigact.sa_mask);
  845. sigact.sa_flags = 0;
  846. sigaction(SIGINT, &sigact, NULL);
  847. sigaction(SIGTERM, &sigact, NULL);
  848. sigaction(SIGQUIT, &sigact, NULL);
  849. sigaction(SIGPIPE, &sigact, NULL);
  850. #else
  851. SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
  852. #endif
  853. if (direct_sampling) {
  854. verbose_direct_sampling(dev, 1);
  855. }
  856. if (offset_tuning) {
  857. verbose_offset_tuning(dev);
  858. }
  859. /* Set the tuner gain */
  860. if (gain == AUTO_GAIN) {
  861. verbose_auto_gain(dev);
  862. } else {
  863. gain = nearest_gain(dev, gain);
  864. verbose_gain_set(dev, gain);
  865. }
  866. verbose_ppm_set(dev, ppm_error);
  867. if (strcmp(filename, "-") == 0) { /* Write log to stdout */
  868. file = stdout;
  869. #ifdef _WIN32
  870. // Is this necessary? Output is ascii.
  871. _setmode(_fileno(file), _O_BINARY);
  872. #endif
  873. } else {
  874. file = fopen(filename, "wb");
  875. if (!file) {
  876. fprintf(stderr, "Failed to open %s\n", filename);
  877. exit(1);
  878. }
  879. }
  880. /* Reset endpoint before we start reading from it (mandatory) */
  881. verbose_reset_buffer(dev);
  882. /* actually do stuff */
  883. rtlsdr_set_sample_rate(dev, (uint32_t)tunes[0].rate);
  884. sine_table(tunes[0].bin_e);
  885. next_tick = time(NULL) + interval;
  886. if (exit_time) {
  887. exit_time = time(NULL) + exit_time;}
  888. fft_buf = malloc(tunes[0].buf_len * sizeof(int16_t));
  889. length = 1 << tunes[0].bin_e;
  890. window_coefs = malloc(length * sizeof(int));
  891. for (i=0; i<length; i++) {
  892. window_coefs[i] = (int)(256*window_fn(i, length));
  893. }
  894. while (!do_exit) {
  895. scanner();
  896. time_now = time(NULL);
  897. if (time_now < next_tick) {
  898. continue;}
  899. // time, Hz low, Hz high, Hz step, samples, dbm, dbm, ...
  900. cal_time = localtime(&time_now);
  901. strftime(t_str, 50, "%Y-%m-%d, %H:%M:%S", cal_time);
  902. for (i=0; i<tune_count; i++) {
  903. fprintf(file, "%s, ", t_str);
  904. csv_dbm(&tunes[i]);
  905. }
  906. fflush(file);
  907. while (time(NULL) >= next_tick) {
  908. next_tick += interval;}
  909. if (single) {
  910. do_exit = 1;}
  911. if (exit_time && time(NULL) >= exit_time) {
  912. do_exit = 1;}
  913. }
  914. /* clean up */
  915. if (do_exit) {
  916. fprintf(stderr, "\nUser cancel, exiting...\n");}
  917. else {
  918. fprintf(stderr, "\nLibrary error %d, exiting...\n", r);}
  919. if (file != stdout) {
  920. fclose(file);}
  921. rtlsdr_close(dev);
  922. free(fft_buf);
  923. free(window_coefs);
  924. //for (i=0; i<tune_count; i++) {
  925. // free(tunes[i].avg);
  926. // free(tunes[i].buf8);
  927. //}
  928. return r >= 0 ? r : -r;
  929. }
  930. // vim: tabstop=8:softtabstop=8:shiftwidth=8:noexpandtab