Skip to content

uno-q — an RTL-SDR receive front end on a small ARM board

Get the code

The files are listed at the bottom of this page. The tabs there show the project on the development branch; this fetches the project's folder from the latest release, which can differ from them until the next release:

curl -fsSL https://github.com/doppler-dsp/doppler/archive/refs/tags/v0.88.0.tar.gz \
  | tar -xz --strip-components=2 doppler-0.88.0/example-projects/uno-q

Or browse example-projects/uno-q/.

The first stages of a receiver fed by an RTL-SDR, as a downstream project:

cu8 bytes ─→ U8ToF32 ─→ DDC (mix by −offset, decimate by rate) ─→ PSD

It was written for, and measured on, an Arduino UNO Q (Qualcomm QRB2210, four Cortex-A53-class cores, Debian 13), but nothing in it is board-specific. It builds and runs anywhere doppler does, which is how CI checks it. Copy the directory as the starting point for an SDR front end.

Three modes

command input what it does
uno_q_shared [flags] none Self-test. Synthesises one second of what an RTL-SDR would send (a tone at --offset in noise, through a model of its 8-bit ADC), runs the chain and checks the result. Any failed check exits non-zero.
uno_q_shared [flags] - or uno_q_shared [flags] FILE cu8 on stdin, or a capture file Live. Reports throughput, CPU load, the strongest peaks and the level in the channel. Nothing is checked, because live RF is not known in advance.
uno_q_shared [flags] --nats URL ci8 frames from uno_q_pub over NATS NATS. Counts lost and repeated frames from the wire header, then runs the same chain. Built when the doppler install has its stream component.
flag default meaning
--fs HZ 2.4e6 input sample rate
--offset HZ 250e3 where the wanted channel sits relative to the tuned centre; the DDC mixes it to DC
--rate R 0.125 DDC output/input rate
--n N 1024 PSD frame length
--seconds S until EOF live only: stop after S seconds of input
--nats URL none NATS mode: receive from this endpoint
--pattern P sub NATS: sub (core pub/sub) or pull (JetStream work queue)
--check off NATS: apply the self-test's checks to what arrived

Build and run

make build              # configure and compile
make run                # build, then self-test in both link modes
make clean

PREFIX=<dir> points at a doppler install (a make package-c tree or a release tarball); CPU_FLAGS=<flags> adds compiler flags for this program.

What the self-test checks

Every number is measured on the machine that runs it. Throughput is printed and never asserted, because it is a property of the machine.

  1. The cu8 bias is present before the DDC. An RTL-SDR's zero sits at code 127.5, and U8ToF32's fast shift mode centres on 128, so the converted stream reads 0.5/128 low. The self-test measures it: −0.003824 (I) and −0.003913 (Q), against −0.003906 predicted.
  2. The tone is mixed to DC, within one bin.
  3. The in-channel SNR matches its prediction, within 1 dB. The prediction is computed from the scene and the chain's own parameters: 48.33 dB predicted, 48.48 dB measured.
  4. The DDC filters the bias out. Mixing moves the bias to −offset, outside the channel. Its image reads −62.1 dB against −62.0 dB of noise around it; unfiltered, it would read −45.2 dB.

Each check has been shown to fail when the thing it guards is broken:

deliberate defect caught by
mixing in the wrong direction 2 and 3
the midpoint converter, which has no bias 1
noise 1.5× what the prediction assumes 3
an ADC model centred on 128 1
--rate 1, so no decimation filter 4

Two lessons are built into how it measures:

  • Measure noise where the signal is. dp_psd_noise_floor() is a median over the whole output band. The plain DDC uses an uncompensated CIC (see ddc_core.h), so the band isn't flat: −0.2 dB within ±0.1 of the output rate, −3.5 dB at ±0.25 and −12 dB near the edge. Against the band-wide median, the SNR read 3.6 dB too high.
  • Keep wideband channels in the flat part. For the same reason, choose --rate so the channel fits within about ±0.1 of the output rate. For broadcast FM (±75 kHz) that's --rate 0.25 (600 kSa/s), not 0.125.

On an Arduino UNO Q

Measured on 2026-09-26. The board runs Debian 13 on four Cortex-A53-class cores (/proc/cpuinfo part 0x801); GCC 14.2 and CMake 3.31 from Debian.

Connecting to the board.

The board has one USB-C port, and it can only report itself as a power sink. So the port is either a device link to a PC (power, adb, and a tunnel for samples) or a host port on a power-delivery hub (the dongle plugs into the hub). Pick one; the build steps are the same.

flowchart LR
    subgraph A["A: PC is the USB host (measured)"]
        direction LR
        pcA["PC<br/>rtl_tcp :1234 or NATS :4222"] -- "USB" --> hubA["powered hub"]
        hubA -- USB --> dA["RTL-SDR"]
        hubA -- "USB-C<br/>adb shell, adb reverse" --> bdA["UNO Q<br/>uno_q_shared"]
        pcA -. "SSH over Wi-Fi" .-> bdA
    end
    subgraph B["B: board is the USB host (measured)"]
        direction LR
        hubB["PD pass-through hub<br/>(+ power supply)"] -- "USB-C" --> bdB["UNO Q<br/>rtl_sdr | uno_q_shared"]
        dB["RTL-SDR"] -- USB --> hubB
        pcB["PC"] -. "SSH over Wi-Fi" .-> bdB
    end

A. PC as the host. The PC's USB port goes to a powered hub; the dongle and the board's USB-C port go to two of the hub's other ports (a direct PC port for either works too). The PC sees both, and the dongle stays on the PC:

lsusb | grep -E 'RTL2838|UNO Q'     # the dongle and the board
adb devices                         # the board is listed as `device`
adb shell                           # a shell on the board

adb reverse carries samples to the board over the same cable (see Dongle on a PC and Over NATS), so the board needs no network for the stream. If it is on Wi-Fi, ssh arduino@<board-address> gives the same shell. Under adb shell, set TMPDIR=/tmp (see Board notes).

B. Board as the host. The single USB-C port must carry power in and USB data out at once, so this needs a USB-C hub or dock with power-delivery pass-through: the hub takes the supply on its PD input, powers the board over the same cable, and exposes its downstream ports to the board as host. A plain bus-powered hub can't do this, and neither can an unpowered adapter.

Arduino sells one for the board (not tested here), the USB-C Hub (8-in-1) (65 W power passthrough, a USB-C data port, USB-A 2.0 and 3.0 ports, 4K30 HDMI, 100 Mbps Ethernet, SD and TF readers). It needs external power on its PD port. The dongle goes in a USB-A port (2.4 MSa/s is about 4.8 MB/s, well inside even USB 2.0), and the Ethernet port gives the board a wired address for SSH if Wi-Fi is a problem.

Nothing arrives over the cable to the PC, so the shell comes over the network. Join the board to Wi-Fi once, then:

ssh arduino@<board-address>         # a fixed address avoids DHCP surprises

Measured with the board booted with a PD pass-through hub already attached. That hub is not Arduino's: it reports two Genesys Logic hub chips (05e3:0610 and 05e3:0626) and a Gigabit Ethernet adapter (ASIX AX88179). The board enumerated all of them and the dongle. lsusb on the board lists the dongle when it works; if it doesn't, the board did not take the host role.

The dongle needs the RTL-SDR tools and permission to open it:

sudo apt install rtl-sdr
sudo usermod -aG plugdev arduino    # then log in again; the udev rule grants plugdev
rtl_test -t                         # finds the R820T tuner

Without the group, rtl_test fails with usb_open error -3 ("Please fix the device permissions"). rtl_test -t ends with "No E4000 tuner found" on an R820T dongle; that is the expected result. arduino is the board's default user; the address is whatever your router or nmcli shows. If Wi-Fi connects but gets no IPv4 address, see Board notes.

Either way, finish with the toolchain and build below, run on the board.

Toolchain. The board ships without one:

sudo apt install build-essential cmake ninja-build

Install doppler from a clone of this repository, then build this project against it:

make package-c PREFIX=$HOME/.local                 # from doppler's root
make -C example-projects/uno-q PREFIX=$HOME/.local run

Tuning. -march=native does nothing on this board: GCC does not know the core and resolves it to plain armv8-a+crc+crypto with no tuning. The Cortex-A53 scheduling model is what helps, because the core is in-order. Across 63 of doppler's C benchmarks, measured alternately against a portable build, a -mcpu=cortex-a53 build was slower on none by more than the ±5% run-to-run noise, and faster on 13, by up to 32% on multiply-accumulate loops (real FIR +25–32%). To build doppler that way, from its root:

make package-c PREFIX=$HOME/.local CMAKE_ARGS=-DCMAKE_C_FLAGS=-mcpu=cortex-a53

Throughput of this chain, from the self-test on one core: 20.0 MSa/s, 8.3× real time at 2.4 MSa/s (portable build). The desktop x86-64 machine used for comparison ran it at 275 MSa/s.

Benchmarks of the 2-D correlation detector and its parts. make bench times them through doppler's installed public API (bench.c), single thread, and prints a table in this shape; re-run it on your board or build (make bench PREFIX=$HOME/.local-a53 CPU_FLAGS=-mcpu=cortex-a53). Each case reports its fastest of 60 rounds. The UNO Q columns were measured on 2026-10-04 with the release current on that date, CPU governor schedutil. "Portable" is the default build; "A53" adds -mcpu=cortex-a53 (see Tuning).

The last column is doppler's published portable build for that release on an AMD Ryzen AI 9 465 (governor performance, boost on, pinned to the fastest cores; benchmarks/published/), from the library's own benchmarks rather than bench.c.

algorithm case UNO Q portable UNO Q A53 Ryzen AI 9 465
detector2d (corr + ring + peak) 16 × 1024 bins 6.4 MSa/s 6.4 MSa/s 100.2 MSa/s
128 × 128 bins 6.7 MSa/s 6.6 MSa/s 162.9 MSa/s
corr2d 16 × 2046, single-row ref 3.1 MSa/s 3.1 MSa/s 76.0 MSa/s
16 × 2046, multi-row ref 2.5 MSa/s 2.5 MSa/s 60.9 MSa/s
fft2d (cf32, forward) 256 × 256 11.0 Mbin/s 11.3 Mbin/s 390.3 Mbin/s
16 × 4096 10.9 Mbin/s 10.6 Mbin/s 223.8 Mbin/s
fft (cf32, forward) n = 256 67.8 Mbin/s 69.7 Mbin/s 686.6 Mbin/s
n = 4096 34.3 Mbin/s 33.6 Mbin/s 683.8 Mbin/s
n = 65536 6.7 Mbin/s 6.8 Mbin/s 551.8 Mbin/s
fir, real taps 15 taps 24.9 MSa/s 32.1 MSa/s 393.7 MSa/s
63 taps 7.2 MSa/s 9.5 MSa/s 91.1 MSa/s
255 taps 1.9 MSa/s 2.5 MSa/s 17.5 MSa/s
fir, complex taps 15 taps 10.7 MSa/s 11.2 MSa/s 168.3 MSa/s
63 taps 3.0 MSa/s 3.0 MSa/s 56.7 MSa/s
255 taps 0.8 MSa/s 0.8 MSa/s 17.0 MSa/s

