You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

359 lines
13 KiB

/* SPDX-License-Identifier: MIT
* Copyright (c) 2026 Dan Chokola, KD2HSG
*
* cm_rx: streaming chirpmodem receiver (the C counterpart of stream_rx.py),
* a thin command-line front end to the library's chirpmodem_rx.
*
* rtl_sdr -f 223330000 -s 1000000 -g 40 - | ./cm_rx --sf 12
* ./cm_rx --rtl --sf 12 --gain 49.6 (runs rtl_sdr itself)
* ./cm_rx capture.cu8 --fs 2.4e6 --lo 223.33e6 --sf 12 (replay, full speed)
* ./cm_rx capture --sf 12 (SigMF: name, name.sigmf-meta or -data)
*
* Input: raw interleaved I/Q (--format cu8 [rtl_sdr], ci8, ci16, cf32) at
* --fs, centered at --lo; the signal is at --freq (default 223.580 MHz,
* LO default 250 kHz below it). A file with a .sigmf-meta beside it takes
* format, rate and LO from the metadata (as stream_rx.py does) unless
* --format is given; a raw file needs --fs and --lo. Not yet: narrowband
* excision (use the Python receiver where strong interferers are present).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <getopt.h>
#include "chirpmodem.h"
typedef struct {
int live;
} app_t;
static void print_body(const uint8_t *b, int n)
{
int text = 1;
for (int i = 0; i < n; i++)
if (!((b[i] >= 0x20 && b[i] < 0x7F) || b[i] == '\n' || b[i] == '\t'))
text = 0;
if (text) {
putchar('\'');
for (int i = 0; i < n; i++)
if (b[i] == '\n')
fputs("\\n", stdout);
else if (b[i] == '\t')
fputs("\\t", stdout);
else if (b[i] == '\'' || b[i] == '\\')
printf("\\%c", b[i]);
else
putchar(b[i]);
putchar('\'');
} else {
for (int i = 0; i < n; i++)
printf("%02x", b[i]);
}
}
static void on_frame(void *user, const chirpmodem_frame *f)
{
const app_t *app = user;
if (f->status != CHIRPMODEM_FRAME_OK) {
printf("[%9.3f s] preamble found, %s (offset %+.1f Hz)\n", f->t,
f->status == CHIRPMODEM_FRAME_HEADER_FAIL ? "header fail" : "payload fail",
f->offset_hz);
return;
}
if (app->live) {
time_t tt = time(NULL);
char hm[16];
strftime(hm, sizeof hm, "%H:%M:%S ", localtime(&tt));
fputs(hm, stdout);
}
printf("[%9.3f s] %s%s%s: ", f->t, f->src[0] ? f->src : "?", f->dst[0] ? " -> " : "", f->dst);
print_body(f->body, f->body_len);
int lic = f->profile == CHIRPMODEM_LICENSED;
printf("\n SNR %+.1f dB, offset %+.1f Hz (%+.2f ppm), %s, %d B",
f->snr_db, f->offset_hz, f->offset_ppm, lic ? "licensed" : "unlicensed", f->body_len);
const char *sep = "; ";
if (!f->coherent)
printf("%snon-coherent", sep);
if (!f->policy_ok)
printf("%sPOLICY VIOLATION for licensed", sep);
if (f->encrypted)
printf("%sencrypted", sep);
if (f->ramp_retry)
printf("%scarrier drift removed (%+.2f Hz/s)", sep, f->ramp_hz_per_s);
if (f->drift_retry)
printf("%sclock corrected to %+.2f ppm", sep, f->clock_ppm);
if (f->dd_passes)
printf("%sdecision-directed x%d", sep, f->dd_passes);
printf("\n");
fflush(stdout);
}
static void on_log(void *user, const char *msg)
{
(void)user;
printf("(%s)\n", msg);
fflush(stdout);
}
/* ------------------------------------------------------------- SigMF */
/* Just enough JSON for a SigMF meta file: the first value of a key, as a
* number or a string. SigMF puts global first and captures before
* annotations, so the first "core:frequency" is captures[0]'s. */
static const char *json_value(const char *js, const char *key)
{
char pat[64];
snprintf(pat, sizeof pat, "\"%s\"", key);
const char *k = strstr(js, pat);
if (!k)
return NULL;
k += strlen(pat);
while (*k == ' ' || *k == '\t' || *k == '\r' || *k == '\n')
k++;
if (*k != ':')
return NULL;
k++;
while (*k == ' ' || *k == '\t' || *k == '\r' || *k == '\n')
k++;
return k;
}
static char *read_file(const char *path)
{
FILE *f = fopen(path, "rb");
if (!f)
return NULL;
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
char *s = malloc((size_t)n + 1);
if (fread(s, 1, (size_t)n, f) != (size_t)n) {
free(s);
fclose(f);
return NULL;
}
s[n] = 0;
fclose(f);
return s;
}
/* path ("name", "name.sigmf-meta" or "name.sigmf-data") -> data path, format,
* rate and LO. Returns 0 if there is no meta file, 1 if read, -1 on error. */
static int sigmf_open(const char *path, char *data, size_t ndata, char *fmt, size_t nfmt,
double *fs, double *lo)
{
static const char *exts[] = {".sigmf-meta", ".sigmf-data", ".sigmf"};
char base[4096], meta[4200];
snprintf(base, sizeof base, "%s", path);
for (int i = 0; i < 3; i++) {
size_t lb = strlen(base), le = strlen(exts[i]);
if (lb > le && !strcmp(base + lb - le, exts[i])) {
base[lb - le] = 0;
break;
}
}
snprintf(meta, sizeof meta, "%s.sigmf-meta", base);
char *js = read_file(meta);
if (!js)
return 0;
snprintf(data, ndata, "%s.sigmf-data", base);
const char *dt = json_value(js, "core:datatype"), *sr = json_value(js, "core:sample_rate"),
*fc = json_value(js, "core:frequency");
int ok = dt && *dt == '"' && sr && fc;
if (ok) {
char t[32] = {0};
size_t n = 0;
for (dt++; *dt && *dt != '"' && n < sizeof t - 1;)
t[n++] = *dt++;
/* SigMF names -> ours; little-endian only (big-endian would need swapping) */
const char *m = !strcmp(t, "cu8") ? "cu8" : !strcmp(t, "ci8") ? "ci8"
: !strcmp(t, "ci16_le") ? "ci16" : !strcmp(t, "cf32_le") ? "cf32" : NULL;
if (!m) {
fprintf(stderr, "%s: datatype %s is not supported (cu8, ci8, ci16_le, cf32_le)\n",
meta, t);
free(js);
return -1;
} else {
snprintf(fmt, nfmt, "%s", m);
*fs = atof(sr);
*lo = atof(fc);
ok = *fs > 0 && *lo > 0;
}
}
if (!ok)
fprintf(stderr, "%s: needs core:datatype, core:sample_rate and core:frequency\n", meta);
free(js);
return ok ? 1 : -1;
}
/* ------------------------------------------------------------- main */
static void usage(const char *a)
{
fprintf(stderr,
"usage: %s [FILE|-] [--rtl] [--gain DB] [--format cu8|ci8|ci16|cf32] [--fs HZ]\n"
" [--lo HZ] [--freq HZ] [--sf N] [--bw HZ] [--effort 0-2] [--auto-effort]\n"
" [--max-bytes N] [--status S] [-v]\n"
"FILE: a SigMF recording (name, name.sigmf-meta or name.sigmf-data; format, rate\n"
"and LO from its metadata unless --format is given), or raw I/Q with --fs and --lo.\n"
"- or no FILE: raw I/Q on stdin (default cu8 at 1 MS/s, as rtl_sdr -s 1000000).\n", a);
exit(2);
}
int main(int argc, char **argv)
{
const char *fmt = "cu8", *path = NULL;
double fs = 1e6, lo = 0, freq = 223.58e6, bw = 62.5e3, gain = 40, status = 30, rx_if = 250e3;
int sf = 9, effort = 2, auto_eff = 0, verbose = 0, rtl = 0, max_bytes = 255;
int set_fmt = 0, set_fs = 0, set_lo = 0;
char data_path[4200], sig_fmt[8];
static struct option opts[] = {
{"rtl", no_argument, 0, 'R'}, {"gain", required_argument, 0, 'g'},
{"format", required_argument, 0, 'F'}, {"fs", required_argument, 0, 's'},
{"lo", required_argument, 0, 'l'}, {"freq", required_argument, 0, 'f'},
{"sf", required_argument, 0, 'S'}, {"bw", required_argument, 0, 'b'},
{"effort", required_argument, 0, 'e'}, {"auto-effort", no_argument, 0, 'a'},
{"max-bytes", required_argument, 0, 'm'}, {"status", required_argument, 0, 't'},
{"rx-if", required_argument, 0, 'i'}, {"verbose", no_argument, 0, 'v'}, {0, 0, 0, 0}};
int o;
while ((o = getopt_long(argc, argv, "v", opts, NULL)) != -1) {
switch (o) {
case 'R': rtl = 1; break;
case 'g': gain = atof(optarg); break;
case 'F': fmt = optarg; set_fmt = 1; break;
case 's': fs = atof(optarg); set_fs = 1; break;
case 'l': lo = atof(optarg); set_lo = 1; break;
case 'f': freq = atof(optarg); break;
case 'S': sf = atoi(optarg); break;
case 'b': bw = atof(optarg); break;
case 'e': effort = atoi(optarg); break;
case 'a': auto_eff = 1; break;
case 'm': max_bytes = atoi(optarg); break;
case 't': status = atof(optarg); break;
case 'i': rx_if = atof(optarg); break;
case 'v': verbose = 1; break;
default: usage(argv[0]);
}
}
if (optind < argc)
path = argv[optind];
int live = rtl || !path || !strcmp(path, "-");
if (!live && !set_fmt) {
double mfs, mlo;
int r = sigmf_open(path, data_path, sizeof data_path, sig_fmt, sizeof sig_fmt, &mfs, &mlo);
if (r < 0)
return 1;
if (r > 0) {
/* the recording knows its own rate and LO; flags override with a warning */
if (set_fs && fabs(fs - mfs) > 1e-6)
fprintf(stderr, "warning: --fs %g overrides the recording's %g\n", fs, mfs);
if (set_lo && fabs(lo - mlo) > 1e-3)
fprintf(stderr, "warning: --lo %.0f overrides the recording's %.0f\n", lo, mlo);
fmt = sig_fmt;
if (!set_fs)
fs = mfs;
if (!set_lo)
lo = mlo;
path = data_path;
} else {
size_t lp = strlen(path);
if (lp > 11 && !strcmp(path + lp - 11, ".sigmf-data")) {
fprintf(stderr, "%s: no .sigmf-meta beside it; give --format, --fs and --lo\n", path);
return 1;
}
}
}
if (!live && !(set_fs && set_lo) && path != data_path) {
/* raw file: the defaults are rtl_sdr's live ones, a guess for a file */
fprintf(stderr, "%s: raw I/Q needs --fs and --lo (or a SigMF recording)\n", path);
return 1;
}
if (!lo)
lo = freq - rx_if;
FILE *in;
if (rtl) {
char cmd[256];
snprintf(cmd, sizeof cmd, "rtl_sdr -f %.0f -s %.0f -g %g - 2>/dev/null", lo, fs, gain);
fprintf(stderr, "$ %s\n", cmd);
in = popen(cmd, "r");
} else {
in = live ? stdin : fopen(path, "rb");
}
if (!in) {
perror(path ? path : "input");
return 1;
}
int bytes = !strcmp(fmt, "cu8") || !strcmp(fmt, "ci8") ? 2 : !strcmp(fmt, "ci16") ? 4
: !strcmp(fmt, "cf32") ? 8 : 0;
if (!bytes)
usage(argv[0]);
double if_off = freq - lo;
if (fabs(if_off) + bw / 2 > fs / 2) {
fprintf(stderr, "signal at %+.1f kHz from the LO is outside %g MS/s\n", if_off / 1e3, fs / 1e6);
return 1;
}
chirpmodem_format cfmt = !strcmp(fmt, "cu8") ? CHIRPMODEM_CU8 : !strcmp(fmt, "ci8") ? CHIRPMODEM_CI8
: !strcmp(fmt, "ci16") ? CHIRPMODEM_CI16 : CHIRPMODEM_CF32;
app_t app = {live};
chirpmodem_rx_config cfg;
chirpmodem_rx_config_init(&cfg);
cfg.sf = sf;
cfg.bw = bw;
cfg.fs = fs;
cfg.if_offset = if_off;
cfg.freq = freq;
cfg.max_bytes = max_bytes;
cfg.effort = effort;
cfg.auto_effort = auto_eff || live;
cfg.report_failures = verbose;
cfg.on_frame = on_frame;
cfg.on_log = on_log;
cfg.user = &app;
int err;
chirpmodem_rx *rx = chirpmodem_rx_new(&cfg, &err);
if (!rx) {
fprintf(stderr, "%s\n", chirpmodem_strerror(err));
return 1;
}
printf("SF%d, %g kHz at %.6f MHz; input %g MS/s %s, LO %.6f MHz; effort %d%s\n", sf,
bw / 1e3, freq / 1e6, fs / 1e6, fmt, lo / 1e6, effort, cfg.auto_effort ? " (auto)" : "");
long nblk = (long)(0.1 * fs);
uint8_t *raw = malloc((size_t)nblk * bytes);
long n_in = 0;
double last = 0;
chirpmodem_rx_stats st;
for (;;) {
size_t got = fread(raw, (size_t)bytes, (size_t)nblk, in);
if (!got)
break;
chirpmodem_rx_push(rx, raw, (long)got, cfmt);
n_in += (long)got;
double t = n_in / fs;
if (live && t - last >= status) {
last = t;
chirpmodem_rx_get_stats(rx, &st);
printf(" [%7.0f s] load %.0f%% (rate conversion %.0f%%, detection %.0f%%, decoding %.0f%%); "
"%ld decoded, effort %d\n", t,
100 * (st.cpu_convert + st.cpu_detect + st.cpu_decode) / t,
100 * st.cpu_convert / t, 100 * st.cpu_detect / t, 100 * st.cpu_decode / t,
st.frames_ok, st.effort);
fflush(stdout);
}
}
chirpmodem_rx_finish(rx);
chirpmodem_rx_get_stats(rx, &st);
double t = n_in / fs, busy = st.cpu_convert + st.cpu_detect + st.cpu_decode;
printf("%ld frame(s) decoded, %ld failed after sync; %.1f s of signal\n", st.frames_ok,
st.frames_failed, t);
if (t > 0 && busy > 0)
printf("processing: %.2f s = %.1fx real time (rate conversion %.2f s, detection %.2f s, "
"decoding %.2f s)\n", busy, t / busy, st.cpu_convert, st.cpu_detect, st.cpu_decode);
if (rtl)
pclose(in);
else if (!live)
fclose(in);
free(raw);
chirpmodem_rx_free(rx);
return 0;
}