rtl_fm.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. * written because people could not do real time
  22. * FM demod on Atom hardware with GNU radio
  23. * based on rtl_sdr.c and rtl_tcp.c
  24. * todo: realtime ARMv5
  25. * remove float math (disqualifies complex.h)
  26. * in-place array operations
  27. * sanity checks
  28. * nicer FIR than square
  29. * scale squelch to other input parameters
  30. * test all the demodulations
  31. * pad output on hop
  32. * nearest gain approx
  33. * frequency ranges could be stored better
  34. */
  35. #include <errno.h>
  36. #include <signal.h>
  37. #include <string.h>
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. #include <math.h>
  41. #ifndef _WIN32
  42. #include <unistd.h>
  43. #else
  44. #include <Windows.h>
  45. #include <fcntl.h>
  46. #include <io.h>
  47. #include "getopt/getopt.h"
  48. #define usleep(x) Sleep(x/1000)
  49. #define round(x) (x > 0.0 ? floor(x + 0.5): ceil(x - 0.5))
  50. #endif
  51. #include <semaphore.h>
  52. #include <pthread.h>
  53. #include <libusb.h>
  54. #include "rtl-sdr.h"
  55. #define DEFAULT_SAMPLE_RATE 24000
  56. #define DEFAULT_ASYNC_BUF_NUMBER 32
  57. #define DEFAULT_BUF_LENGTH (1 * 16384)
  58. #define MAXIMUM_OVERSAMPLE 16
  59. #define MAXIMUM_BUF_LENGTH (MAXIMUM_OVERSAMPLE * DEFAULT_BUF_LENGTH)
  60. #define AUTO_GAIN -100
  61. static pthread_t demod_thread;
  62. static sem_t data_ready;
  63. static int do_exit = 0;
  64. static rtlsdr_dev_t *dev = NULL;
  65. static int lcm_post[17] = {1,1,1,3,1,5,3,7,1,9,5,11,3,13,7,15,1};
  66. static int *atan_lut = NULL;
  67. static int atan_lut_size = 131072; /* 512 KB */
  68. static int atan_lut_coef = 8;
  69. struct fm_state
  70. {
  71. int now_r, now_j;
  72. int pre_r, pre_j;
  73. int prev_index;
  74. int downsample; /* min 1, max 256 */
  75. int post_downsample;
  76. int output_scale;
  77. int squelch_level, conseq_squelch, squelch_hits, terminate_on_squelch;
  78. int exit_flag;
  79. uint8_t buf[MAXIMUM_BUF_LENGTH];
  80. uint32_t buf_len;
  81. int signal[MAXIMUM_BUF_LENGTH]; /* 16 bit signed i/q pairs */
  82. int16_t signal2[MAXIMUM_BUF_LENGTH]; /* signal has lowpass, signal2 has demod */
  83. int signal_len;
  84. int signal2_len;
  85. FILE *file;
  86. int edge;
  87. uint32_t freqs[1000];
  88. int freq_len;
  89. int freq_now;
  90. uint32_t sample_rate;
  91. int output_rate;
  92. int fir_enable;
  93. int fir[256]; /* fir_len == downsample */
  94. int fir_sum;
  95. int custom_atan;
  96. int deemph, deemph_a;
  97. int now_lpr;
  98. int prev_lpr_index;
  99. int dc_block, dc_avg;
  100. void (*mode_demod)(struct fm_state*);
  101. };
  102. void usage(void)
  103. {
  104. fprintf(stderr,
  105. "rtl_fm, a simple narrow band FM demodulator for RTL2832 based DVB-T receivers\n\n"
  106. "Use:\trtl_fm -f freq [-options] [filename]\n"
  107. "\t-f frequency_to_tune_to [Hz]\n"
  108. "\t (use multiple -f for scanning, requires squelch)\n"
  109. "\t (ranges supported, -f 118M:137M:25k)\n"
  110. "\t[-s sample_rate (default: 24k)]\n"
  111. "\t[-d device_index (default: 0)]\n"
  112. "\t[-g tuner_gain (default: automatic)]\n"
  113. "\t[-l squelch_level (default: 0/off)]\n"
  114. "\t[-o oversampling (default: 1, 4 recommended)]\n"
  115. "\t[-p ppm_error (default: 0)]\n"
  116. "\t[-E sets lower edge tuning (default: center)]\n"
  117. "\t[-N enables NBFM mode (default: on)]\n"
  118. "\t[-W enables WBFM mode (default: off)]\n"
  119. "\t (-N -s 170k -o 4 -A fast -r 32k -l 0 -D)\n"
  120. "\tfilename (a '-' dumps samples to stdout)\n"
  121. "\t (omitting the filename also uses stdout)\n\n"
  122. "Experimental options:\n"
  123. "\t[-r output_rate (default: same as -s)]\n"
  124. "\t[-t squelch_delay (default: 20)]\n"
  125. "\t (+values will mute/scan, -values will exit)\n"
  126. "\t[-M enables AM mode (default: off)]\n"
  127. "\t[-L enables LSB mode (default: off)]\n"
  128. "\t[-U enables USB mode (default: off)]\n"
  129. //"\t[-D enables DSB mode (default: off)]\n"
  130. "\t[-R enables raw mode (default: off, 2x16 bit output)]\n"
  131. "\t[-F enables high quality FIR (default: off/square)]\n"
  132. "\t[-D enables de-emphasis (default: off)]\n"
  133. "\t[-C enables DC blocking of output (default: off)]\n"
  134. "\t[-A std/fast/lut choose atan math (default: std)]\n\n"
  135. "Produces signed 16 bit ints, use Sox or aplay to hear them.\n"
  136. "\trtl_fm ... - | play -t raw -r 24k -e signed-integer -b 16 -c 1 -V1 -\n"
  137. "\t | aplay -r 24k -f S16_LE -t raw -c 1\n"
  138. "\t -s 22.5k - | multimon -t raw /dev/stdin\n\n");
  139. exit(1);
  140. }
  141. #ifdef _WIN32
  142. BOOL WINAPI
  143. sighandler(int signum)
  144. {
  145. if (CTRL_C_EVENT == signum) {
  146. fprintf(stderr, "Signal caught, exiting!\n");
  147. do_exit = 1;
  148. rtlsdr_cancel_async(dev);
  149. return TRUE;
  150. }
  151. return FALSE;
  152. }
  153. #else
  154. static void sighandler(int signum)
  155. {
  156. fprintf(stderr, "Signal caught, exiting!\n");
  157. do_exit = 1;
  158. rtlsdr_cancel_async(dev);
  159. }
  160. #endif
  161. void rotate_90(unsigned char *buf, uint32_t len)
  162. /* 90 rotation is 1+0j, 0+1j, -1+0j, 0-1j
  163. or [0, 1, -3, 2, -4, -5, 7, -6] */
  164. {
  165. uint32_t i;
  166. unsigned char tmp;
  167. for (i=0; i<len; i+=8) {
  168. /* uint8_t negation = 255 - x */
  169. tmp = 255 - buf[i+3];
  170. buf[i+3] = buf[i+2];
  171. buf[i+2] = tmp;
  172. buf[i+4] = 255 - buf[i+4];
  173. buf[i+5] = 255 - buf[i+5];
  174. tmp = 255 - buf[i+6];
  175. buf[i+6] = buf[i+7];
  176. buf[i+7] = tmp;
  177. }
  178. }
  179. void low_pass(struct fm_state *fm, unsigned char *buf, uint32_t len)
  180. /* simple square window FIR */
  181. {
  182. int i=0, i2=0;
  183. while (i < (int)len) {
  184. fm->now_r += ((int)buf[i] - 128);
  185. fm->now_j += ((int)buf[i+1] - 128);
  186. i += 2;
  187. fm->prev_index++;
  188. if (fm->prev_index < fm->downsample) {
  189. continue;
  190. }
  191. fm->signal[i2] = fm->now_r * fm->output_scale;
  192. fm->signal[i2+1] = fm->now_j * fm->output_scale;
  193. fm->prev_index = 0;
  194. fm->now_r = 0;
  195. fm->now_j = 0;
  196. i2 += 2;
  197. }
  198. fm->signal_len = i2;
  199. }
  200. void build_fir(struct fm_state *fm)
  201. /* for now, a simple triangle
  202. * fancy FIRs are equally expensive, so use one */
  203. /* point = sum(sample[i] * fir[i] * fir_len / fir_sum) */
  204. {
  205. int i, len;
  206. len = fm->downsample;
  207. for(i = 0; i < (len/2); i++) {
  208. fm->fir[i] = i;
  209. }
  210. for(i = len-1; i >= (len/2); i--) {
  211. fm->fir[i] = len - i;
  212. }
  213. fm->fir_sum = 0;
  214. for(i = 0; i < len; i++) {
  215. fm->fir_sum += fm->fir[i];
  216. }
  217. }
  218. void low_pass_fir(struct fm_state *fm, unsigned char *buf, uint32_t len)
  219. /* perform an arbitrary FIR, doubles CPU use */
  220. // possibly bugged, or overflowing
  221. {
  222. int i=0, i2=0, i3=0;
  223. while (i < (int)len) {
  224. i3 = fm->prev_index;
  225. fm->now_r += ((int)buf[i] - 128) * fm->fir[i3] * fm->downsample / fm->fir_sum;
  226. fm->now_j += ((int)buf[i+1] - 128) * fm->fir[i3] * fm->downsample / fm->fir_sum;
  227. i += 2;
  228. fm->prev_index++;
  229. if (fm->prev_index < fm->downsample) {
  230. continue;
  231. }
  232. fm->signal[i2] = fm->now_r * fm->output_scale;
  233. fm->signal[i2+1] = fm->now_j * fm->output_scale;
  234. fm->prev_index = 0;
  235. fm->now_r = 0;
  236. fm->now_j = 0;
  237. i2 += 2;
  238. }
  239. fm->signal_len = i2;
  240. }
  241. int low_pass_simple(int16_t *signal2, int len, int step)
  242. // no wrap around, length must be multiple of step
  243. {
  244. int i, i2, sum;
  245. for(i=0; i < len; i+=step) {
  246. sum = 0;
  247. for(i2=0; i2<step; i2++) {
  248. sum += (int)signal2[i + i2];
  249. }
  250. //signal2[i/step] = (int16_t)(sum / step);
  251. signal2[i/step] = (int16_t)(sum);
  252. }
  253. signal2[i/step + 1] = signal2[i/step];
  254. return len / step;
  255. }
  256. void low_pass_real(struct fm_state *fm)
  257. /* simple square window FIR */
  258. // add support for upsampling?
  259. {
  260. int i=0, i2=0;
  261. int fast = (int)fm->sample_rate / fm->post_downsample;
  262. int slow = fm->output_rate;
  263. while (i < fm->signal2_len) {
  264. fm->now_lpr += fm->signal2[i];
  265. i++;
  266. fm->prev_lpr_index += slow;
  267. if (fm->prev_lpr_index < fast) {
  268. continue;
  269. }
  270. fm->signal2[i2] = (int16_t)(fm->now_lpr / (fast/slow));
  271. fm->prev_lpr_index -= fast;
  272. fm->now_lpr = 0;
  273. i2 += 1;
  274. }
  275. fm->signal2_len = i2;
  276. }
  277. /* define our own complex math ops
  278. because ARMv5 has no hardware float */
  279. void multiply(int ar, int aj, int br, int bj, int *cr, int *cj)
  280. {
  281. *cr = ar*br - aj*bj;
  282. *cj = aj*br + ar*bj;
  283. }
  284. int polar_discriminant(int ar, int aj, int br, int bj)
  285. {
  286. int cr, cj;
  287. double angle;
  288. multiply(ar, aj, br, -bj, &cr, &cj);
  289. angle = atan2((double)cj, (double)cr);
  290. return (int)(angle / 3.14159 * (1<<14));
  291. }
  292. int fast_atan2(int y, int x)
  293. /* pre scaled for int16 */
  294. {
  295. int yabs, angle;
  296. int pi4=(1<<12), pi34=3*(1<<12); // note pi = 1<<14
  297. if (x==0 && y==0) {
  298. return 0;
  299. }
  300. yabs = y;
  301. if (yabs < 0) {
  302. yabs = -yabs;
  303. }
  304. if (x >= 0) {
  305. angle = pi4 - pi4 * (x-yabs) / (x+yabs);
  306. } else {
  307. angle = pi34 - pi4 * (x+yabs) / (yabs-x);
  308. }
  309. if (y < 0) {
  310. return -angle;
  311. }
  312. return angle;
  313. }
  314. int polar_disc_fast(int ar, int aj, int br, int bj)
  315. {
  316. int cr, cj;
  317. multiply(ar, aj, br, -bj, &cr, &cj);
  318. return fast_atan2(cj, cr);
  319. }
  320. int atan_lut_init()
  321. {
  322. int i = 0;
  323. atan_lut = malloc(atan_lut_size * sizeof(int));
  324. for (i = 0; i < atan_lut_size; i++) {
  325. atan_lut[i] = (int) (atan((double) i / (1<<atan_lut_coef)) / 3.14159 * (1<<14));
  326. }
  327. return 0;
  328. }
  329. int polar_disc_lut(int ar, int aj, int br, int bj)
  330. {
  331. int cr, cj, x, x_abs;
  332. multiply(ar, aj, br, -bj, &cr, &cj);
  333. /* special cases */
  334. if (cr == 0 || cj == 0) {
  335. if (cr == 0 && cj == 0)
  336. {return 0;}
  337. if (cr == 0 && cj > 0)
  338. {return 1 << 13;}
  339. if (cr == 0 && cj < 0)
  340. {return -(1 << 13);}
  341. if (cj == 0 && cr > 0)
  342. {return 0;}
  343. if (cj == 0 && cr < 0)
  344. {return 1 << 14;}
  345. }
  346. /* real range -32768 - 32768 use 64x range -> absolute maximum: 2097152 */
  347. x = (cj << atan_lut_coef) / cr;
  348. x_abs = abs(x);
  349. if (x_abs >= atan_lut_size) {
  350. /* we can use linear range, but it is not necessary */
  351. return (cj > 0) ? 1<<13 : -1<<13;
  352. }
  353. if (x > 0) {
  354. return (cj > 0) ? atan_lut[x] : atan_lut[x] - (1<<14);
  355. } else {
  356. return (cj > 0) ? (1<<14) - atan_lut[-x] : -atan_lut[-x];
  357. }
  358. return 0;
  359. }
  360. void fm_demod(struct fm_state *fm)
  361. {
  362. int i, pcm;
  363. pcm = polar_discriminant(fm->signal[0], fm->signal[1],
  364. fm->pre_r, fm->pre_j);
  365. fm->signal2[0] = (int16_t)pcm;
  366. for (i = 2; i < (fm->signal_len); i += 2) {
  367. switch (fm->custom_atan) {
  368. case 0:
  369. pcm = polar_discriminant(fm->signal[i], fm->signal[i+1],
  370. fm->signal[i-2], fm->signal[i-1]);
  371. break;
  372. case 1:
  373. pcm = polar_disc_fast(fm->signal[i], fm->signal[i+1],
  374. fm->signal[i-2], fm->signal[i-1]);
  375. break;
  376. case 2:
  377. pcm = polar_disc_lut(fm->signal[i], fm->signal[i+1],
  378. fm->signal[i-2], fm->signal[i-1]);
  379. break;
  380. }
  381. fm->signal2[i/2] = (int16_t)pcm;
  382. }
  383. fm->pre_r = fm->signal[fm->signal_len - 2];
  384. fm->pre_j = fm->signal[fm->signal_len - 1];
  385. fm->signal2_len = fm->signal_len/2;
  386. }
  387. void am_demod(struct fm_state *fm)
  388. // todo, fix this extreme laziness
  389. {
  390. int i, pcm;
  391. for (i = 0; i < (fm->signal_len); i += 2) {
  392. // hypot uses floats but won't overflow
  393. //fm->signal2[i/2] = (int16_t)hypot(fm->signal[i], fm->signal[i+1]);
  394. pcm = fm->signal[i] * fm->signal[i];
  395. pcm += fm->signal[i+1] * fm->signal[i+1];
  396. fm->signal2[i/2] = (int16_t)sqrt(pcm); // * fm->output_scale;
  397. }
  398. fm->signal2_len = fm->signal_len/2;
  399. // lowpass? (3khz) highpass? (dc)
  400. }
  401. void usb_demod(struct fm_state *fm)
  402. {
  403. int i, pcm;
  404. for (i = 0; i < (fm->signal_len); i += 2) {
  405. pcm = fm->signal[i] + fm->signal[i+1];
  406. fm->signal2[i/2] = (int16_t)pcm; // * fm->output_scale;
  407. }
  408. fm->signal2_len = fm->signal_len/2;
  409. }
  410. void lsb_demod(struct fm_state *fm)
  411. {
  412. int i, pcm;
  413. for (i = 0; i < (fm->signal_len); i += 2) {
  414. pcm = fm->signal[i] - fm->signal[i+1];
  415. fm->signal2[i/2] = (int16_t)pcm; // * fm->output_scale;
  416. }
  417. fm->signal2_len = fm->signal_len/2;
  418. }
  419. void raw_demod(struct fm_state *fm)
  420. {
  421. /* hacky and pointless code */
  422. int i;
  423. for (i = 0; i < (fm->signal_len); i++) {
  424. fm->signal2[i] = (int16_t)fm->signal[i];
  425. }
  426. fm->signal2_len = fm->signal_len;
  427. }
  428. void deemph_filter(struct fm_state *fm)
  429. {
  430. static int avg; // cheating...
  431. int i, d;
  432. // de-emph IIR
  433. // avg = avg * (1 - alpha) + sample * alpha;
  434. for (i = 0; i < fm->signal2_len; i++) {
  435. d = fm->signal2[i] - avg;
  436. if (d > 0) {
  437. avg += (d + fm->deemph_a/2) / fm->deemph_a;
  438. } else {
  439. avg += (d - fm->deemph_a/2) / fm->deemph_a;
  440. }
  441. fm->signal2[i] = (int16_t)avg;
  442. }
  443. }
  444. void dc_block_filter(struct fm_state *fm)
  445. {
  446. int i, avg;
  447. int64_t sum = 0;
  448. for (i=0; i < fm->signal2_len; i++) {
  449. sum += fm->signal2[i];
  450. }
  451. avg = sum / fm->signal2_len;
  452. avg = (avg + fm->dc_avg * 9) / 10;
  453. for (i=0; i < fm->signal2_len; i++) {
  454. fm->signal2[i] -= avg;
  455. }
  456. fm->dc_avg = avg;
  457. }
  458. int mad(int *samples, int len, int step)
  459. /* mean average deviation */
  460. {
  461. int i=0, sum=0, ave=0;
  462. if (len == 0)
  463. {return 0;}
  464. for (i=0; i<len; i+=step) {
  465. sum += samples[i];
  466. }
  467. ave = sum / (len * step);
  468. sum = 0;
  469. for (i=0; i<len; i+=step) {
  470. sum += abs(samples[i] - ave);
  471. }
  472. return sum / (len / step);
  473. }
  474. int post_squelch(struct fm_state *fm)
  475. /* returns 1 for active signal, 0 for no signal */
  476. {
  477. int dev_r, dev_j, len, sq_l;
  478. /* only for small samples, big samples need chunk processing */
  479. len = fm->signal_len;
  480. sq_l = fm->squelch_level;
  481. dev_r = mad(&(fm->signal[0]), len, 2);
  482. dev_j = mad(&(fm->signal[1]), len, 2);
  483. if ((dev_r > sq_l) || (dev_j > sq_l)) {
  484. fm->squelch_hits = 0;
  485. return 1;
  486. }
  487. fm->squelch_hits++;
  488. return 0;
  489. }
  490. static void optimal_settings(struct fm_state *fm, int freq, int hopping)
  491. {
  492. int r, capture_freq, capture_rate;
  493. fm->downsample = (1000000 / fm->sample_rate) + 1;
  494. fm->freq_now = freq;
  495. capture_rate = fm->downsample * fm->sample_rate;
  496. capture_freq = fm->freqs[freq] + capture_rate/4;
  497. capture_freq += fm->edge * fm->sample_rate / 2;
  498. fm->output_scale = (1<<15) / (128 * fm->downsample);
  499. if (fm->output_scale < 1) {
  500. fm->output_scale = 1;}
  501. fm->output_scale = 1;
  502. /* Set the frequency */
  503. r = rtlsdr_set_center_freq(dev, (uint32_t)capture_freq);
  504. if (hopping) {
  505. return;}
  506. fprintf(stderr, "Oversampling input by: %ix.\n", fm->downsample);
  507. fprintf(stderr, "Oversampling output by: %ix.\n", fm->post_downsample);
  508. fprintf(stderr, "Buffer size: %0.2fms\n",
  509. 1000 * 0.5 * lcm_post[fm->post_downsample] * (float)DEFAULT_BUF_LENGTH / (float)capture_rate);
  510. if (r < 0) {
  511. fprintf(stderr, "WARNING: Failed to set center freq.\n");}
  512. else {
  513. fprintf(stderr, "Tuned to %u Hz.\n", capture_freq);}
  514. /* Set the sample rate */
  515. fprintf(stderr, "Sampling at %u Hz.\n", capture_rate);
  516. if (fm->output_rate > 0) {
  517. fprintf(stderr, "Output at %u Hz.\n", fm->output_rate);
  518. } else {
  519. fprintf(stderr, "Output at %u Hz.\n", fm->sample_rate/fm->post_downsample);}
  520. r = rtlsdr_set_sample_rate(dev, (uint32_t)capture_rate);
  521. if (r < 0) {
  522. fprintf(stderr, "WARNING: Failed to set sample rate.\n");}
  523. }
  524. void full_demod(struct fm_state *fm)
  525. {
  526. int i, sr, freq_next, hop = 0;
  527. rotate_90(fm->buf, fm->buf_len);
  528. if (fm->fir_enable) {
  529. low_pass_fir(fm, fm->buf, fm->buf_len);
  530. } else {
  531. low_pass(fm, fm->buf, fm->buf_len);
  532. }
  533. fm->mode_demod(fm);
  534. if (fm->mode_demod == &raw_demod) {
  535. fwrite(fm->signal2, 2, fm->signal2_len, fm->file);
  536. return;
  537. }
  538. sr = post_squelch(fm);
  539. if (!sr && fm->squelch_hits > fm->conseq_squelch) {
  540. if (fm->terminate_on_squelch) {
  541. fm->exit_flag = 1;}
  542. if (fm->freq_len == 1) { /* mute */
  543. for (i=0; i<fm->signal_len; i++) {
  544. fm->signal2[i] = 0;}
  545. }
  546. else {
  547. hop = 1;}
  548. }
  549. if (fm->post_downsample > 1) {
  550. fm->signal2_len = low_pass_simple(fm->signal2, fm->signal2_len, fm->post_downsample);}
  551. if (fm->output_rate > 0) {
  552. low_pass_real(fm);
  553. }
  554. if (fm->deemph) {
  555. deemph_filter(fm);}
  556. if (fm->dc_block) {
  557. dc_block_filter(fm);}
  558. /* ignore under runs for now */
  559. fwrite(fm->signal2, 2, fm->signal2_len, fm->file);
  560. if (hop) {
  561. freq_next = (fm->freq_now + 1) % fm->freq_len;
  562. optimal_settings(fm, freq_next, 1);
  563. fm->squelch_hits = fm->conseq_squelch + 1; /* hair trigger */
  564. /* wait for settling and flush buffer */
  565. usleep(5000);
  566. rtlsdr_read_sync(dev, NULL, 4096, NULL);
  567. }
  568. }
  569. static void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
  570. {
  571. struct fm_state *fm2 = ctx;
  572. int dr_val;
  573. if (do_exit) {
  574. return;}
  575. if (!ctx) {
  576. return;}
  577. memcpy(fm2->buf, buf, len);
  578. fm2->buf_len = len;
  579. /* single threaded uses 25% less CPU? */
  580. /* full_demod(fm2); */
  581. sem_getvalue(&data_ready, &dr_val);
  582. if (dr_val <= 0) {
  583. sem_post(&data_ready);}
  584. }
  585. static void *demod_thread_fn(void *arg)
  586. {
  587. struct fm_state *fm2 = arg;
  588. while (!do_exit) {
  589. sem_wait(&data_ready);
  590. full_demod(fm2);
  591. if (fm2->exit_flag) {
  592. do_exit = 1;
  593. rtlsdr_cancel_async(dev);}
  594. }
  595. return 0;
  596. }
  597. double atofs(char* f)
  598. /* standard suffixes */
  599. {
  600. char* chop;
  601. double suff = 1.0;
  602. chop = malloc((strlen(f)+1)*sizeof(char));
  603. strncpy(chop, f, strlen(f)-1);
  604. switch (f[strlen(f)-1]) {
  605. case 'G':
  606. suff *= 1e3;
  607. case 'M':
  608. suff *= 1e3;
  609. case 'k':
  610. suff *= 1e3;
  611. suff *= atof(chop);}
  612. free(chop);
  613. if (suff != 1.0) {
  614. return suff;}
  615. return atof(f);
  616. }
  617. void frequency_range(struct fm_state *fm, char *arg)
  618. {
  619. char *start, *stop, *step;
  620. int i;
  621. start = arg;
  622. stop = strchr(start, ':') + 1;
  623. stop[-1] = '\0';
  624. step = strchr(stop, ':') + 1;
  625. step[-1] = '\0';
  626. for(i=(int)atofs(start); i<=(int)atofs(stop); i+=(int)atofs(step))
  627. {
  628. fm->freqs[fm->freq_len] = (uint32_t)i;
  629. fm->freq_len++;
  630. }
  631. stop[-1] = ':';
  632. step[-1] = ':';
  633. }
  634. void fm_init(struct fm_state *fm)
  635. {
  636. fm->freqs[0] = 100000000;
  637. fm->sample_rate = DEFAULT_SAMPLE_RATE;
  638. fm->squelch_level = 0;
  639. fm->conseq_squelch = 20;
  640. fm->terminate_on_squelch = 0;
  641. fm->squelch_hits = 0;
  642. fm->freq_len = 0;
  643. fm->edge = 0;
  644. fm->fir_enable = 0;
  645. fm->prev_index = 0;
  646. fm->post_downsample = 1; // once this works, default = 4
  647. fm->custom_atan = 0;
  648. fm->deemph = 0;
  649. fm->output_rate = -1; // flag for disabled
  650. fm->mode_demod = &fm_demod;
  651. fm->pre_j = fm->pre_r = fm->now_r = fm->now_j = 0;
  652. fm->prev_lpr_index = 0;
  653. fm->deemph_a = 0;
  654. fm->now_lpr = 0;
  655. fm->dc_block = 0;
  656. fm->dc_avg = 0;
  657. }
  658. int main(int argc, char **argv)
  659. {
  660. #ifndef _WIN32
  661. struct sigaction sigact;
  662. #endif
  663. struct fm_state fm;
  664. char *filename = NULL;
  665. int n_read, r, opt, wb_mode = 0;
  666. int i, gain = AUTO_GAIN; // tenths of a dB
  667. uint8_t *buffer;
  668. uint32_t dev_index = 0;
  669. int device_count;
  670. int ppm_error = 0;
  671. char vendor[256], product[256], serial[256];
  672. fm_init(&fm);
  673. sem_init(&data_ready, 0, 0);
  674. while ((opt = getopt(argc, argv, "d:f:g:s:b:l:o:t:r:p:EFA:NWMULRDC")) != -1) {
  675. switch (opt) {
  676. case 'd':
  677. dev_index = atoi(optarg);
  678. break;
  679. case 'f':
  680. if (strchr(optarg, ':'))
  681. {frequency_range(&fm, optarg);}
  682. else
  683. {
  684. fm.freqs[fm.freq_len] = (uint32_t)atofs(optarg);
  685. fm.freq_len++;
  686. }
  687. break;
  688. case 'g':
  689. gain = (int)(atof(optarg) * 10);
  690. break;
  691. case 'l':
  692. fm.squelch_level = (int)atof(optarg);
  693. break;
  694. case 's':
  695. fm.sample_rate = (uint32_t)atofs(optarg);
  696. break;
  697. case 'r':
  698. fm.output_rate = (int)atofs(optarg);
  699. break;
  700. case 'o':
  701. fm.post_downsample = (int)atof(optarg);
  702. if (fm.post_downsample < 1 || fm.post_downsample > MAXIMUM_OVERSAMPLE) {
  703. fprintf(stderr, "Oversample must be between 1 and %i\n", MAXIMUM_OVERSAMPLE);}
  704. break;
  705. case 't':
  706. fm.conseq_squelch = (int)atof(optarg);
  707. if (fm.conseq_squelch < 0) {
  708. fm.conseq_squelch = -fm.conseq_squelch;
  709. fm.terminate_on_squelch = 1;
  710. }
  711. break;
  712. case 'p':
  713. ppm_error = atoi(optarg);
  714. break;
  715. case 'E':
  716. fm.edge = 1;
  717. break;
  718. case 'F':
  719. fm.fir_enable = 1;
  720. break;
  721. case 'A':
  722. if (strcmp("std", optarg) == 0) {
  723. fm.custom_atan = 0;}
  724. if (strcmp("fast", optarg) == 0) {
  725. fm.custom_atan = 1;}
  726. if (strcmp("lut", optarg) == 0) {
  727. atan_lut_init();
  728. fm.custom_atan = 2;}
  729. break;
  730. case 'D':
  731. fm.deemph = 1;
  732. break;
  733. case 'C':
  734. fm.dc_block = 1;
  735. break;
  736. case 'N':
  737. fm.mode_demod = &fm_demod;
  738. break;
  739. case 'W':
  740. wb_mode = 1;
  741. fm.mode_demod = &fm_demod;
  742. fm.sample_rate = 170000;
  743. fm.output_rate = 32000;
  744. fm.custom_atan = 1;
  745. fm.post_downsample = 4;
  746. fm.deemph = 1;
  747. fm.squelch_level = 0;
  748. break;
  749. case 'M':
  750. fm.mode_demod = &am_demod;
  751. break;
  752. case 'U':
  753. fm.mode_demod = &usb_demod;
  754. break;
  755. case 'L':
  756. fm.mode_demod = &lsb_demod;
  757. break;
  758. case 'R':
  759. fm.mode_demod = &raw_demod;
  760. break;
  761. default:
  762. usage();
  763. break;
  764. }
  765. }
  766. /* quadruple sample_rate to limit to Δθ to ±π/2 */
  767. fm.sample_rate *= fm.post_downsample;
  768. if (fm.freq_len == 0) {
  769. fprintf(stderr, "Please specify a frequency.\n");
  770. exit(1);
  771. }
  772. if (fm.freq_len > 1) {
  773. fm.terminate_on_squelch = 0;
  774. }
  775. if (argc <= optind) {
  776. //usage();
  777. filename = "-";
  778. } else {
  779. filename = argv[optind];
  780. }
  781. buffer = malloc(lcm_post[fm.post_downsample] * DEFAULT_BUF_LENGTH * sizeof(uint8_t));
  782. device_count = rtlsdr_get_device_count();
  783. if (!device_count) {
  784. fprintf(stderr, "No supported devices found.\n");
  785. exit(1);
  786. }
  787. fprintf(stderr, "Found %d device(s):\n", device_count);
  788. for (i = 0; i < device_count; i++) {
  789. rtlsdr_get_device_usb_strings(i, vendor, product, serial);
  790. fprintf(stderr, " %d: %s, %s, SN: %s\n", i, vendor, product, serial);
  791. }
  792. fprintf(stderr, "\n");
  793. fprintf(stderr, "Using device %d: %s\n",
  794. dev_index, rtlsdr_get_device_name(dev_index));
  795. r = rtlsdr_open(&dev, dev_index);
  796. if (r < 0) {
  797. fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
  798. exit(1);
  799. }
  800. #ifndef _WIN32
  801. sigact.sa_handler = sighandler;
  802. sigemptyset(&sigact.sa_mask);
  803. sigact.sa_flags = 0;
  804. sigaction(SIGINT, &sigact, NULL);
  805. sigaction(SIGTERM, &sigact, NULL);
  806. sigaction(SIGQUIT, &sigact, NULL);
  807. sigaction(SIGPIPE, &sigact, NULL);
  808. #else
  809. SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
  810. #endif
  811. /* WBFM is special */
  812. if (wb_mode) {
  813. fm.freqs[0] += 16000;
  814. }
  815. if (fm.deemph) {
  816. fm.deemph_a = (int)round(1.0/((1.0-exp(-1.0/(fm.output_rate * 75e-6)))));
  817. }
  818. optimal_settings(&fm, 0, 0);
  819. build_fir(&fm);
  820. /* Set the tuner gain */
  821. if (gain == AUTO_GAIN) {
  822. r = rtlsdr_set_tuner_gain_mode(dev, 0);
  823. } else {
  824. r = rtlsdr_set_tuner_gain_mode(dev, 1);
  825. r = rtlsdr_set_tuner_gain(dev, gain);
  826. }
  827. if (r != 0) {
  828. fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
  829. } else if (gain == AUTO_GAIN) {
  830. fprintf(stderr, "Tuner gain set to automatic.\n");
  831. } else {
  832. fprintf(stderr, "Tuner gain set to %0.2f dB.\n", gain/10.0);
  833. }
  834. r = rtlsdr_set_freq_correction(dev, ppm_error);
  835. if (strcmp(filename, "-") == 0) { /* Write samples to stdout */
  836. fm.file = stdout;
  837. #ifdef _WIN32
  838. _setmode(_fileno(fm.file), _O_BINARY);
  839. #endif
  840. } else {
  841. fm.file = fopen(filename, "wb");
  842. if (!fm.file) {
  843. fprintf(stderr, "Failed to open %s\n", filename);
  844. exit(1);
  845. }
  846. }
  847. /* Reset endpoint before we start reading from it (mandatory) */
  848. r = rtlsdr_reset_buffer(dev);
  849. if (r < 0) {
  850. fprintf(stderr, "WARNING: Failed to reset buffers.\n");}
  851. pthread_create(&demod_thread, NULL, demod_thread_fn, (void *)(&fm));
  852. rtlsdr_read_async(dev, rtlsdr_callback, (void *)(&fm),
  853. DEFAULT_ASYNC_BUF_NUMBER,
  854. lcm_post[fm.post_downsample] * DEFAULT_BUF_LENGTH);
  855. if (do_exit) {
  856. fprintf(stderr, "\nUser cancel, exiting...\n");}
  857. else {
  858. fprintf(stderr, "\nLibrary error %d, exiting...\n", r);}
  859. rtlsdr_cancel_async(dev);
  860. if (fm.file != stdout) {
  861. fclose(fm.file);}
  862. rtlsdr_close(dev);
  863. free (buffer);
  864. return r >= 0 ? r : -r;
  865. }