How to read it:

  • The detector runs about 2.7× faster than the dongle's 2.4 MSa/s on one core, in either shape. detector2d is the corr2d transform plus a ring, a peak search and a noise estimate; the shape (16 × 1024 against 128 × 128) moves it by under 10%. One UNO Q core is 16–24× slower than a Ryzen core on it.
  • The A53 build helps the real-tap FIR and little else. Real-tap FIR gained 29–32% at every length; complex taps, the FFTs, corr2d and the detector did not move beyond run-to-run noise (about 5%).
  • A real-tap FIR costs 2.3–3.2× less per sample than a complex-tap one on the same coefficients, so give a symmetric real filter real taps.
  • The fft n = 4096 row differs from doppler's own bench_fft_core (22 Mbin/s there, 34 here). The cause wasn't investigated, so compare columns within one table rather than across tools.

Board notes:

  • The CPU governor defaults to schedutil. For repeatable timing, run echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; it resets on reboot.
  • If Wi-Fi connects but gets no IPv4 address, check the NetworkManager log for acd conflict. That means the router offered an address another device already holds. Reserve an address for the board on the router, or give it a fixed one with nmcli.
  • Under adb shell, TMPDIR is /data/local/tmp, which doesn't exist on Debian. Set TMPDIR=/tmp, or use SSH.

Over NATS: every frame accounted for

librtlsdr and rtl_tcp never report lost samples. doppler's own wire header numbers every frame, so over NATS a missing frame is a gap in the sequence and a redelivered one is a repeat, and the receiver counts both exactly. The end-of-stream frame takes the next number, so loss at the tail is counted too.

uno_q_pub puts the dongle on the wire. The wire has no unsigned-8 format, so it sends each code as x - 128 (ci8). The receiver decodes that with I8ToF32, which is bit-identical to U8ToF32("shift") on the original bytes.

The first line below starts a NATS broker; if you have none, the docs say how to get one.

nats-server -js                                                  # a broker
rtl_sdr -f 100e6 -s 2.4e6 - | build/uno_q_pub --nats nats://127.0.0.1:4222/rtl --fs 2.4e6 --fc 100e6
build/uno_q_shared --nats nats://127.0.0.1:4222/rtl --offset -100e3 --rate 0.25 --seconds 10

Two patterns, with the same code on both ends:

pattern flags delivery what a failure looks like
pub/sub (default) --pattern pub / sub at-most-once, freshest data a lost frame is a gap in the count
JetStream push/pull --pattern push / pull at-least-once, the broker keeps frames until acked nothing lost across a consumer stall or broker restart; a frame the broker refused is counted by the publisher; a redelivery is dropped as a duplicate

Measured (x86 PC, local broker):

  • A 1.5 s broker restart mid-stream: pub/sub delivered 367 of 367 frames, because the publisher's reconnect buffer held the frames and the subscriber resubscribed. Push/pull delivered 367 of 367 after riding out one receive error, because the durable consumer resumed.
  • A 400 MB burst into a subscriber stalled for 5 s: 6104 of 6104 frames on both patterns. doppler's subscriber queues without limit, so pub/sub loss comes from a lost connection or a link slower than the stream, not from a slow reader.
  • On the UNO Q, with the dongle on the PC and the broker reached through adb reverse tcp:4222 tcp:4222: 733 frames of live FM, 0 lost, 0 repeated. That's 10.01 s of input in 9.99 s at 46% of one core, against 32% for the same chain on a raw pipe; the difference is the NATS client and per-frame handling.

make nats-check runs both patterns end to end against a broker (NATS_URL, default nats://127.0.0.1:4222). Each run is held to the self-test's checks.

The source rate needs a long window. The receiver estimates it from the headers' capture times. rtl_sdr hands over a USB transfer (four frames) at a time, so the frames of one transfer carry nearly the same timestamp. Over 2 s the estimate read +1.4%; over 10 s it read −60 ppm.

Watching it live

doppler's spectrum analyzer subscribes to the same stream:

doppler-specan --source socket --address nats://127.0.0.1:4222/rtl --web

It needs the specan and specan-web extras. The display centres on the frequency the stream's header reports, unless you give --center.

Live input from an RTL-SDR

Measured with a Nooelec NESDR SMArt v5 (R820T tuner). On any Linux host with the dongle, first stop the kernel's DVB-T driver from claiming it: install rtl-sdr (which usually ships a blacklist), or blacklist dvb_usb_rtl28xxu yourself and unload it. rtl_test -t then finds the tuner.

Dongle on the board. The UNO Q has one USB-C port, and it can only report itself as a power sink. To use the dongle directly, the board must be the USB host of a power-delivery pass-through hub (see Connecting to the board, setup B), with the dongle on the hub and SSH over Wi-Fi for control. Then:

rtl_sdr -f 100e6 -s 2.4e6 - | build/uno_q_shared --offset -100e3 --rate 0.25 --seconds 10 -

Measured this way through a power-delivery hub: 24,000,000 samples, which is 10.00 s of input at 2.400 MSa/s, at 49.5% of one core (the receiver's own CPU time, with schedutil). rtl_sdr then prints "Short write, samples lost, exiting!": that is it noticing the receiver closed the pipe at --seconds, not a loss.

Dongle on a PC, stream to the board (how this was measured). This works when the board is a USB device of the PC, directly or through a hub. The PC serves the dongle with rtl_tcp, and adb reverse carries the stream over the same USB cable:

rtl_tcp -a 127.0.0.1 -f 100e6 -s 2.4e6        # on the PC
adb reverse tcp:1234 tcp:1234                 # on the PC
nc 127.0.0.1 1234 | tail -c +13 | build/uno_q_shared --offset -100e3 --rate 0.25 --seconds 5 -   # on the board

tail -c +13 drops rtl_tcp's 12-byte header. The link delivered 2.38 MSa/s to the board. With the dongle tuned to 100.0 MHz, a station at 99.9 MHz (--offset -100e3) was brought to DC at 32% of one core. The dongle's own DC spike moved to +100 kHz, out of the channel, which is the point of offset tuning.

Two rtl_tcp quirks. It prints "Signal caught, exiting!" each time a client disconnects, yet keeps serving. And it sends the 12-byte header before the samples, which tail -c +13 removes.

The files

cmake_minimum_required(VERSION 3.16)
project(doppler_uno_q C)

# An RTL-SDR receive front end on a small ARM board: cu8 -> U8ToF32 -> DDC
# -> PSD, self-testing on a synthetic capture or reading a live cu8 stream.
#
# Point CMake at an install prefix (a `cmake --install` tree or an extracted
# release tarball) with
#   -DCMAKE_PREFIX_PATH=/path/to/doppler-install
# or rely on a system install. Everything the receiver needs is in the
# pure-C core.
#
# `m` is on the link line because THIS program calls log10(), floorf() and
# friends for its own arithmetic; doppler's own libm use comes with the
# imported target.
# <!-- doc-version:start -->
find_package(doppler 0.88.0 REQUIRED)
# <!-- doc-version:end -->

add_executable(uno_q_shared main.c scene.c)
target_link_libraries(uno_q_shared PRIVATE doppler::doppler m)

if(TARGET doppler::doppler-static)
    add_executable(uno_q_static main.c scene.c)
    target_link_libraries(uno_q_static PRIVATE doppler::doppler-static m)
endif()

# The 2-D correlation detector and its parts, timed through the public API
# only (`make bench`). It is built with everything else so CI compiles it.
add_executable(uno_q_bench bench.c)
target_link_libraries(uno_q_bench PRIVATE doppler::doppler m)

# The NATS transport is OPTIONAL: doppler's stream component (doppler::stream,
# the vendored nats.c folded in) exists only in a POSIX install built with
# it. Where it does, the receiver gains --nats and the publisher is built;
# where it does not, the example is exactly what it was without it.
if(TARGET doppler::stream)
    target_compile_definitions(uno_q_shared PRIVATE UNO_Q_NATS)
    target_link_libraries(uno_q_shared PRIVATE doppler::stream)
    add_executable(uno_q_pub pub.c scene.c)
    target_link_libraries(uno_q_pub PRIVATE doppler::stream doppler::doppler m)
    if(TARGET uno_q_static AND TARGET doppler::stream-static)
        target_compile_definitions(uno_q_static PRIVATE UNO_Q_NATS)
        target_link_libraries(uno_q_static PRIVATE doppler::stream-static)
    endif()
    message(STATUS "uno-q: doppler::stream found -- NATS transport enabled")
else()
    message(STATUS "uno-q: no doppler::stream -- NATS transport not built")
endif()
# example-projects/uno-q — a downstream project's own Makefile.
#
# Deliberately thin: CMake is the build system, and this wraps the commands
# you would otherwise type. `make help` lists everything.

BUILD_DIR        ?= build
CMAKE_BUILD_TYPE ?= Release
# Where doppler is installed. Empty means "a system install CMake can already
# find"; set it to a `cmake --install` tree or an extracted release tarball:
#   make PREFIX=~/.local run
PREFIX           ?=
# Extra compiler flags for THIS program, e.g. CPU_FLAGS=-mcpu=cortex-a53 on
# an Arduino UNO Q, where -march=native resolves to a generic ARMv8 target
# (see README.md). doppler itself is tuned when IT is built, not here.
CPU_FLAGS        ?=
# The broker `nats-check` talks to: a JetStream one (`nats-server -js`).
NATS_URL         ?= nats://127.0.0.1:4222
# Timed rounds per case in `make bench`; each case reports its fastest.
BENCH_ROUNDS     ?= 60

CMAKE_FLAGS := -DCMAKE_BUILD_TYPE=$(CMAKE_BUILD_TYPE)
ifneq ($(strip $(PREFIX)),)
CMAKE_FLAGS += -DCMAKE_PREFIX_PATH=$(abspath $(PREFIX))
endif
ifneq ($(strip $(CPU_FLAGS)),)
CMAKE_FLAGS += "-DCMAKE_C_FLAGS=$(CPU_FLAGS)"
endif

.PHONY: all build run bench nats-check clean help
.DEFAULT_GOAL := build

all: build

# Configure every time rather than gating on CMakeCache.txt: re-running
# configure is cheap and idempotent, while a cached one silently ignores a
# changed PREFIX or CPU_FLAGS.
build:
    cmake -S . -B $(BUILD_DIR) $(CMAKE_FLAGS)
    cmake --build $(BUILD_DIR)

# The self-test, in BOTH link modes: the static one is where a missing
# transitive dependency shows up. It checks its own result and exits
# non-zero on any failure, so `make run` succeeding is the whole test.
run: build
    $(BUILD_DIR)/uno_q_shared
    @if [ -x $(BUILD_DIR)/uno_q_static ]; then \
        echo; echo "── again, linked statically ──"; \
        $(BUILD_DIR)/uno_q_static; \
    else \
        echo "note: no static target — this install ships no doppler::doppler-static"; \
    fi

# What the 2-D correlation detector and its parts cost on THIS machine (see
# bench.c). The table it prints has the same shape as README.md's, so a run
# on another board or build (CPU_FLAGS=...) pastes straight in. For
# repeatable numbers pin the governor first (README.md, "Board notes").
bench: build
    $(BUILD_DIR)/uno_q_bench $(BENCH_ROUNDS)

# The NATS transport end to end, both patterns (see nats-check.sh). Needs a
# JetStream broker at NATS_URL and a doppler install with its stream
# component; either missing is a failure, never a skip.
nats-check: build
    ./nats-check.sh $(BUILD_DIR) $(NATS_URL)

clean:
    rm -rf $(BUILD_DIR)

help:
    @echo "uno-q — an RTL-SDR receive front end (cu8 -> U8ToF32 -> DDC -> PSD)"
    @echo
    @echo "  make build              configure and compile"
    @echo "  make run                build, then self-test in both link modes"
    @echo "  make bench              time detector2d, corr2d, fft2d, fft, fir (single thread)"
    @echo "  make nats-check         NATS transport, pub/sub + push/pull (needs a broker)"
    @echo "  make clean              remove $(BUILD_DIR)/"
    @echo
    @echo "  PREFIX=<dir>            where doppler is installed"
    @echo "  CPU_FLAGS=<flags>       e.g. -mcpu=cortex-a53"
    @echo "  BENCH_ROUNDS=<n>        rounds per case in make bench, default 60"
    @echo "  NATS_URL=<url>          default nats://127.0.0.1:4222"
    @echo "  CMAKE_BUILD_TYPE=<t>    default Release"
    @echo "  BUILD_DIR=<dir>         default build"
    @echo
    @echo "  live input: $(BUILD_DIR)/uno_q_shared [--offset HZ ...] -   (cu8 on stdin)"
/* bench.c — what the 2-D correlation detector and its parts cost on THIS
 * machine, through doppler's installed public API only.
 *
 *     uno_q_bench [ROUNDS]            (default 60; `make bench` runs it)
 *
 * It prints one row per case: the algorithm, the case, and a rate, in the
 * same shape as the table in README.md ("On an Arduino UNO Q"), so a re-run
 * on another board or another build can be pasted straight over it.
 *
 *   detector2d   the whole detector: correlate, ring, peak search, noise
 *   corr2d       its transform alone, fast path and general path
 *   fft2d, fft   the transforms underneath it
 *   fir          a block filter, real taps against complex taps
 *
 * METHOD. The same three rules as doppler's own native/benchmarks (which
 * are not installed, so they cannot be linked from here):
 *
 *   - MIN over rounds, never the mean. Interrupts, migrations and clock
 *     steps only ever ADD time, so the minimum is the least-biased cost.
 *   - SETTLE once, untimed, before anything is measured, so the first case
 *     does not pay for the governor ramping up from idle.
 *   - Rounds on the OUTSIDE, cases on the inside, so whatever drift
 *     remains lands on every case instead of on the one timed first.
 *
 * Single thread throughout. Every case is a single-thread kernel, because
 * what a board has to spare is cores, and one core is the number that
 * scales.
 */
#include <complex.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "doppler/correlator/correlator_core.h"
#include "doppler/fft/fft_core.h"
#include "doppler/fft2d/fft2d_core.h"
#include "doppler/fir/fir_core.h"

#define DEFAULT_ROUNDS 60
#define SETTLE_S 0.25
#define MIN_ROUND_S 1e-3
#define FFT_FORWARD (-1)
#define MAX_RESULTS 64

/* One measured case. `run` does ONE round of work on `ctx`; `units` is how
   many samples (or bins) that round processes, so rate = units / time. */
typedef struct
{
  const char *algo;
  const char *what;
  const char *unit; /* "MSa/s" or "Mbin/s" */
  size_t      units;
  void (*run) (void *ctx);
  void  *ctx;
  size_t reps; /* calls per timed round, so a round lasts >= MIN_ROUND_S */
  double best; /* fastest round, per call, seconds */
} bench_case_t;

static double
now_s (void)
{
  struct timespec ts;
  (void)clock_gettime (CLOCK_MONOTONIC, &ts);
  return (double)ts.tv_sec + 1e-9 * (double)ts.tv_nsec;
}

/* A smooth chirp: a real correlation peak, and nothing the hardware can
   shortcut (a constant or zero input invites denormals). */
static void
chirp (float _Complex *x, size_t n, double rate)
{
  for (size_t i = 0; i < n; i++)
    {
      const double p = rate * (double)i * (double)i;
      x[i]           = (float _Complex) (cos (p) + sin (p) * I);
    }
}

static void *
must (void *p)
{
  if (!p)
    {
      (void)fprintf (stderr, "uno_q_bench: allocation or create() failed\n");
      exit (1);
    }
  return p;
}

/* ── detector2d: 4 frames of 16384 bins per round ────────────────────── */

#define DET_BINS 16384
#define DET_FRAMES 4

typedef struct
{
  dp_correlator_state_t *det;
  const float _Complex  *in;
  dp_correlator_hit_t    res[MAX_RESULTS];
} det_ctx_t;

static void
run_detector (void *c)
{
  det_ctx_t *d = c;
  dp_correlator_reset (d->det);
  for (int f = 0; f < DET_FRAMES; f++)
    (void)dp_correlator_push (d->det, d->in + (size_t)f * DET_BINS, DET_BINS,
                              d->res, MAX_RESULTS);
}

/* ── corr2d: one dump of a 16 x 2046 grid ────────────────────────────── */

#define C2_NY 16
#define C2_NX 2046

typedef struct
{
  dp_correlator_state_t *obj;
  float _Complex        *in, *out;
} corr_ctx_t;

static void
run_corr2d (void *c)
{
  corr_ctx_t  *k = c;
  const size_t n = (size_t)C2_NY * C2_NX;
  dp_correlator_execute (k->obj, k->in, n, k->out, n, NULL);
}

/* ── fft / fft2d, forward, complex float ─────────────────────────────── */

typedef struct
{
  dp_fft_state_t   *p1;
  dp_fft2d_state_t *p2;
  size_t            n;
  float _Complex   *in, *out;
} fft_ctx_t;

static void
run_fft (void *c)
{
  fft_ctx_t *f = c;
  dp_fft_execute_cf32 (f->p1, f->in, f->n, f->out, f->n);
}

static void
run_fft2d (void *c)
{
  fft_ctx_t *f = c;
  dp_fft2d_execute_cf32 (f->p2, f->in, f->n, f->out, f->n);
}

/* ── fir: one block of 65536 samples ─────────────────────────────────── */

#define FIR_BLOCK 65536

typedef struct
{
  dp_fir_state_t       *fir;
  const float _Complex *in;
  float _Complex       *out;
} fir_ctx_t;

static void
run_fir (void *c)
{
  fir_ctx_t *f = c;
  dp_fir_execute (f->fir, f->in, FIR_BLOCK, f->out);
}

/* A windowed sinc: real coefficients with a realistic mix of magnitudes and
   signs. The complex filter gets the SAME coefficients with zero imaginary
   parts, which is what a caller gets by handing real taps to the complex
   constructor — the mistake this row prices. */
static void
sinc_taps (float *t, size_t n)
{
  for (size_t k = 0; k < n; k++)
    {
      const double m = (double)k - (double)(n - 1) / 2.0;
      const double s = (m == 0.0) ? 1.0 : sin (M_PI * 0.25 * m) / (M_PI * m);
      t[k]           = (float)(s
                               * (0.54
                                  - 0.46
                                        * cos (2.0 * M_PI * (double)k
                                               / (double)(n - 1))));
    }
}

#define MAX_CASES 24

int
main (int argc, char **argv)
{
  const long   arg    = argc > 1 ? strtol (argv[1], NULL, 10) : 0;
  const int    rounds = arg > 0 ? (int)arg : DEFAULT_ROUNDS;
  bench_case_t cases[MAX_CASES];
  size_t       nc = 0;

#define ADD(A, W, U, N, F, C)                                                 \
  cases[nc++] = (bench_case_t){ A, W, U, N, F, C, 1, 1e30 }

  /* detector2d — the 16 x 1024 and 128 x 128 shapes of 16384 bins. */
  float _Complex *dref = must (malloc (DET_BINS * sizeof *dref));
  float _Complex *din
      = must (malloc ((size_t)DET_FRAMES * DET_BINS * sizeof *din));
  chirp (dref, DET_BINS, 1e-5);
  for (int f = 0; f < DET_FRAMES; f++)
    chirp (din + (size_t)f * DET_BINS, DET_BINS, 1e-5);
  static det_ctx_t    det[2];
  static const size_t dny[2] = { 16, 128 }, dnx[2] = { 1024, 128 };
  static char         dname[2][32];
  for (int i = 0; i < 2; i++)
    {
      det[i].in  = din;
      det[i].det = must (dp_correlator_create_detector_2d (
          dref, dny[i], dnx[i], 1, 1, DET_BINS - 1, DET_NOISE_MEAN, 0.0f, 1));
      (void)snprintf (dname[i], sizeof dname[i], "%zu x %zu bins", dny[i],
                      dnx[i]);
      ADD ("detector2d", dname[i], "MSa/s", (size_t)DET_FRAMES * DET_BINS,
           run_detector, &det[i]);
    }

  /* corr2d — a single-row reference takes the fast path; a full-grid one
     takes the general 2-D path. */
  const size_t       cn = (size_t)C2_NY * C2_NX;
  static corr_ctx_t  cor[2];
  static const char *cname[2]
      = { "16 x 2046, single-row ref", "16 x 2046, multi-row ref" };
  for (int i = 0; i < 2; i++)
    {
      float _Complex *ref = must (calloc (cn, sizeof *ref));
      chirp (ref, i == 0 ? C2_NX : cn, 1e-5);
      cor[i].in  = must (malloc (cn * sizeof *cor[i].in));
      cor[i].out = must (malloc (cn * sizeof *cor[i].out));
      chirp (cor[i].in, cn, 3e-6);
      cor[i].obj
          = must (dp_correlator_create_2d (ref, C2_NY, C2_NX, 1, 1, 0, 0, -1));
      free (ref);
      ADD ("corr2d", cname[i], "MSa/s", cn, run_corr2d, &cor[i]);
    }

  /* fft2d and fft — complex float, forward. */
  static fft_ctx_t    f2[2], f1[3];
  static const size_t f2y[2] = { 256, 16 }, f2x[2] = { 256, 4096 };
  static const size_t f1n[3] = { 256, 4096, 65536 };
  static char         f2name[2][32], f1name[3][32];
  for (int i = 0; i < 2; i++)
    {
      f2[i].n   = f2y[i] * f2x[i];
      f2[i].in  = must (malloc (f2[i].n * sizeof *f2[i].in));
      f2[i].out = must (malloc (f2[i].n * sizeof *f2[i].out));
      chirp (f2[i].in, f2[i].n, 1e-6);
      f2[i].p2 = must (dp_fft2d_create (f2y[i], f2x[i], FFT_FORWARD, 1));
      (void)snprintf (f2name[i], sizeof f2name[i], "%zu x %zu", f2y[i],
                      f2x[i]);
      ADD ("fft2d (cf32, forward)", f2name[i], "Mbin/s", f2[i].n, run_fft2d,
           &f2[i]);
    }
  for (int i = 0; i < 3; i++)
    {
      f1[i].n   = f1n[i];
      f1[i].in  = must (malloc (f1n[i] * sizeof *f1[i].in));
      f1[i].out = must (malloc (f1n[i] * sizeof *f1[i].out));
      chirp (f1[i].in, f1n[i], 1e-6);
      f1[i].p1 = must (dp_fft_create (f1n[i], FFT_FORWARD, 1));
      (void)snprintf (f1name[i], sizeof f1name[i], "n = %zu", f1n[i]);
      ADD ("fft (cf32, forward)", f1name[i], "Mbin/s", f1n[i], run_fft,
           &f1[i]);
    }

  /* fir — real taps and complex taps at three lengths. */
  static const size_t taps[3] = { 15, 63, 255 };
  static fir_ctx_t    fr[6];
  static char         fname[6][32];
  float              *rt   = must (malloc (taps[2] * sizeof *rt));
  float _Complex     *ct   = must (malloc (taps[2] * sizeof *ct));
  float _Complex     *fin  = must (malloc (FIR_BLOCK * sizeof *fin));
  float _Complex     *fout = must (malloc (FIR_BLOCK * sizeof *fout));
  chirp (fin, FIR_BLOCK, 1e-6);
  for (int l = 0; l < 3; l++)
    {
      sinc_taps (rt, taps[l]);
      for (size_t k = 0; k < taps[l]; k++)
        ct[k] = (float _Complex)rt[k];
      for (int kind = 0; kind < 2; kind++)
        {
          fir_ctx_t *f = &fr[l * 2 + kind];
          f->in        = fin;
          f->out       = fout;
          f->fir       = must (kind == 0 ? dp_fir_create_real (rt, taps[l])
                                         : dp_fir_create (ct, taps[l]));
          (void)snprintf (fname[l * 2 + kind], sizeof fname[0], "%zu taps",
                          taps[l]);
        }
    }
  /* Listed by tap kind, so the real rows and the complex rows read as two
     blocks and the ratio between them is a look down the column. */
  for (int kind = 0; kind < 2; kind++)
    for (int l = 0; l < 3; l++)
      ADD (kind == 0 ? "fir, real taps" : "fir, complex taps",
           fname[l * 2 + kind], "MSa/s", FIR_BLOCK, run_fir,
           &fr[l * 2 + kind]);

  /* Settle: untimed work until the clock has stopped ramping. */
  for (double w0 = now_s (); now_s () - w0 < SETTLE_S;)
    cases[0].run (cases[0].ctx);

  /* A call of a few microseconds is mostly clock and call overhead, so a
     short case repeats inside one timed round until the round lasts at
     least MIN_ROUND_S; the reported time is per call. */
  for (size_t i = 0; i < nc; i++)
    {
      const double t0 = now_s ();
      cases[i].run (cases[i].ctx);
      const double dt = now_s () - t0;
      if (dt < MIN_ROUND_S)
        cases[i].reps = (size_t)(MIN_ROUND_S / (dt > 1e-7 ? dt : 1e-7)) + 1;
    }

  for (int r = 0; r < rounds; r++)
    for (size_t i = 0; i < nc; i++)
      {
        const double t0 = now_s ();
        for (size_t k = 0; k < cases[i].reps; k++)
          cases[i].run (cases[i].ctx);
        const double dt = (now_s () - t0) / (double)cases[i].reps;
        if (dt < cases[i].best)
          cases[i].best = dt;
      }

  (void)printf ("uno_q_bench: single thread, min over %d rounds\n\n", rounds);
  (void)printf ("| %-24s | %-26s | %12s |\n", "algorithm", "case", "rate");
  (void)printf ("| %-24s | %-26s | %12s |\n", "------------------------",
                "--------------------------", "------------");
  const char *last = "";
  for (size_t i = 0; i < nc; i++)
    {
      char rate[32];
      (void)snprintf (rate, sizeof rate, "%.1f %s",
                      (double)cases[i].units / cases[i].best / 1e6,
                      cases[i].unit);
      const int same = strcmp (cases[i].algo, last) == 0;
      (void)printf ("| %-24s | %-26s | %12s |\n", same ? "" : cases[i].algo,
                    cases[i].what, rate);
      last = cases[i].algo;
    }
  return 0;
}
/* uno-q — an RTL-SDR receive front end on a small ARM board.
 *
 * The first stages of a receiver fed by an RTL-SDR: take its native `cu8`
 * bytes, bring one channel to DC, decimate, and look at the spectrum.
 *
 *     cu8 bytes -> U8ToF32 -> DDC (mix by -offset, decimate by rate) -> PSD
 *
 * Written for, and measured on, an Arduino UNO Q (Qualcomm QRB2210, four
 * Cortex-A53-class cores), but nothing in it is board-specific: it builds and
 * runs anywhere doppler does, which is how CI checks it.
 *
 * Three ways to run it:
 *
 *   uno_q_shared [flags]
 *       SELF-TEST. Synthesises one second of what an RTL-SDR would send for
 *       a tone at --offset in noise, runs the chain, and CHECKS the result.
 *       Every failed check exits non-zero; this is the mode `make run` and
 *       CI use.
 *   uno_q_shared [flags] - | FILE
 *       LIVE. Reads cu8 from stdin or a capture file and reports what it
 *       found. Nothing is checked — live RF is not known in advance.
 *   uno_q_shared [flags] --nats URL
 *       NATS. Receives ci8 frames that uno_q_pub published (built only when
 *       the doppler install has its stream component). Counts lost and
 *       duplicated frames from the wire header, then runs the same chain.
 *
 * (`uno_q_static` is the same program linked against libdoppler.a.)
 *
 *     --fs HZ        input sample rate (default 2.4e6; NATS: from the header)
 *     --offset HZ    where the wanted channel sits relative to the tuned
 *                    centre; the DDC mixes it to DC (default 250e3)
 *     --rate R       output/input rate of the DDC (default 0.125)
 *     --n N          PSD frame length (default 1024)
 *     --seconds S    LIVE/NATS: stop after S seconds of input (default: end)
 *     --pattern P    NATS: `sub` (default; core pub/sub, at-most-once) or
 *                    `pull` (JetStream work queue, at-least-once)
 *     --check        NATS: apply the self-test's checks to what arrived
 *                    (meaningful when `uno_q_pub --synthetic` sent it)
 *     --expect-frames N  NATS: fail unless exactly N frames were received
 *     --stall-ms MS  NATS: pause once, mid-stream, for MS milliseconds —
 *                    what a busy consumer does. Neither pattern may lose a
 *                    frame to it: doppler's subscriber queues without limit
 *                    (so pub/sub loss comes from a lost connection or a
 *                    link slower than the stream, not a slow reader), and
 *                    a pull consumer's frames wait on the broker
 *
 * WHY THE OFFSET. An RTL-SDR puts its own DC spike at the tuned centre, and
 * U8ToF32's fast `shift` mapping adds another DC term (it reads 0.5/128 low;
 * see u8_to_f32_core.h). Tuning the dongle a few hundred kHz away from the
 * wanted signal and mixing it down digitally moves BOTH out of the channel,
 * where the DDC's filter removes them. The self-test checks exactly that:
 * the bias is present before the DDC and gone after it.
 *
 * LOSS. Neither librtlsdr nor rtl_tcp reports dropped samples. doppler's
 * wire header numbers every frame, so over NATS a missing frame is a gap in
 * `sequence` and a redelivered one is a repeat — both counted exactly. The
 * end-of-stream frame takes the next number, so loss at the tail shows too.
 *
 * Measurement comes from the library: PSD (a Welch averager) supplies the
 * spectrum, its noise floor and the in-band SNR. Every number printed is
 * measured on the machine that runs it and carries its units; throughput
 * is printed and never asserted, because it is a property of the machine.
 */
#include <complex.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "doppler/ddc/ddc_core.h"
#include "doppler/i8_to_f32/i8_to_f32_core.h"
#include "doppler/psd/psd_core.h"
#include "doppler/spectral/spectral_core.h"
#include "doppler/timing/timing_core.h"
#include "doppler/u8_to_f32/u8_to_f32_core.h"
#ifdef UNO_Q_NATS
#include "doppler/stream/stream.h"
#endif

#include "scene.h"

/* Complex samples per processing block: 64 KiB of cu8 bytes. */
#define BLOCK ((size_t)32768)

#define SCENE_SECONDS 1.0 /* length of the self-test scene                */
#define N_PEAKS 6         /* LIVE: how many spectral peaks to list        */
#define SNR_TOL_DB 1.0    /* in-channel SNR against its prediction, dB     */
#define CHANNEL 0.1 /* |f| < CHANNEL * fs_out: the flat, in-channel band */

static int failures = 0;

/** @brief Report one named check; any failure sets the exit status. */
static void
check (int ok, const char *what)
{
  printf ("  [%s] %s\n", ok ? "ok" : "FAIL", what);
  if (!ok)
    failures++;
}

/** @brief Monotonic seconds, from the library's clock (dp_mono_ns). */
static double
now_s (void)
{
  return (double)dp_mono_ns () * 1e-9;
}

/** @brief Process CPU seconds, to report load as a share of one core. */
static double
cpu_s (void)
{
  return (double)clock () / CLOCKS_PER_SEC;
}

/* ── Sequence accounting ───────────────────────────────────────────────────
 */

/**
 * @brief Frame bookkeeping from the wire header's `sequence`.
 *
 * The first frame sets the baseline — a subscriber that joins a running
 * stream has not LOST the frames before it joined — and from then on a jump
 * forward is a gap of that many frames and a number already seen is a
 * duplicate (JetStream redelivery; PUB/SUB never repeats one).
 */
typedef struct
{
  int      started;
  uint64_t first, next;
  uint64_t frames, gaps, dups;
} seq_t;

/** @brief Account one frame; 1 if it is new data, 0 if a duplicate. */
static int
seq_account (seq_t *s, uint64_t seq)
{
  if (!s->started)
    {
      s->started = 1;
      s->first   = seq;
      s->next    = seq;
    }
  if (seq < s->next)
    {
      s->dups++;
      return 0;
    }
  s->gaps += seq - s->next;
  s->next = seq + 1;
  s->frames++;
  return 1;
}

/* ── The chain ─────────────────────────────────────────────────────────────
 */

/** @brief The chain's state, shared by every mode. */
typedef struct
{
  dp_u8_to_f32_state_t *cvt_u8; /* cu8 in (stdin, file, self-test)      */
  dp_i8_to_f32_state_t *cvt_i8; /* ci8 in (NATS)                        */
  dp_ddc_state_t       *ddc;
  dp_psd_state_t       *psd;
  float complex        *cf;    /* converted input block, BLOCK        */
  float complex        *stage; /* DDC output awaiting a whole frame   */
  size_t                stage_len, stage_cap;
  size_t                n; /* PSD frame length                    */
  double sum_re, sum_im;   /* converted-input sums (bias check)  */
  size_t n_in;             /* complex input samples processed    */
} chain_t;

static int
chain_init (chain_t *c, double fs, double offset, double rate, size_t n)
{
  memset (c, 0, sizeof *c);
  c->n      = n;
  c->cvt_u8 = dp_u8_to_f32_create (U8_TO_F32_SHIFT);
  /* ci8 at scale 128 is bit-identical to cu8 through U8ToF32's `shift`:
     the publisher sends (x - 128), and #1568's tests pin the equivalence. */
  c->cvt_i8 = dp_i8_to_f32_create (128.0f);
  c->ddc    = dp_ddc_create (-offset / fs, rate);
  /* Hann window, no padding, 0 dBFS = amplitude 1.0, linear mean. */
  c->psd = dp_psd_create (n, fs * rate, DP_PSD_WINDOW_HANN, 0.0f, 1, 1.0, 0,
                          ACC_TRACE_MEAN, 0.0);
  c->cf  = malloc (BLOCK * sizeof *c->cf);
  c->stage_cap = dp_ddc_execute_max_out (c->ddc, BLOCK) + n;
  c->stage     = malloc (c->stage_cap * sizeof *c->stage);
  return c->cvt_u8 && c->cvt_i8 && c->ddc && c->psd && c->cf && c->stage;
}

static void
chain_free (chain_t *c)
{
  dp_u8_to_f32_destroy (c->cvt_u8);
  dp_i8_to_f32_destroy (c->cvt_i8);
  dp_ddc_destroy (c->ddc);
  dp_psd_destroy (c->psd);
  free (c->cf);
  free (c->stage);
}

/**
 * @brief Push `pairs` converted complex samples (in c->cf) through the DDC
 * and into the PSD.
 *
 * The PSD consumes whole frames only, so DDC output accumulates in a stage
 * buffer and the remainder carries into the next block: the spectrum sees
 * one unbroken stream however the input was chunked.
 */
static void
chain_push_cf (chain_t *c, size_t pairs)
{
  for (size_t i = 0; i < pairs; i++)
    {
      c->sum_re += crealf (c->cf[i]);
      c->sum_im += cimagf (c->cf[i]);
    }
  c->n_in += pairs;

  c->stage_len
      += dp_ddc_execute (c->ddc, c->cf, pairs, c->stage + c->stage_len,
                         c->stage_cap - c->stage_len);
  size_t whole = c->stage_len - c->stage_len % c->n;
  dp_psd_accumulate (c->psd, c->stage, whole);
  memmove (c->stage, c->stage + whole,
           (c->stage_len - whole) * sizeof *c->stage);
  c->stage_len -= whole;
}

/** @brief cu8 in: at most BLOCK pairs per call. */
static void
chain_push (chain_t *c, const uint8_t *cu8, size_t pairs)
{
  dp_u8_to_f32_steps (c->cvt_u8, cu8, (float *)c->cf, 2 * pairs);
  chain_push_cf (c, pairs);
}

/** @brief ci8 in, any length: converted and pushed BLOCK pairs at a time. */
static void
chain_push_ci8 (chain_t *c, const int8_t *ci8, size_t pairs)
{
  for (size_t done = 0; done < pairs;)
    {
      size_t m = pairs - done < BLOCK ? pairs - done : BLOCK;
      dp_i8_to_f32_steps (c->cvt_i8, ci8 + 2 * done, (float *)c->cf, 2 * m);
      chain_push_cf (c, m);
      done += m;
    }
}

/**
 * @brief Strongest peak of the averaged spectrum, as (frequency Hz, dB), from
 * the library's interpolating peak finder rather than a bin argmax.
 */
static void
spectrum_peak (chain_t *c, double fs_out, float *db, double *f_hz,
               double *level_db)
{
  dp_peak_t pk;
  dp_psd_psd_db (c->psd, db, c->n);
  /* A gate nothing falls under: the strongest local maximum, whatever it is.
   */
  size_t np = dp_find_peaks_f32 (db, c->n, 1, -1e30f, &pk);
  *f_hz     = np ? (double)pk.freq_norm * fs_out : 0.0;
  *level_db = np ? (double)pk.amplitude_db : -1e30;
}

/**
 * @brief Noise level in the bins within `half` of bin `k`, dB: the library's
 * dp_noise_floor_db() (a median) over just those bins.
 *
 * Why a sub-array and not dp_psd_noise_floor(): that is the median over the
 * WHOLE output band, and the plain DDC's output is not white.
 * dp_ddc_create() uses an UNCOMPENSATED CIC (see ddc_core.h), whose droop
 * reaches about -3.5 dB at a quarter of the output rate and -12 dB near its
 * edge, so the band-wide median sits ~3.5 dB below the noise actually next to
 * the tone. Measure the noise where the signal is. A median needs no bins
 * excluded: the tone's few bins are outliers it ignores. Against the mean of
 * the linear power it agrees to 0.02 dB here (the PSD has averaged hundreds
 * of frames, so each bin is nearly Gaussian in dB).
 */
static double
noise_near (const float *db, size_t n, size_t k, size_t half)
{
  size_t lo = k > half ? k - half : 0;
  size_t hi = k + half < n ? k + half : n - 1;
  return dp_noise_floor_db (db + lo, hi - lo + 1);
}

/** @brief Index of the bin nearest `f_hz` in the DC-centred spectrum. */
static size_t
bin_of (size_t n, double fs_out, double f_hz)
{
  long k = lround (f_hz / fs_out * (double)n) + (long)(n / 2);
  return k < 0 ? 0 : k >= (long)n ? n - 1 : (size_t)k;
}

/* ── Reports ───────────────────────────────────────────────────────────────
 */

/**
 * @brief The self-test's analysis: report the chain's result for the
 * synthetic scene and check it against predictions. Used by the self-test
 * and by `--nats ... --check`, so data that crossed the transport is held
 * to the same numbers as data built in place.
 */
static void
report_checked (chain_t *c, double fs, double offset, double rate)
{
  const size_t n      = c->n;
  const double fs_out = fs * dp_ddc_get_rate (c->ddc);
  float       *db     = malloc (n * sizeof *db);
  if (!db)
    {
      check (0, "allocate the spectrum");
      return;
    }
  double f_peak, peak_db;
  spectrum_peak (c, fs_out, db, &f_peak, &peak_db);
  const double floor_db = dp_psd_noise_floor (c->psd);
  const double chan_db
      = noise_near (db, n, n / 2, (size_t)(CHANNEL * (double)n));
  const double bin_hz = fs_out / (double)n;
  const double snr    = peak_db - chan_db;

  /* Predictions, from the scene and the chain's own parameters. In the flat
     channel around DC the DDC passes white input noise (quantization
     included) at the density it had, i.e. the share `rate` of its power per
     output-rate band; the PSD reads a tone at its power and noise at
     power * ENBW / n per bin. */
  const double q = 1.0 / 128.0;
  const double p_noise_in
      = 2.0 * SCENE_NOISE_SIGMA * SCENE_NOISE_SIGMA + 2.0 * q * q / 12;
  const double bin_noise = p_noise_in * rate * c->psd->enbw / (double)n;
  const double snr_pred  = 10.0 * log10 (SCENE_TONE_AMP * SCENE_TONE_AMP)
                           - 10.0 * log10 (bin_noise);
  const double bias      = -0.5 / 128.0;
  const double bias_se   = SCENE_NOISE_SIGMA / sqrt ((double)c->n_in);
  const double mean_re   = c->sum_re / (double)c->n_in;
  const double mean_im   = c->sum_im / (double)c->n_in;

  /* Where the bias lands after the DDC: input DC mixed by -offset, folded
     into the output band. */
  double       f_bias             = remainder (-offset, fs_out);
  const size_t k_bias             = bin_of (n, fs_out, f_bias);
  const double bias_db            = db[k_bias];
  const double bias_local_db      = noise_near (db, n, k_bias, 12);
  const double bias_unfiltered_db = 10.0 * log10 (2.0 * bias * bias);

  printf ("\nconverted input (before the DDC):\n");
  printf ("  mean I %+.6f, Q %+.6f   (0.5/128 low = %+.6f)\n", mean_re,
          mean_im, bias);
  printf ("after the DDC (%.1f kSa/s out, %zu-point Hann PSD):\n",
          fs_out / 1e3, n);
  printf ("  peak %+.1f Hz at %.1f dB\n", f_peak, peak_db);
  printf ("  noise in the channel (|f| < %.2f fs_out) %.2f dB/bin; band-wide "
          "median %.2f dB/bin\n",
          CHANNEL, chan_db, floor_db);
  printf ("  SNR in the channel %.2f dB (predicted %.2f dB)\n", snr, snr_pred);
  printf ("  at %+.1f kHz, where the bias lands: %.1f dB against %.1f dB of "
          "noise around it\n    (%.1f dB if it had passed unfiltered)\n\n",
          f_bias / 1e3, bias_db, bias_local_db, bias_unfiltered_db);

  check (fabs (mean_re - bias) < 6 * bias_se
             && fabs (mean_im - bias) < 6 * bias_se,
         "the cu8 bias is present before the DDC (0.5/128 low, I and Q)");
  check (fabs (f_peak) <= bin_hz, "the tone is mixed to DC (within 1 bin)");
  check (fabs (snr - snr_pred) <= SNR_TOL_DB,
         "in-channel SNR matches the prediction (within 1 dB)");
  if (fabs (f_bias) > 3.0 * bin_hz)
    check (bias_db <= bias_local_db + 3.0,
           "the DDC filters the bias out (its image reads as noise)");
  else
    printf ("  [skip] bias image lands on the tone; pick another --offset\n");
  free (db);
}

/** @brief The live report: what arrived, what it cost, what is in it. */
static void
report_live (chain_t *c, double fs, double offset, double dt, double dc)
{
  const size_t n      = c->n;
  const double fs_out = fs * dp_ddc_get_rate (c->ddc);
  float       *db     = malloc (n * sizeof *db);
  if (!db)
    return;
  double f_peak, peak_db;
  spectrum_peak (c, fs_out, db, &f_peak, &peak_db);
  const double input_s = (double)c->n_in / fs;

  printf ("  %zu samples = %.2f s of input at %.3f MSa/s\n", c->n_in, input_s,
          fs / 1e6);
  printf ("  wall %.2f s; CPU %.2f s = %.1f%% of one core at real time\n", dt,
          dc, input_s > 0 ? 100.0 * dc / input_s : 0.0);
  printf ("  converted input mean I %+.6f, Q %+.6f\n",
          c->n_in ? c->sum_re / (double)c->n_in : 0.0,
          c->n_in ? c->sum_im / (double)c->n_in : 0.0);
  printf ("  channel at %+.1f kHz -> DC, %.1f kSa/s out\n", offset / 1e3,
          fs_out / 1e3);
  printf ("  strongest bin %+.1f kHz at %.1f dBFS\n", f_peak / 1e3, peak_db);
  /* Not "noise" here: live, whatever occupies the channel is in it. */
  printf ("  median level in the channel (|f| < %.2f fs_out) "
          "%.1f dBFS/bin;\n    band-wide median %.1f dBFS/bin\n",
          CHANNEL, noise_near (db, n, n / 2, (size_t)(CHANNEL * (double)n)),
          dp_psd_noise_floor (c->psd));
  printf ("  occupied bandwidth (99%%): %.1f kHz\n",
          dp_psd_occupied_bw (c->psd, 0.99) / 1e3);

  /* The strongest peaks, from the library's interpolating peak finder,
     gated 10 dB above the band-wide median so noise bumps are not listed.
     With --offset 0 the one at DC is the dongle's own spike. */
  dp_peak_t pk[N_PEAKS];
  size_t    np = dp_find_peaks_f32 (
      db, n, N_PEAKS, (float)dp_psd_noise_floor (c->psd) + 10.0f, pk);
  printf ("  strongest peaks (relative to the tuned centre + offset):\n");
  for (size_t i = 0; i < np; i++)
    printf ("    %+8.1f kHz  %6.1f dBFS\n",
            (double)pk[i].freq_norm * fs_out / 1e3, pk[i].amplitude_db);
  free (db);
}

/* ── Modes ─────────────────────────────────────────────────────────────────
 */

static int
self_test (double fs, double offset, double rate, size_t n)
{
  const size_t total = (size_t)(SCENE_SECONDS * fs);
  printf ("self-test: %.3f s of cu8 at %.3f MSa/s, tone at %+.1f kHz\n",
          SCENE_SECONDS, fs / 1e6, offset / 1e3);

  uint8_t *cu8 = scene_cu8 (fs, offset, total);
  chain_t  c;
  if (!cu8 || !chain_init (&c, fs, offset, rate, n))
    return 1;

  /* The first block carries the DDC's filter start-up; restart the average
     after it so the spectrum describes the steady state. */
  double t0   = now_s ();
  size_t done = 0;
  while (done < total)
    {
      size_t m = total - done < BLOCK ? total - done : BLOCK;
      chain_push (&c, cu8 + 2 * done, m);
      if (done == 0)
        dp_psd_reset (c.psd);
      done += m;
    }
  double dt = now_s () - t0;

  report_checked (&c, fs, offset, rate);
  printf ("  throughput: %.2f MSa/s complex in, %.1fx real time at %.2f "
          "MSa/s\n",
          (double)c.n_in / dt / 1e6, (double)c.n_in / dt / fs, fs / 1e6);

  /* The loss accounting NATS mode relies on, held to a scripted sequence:
     frame 3 missing, frame 4 delivered twice. */
  seq_t                 s        = { 0 };
  static const uint64_t script[] = { 0, 1, 2, 4, 4, 5 };
  for (size_t i = 0; i < sizeof script / sizeof script[0]; i++)
    seq_account (&s, script[i]);
  check (s.frames == 5 && s.gaps == 1 && s.dups == 1,
         "loss accounting counts a skipped frame and a repeated one");

  free (cu8);
  chain_free (&c);
  printf ("%s\n", failures ? "FAILED" : "all checks passed");
  return failures ? 1 : 0;
}

static int
live (const char *path, double fs, double offset, double rate, size_t n,
      double seconds)
{
  FILE *in = strcmp (path, "-") == 0 ? stdin : fopen (path, "rb");
  if (!in)
    {
      perror (path);
      return 1;
    }
  chain_t  c;
  uint8_t *buf = malloc (2 * BLOCK);
  if (!buf || !chain_init (&c, fs, offset, rate, n))
    return 1;
  const size_t limit = seconds > 0.0 ? (size_t)(seconds * fs) : (size_t)-1;

  double t0 = now_s (), c0 = cpu_s ();
  size_t have = 0; /* bytes in buf, carried across reads for I/Q pairing */
  while (c.n_in < limit)
    {
      size_t got = fread (buf + have, 1, 2 * BLOCK - have, in);
      if (got == 0)
        break;
      have += got;
      size_t pairs = have / 2;
      if (pairs > limit - c.n_in)
        pairs = limit - c.n_in;
      chain_push (&c, buf, pairs);
      memmove (buf, buf + 2 * pairs, have - 2 * pairs);
      have -= 2 * pairs;
    }
  double dt = now_s () - t0, dc = cpu_s () - c0;
  if (in != stdin)
    (void)fclose (in);

  printf ("live:\n");
  report_live (&c, fs, offset, dt, dc);
  free (buf);
  chain_free (&c);
  return 0;
}

#ifdef UNO_Q_NATS
/** @brief Sleep `ms` milliseconds. */
static void
sleep_ms (long ms)
{
  struct timespec t = { ms / 1000, (ms % 1000) * 1000000L };
  nanosleep (&t, NULL);
}

static int
nats_receive (const char *url, int pull, double fs_flag, double offset,
              double rate, size_t n, double seconds, int do_check,
              long expect_frames, long stall_ms)
{
  dp_sub_t  *sub = NULL;
  dp_pull_t *pl  = NULL;
  if (pull)
    pl = dp_pull_create (url);
  else
    sub = dp_sub_create (url);
  if (!sub && !pl)
    {
      (void)fprintf (stderr, "cannot connect to %s\n", url);
      return 1;
    }
  /* A timeout, not a hang: PUB/SUB can lose the end-of-stream frame like
     any other, so silence must end the run too. */
  if (pull)
    dp_pull_set_timeout (pl, 3000);
  else
    dp_sub_set_timeout (sub, 3000);
  printf ("ready: %s (%s)\n", url,
          pull ? "JetStream pull, at-least-once" : "pub/sub, at-most-once");
  (void)fflush (stdout);

  chain_t  c;
  int      have_chain = 0, stalled = 0, eos = 0, hit_limit = 0;
  uint64_t eos_seq = 0;
  seq_t    s       = { 0 };
  double   fs = fs_flag, fc = 0.0;
  uint64_t ts_first = 0, ts_last = 0, last_frame_samples = 0;
  double   t0 = 0.0, c0 = 0.0, waited = 0.0;
  /* A dropped connection (a broker restart, a Wi-Fi blip) is DP_ERR_RECV,
     and it is transient: the client reconnects, and a durable pull consumer
     picks up where it stopped. Retry it, counted, for a bounded time. */
  unsigned long recv_errors = 0;
  double        err_since   = 0.0;

  for (;;)
    {
      dp_msg_t   *msg = NULL;
      dp_header_t h;
      memset (&h, 0, sizeof h); /* EOS: 0, not garbage, if it isn't filled */
      int rc
          = pull ? dp_pull_recv (pl, &msg, &h) : dp_sub_recv (sub, &msg, &h);
      if (rc == DP_ERR_EOF)
        {
          eos     = 1;
          eos_seq = h.sequence;
          break;
        }
      if (rc == DP_ERR_TIMEOUT)
        {
          if (s.frames)
            break; /* the stream went quiet: end of input */
          if ((waited += 3.0) >= 30.0)
            {
              (void)fprintf (stderr, "no frames on %s in %.0f s\n", url,
                             waited);
              return 1;
            }
          continue;
        }
      if (rc == DP_ERR_RECV)
        {
          recv_errors++;
          if (err_since == 0.0)
            err_since = now_s ();
          if (now_s () - err_since >= 30.0)
            {
              (void)fprintf (stderr, "no connection to %s for 30 s\n", url);
              return 1;
            }
          sleep_ms (200);
          continue;
        }
      if (rc != DP_OK)
        {
          (void)fprintf (stderr, "receive failed: %d\n", rc);
          return 1;
        }
      err_since = 0.0;
      if (h.format != CI8)
        {
          (void)fprintf (stderr, "expected ci8 frames, got format 0x%04x\n",
                         h.format);
          dp_msg_free (msg);
          return 1;
        }
      if (!have_chain)
        {
          if (h.sample_rate > 0.0)
            fs = h.sample_rate;
          fc = h.center_freq;
          /* main() checked --offset against --fs; the stream's own rate
             is the one the DDC normalises by, so check it again here. */
          if (fabs (offset) >= fs / 2.0)
            {
              (void)fprintf (stderr,
                             "--offset %.1f Hz is outside the stream's "
                             "+/- %.1f Hz (sample_rate %.1f)\n",
                             offset, fs / 2.0, fs);
              dp_msg_free (msg);
              return 2;
            }
          if (!chain_init (&c, fs, offset, rate, n))
            {
              (void)fprintf (stderr, "could not build the chain\n");
              dp_msg_free (msg);
              return 1;
            }
          have_chain = 1;
          t0         = now_s ();
          c0         = cpu_s ();
        }
      if (seq_account (&s, h.sequence))
        {
          if (!ts_first)
            ts_first = h.timestamp_ns;
          ts_last            = h.timestamp_ns;
          last_frame_samples = h.num_samples;
          chain_push_ci8 (&c, (const int8_t *)dp_msg_data (msg),
                          h.num_samples);
          if (s.frames == 1)
            dp_psd_reset (c.psd); /* drop the DDC start-up, as the self-test */
        }
      if (pull)
        dp_msg_ack (msg); /* a duplicate is acked too: it is handled */
      dp_msg_free (msg);

      if (stall_ms > 0 && !stalled && s.frames >= 8)
        {
          stalled = 1;
          sleep_ms (stall_ms);
        }
      if (seconds > 0.0 && (double)c.n_in >= seconds * fs)
        {
          hit_limit = 1;
          break;
        }
    }
  double dt = now_s () - t0, dc = cpu_s () - c0;

  /* Frames the sender numbered but we never saw: gaps inside the stream,
     plus any missing between the last one and the end-of-stream frame. */
  uint64_t tail = eos && eos_seq > s.next ? eos_seq - s.next : 0;
  double   span = (double)(ts_last - ts_first) * 1e-9;
  double   src_rate
      = span > 0 ? (double)(c.n_in - last_frame_samples) / span : 0.0;

  printf ("nats (%s): %s\n", pull ? "pull" : "sub", url);
  printf (
      "  frames %llu (first sequence %llu), lost %llu in the stream + %llu "
      "at the tail, duplicates %llu\n",
      (unsigned long long)s.frames, (unsigned long long)s.first,
      (unsigned long long)s.gaps, (unsigned long long)tail,
      (unsigned long long)s.dups);
  if (recv_errors)
    printf ("  receive errors ridden out (connection lost and back): %lu\n",
            recv_errors);
  if (eos)
    printf ("  end-of-stream received, numbered %llu\n",
            (unsigned long long)eos_seq);
  else if (hit_limit)
    printf ("  stopped after --seconds %.3g (the stream was still live)\n",
            seconds);
  else
    printf ("  end-of-stream not seen (the stream went quiet)\n");
  if (src_rate > 0)
    printf ("  source rate from header timestamps: %.0f Sa/s (%+.0f ppm of "
            "%.0f)\n",
            src_rate, (src_rate / fs - 1.0) * 1e6, fs);
  if (fc > 0)
    printf ("  tuned to %.6f MHz\n", fc / 1e6);
  if (have_chain)
    {
      if (do_check)
        report_checked (&c, fs, offset, rate);
      else
        report_live (&c, fs, offset, dt, dc);
    }

  if (do_check || expect_frames >= 0)
    {
      check (s.gaps == 0 && tail == 0, "no frame was lost in transport");
      check (s.dups == 0, "no frame was delivered twice");
      if (expect_frames >= 0)
        check ((long)s.frames == expect_frames && s.first == 0,
               "every frame the publisher sent arrived");
    }
  if (have_chain)
    chain_free (&c);
  if (pull)
    dp_pull_destroy (pl);
  else
    dp_sub_destroy (sub);
  if (do_check || expect_frames >= 0)
    printf ("%s\n", failures ? "FAILED" : "all checks passed");
  return failures ? 1 : 0;
}
#endif /* UNO_Q_NATS */

static void
usage (const char *argv0)
{
  (void)fprintf (stderr,
                 "usage: %s [--fs HZ] [--offset HZ] [--rate R] [--n N]\n"
                 "          [--seconds S] [- | FILE]\n"
#ifdef UNO_Q_NATS
                 "       %s [...] --nats URL [--pattern sub|pull] [--check]\n"
                 "          [--expect-frames N] [--stall-ms MS]\n"
#endif
                 "  no input: self-test (synthetic cu8, checked)\n"
                 "  - / FILE: live cu8 from stdin or a capture file\n",
                 argv0
#ifdef UNO_Q_NATS
                 ,
                 argv0
#endif
  );
}

int
main (int argc, char **argv)
{
  double      fs = 2.4e6, offset = 250e3, rate = 0.125, seconds = 0.0;
  size_t      n     = 1024;
  const char *input = NULL, *nats = NULL, *pattern = "sub";
  int         do_check      = 0;
  long        expect_frames = -1, stall_ms = 0;

  for (int i = 1; i < argc; i++)
    {
      const char *a       = argv[i];
      int         has_val = i + 1 < argc;
      if (strcmp (a, "--fs") == 0 && has_val)
        fs = strtod (argv[++i], NULL);
      else if (strcmp (a, "--offset") == 0 && has_val)
        offset = strtod (argv[++i], NULL);
      else if (strcmp (a, "--rate") == 0 && has_val)
        rate = strtod (argv[++i], NULL);
      else if (strcmp (a, "--n") == 0 && has_val)
        n = (size_t)strtoul (argv[++i], NULL, 10);
      else if (strcmp (a, "--seconds") == 0 && has_val)
        seconds = strtod (argv[++i], NULL);
      else if (strcmp (a, "--nats") == 0 && has_val)
        nats = argv[++i];
      else if (strcmp (a, "--pattern") == 0 && has_val)
        pattern = argv[++i];
      else if (strcmp (a, "--check") == 0)
        do_check = 1;
      else if (strcmp (a, "--expect-frames") == 0 && has_val)
        expect_frames = strtol (argv[++i], NULL, 10);
      else if (strcmp (a, "--stall-ms") == 0 && has_val)
        stall_ms = strtol (argv[++i], NULL, 10);
      else if ((strcmp (a, "-") == 0 || a[0] != '-') && !input)
        input = a;
      else
        {
          usage (argv[0]);
          return 2;
        }
    }
  if (!(fs > 0.0) || !(rate > 0.0 && rate <= 1.0) || n < 2
      || fabs (offset) >= fs / 2.0)
    {
      (void)fprintf (stderr, "need fs > 0, 0 < rate <= 1, n >= 2 and "
                             "|offset| < fs/2\n");
      return 2;
    }
  if (nats)
    {
#ifdef UNO_Q_NATS
      int pull = strcmp (pattern, "pull") == 0;
      if (!pull && strcmp (pattern, "sub") != 0)
        {
          (void)fprintf (stderr, "--pattern is sub or pull\n");
          return 2;
        }
      return nats_receive (nats, pull, fs, offset, rate, n, seconds, do_check,
                           expect_frames, stall_ms);
#else
      (void)fprintf (stderr, "--nats needs a doppler install with its stream "
                             "component (doppler::stream)\n");
      return 2;
#endif
    }
  return input ? live (input, fs, offset, rate, n, seconds)
               : self_test (fs, offset, rate, n);
}
#!/usr/bin/env bash
# nats-check.sh — the uno-q NATS transport, both patterns, end to end.
#
#   nats-check.sh BUILD_DIR [NATS_URL]      (default nats://127.0.0.1:4222)
#
# Needs a JetStream broker at NATS_URL (`nats-server -js`; in doppler's CI,
# `make nats-up`). A broker that is not there is a FAILURE, not a skip: a
# check that could not run has not passed.
#
# 1. PUB/SUB (the default pattern). The receiver subscribes first and says
#    so; the publisher then sends one second of the self-test scene, paced
#    at real time, and an end-of-stream frame. The receiver must get every
#    frame (none lost, none repeated, starting at sequence 0) and hold the
#    data to the self-test's own checks.
# 2. PUSH/PULL (JetStream). The publisher sends first -- the broker keeps
#    it, so no subscriber has to be listening -- and the receiver pulls it
#    all with a deliberate stall mid-stream. Every frame must still arrive,
#    once: at-least-once delivery may REPEAT a frame, and the receiver's
#    duplicate count must stay 0 on this clean run.
# 3. OFFSET vs STREAM RATE -- see the stage below.
set -euo pipefail

bin=${1:?usage: nats-check.sh BUILD_DIR [NATS_URL]}
url=${2:-nats://127.0.0.1:4222}
fs=2400000
frame=32768
# ceil(fs * 1 s / frame): the frames one second of the scene makes.
frames=$(( (fs + frame - 1) / frame ))
tag="unoq_check_$$"
log=$(mktemp -d)
trap 'rm -rf "$log"' EXIT

for exe in uno_q_shared uno_q_pub; do
    [ -x "$bin/$exe" ] || {
        echo "nats-check: $bin/$exe missing -- was the doppler install built" \
             "with its stream component (doppler::stream)?"
        exit 1
    }
done

echo "── pub/sub: $url/${tag}_sub, $frames frames expected ──"
"$bin/uno_q_shared" --nats "$url/${tag}_sub" --check \
    --expect-frames "$frames" > "$log/sub.out" 2>&1 &
rx=$!
# The subscriber must be listening before anything is published, or the
# first frames were never offered to it: wait for it to say so.
for _ in $(seq 100); do
    grep -q '^ready:' "$log/sub.out" 2>/dev/null && break
    kill -0 "$rx" 2>/dev/null || break
    sleep 0.1
done
grep -q '^ready:' "$log/sub.out" || {
    cat "$log/sub.out"; echo "nats-check: subscriber never became ready"
    kill "$rx" 2>/dev/null || true; exit 1
}
# A failing publisher must not end the script here: set -e would orphan the
# receiver and the EXIT trap would delete its log unread. Wait for it (it
# times out on its own) and print what it saw either way.
prc=0
"$bin/uno_q_pub" --nats "$url/${tag}_sub" --synthetic 1 --fs "$fs" \
    --frame "$frame" || prc=$?
rc=0; wait "$rx" || rc=$?
cat "$log/sub.out"
[ "$prc" -eq 0 ] || { echo "nats-check: publisher FAILED ($prc)"; exit 1; }
[ "$rc" -eq 0 ] || { echo "nats-check: pub/sub FAILED"; exit 1; }

echo "── push/pull: $url/${tag}_pull, stall 1500 ms mid-stream ──"
"$bin/uno_q_pub" --nats "$url/${tag}_pull" --pattern push --synthetic 1 \
    --fs "$fs" --frame "$frame"
"$bin/uno_q_shared" --nats "$url/${tag}_pull" --pattern pull --check \
    --expect-frames "$frames" --stall-ms 1500 \
    || { echo "nats-check: push/pull FAILED"; exit 1; }

# 3. The receiver checks --offset against the STREAM's rate, not --fs: the
#    header's sample_rate replaces the flag, so an offset legal at the
#    default 2.4 MSa/s can be outside a 1.024 MSa/s stream. It must refuse
#    (exit 2, saying why) rather than hand the DDC a frequency past Nyquist.
slow=1024000
echo "── offset vs stream rate: $url/${tag}_rate, ${slow} Sa/s stream ──"
"$bin/uno_q_pub" --nats "$url/${tag}_rate" --pattern push --synthetic 0.1 \
    --fs "$slow" --frame "$frame"
orc=0
"$bin/uno_q_shared" --nats "$url/${tag}_rate" --pattern pull \
    --offset 600e3 > "$log/rate.out" 2>&1 || orc=$?
cat "$log/rate.out"
[ "$orc" -eq 2 ] && grep -q "outside the stream's" "$log/rate.out" || {
    echo "nats-check: --offset past the stream's Nyquist was not refused" \
         "(exit $orc)"
    exit 1
}

echo "nats-check: OK -- both patterns, no frame lost or repeated;" \
     "offset checked against the stream's rate"
/* uno_q_pub — put an RTL-SDR's samples on doppler's NATS wire.
 *
 *     rtl_sdr -f FC -s FS - | uno_q_pub --nats URL --fs FS --fc FC
 *     uno_q_pub --nats URL --synthetic SECONDS        (the self-test scene)
 *
 * Reads cu8 (the dongle's unsigned offset-binary bytes) from stdin, or
 * synthesises the uno-q self-test scene, and publishes it in frames of
 * --frame complex samples. Every frame carries doppler's wire header: a
 * sequence number, the capture time, the sample rate and the centre
 * frequency — what rtl_tcp's stream does not have, and what lets the
 * receiver count lost and repeated frames exactly.
 *
 * ON THE WIRE IT IS ci8. The wire's formats are BLUE codes, and BLUE has no
 * unsigned byte, so each code goes out as (x - 128): exact, and bit-identical
 * downstream — I8ToF32 at scale 128 of (x - 128) is U8ToF32's `shift` of x.
 *
 *     --nats URL        endpoint, e.g. nats://127.0.0.1:4222/rtl (required)
 *     --pattern P       `pub` (default; core pub/sub) or `push` (JetStream
 *                       work queue, server-acked, at-least-once)
 *     --fs HZ           sample rate for the header (default 2.4e6)
 *     --fc HZ           centre frequency for the header (default 0: unknown)
 *     --frame N         complex samples per frame (default 32768)
 *     --synthetic S     publish S seconds of the self-test scene instead of
 *                       stdin, paced at real time
 *     --offset HZ       the scene's tone offset (default 250e3)
 *
 * A send the broker refuses is counted and reported, never retried
 * silently: on `push` that is the broker saying it did not take the frame.
 * The run ends with an end-of-stream frame and a drain, so everything sent
 * is on the server before the program exits.
 */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "doppler/stream/stream.h"
#include "doppler/timing/timing_core.h"
#include "scene.h"

static double
now_s (void)
{
  return (double)dp_mono_ns () * 1e-9;
}

int
main (int argc, char **argv)
{
  const char *url = NULL, *pattern = "pub";
  double      fs = 2.4e6, fc = 0.0, synthetic = 0.0, offset = 250e3;
  size_t      frame = 32768;

  for (int i = 1; i < argc; i++)
    {
      const char *a       = argv[i];
      int         has_val = i + 1 < argc;
      if (strcmp (a, "--nats") == 0 && has_val)
        url = argv[++i];
      else if (strcmp (a, "--pattern") == 0 && has_val)
        pattern = argv[++i];
      else if (strcmp (a, "--fs") == 0 && has_val)
        fs = strtod (argv[++i], NULL);
      else if (strcmp (a, "--fc") == 0 && has_val)
        fc = strtod (argv[++i], NULL);
      else if (strcmp (a, "--frame") == 0 && has_val)
        frame = (size_t)strtoul (argv[++i], NULL, 10);
      else if (strcmp (a, "--synthetic") == 0 && has_val)
        synthetic = strtod (argv[++i], NULL);
      else if (strcmp (a, "--offset") == 0 && has_val)
        offset = strtod (argv[++i], NULL);
      else
        {
          (void)fprintf (stderr,
                         "usage: %s --nats URL [--pattern pub|push] [--fs HZ] "
                         "[--fc HZ]\n          [--frame N] [--synthetic S] "
                         "[--offset HZ]\n",
                         argv[0]);
          return 2;
        }
    }
  int push = strcmp (pattern, "push") == 0;
  if (!url || frame == 0 || !(fs > 0.0) || (!push && strcmp (pattern, "pub")))
    {
      (void)fprintf (stderr, "need --nats URL, --frame > 0, --fs > 0 and "
                             "--pattern pub|push\n");
      return 2;
    }

  /* PUSH and PUB are the same send-capable context underneath; only the
     constructor differs. */
  dp_pub_t *pub = push ? (dp_pub_t *)dp_push_create (url, CI8)
                       : dp_pub_create (url, CI8);
  if (!pub)
    {
      (void)fprintf (stderr, "cannot connect to %s\n", url);
      return 1;
    }

  uint8_t *scene   = NULL;
  size_t   scene_n = 0;
  if (synthetic > 0.0)
    {
      scene_n = (size_t)(synthetic * fs);
      scene   = scene_cu8 (fs, offset, scene_n);
      if (!scene)
        return 1;
    }

  uint8_t *cu8 = malloc (2 * frame);
  int8_t  *ci8 = malloc (2 * frame);
  if (!cu8 || !ci8)
    return 1;

  size_t            sent = 0, refused = 0, samples = 0;
  double            t0 = now_s ();
  dp_sample_clock_t clk;
  dp_sample_clock_init (&clk, fs, 0);
  for (;;)
    {
      size_t pairs;
      if (scene)
        {
          if (samples >= scene_n)
            break;
          pairs = scene_n - samples < frame ? scene_n - samples : frame;
          memcpy (cu8, scene + 2 * samples, 2 * pairs);
          /* Real-time pacing: the library's sample clock sleeps until this
             block's deadline (epoch + n/fs) and counts a late one. */
          (void)dp_sample_clock_pace (&clk, pairs);
        }
      else
        {
          size_t got = fread (cu8, 2, frame, stdin); /* whole I/Q pairs */
          if (got == 0)
            break;
          pairs = got;
        }
      for (size_t i = 0; i < 2 * pairs; i++)
        ci8[i] = (int8_t)((int)cu8[i] - 128);
      int rc = push ? dp_push_send_ci8 ((dp_push_t *)pub, ci8, pairs, fs, fc)
                    : dp_pub_send_ci8 (pub, ci8, pairs, fs, fc);
      if (rc == DP_OK)
        sent++;
      else
        refused++;
      samples += pairs;
    }

  if (dp_pub_send_eos (pub) != DP_OK)
    (void)fprintf (stderr, "pub: end-of-stream refused; subscribers will "
                           "see silence, not an end\n");
  int drained = dp_stream_drain (pub, 5000);
  if (push)
    dp_push_destroy ((dp_push_t *)pub);
  else
    dp_pub_destroy (pub);

  printf ("uno_q_pub (%s): %zu frames sent, %zu refused, %zu samples in "
          "%.2f s; drain %s\n",
          push ? "push" : "pub", sent, refused, samples, now_s () - t0,
          drained == DP_OK ? "ok" : "timed out");
  free (scene);
  free (cu8);
  free (ci8);
  return refused || drained != DP_OK ? 1 : 0;
}
#include "scene.h"

#include <complex.h>
#include <math.h>
#include <stdlib.h>

#include "doppler/wfm_synth/wfm_synth_core.h"

uint8_t
scene_rtl_code (float v)
{
  float c = floorf (128.0f + 128.0f * v);
  return (uint8_t)(c < 0.0f ? 0.0f : c > 255.0f ? 255.0f : c);
}

uint8_t *
scene_cu8 (double fs, double offset, size_t n)
{
  float complex *x   = malloc (n * sizeof *x);
  uint8_t       *cu8 = malloc (2 * n);

  /* The tone and its noise come from the library's waveform synthesizer —
     the engine behind `wfmgen --type tone --snr` — at the SNR the scene's
     amplitude and noise sigma imply: tone power A^2 over complex noise power
     2*sigma^2, in the full sample-rate band (snr_mode 1). It returns a unit
     tone plus noise at that ratio; scale it to the scene's amplitude. */
  const double snr_db
      = 10.0
        * log10 (SCENE_TONE_AMP * SCENE_TONE_AMP
                 / (2.0 * SCENE_NOISE_SIGMA * SCENE_NOISE_SIGMA));
  dp_wfm_synth_state_t *syn = dp_wfm_synth_create (
      WFM_SYNTH_TONE, fs, offset, snr_db, 1, SCENE_SEED, 1, 8, 0, 0, 0.0);
  if (x && cu8 && syn)
    {
      dp_wfm_synth_steps (syn, x, n);
      for (size_t i = 0; i < n; i++)
        {
          const float complex v = (float)SCENE_TONE_AMP * x[i];
          cu8[2 * i]            = scene_rtl_code (crealf (v));
          cu8[2 * i + 1]        = scene_rtl_code (cimagf (v));
        }
    }
  else
    {
      free (cu8);
      cu8 = NULL;
    }
  dp_wfm_synth_destroy (syn);
  free (x);
  return cu8;
}
/* scene.h — the synthetic RTL-SDR capture both uno-q programs share.
 *
 * One definition of the test scene: the receiver's self-test builds it
 * locally, and `uno_q_pub --synthetic` publishes the same bytes over NATS, so
 * `uno_q_shared --check` can hold data that crossed the transport to exactly
 * the predictions the self-test uses.
 */
#ifndef UNO_Q_SCENE_H
#define UNO_Q_SCENE_H

#include <stddef.h>
#include <stdint.h>

/* A tone in noise, well inside the 8-bit range (peaks near 0.45 of full
   scale, so nothing clips). */
#define SCENE_TONE_AMP 0.25    /* complex tone amplitude; power -12.0 dBFS */
#define SCENE_NOISE_SIGMA 0.05 /* per-component std dev; complex -23 dBFS */
#define SCENE_SEED 0x5eedu

/**
 * @brief The dongle's 8-bit ADC, as a model: analog `v` to its cu8 code.
 *
 * The RTL2832U's zero sits BETWEEN codes 127 and 128, so a code covers
 * `[c - 128, c - 127) / 128` and the analog zero reads 127.5 on average —
 * which is what makes U8ToF32's `shift` read 0.5/128 low. A model of the
 * hardware, not a DSP stage.
 */
uint8_t scene_rtl_code (float v);

/**
 * @brief `n` complex samples of the scene as interleaved cu8 (2n bytes):
 * a tone at `offset` Hz plus AWGN, through scene_rtl_code(). Built with the
 * library's waveform synthesizer (the engine behind wfmgen). Returns a
 * malloc'd buffer, or NULL.
 */
uint8_t *scene_cu8 (double fs, double offset, size_t n);

#endif /* UNO_Q_SCENE_H */