Skip to content

ccsds-415 — the 415.1-B-1 receiver from C++, against the RPM

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=3 doppler-0.88.0/example-projects/rpm-consumer/ccsds-415

Or browse example-projects/rpm-consumer/ccsds-415/.

The async DSSS receiver at the CCSDS 415.1-B-1 specification point, driven from a C++17 program that links doppler statically from the installed -devel RPM. It streams the point's scene through the receiver one chunk at a time, times every chunk, captures every telemetry probe the receiver has to a file, and checks itself. plot.py draws the capture and does nothing else.

It runs at both ends of the point's band, 2.2 and 2.8 GHz, and prints each run's processing time per sample.

Build and run it

On Fedora or EL8 (AlmaLinux, Rocky), install the two packages from the release and a C++ toolchain:

sudo dnf install ./libdoppler-dsp-*.rpm ./libdoppler-dsp-devel-*.rpm \
    gcc-c++ cmake make
make run

The RPM is the install, so CMake finds it with no path. Any other doppler install works too: make PREFIX=<prefix> run for a cmake --install tree or an extracted release tarball. CI builds it both ways: against the RPM on Fedora and EL8 (make package-linux-smoke), and against a scratch install on Ubuntu (make rpm-consumer-check).

Then plot what it captured, with numpy and matplotlib (no doppler wheel):

make plot                    # shows a figure per carrier
make plot PLOT_ARGS=--save   # writes build/out/<capture>.png instead

make help lists the knobs. The program's own options go through ARGS, for example make run ARGS='--carrier hi --esn0 6', or the point's Es/N0 4 dB over 20 s, make run ARGS='--carrier lo --esn0 4 --seconds 20'; --help lists them. --errors prints where the bit errors fall in the scored stream: the first and last, the longest run, and a count for each tenth of it. --drop-symbol N and --repeat-symbol N force a whole-symbol slip at the receiver's Nth symbol, to see what the frames do across one.

What it runs

The point's scene, built from installed objects. Its rates and limits are the ones doppler/ccsds/ccsds_415.h holds; the code's parameters are 415.0-G-1's, named where run.cpp passes them (the C face has no names for them yet, #3348):

  • a 1,023-chip Gold code spreading the point's stimulus at 3,000 symbols a second (the shipped wfm_synth continuous DSSS). The stimulus is the design page's §1.4 period, repeated: a 275-symbol gap of the code alone, the 128-bit acquisition sequence, the EB90 start sequence and one CCSDS TC transfer frame (232.0-B-4) of 1 to 1,017 data octets, the length drawn per frame. The library describes and assembles each period (dp_ccsds_415_frame_desc(), dp_wfm_frame_assemble_data()); this program draws the lengths and fills the data from doppler's PN15;
  • the chip rate the carrier sets, resampled to the 11 MSa/s capture (RateConverter, at the ratio dp_ccsds_415_scene() computes);
  • a Doppler ramping at R_env, 11 Hz/s, through zero at mid-run (doppler_channel);
  • noise at Es/N0 10 dB, 6 dB above the point's Es/N0 4 dB (awgn).

The receiver is the one the library builds at the point, dp_async_dsss_receiver_create_ccsds415() (Python: Ccsds415Receiver), designed for Es/N0 4 dB, so it is built once for its weakest signal.

The frames are read back from the receiver's decided symbols with no truth, as a ground station would read them:

  • a period is found by its 128-bit acquisition sequence and start sequence, one 144-bit marker, in either polarity (dp_syncword_find()), at the most errors whose false-frame probability over the bits searched is 1e-6 (dp_syncword_max_errors_for());
  • the header's fields are read back by name through the same description (dp_wfm_frame_desc_field()): the length, the SCID, the VCID and the frame sequence number;
  • the CRC is checked (dp_wfm_frame_desc_crc_ok()), and every frame found counts, whatever it says;
  • after a frame whose CRC holds, the next marker is one period on, and is tracked there, within 4 symbols; after one whose CRC fails, whose length field may itself be wrong, the search resumes;
  • a frame found 1 to 4 symbols from where the last one ended is a slip: the stream gained or lost whole symbols between them, and the reader counts it and says where. (A length field with its lowest bit wrong moves the next frame by 8, so that is not counted.)

A whole-symbol slip in the receiver (#3349) shows here as one failed CRC, then frames read shifted by the slip, which the reader and the report count.

What it checks

make run exits non-zero unless, at each carrier:

  1. the lock is sustained within the point's lock allocation, 20 s from arrival (DP_CCSDS_415_LOCK_S);
  2. the BER over the locked stream, scored against the stimulus that was sent (dp_ber_meter), is not shown to be worse than the BPSK bound at the Es/N0 run less 1.13 dB: it fails when the meter's exact 99% interval (dp_ber_confidence()) lies wholly above dp_ber_theory_ber() there. 1.13 dB is the worst settled loss the receiver's certification record measured at this point (2.8 GHz, Es/N0 4 dB; §2.6 of src/doppler/dsss/tests/validation/async_dsss_receiver/results.md), and the allowed loss itself is the owner's to set (#3157). The record covers unslipped bursts at Es/N0 4 to 7 dB, so above 7 dB, the default 10 dB included, the figure is carried beyond what it measured. Each run prints the loss its own rate implies (dp_ber_esn0_db_for_ser());
  3. no call filled its output capacity, so no symbol was dropped;
  4. the capture is complete (dp_tlm_capture_close() returns DP_OK);
  5. every probe the receiver registers emitted at least once;
  6. every frame sent whole inside the locked stream was read, and each frame's CRC verdict is the one the truth gives: pass when it was received as sent, fail when not. Each frame is the period nearest where the meter's alignment puts it, within 4 symbols, so frames read across a slip are judged where they are, and the report says how many were shifted and by how much. A frame read where none was sent is wrong whatever its CRC says.

The locked stream opens where all five lock flags of dp_async_dsss_receiver_status() are sustained: symbol, code, carrier, demodulator carrier and sync, each read as up only while the receiver is tracking. dp_ber_lock_all() takes the latest of their sustained symbols, each sustained by dp_ber_lock_symbol()'s rule. That is the window the receiver's certification record scores in (the design page's §4.12, "The error-rate window"), through the same primitive. Since #3350 the symbol and code flags are gated on tracking too, as the record reads them, so a run from before it may open its window earlier than one after.

Chunks

A call to dp_async_dsss_receiver_steps() writes its symbols into a buffer the caller sizes. This program sizes it with dp_async_dsss_receiver_steps_max_out (rx, chunk): the most one call of chunk samples can deliver. Sized to that, no call holds symbols back for the next one or refuses its input (doppler#2469), so any chunk works, and the run checks that every call took its chunk.

That count is bounded by the chain's structure, never by the timing loop. The demodulator emits at most one symbol per input; its inputs are a fixed-rate converter's outputs from the code loop's partial correlations; a call runs at most x_len + H samples (its own, plus the carried code period or a hand-over's history), and the code loop emits at most its own bound of partials for them. At the point, with the receiver's own configuration:

carrier bound at 1 bound at 4,096 bound at 65,536
2.2 GHz 49 72 339
2.8 GHz 40 58 328

Read from Ccsds415Receiver(code, carrier_freq_hz=fc).steps_max_out(n) (measured 2026-11-28). The bound is a worst case by the demodulator's one symbol per input: a tracking call of 4,096 samples makes a few symbols.

What it measures

Each chunk's processing time per sample goes into the capture as the probe app.proc_ns, beside the receiver's own. The summary states the run's processing time per sample against the sample period, 90.9 ns at 11 MSa/s, and their ratio both as what it is and as what it means. The slowest chunk is the one that searches or hands over.

An example, not a claim: on 2026-11-24, on an AMD Ryzen AI 7 445 (one thread, a Release build of this tree linked against the build's libdoppler.a), it printed

ccsds415-2.2GHz: locked 0.26 s after arrival (allocation 20 s); BER 3.5e-05 (1 errors in 28952 bits; 99% interval 1.7e-07 to 1.8e-04)
  the bound at Es/N0 10.0 dB less the allowed 1.13 dB: 4.3e-05; the loss this rate implies: 1.01 dB
  processing time per sample 5.1 ns, sample period 90.9 ns: 5.7% of the sample period (17.7 times faster than real time); slowest chunk 4072.4 ns a sample; 26989 chunks of 4096
  frames: 4 of the 4 sent in the locked stream read; CRC passed 3, failed 1; 0 verdicts the truth contradicts
ccsds415-2.8GHz: locked 0.28 s after arrival (allocation 20 s); BER 0.0e+00 (0 errors in 28894 bits; 99% interval 0.0e+00 to 1.6e-04)
  the bound at Es/N0 10.0 dB less the allowed 1.13 dB: 4.3e-05; the loss this rate implies: none measurable (no errors)
  processing time per sample 4.8 ns, sample period 90.9 ns: 5.2% of the sample period (19.1 times faster than real time); slowest chunk 2491.4 ns a sample; 26989 chunks of 4096
  frames: 4 of the 4 sent in the locked stream read; CRC passed 4, failed 0; 0 verdicts the truth contradicts
OK

The capture

One file per carrier, ccsds415-<carrier>.tlm, written by doppler's lossless capture (doppler/dp_tlm_capture/dp_tlm_capture_core.h), with a -meta JSON sidecar. The records are 16 bytes each. The sidecar carries their layout (dtype), the probe table and the sample clock, so plot.py reads the format from the file rather than restating it.

The TUI

ccsds415-tui is a second front end over the same run (run.cpp), not a second receiver: the scene, the receiver, the capture and the checks are the batch binary's. It draws, at most every 100 ms of wall time:

  • cost: the last chunk's processing time per sample and the run's, the sample period, and their ratio as a share of the sample period and as times faster than real time; and, apart, the display's own time per refresh, so it is plain that drawing is not what is being measured;
  • receiver: its state, both lock flags, the symbol-lock metric against its threshold, C/N0, the Doppler and the code rate (received over nominal: 1 is no Doppler), as dp_async_dsss_receiver_status() reports them;
  • scene: the carrier, the time, the symbols out, and progress;
  • frames: whether the start sequence is searched for or tracked, the frames read with their CRC verdicts, the start sequences missed, the slips and the last one's shift and place, and the last frame's header read back: its data octets, SCID, VCID and frame sequence number, and the polarity it was read in.

It runs on one thread. The timed span is the receiver call alone; the drawing and the pacing fall outside it. By default each chunk is held to real time, so its 30 s scene takes 30 s and lock can be watched happening, then the Doppler ramping through zero; --unpaced runs it as fast as it goes. Paced, the processing time per sample reads higher than unpaced (7.6 against 5.6 ns in one run on the box above): the receiver starts each chunk with a cache the sleep has let go cold, so the panel labels it "(paced)".

When every scene has ended, the last frame stays on screen with a line saying so, until q.

q quits early, through the same teardown: the display closes, then the capture. Stopping is the user's choice, not the receiver's failure, so a stopped run answers only what a partial run can: the capture is complete and holds every record emitted so far, and no call filled its capacity. It exits 0 when those hold, and says in one line when it stopped and which full-scene checks (the lock time, if not yet reached; the BER; the payload marker; the frames) it did not evaluate. --snapshot and ccsds415 keep the full checks.

sudo dnf install ftxui-devel   # Fedora; EL8 needs EPEL
make tui

It is built against FTXUI 5 or later and written to what 5.0.0 through 7.0.3 share. --snapshot needs no terminal: it runs the scene unpaced and prints the last frame as text. CI runs it on Fedora, against the distribution's FTXUI, and requires every panel row to carry a value of its kind (tests/install/tui-snapshot-check.sh).

Where no package provides FTXUI (Ubuntu), fetch a pinned, hashed release: make tui CMAKE_ARGS=-DCCSDS415_FETCH_FTXUI=ON. That path builds on Ubuntu with FTXUI 7.0.3 and 5.0.0, but no CI job runs it; neither does one run EL8 with EPEL's FTXUI.

Compilers

The example is C++17 over doppler's C headers, and passes doppler's complex samples as C99 float _Complex, which GCC and Clang accept in C++ as an extension and MSVC does not. So it builds with:

  • GCC: 8.5 (EL8, the RPM's toolchain), 13.3 (Ubuntu) and Fedora's, each in CI;
  • Clang: 21.1.8, by hand, not in CI (#3347);
  • not MSVC, so not the Windows build doppler itself has.

The files

cmake_minimum_required(VERSION 3.16)
project(doppler_ccsds_415 CXX)

# The async DSSS receiver at the CCSDS 415.1-B-1 point, from C++, linked
# statically against doppler's installed -devel RPM (/usr/lib64/libdoppler.a
# and /usr/lib64/cmake/doppler). With the RPM installed, CMake finds it with
# no path of ours; any other install works too:
#   -DCMAKE_PREFIX_PATH=/path/to/doppler-install
#
# C++17: the RPM is built on manylinux_2_28 (gcc 8.5), where C++17 is
# complete. doppler's headers are C with extern "C" guards, so a .cpp
# includes them directly, with no wrapper.
#
# Static only: doppler::doppler-static carries what the archive needs (libm,
# Threads), so the link line names nothing else.
# <!-- doc-version:start -->
find_package(doppler 0.88.0 REQUIRED)
# <!-- doc-version:end -->

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# The run both front ends drive: the scene, the receiver, the capture, the
# checks.
add_library(ccsds415_run STATIC run.cpp)
target_link_libraries(ccsds415_run PUBLIC doppler::doppler-static)

add_executable(ccsds415 main.cpp)
target_link_libraries(ccsds415 PRIVATE ccsds415_run)

# The TUI, when FTXUI is at hand: an installed one first (Fedora's
# ftxui-devel; EL8's from EPEL), FTXUI 5 or later. Elsewhere, opt in to
# fetching a pinned, hashed release with -DCCSDS415_FETCH_FTXUI=ON. Without
# either, the batch binary builds alone and says so.
option(CCSDS415_FETCH_FTXUI "Fetch FTXUI 7.0.3 if none is installed" OFF)
# Not find_package(ftxui 5 ...): FTXUI's package declares SameMajorVersion
# compatibility, so asking for 5 refuses an installed 7 (Fedora's). Any
# version is found, then held to that minimum here.
find_package(ftxui CONFIG QUIET)
if(ftxui_FOUND AND ftxui_VERSION VERSION_LESS 5)
    message(STATUS "FTXUI ${ftxui_VERSION} is older than 5: not used")
    set(ftxui_FOUND FALSE)
endif()
if(NOT ftxui_FOUND AND CCSDS415_FETCH_FTXUI)
    include(FetchContent)
    FetchContent_Declare(ftxui
        URL https://github.com/ArthurSonzogni/FTXUI/archive/refs/tags/v7.0.3.tar.gz
        URL_HASH SHA256=e7c62ffe19009759821b4f0f8df7f2a6fb83784c3a9f1477d81f56d3ee723c88)
    set(FTXUI_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
    set(FTXUI_BUILD_DOCS OFF CACHE BOOL "" FORCE)
    set(FTXUI_BUILD_TESTS OFF CACHE BOOL "" FORCE)
    FetchContent_MakeAvailable(ftxui)
    set(ftxui_FOUND TRUE)
endif()
if(ftxui_FOUND)
    add_executable(ccsds415-tui tui.cpp)
    target_link_libraries(ccsds415-tui PRIVATE ccsds415_run
        ftxui::component ftxui::dom ftxui::screen)
else()
    message(STATUS "ccsds415-tui not built: no FTXUI 5 or later found "
                   "(install ftxui-devel, or -DCCSDS415_FETCH_FTXUI=ON)")
endif()
# example-projects/rpm-consumer/ccsds-415 — a downstream project's own
# Makefile.
#
# Thin on purpose: 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, which the -devel RPM is; set it for any other install:
#   make PREFIX=~/.local run
PREFIX           ?=
# More CMake options, e.g. CMAKE_ARGS=-DCCSDS415_FETCH_FTXUI=ON to fetch
# FTXUI for the TUI where no package provides it.
CMAKE_ARGS       ?=
# The program's own options, e.g. ARGS='--carrier lo --esn0 6'.
ARGS             ?=
# Where the captures go, and the plots from them.
OUT              ?= $(BUILD_DIR)/out
PYTHON           ?= python3

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

.PHONY: all build run tui plot clean help
.DEFAULT_GOAL := build

all: build

# Configure every time: cheap, and a cached configure would silently ignore
# a changed PREFIX.
build:
    cmake -S . -B $(BUILD_DIR) $(CMAKE_FLAGS)
    cmake --build $(BUILD_DIR)

# The program checks itself and exits non-zero on any failed check, so
# `make run` succeeding is the test.
run: build
    @mkdir -p $(OUT)
    $(BUILD_DIR)/ccsds415 --out $(OUT) $(ARGS)

# The same run, drawn live at real time (q quits). Built only where FTXUI
# is found: see CMakeLists.txt.
tui: build
    @mkdir -p $(OUT)
    @[ -x $(BUILD_DIR)/ccsds415-tui ] || { \
        echo "no ccsds415-tui: install ftxui-devel, or" \
             "CMAKE_ARGS=-DCCSDS415_FETCH_FTXUI=ON"; exit 1; }
    $(BUILD_DIR)/ccsds415-tui --out $(OUT) $(ARGS)

# Plots what `make run` captured: numpy and matplotlib, no doppler wheel.
# PLOT_ARGS=--save writes PNGs beside the captures instead of showing them.
PLOT_ARGS ?=
plot:
    $(PYTHON) plot.py $(OUT) $(PLOT_ARGS)

clean:
    rm -rf $(BUILD_DIR)

help:
    @echo "rpm-consumer/ccsds-415 — the 415.1-B-1 receiver from C++"
    @echo
    @echo "  make build              configure and compile"
    @echo "  make run                build, then run and self-check"
    @echo "  make tui                the same run drawn live (needs FTXUI)"
    @echo "  make plot               plot the captures (numpy, matplotlib)"
    @echo "  make clean              remove $(BUILD_DIR)/"
    @echo
    @echo "  PREFIX=<dir>            where doppler is installed"
    @echo "  CMAKE_ARGS='<flags>'    more CMake options"
    @echo "  ARGS='<options>'        the program's options (--help lists them)"
    @echo "  OUT=<dir>               captures and plots (default $(BUILD_DIR)/out)"
    @echo "  PLOT_ARGS=--save        write PNGs rather than showing them"
    @echo "  CMAKE_BUILD_TYPE=<t>    default Release"
    @echo "  BUILD_DIR=<dir>         default build"
// main.cpp -- ccsds415: the async DSSS receiver at the CCSDS 415.1-B-1
// point, from C++, against doppler's installed RPM. The batch front end.
//
// One run per carrier (2.2 and 2.8 GHz, the point's band edges), each:
//
//   1. the point's scene built from installed objects: a 1,023-chip Gold
//      code spreading a PN15 payload at 3,000 symbols a second, the chip
//      rate the carrier sets, resampled to the 11 MSa/s capture, a Doppler
//      that ramps at R_env through zero, and noise at the stated Es/N0;
//   2. streamed a chunk at a time into the receiver the library builds at
//      the point (Ccsds415Receiver's C constructor), unpaced;
//   3. every chunk timed, and every telemetry probe the receiver has, plus
//      that timing, captured losslessly to one file;
//   4. checked: the receiver locked within the point's allocation, decoded
//      the payload, dropped no symbol, and the capture is complete.
//
// The loop is run.cpp's, shared with ccsds415-tui. plot.py reads what this
// writes; it only plots. The point's rates and limits are the library's
// (doppler/ccsds/ccsds_415.h); the code's parameters are the standard's,
// named where run.cpp passes them (gold_code()).
#include "run.hpp"

#include <cstdio>

int
main (int argc, char **argv)
{
  ccsds415::Options o;
  ccsds415::parse (argc, argv, o, false);
  bool ok = true;
  for (const double fc : o.carriers)
    {
      ccsds415::Run run (o, fc);
      while (run.step ())
        {
        }
      ok = ccsds415::report (run.name (), run.finish (), o.chunk) && ok;
    }
  if (!ok)
    return 1;
  std::printf ("OK\n");
  return 0;
}
"""Plot what ``ccsds415`` captured: one figure per carrier.

Usage::

    python3 plot.py OUT_DIR [--save]

Reads every ``OUT_DIR/*.tlm`` with its ``*.tlm-meta`` sidecar and plots, per
carrier:

- the lifecycle and the lock flags (``rx.state``, ``rx.car.locked``,
  ``rx.code.locked``, ``rx.sym.locked``);
- the Doppler the tracking chain was built from (``rx.handover_hz``) and the
  carrier loop's frequency memory (``rx.car.freq``, as the receiver reports
  it);
- the loop discriminators (``rx.car.e``, ``rx.code.e``, ``rx.demod.car.e``,
  ``rx.demod.sync.e``);
- the recovered symbols, I against Q (``rx.demod.sym.i``, ``.q``);
- each chunk's processing time per sample (``app.proc_ns``) against the
  sample period.

It only plots. It needs numpy and matplotlib, not the doppler wheel, which
an RPM consumer does not have. The format is read from the sidecar, never
restated here: the record layout is the sidecar's ``dtype`` (the 16-byte
``dp_tlm_rec_t`` of ``doppler/dp_tlm/dp_tlm_core.h``), the probe names are
its ``probes`` table, and a record's time is ``n / fs`` with ``fs`` the
sidecar's sample clock.

With ``--save`` it writes ``<capture>.png`` beside each capture and shows
nothing, so it runs headless.
"""

from __future__ import annotations

import json
import sys
from pathlib import Path
from typing import TYPE_CHECKING

import numpy as np

if TYPE_CHECKING:
    from matplotlib.figure import Figure


def load(path: Path) -> tuple[dict[str, np.ndarray], dict]:
    """A capture's records, split by probe name: ``{name: records}``."""
    meta = json.loads(Path(f"{path}-meta").read_text(encoding="utf-8"))
    dtype = np.dtype([(name, fmt) for name, fmt in meta["dtype"]])
    recs = np.fromfile(path, dtype=dtype)
    by_name = {
        name: recs[recs["probe"] == pid]
        for name, pid in meta["probes"].items()
    }
    return by_name, meta


def figure(path: Path) -> Figure:
    """One carrier's figure."""
    import matplotlib.pyplot as plt

    p, meta = load(path)
    fs = float(meta["fs"])

    def t(name: str) -> np.ndarray:
        return p[name]["n"] / fs

    def v(name: str) -> np.ndarray:
        return p[name]["value"]

    fig, ax = plt.subplots(3, 2, figsize=(12, 10))
    fig.suptitle(path.stem)

    a = ax[0, 0]
    a.step(t("rx.state"), v("rx.state"), where="post", label="state")
    for k, name in enumerate(
        ("rx.car.locked", "rx.code.locked", "rx.sym.locked")
    ):
        a.step(
            t(name),
            v(name) + 1.1 * (k + 1),
            where="post",
            label=name.removeprefix("rx."),
        )
    a.set_title("lifecycle and lock flags (offset for clarity)")
    a.set_xlabel("time (s)")
    a.legend(loc="lower right", fontsize="small")

    a = ax[0, 1]
    a.plot(t("rx.handover_hz"), v("rx.handover_hz"), ".", label="hand-over")
    a.set_title("Doppler the chain was built from (Hz)")
    a.set_xlabel("time (s)")
    b = a.twinx()
    b.plot(t("rx.car.freq"), v("rx.car.freq"), "C1", lw=0.8)
    b.set_ylabel("rx.car.freq (as reported)", color="C1")

    a = ax[1, 0]
    for name in ("rx.car.e", "rx.code.e"):
        a.plot(t(name), v(name), lw=0.6, label=name)
    a.set_title("chip-domain loop discriminators")
    a.set_xlabel("time (s)")
    a.legend(fontsize="small")

    a = ax[1, 1]
    for name in ("rx.demod.car.e", "rx.demod.sync.e"):
        a.plot(t(name), v(name), lw=0.6, label=name)
    a.set_title("symbol-domain loop discriminators")
    a.set_xlabel("time (s)")
    a.legend(fontsize="small")

    a = ax[2, 0]
    a.plot(v("rx.demod.sym.i"), v("rx.demod.sym.q"), ".", ms=1, alpha=0.3)
    a.set_title("recovered symbols")
    a.set_xlabel("I")
    a.set_ylabel("Q")
    a.set_aspect("equal", adjustable="datalim")

    a = ax[2, 1]
    a.plot(
        t("app.proc_ns"),
        v("app.proc_ns"),
        lw=0.6,
        label="processing time per sample",
    )
    a.axhline(1e9 / fs, color="C3", ls="--", label="sample period")
    a.set_yscale("log")
    a.set_title("cost per chunk (ns)")
    a.set_xlabel("time (s)")
    a.legend(fontsize="small")

    fig.tight_layout()
    return fig


def main(argv: list[str]) -> int:
    args = [a for a in argv if not a.startswith("--")]
    save = "--save" in argv
    if len(args) != 1:
        print(__doc__)
        return 2
    import matplotlib

    if save:
        matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    captures = sorted(Path(args[0]).glob("*.tlm"))
    if not captures:
        print(f"no captures in {args[0]}: run `make run` first")
        return 1
    for path in captures:
        fig = figure(path)
        if save:
            fig.savefig(path.with_suffix(".png"), dpi=100)
            print(f"wrote {path.with_suffix('.png')}")
    if not save:
        plt.show()
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
// run.cpp -- the run both front ends drive (run.hpp).
#include "run.hpp"

#include <doppler/ber/ber_core.h>
#include <doppler/ccsds/ccsds_415.h>
#include <doppler/ccsds/ccsds_415_frame.h>
#include <doppler/gold/gold_core.h>
#include <doppler/pn/pn_core.h>
#include <doppler/syncword/syncword_core.h>
#include <doppler/timing/timing_core.h>
#include <doppler/wfm/wfm_core.h>

#include <algorithm>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>

namespace ccsds415
{
namespace
{

// std::complex<float> is layout-compatible with float _Complex, so a
// vector's storage crosses to the C API by pointer.
float _Complex *
c_ptr (std::vector<cf32> &v)
{
  return reinterpret_cast<float _Complex *> (v.data ());
}

constexpr double LEAD_IN_S = 0.05; // noise alone before the signal arrives
constexpr unsigned PAYLOAD_SEED = 1, PAYLOAD_PN = 15;
// The data lengths' own PN, apart from the data's.
constexpr unsigned LENGTH_SEED = 2;
// The largest shift, in symbols, the frame reader and the truth check read
// as a receiver slip rather than a frame elsewhere. Below 8: a frame-length
// field received with its lowest bit wrong moves where the next frame is
// due by one octet, 8 symbols, and that is not a slip.
constexpr size_t SLIP_MAX = 4;
// What "sustained" means for each lock flag is dp_ber_lock_symbol()'s
// own: 0 and 0.0 select its defaults, so this file does not restate them.
constexpr size_t LOCK_SUSTAIN = 0;
constexpr double LOCK_MIN_FRAC = 0.0;
// The receiver's allowed implementation loss against the BPSK bound: the
// worst settled loss the certification record measured at this point, 1.13
// dB (2.8 GHz, Es/N0 4 dB; 2.2 and 2.8 GHz from 4 to 7 dB read 0.72 to 1.13
// dB), in src/doppler/dsss/tests/validation/async_dsss_receiver/results.md
// §2.6. Measured there over unslipped bursts at 4 to 7 dB, not chosen
// here; above 7 dB it is carried beyond what the record measured. The
// owner's allowed loss is doppler#3157's to set.
constexpr double LOSS_DB = 1.13;
constexpr long LAG_SPAN = 1000; // symbols the stream may start into the data

// The mission's code, a 1,023-chip Gold code from the CCSDS command-link
// generator (415.0-G-1 §5.2.2.4, Figure 5-1). The library leaves the code
// to the caller (ccsds_415.h: "the mission's, so it is an argument"), and
// its C face has no names for the standard's registers yet (#3348), so
// each argument is named here.
std::vector<uint8_t>
gold_code ()
{
  // Register A's polynomial x^10+x^9+x^8+x^6+x^3+x^2+1: fixed.
  const uint64_t taps_a = 934;
  // Register A's initial value: user dependent, so it picks the mission's
  // member of the family. 350 is Figure 5-2's worked example (PN Code
  // Library Table 1, code number 365).
  const uint64_t seed_a = 350;
  // Register B's polynomial and its initial value 1001001000: both fixed.
  const uint64_t taps_b = 567, seed_b = 73;
  // Ten-stage registers: a period of 2^10 - 1 = 1,023 chips.
  const uint32_t length = 10;
  std::vector<uint8_t> code (DP_CCSDS_415_SF);
  dp_gold_state_t *g = dp_gold_create (taps_a, seed_a, taps_b, seed_b, length);
  check (g != nullptr, "the Gold generator opens");
  dp_gold_generate (g, code.size (), code.data (), code.size ());
  dp_gold_destroy (g);
  return code;
}

// One period of the 415.1-B-1 stimulus (§1.4) with a frame of `octets`
// data octets: the library's description of it and the description's
// layout. The description points into `f`, so a Period is never copied.
struct Period
{
  dp_ccsds_415_frame_t f;
  wfm_frame_desc_layout_t lay;

  explicit Period (unsigned octets)
  {
    const char *why = nullptr;
    check (dp_ccsds_415_frame_desc (&f, nullptr, octets, &why) == 0,
           std::string ("the frame description: ") + (why ? why : "?"));
    check (dp_wfm_frame_desc_layout (&f.desc, &lay) == 0,
           "the frame description lays out");
  }
  Period (const Period &) = delete;
  Period &operator= (const Period &) = delete;

  // A field's first bit in the period, by its name in the description.
  size_t
  off (const char *field) const
  {
    const int i = dp_wfm_frame_field_index (&f.desc, field);
    check (i >= 0, std::string ("the description has a field ") + field);
    return lay.field_off[i];
  }
};

// A data length, 1 to 1,017 octets with every value equally likely: ten
// bits of the length PN at a time, a draw outside the range rejected. A PN
// rather than <random>'s distributions, whose output differs between
// standard libraries, so every build sends the same stimulus.
unsigned
draw_octets (dp_pn_state_t *pn)
{
  for (;;)
    {
      uint8_t b[10];
      dp_pn_generate (pn, sizeof b, b, sizeof b);
      unsigned v = 0;
      for (const uint8_t bit : b)
        v = (v << 1) | bit;
      if (v >= DP_CCSDS_415_DATA_MIN && v <= DP_CCSDS_415_DATA_MAX)
        return v;
    }
}

// At least n bits of the stimulus, whole periods of it: the gap, the
// acquisition and start sequences, and one TC transfer frame, each frame
// with a data field of a length drawn per frame and filled from doppler's
// PN15. The library assembles every period from its description; this
// only draws the lengths and the data, and keeps where each period sits.
Stimulus
stimulus (size_t n)
{
  Owned<dp_pn_state_t, dp_pn_destroy> data (
      dp_pn_create_mls (0, PAYLOAD_SEED, PAYLOAD_PN, PN_GALOIS));
  Owned<dp_pn_state_t, dp_pn_destroy> lengths (
      dp_pn_create_mls (0, LENGTH_SEED, PAYLOAD_PN, PN_GALOIS));
  check (data && lengths, "the stimulus PNs open");
  Stimulus s;
  std::vector<uint8_t> chunk (8 * DP_CCSDS_415_DATA_MAX), period;
  while (s.bits.size () < n)
    {
      const unsigned octets = draw_octets (lengths.get ());
      dp_pn_generate (data.get (), 8 * octets, chunk.data (), chunk.size ());
      // The library sizes and assembles the period (§1.4) from its
      // description; NULL out asks for its length.
      period.resize (dp_ccsds_415_period (nullptr, nullptr, octets, nullptr,
                                          0, nullptr, nullptr));
      size_t      data_off = 0;
      const char *why      = nullptr;
      check (!period.empty ()
                 && dp_ccsds_415_period (nullptr, chunk.data (), octets,
                                         period.data (), period.size (),
                                         &data_off, &why)
                        == period.size (),
             std::string ("a period assembles: ") + (why ? why : "?"));
      s.at.push_back (s.bits.size ());
      s.len.push_back (period.size ());
      s.data_at.push_back (s.bits.size () + data_off);
      s.data_len.push_back (8 * octets);
      s.bits.insert (s.bits.end (), period.begin (), period.end ());
    }
  return s;
}

// Where the BER meter's marker starts: the first data field at least
// LAG_SPAN into the locked stream that is long enough to be the whole
// marker. Data, because the gap, the acquisition sequence and the header
// repeat from period to period, and a marker inside them would match more
// than one lag.
size_t
marker_at (const Stimulus &s, size_t lo)
{
  for (size_t i = 0; i < s.at.size (); i++)
    if (s.data_at[i] >= lo + LAG_SPAN && s.data_len[i] >= BER_SYNC_SYMS)
      return s.data_at[i];
  fail ("no data field long enough for the BER marker in the stimulus");
}

} // namespace

// Reads the stimulus's frames from the receiver's decided symbols, a chunk
// at a time, with no truth: the receiver's side of the link. Each symbol
// is decided by its sign, a bit 1 for a negative real part (bit 0 is sent
// as +1); the stream's polarity is whatever the carrier loop settled on,
// and the start sequence says which.
//
// It finds a period by what §1.4 puts there for the purpose: the 128-bit
// acquisition sequence and the 16-bit start sequence after it, one 144-bit
// marker, searched in either polarity. The tolerance is the most errors
// whose false-frame probability over the bits searched is at most 1e-6
// (dp_syncword_max_errors_for()), so a noisy marker is found and data that
// happens to resemble one is not. It then reads the header's length through
// the library's description and checks the CRC; every frame found counts,
// whatever its CRC says. Once a frame's CRC holds, its length is trusted
// and the reader tracks: the next marker is one period on, where one place
// is tried, and a marker not there is a miss. After a frame whose CRC
// failed, whose length field may itself be wrong, the search resumes.
class FrameReader
{
public:
  // Where a frame was read: its period's first bit in the decided stream,
  // its bits, the polarity, and the CRC's verdict.
  struct Seen
  {
    size_t at, len;
    bool inverted, crc_ok;
  };

  FrameReader () : hdr_ (DP_CCSDS_415_DATA_MIN)
  {
    // Every period's fields up to the data sit at the same offsets, so the
    // shortest description reads any frame's header.
    start_ = hdr_.off ("start");
    acq_ = hdr_.off ("acq");
    header_end_ = hdr_.off ("data");
    // The marker's bits, as the library assembles them: the acquisition
    // and start sequences of a period (its data is irrelevant here).
    std::vector<uint8_t> data (8 * DP_CCSDS_415_DATA_MIN, 0),
        period (hdr_.lay.frame_bits);
    check (dp_wfm_frame_assemble_data (&hdr_.f.desc, nullptr, data.data (),
                                       period.data (), period.size ())
               == period.size (),
           "the marker's period assembles");
    marker_len_ = start_ + DP_CCSDS_415_START_BITS - acq_;
    sw_.reset (dp_syncword_create (&period[acq_], marker_len_));
    check (sw_ != nullptr, "the marker search opens");
    // One offset is tried while tracking.
    track_errors_ = tolerance (1);
  }

  void
  feed (const cf32 *syms, size_t n)
  {
    for (size_t i = 0; i < n; i++)
      bits_.push_back (syms[i].real () < 0.0f ? 1 : 0);
    if (bits_.size () >= need_)
      process ();
  }

  const FrameStats &
  stats () const
  {
    return st_;
  }
  const std::vector<Seen> &
  seen () const
  {
    return seen_;
  }
  const std::vector<uint8_t> &
  bits () const
  {
    return bits_;
  }

private:
  enum Outcome
  {
    NEED,   // not enough bits yet
    MISS,   // tracking: no start sequence where it should be
    REJECT, // searching: not a frame
    READ    // a frame was read and counted
  };

  // The most marker errors whose false-frame probability over `window`
  // offsets is at most 1e-6.
  uint32_t
  tolerance (size_t window) const
  {
    const int t = dp_syncword_max_errors_for (sw_.get (), window, 1e-6);
    return t > 0 ? static_cast<uint32_t> (t) : 0u;
  }

  // The frame whose start sequence begins at bit h, its marker found
  // with `errors` errors in polarity `inverted`. While tracking, the
  // marker is checked here first.
  Outcome
  read_at (size_t h, bool tracking, uint32_t errors = 0, bool inverted = false)
  {
    if (h < start_ + SLIP_MAX)
      return tracking ? MISS : REJECT;
    if (bits_.size () < h - start_ + header_end_ + SLIP_MAX)
      {
        need_ = h - start_ + header_end_ + SLIP_MAX;
        return NEED;
      }
    syncword_hit_t hit{ 1, 0, inverted ? 1 : 0, errors };
    if (tracking)
      {
        // The marker where the last frame puts the next, or within
        // SLIP_MAX symbols of it, where it has the fewest errors: a
        // receiver that slipped whole symbols puts it a few off, and the
        // shift is reported as a slip (the nearest of a tie).
        long best_d = 0;
        hit.found = 0;
        for (long d = 0; d <= static_cast<long> (SLIP_MAX); d++)
          for (const long sd : { d, -d })
            {
              const syncword_hit_t c = dp_syncword_find (
                  sw_.get (), &bits_[h + sd - start_ + acq_], marker_len_,
                  track_errors_);
              if (c.found && c.offset == 0
                  && (!hit.found || c.errors < hit.errors))
                {
                  hit = c;
                  best_d = sd;
                }
              if (d == 0)
                break;
            }
        if (!hit.found)
          return MISS;
        h = static_cast<size_t> (static_cast<long> (h) + best_d);
      }
    const size_t at = h - start_;
    const uint8_t flip = hit.inverted ? 1 : 0;

    // The header, through the shortest description: the frame-length field
    // holds the frame's octets less one (232.0-B-4 §4.1.2.7.2).
    buf_.assign (hdr_.lay.frame_bits, 0);
    for (size_t i = 0; i < header_end_; i++)
      buf_[i] = bits_[at + i] ^ flip;
    uint64_t length = 0;
    const char *why = nullptr;
    check (dp_wfm_frame_desc_field (&hdr_.f.desc, buf_.data (), buf_.size (),
                                    "length", &length, &why)
               == 0,
           std::string ("the length field reads: ") + (why ? why : "?"));
    const uint64_t octets = length + 1 - DP_CCSDS_415_HEADER_BITS / 8 - 2;
    if (length + 1 < DP_CCSDS_415_HEADER_BITS / 8 + 2 + DP_CCSDS_415_DATA_MIN
        || octets > DP_CCSDS_415_DATA_MAX)
      {
        if (!tracking)
          return REJECT;
        // Tracked, but no frame has this length: a frame whose header was
        // received wrong, so its end is unknown and the search resumes.
        count (h, at, 0, flip, false, hit.errors);
        st_.tracking = false;
        scan_ = h + 1;
        return READ;
      }

    const Period p (static_cast<unsigned> (octets));
    if (bits_.size () < at + p.lay.frame_bits)
      {
        need_ = at + p.lay.frame_bits;
        return NEED;
      }
    buf_.resize (p.lay.frame_bits);
    for (size_t i = 0; i < p.lay.frame_bits; i++)
      buf_[i] = bits_[at + i] ^ flip;
    const bool ok = dp_wfm_frame_desc_crc_ok (&p.f.desc, buf_.data ()) == 1;
    count (h, at, p.lay.frame_bits, flip, ok, hit.errors);
    // The header's fields as received, read back by name.
    uint64_t v = 0;
    if (dp_wfm_frame_desc_field (&p.f.desc, buf_.data (), buf_.size (),
                                 "scid", &v, nullptr)
        == 0)
      st_.scid = static_cast<unsigned> (v);
    if (dp_wfm_frame_desc_field (&p.f.desc, buf_.data (), buf_.size (),
                                 "vcid", &v, nullptr)
        == 0)
      st_.vcid = static_cast<unsigned> (v);
    if (dp_wfm_frame_desc_field (&p.f.desc, buf_.data (), buf_.size (),
                                 "seq", &v, nullptr)
        == 0)
      st_.seq = static_cast<unsigned> (v);
    st_.octets = static_cast<unsigned> (octets);
    // The next period's start sequence is one period on, if this frame's
    // length can be trusted: only when its CRC held. A failed frame's
    // length field may be wrong itself, so the search resumes after its
    // start instead.
    if (ok)
      {
        next_ = h + p.lay.frame_bits;
        st_.tracking = true;
      }
    else
      {
        st_.tracking = false;
        scan_ = h + 1;
      }
    return READ;
  }

  void
  count (size_t h, size_t at, size_t len, uint8_t flip, bool ok,
         uint32_t errors)
  {
    // A frame a few symbols from where the last one, read at its own
    // length, ended: the stream slipped whole symbols between them. Further
    // off is a length field received wrong, not a slip, and is not
    // counted.
    if (expect_)
      {
        const long by = static_cast<long> (h) - static_cast<long> (expect_);
        if (by != 0 && std::labs (by) <= static_cast<long> (SLIP_MAX))
          {
            st_.slips++;
            st_.slip_at = h;
            st_.slip_by = by;
          }
      }
    expect_ = len ? h + len : 0;
    st_.found++;
    (ok ? st_.crc_ok : st_.crc_failed)++;
    st_.any = true;
    st_.inverted = flip != 0;
    st_.start_errors = errors;
    seen_.push_back ({ at, len, flip != 0, ok });
    last_h_ = h;
  }

  void
  process ()
  {
    need_ = 0;
    for (;;)
      {
        if (st_.tracking)
          {
            const Outcome o = read_at (next_, true);
            if (o == NEED)
              return;
            if (o == MISS)
              {
                st_.missed++;
                st_.tracking = false;
                scan_ = last_h_ + 1;
              }
            continue;
          }
        if (bits_.size () < scan_ + marker_len_)
          return;
        const size_t window = bits_.size () - scan_ - marker_len_ + 1;
        const syncword_hit_t hit
            = dp_syncword_find (sw_.get (), &bits_[scan_],
                                bits_.size () - scan_, tolerance (window));
        if (!hit.found)
          {
            // The last bits may be a marker's first: keep them.
            scan_ = bits_.size () - (marker_len_ - 1);
            return;
          }
        // The search answers with the FIRST offset within the tolerance,
        // and the acquisition sequence alternates, so a marker shifted by
        // two bits still matches all of it and the first answer can come a
        // few bits early. The marker sits where its errors are fewest, so
        // the offsets the marker's length on are compared and the fewest
        // taken (the earliest of a tie).
        size_t m = scan_ + hit.offset;
        syncword_hit_t best = hit;
        if (bits_.size () < m + 2 * marker_len_)
          {
            scan_ = m;
            need_ = m + 2 * marker_len_;
            return;
          }
        for (size_t k = 1; k < marker_len_; k++)
          {
            const syncword_hit_t c
                = dp_syncword_find (sw_.get (), &bits_[scan_ + hit.offset + k],
                                    marker_len_, best.errors);
            if (c.found && c.offset == 0 && c.errors < best.errors)
              {
                best = c;
                m = scan_ + hit.offset + k;
              }
          }
        // The marker starts at the acquisition sequence; h is the start
        // sequence's first bit.
        const size_t h = m + (start_ - acq_);
        const Outcome o
            = read_at (h, false, best.errors, best.inverted != 0);
        if (o == NEED)
          {
            // Search again from this marker once the frame's bits are in.
            scan_ = h - (start_ - acq_);
            return;
          }
        if (o == REJECT)
          scan_ = h + 1;
      }
  }

  const Period hdr_;
  size_t start_ = 0, acq_ = 0, header_end_ = 0, marker_len_ = 0;
  Owned<dp_syncword_state_t, dp_syncword_destroy> sw_;
  uint32_t track_errors_ = 0;
  std::vector<uint8_t> bits_, buf_;
  size_t scan_ = 0, next_ = 0, last_h_ = 0, need_ = 0;
  size_t expect_ = 0; // where the next start sequence is due, or 0
  FrameStats st_;
  std::vector<Seen> seen_;
};

double
sample_period_ns ()
{
  return 1e9 / DP_CCSDS_415_FS;
}

[[noreturn]] void
fail (const std::string &why)
{
  std::fprintf (stderr, "FAIL: %s\n", why.c_str ());
  std::exit (1);
}

void
check (bool ok, const std::string &why)
{
  if (!ok)
    fail (why);
}

// A whole option value as a number, or a failed check naming the option:
// strtod and strtoul read "abc" as 0 and "6x" as 6 without complaint.
static double
number (const std::string &opt, const std::string &v)
{
  char *end = nullptr;
  errno = 0;
  const double x = std::strtod (v.c_str (), &end);
  check (!v.empty () && end == v.c_str () + v.size () && errno == 0
             && std::isfinite (x),
         opt + " takes a number, not '" + v + "'");
  return x;
}

static size_t
count (const std::string &opt, const std::string &v)
{
  char *end = nullptr;
  errno = 0;
  const unsigned long long x = std::strtoull (v.c_str (), &end, 10);
  check (!v.empty () && v[0] != '-' && end == v.c_str () + v.size ()
             && errno == 0,
         opt + " takes a whole number, not '" + v + "'");
  return static_cast<size_t> (x);
}

void
parse (int argc, char **argv, Options &o, bool tui)
{
  o.carriers = { DP_CCSDS_415_FC_LO, DP_CCSDS_415_FC_HI };
  for (int i = 1; i < argc; i++)
    {
      const std::string a = argv[i];
      if (a == "-h" || a == "--help")
        {
          std::printf (
              "usage: %s [--carrier lo|hi|both] [--esn0 DB] [--seconds S]\n"
              "       [--chunk N] [--out DIR]%s\n"
              "  --carrier   2.2 GHz (lo), 2.8 GHz (hi) or both (default)\n"
              "  --esn0      Es/N0 at the receiver input, dB (default %g)\n"
              "  --seconds   signal duration after the lead-in (default %g)\n"
              "  --chunk     samples a push, at least %zu (default %zu)\n"
              "  --out       directory for the captures (default .)\n"
              "  --errors    print where the bit errors fall in the scored "
              "stream\n"
              "  --drop-symbol N, --repeat-symbol N\n"
              "              force a whole-symbol slip: drop or repeat the "
              "decided\n"
              "              symbol at index N (a test of the frame reader)\n",
              tui ? "ccsds415-tui" : "ccsds415",
              tui ? " [--unpaced] [--snapshot]" : "", o.esn0_db, o.seconds,
              MIN_CHUNK, o.chunk);
          if (tui)
            std::printf (
                "  --unpaced  run as fast as it goes, not at real time\n"
                "  --snapshot no terminal: run unpaced, print the last "
                "frame\n"
                "  q          quit early, through the same checks\n");
          std::exit (0);
        }
      if (a == "--drop-symbol" || a == "--repeat-symbol")
        {
          check (i + 1 < argc, a + " needs a value");
          const size_t k = count (a, argv[++i]);
          (a == "--drop-symbol" ? o.drop_symbol : o.repeat_symbol) = k;
          continue;
        }
      if (a == "--errors")
        {
          o.errors = true;
          continue;
        }
      if (tui && a == "--unpaced")
        {
          o.paced = false;
          continue;
        }
      if (tui && a == "--snapshot")
        {
          o.snapshot = true;
          o.paced = false;
          continue;
        }
      check (i + 1 < argc, a + " needs a value");
      const std::string v = argv[++i];
      if (a == "--carrier")
        {
          if (v == "lo")
            o.carriers = { DP_CCSDS_415_FC_LO };
          else if (v == "hi")
            o.carriers = { DP_CCSDS_415_FC_HI };
          else
            check (v == "both", "--carrier is lo, hi or both");
        }
      else if (a == "--esn0")
        o.esn0_db = number (a, v);
      else if (a == "--seconds")
        o.seconds = number (a, v);
      else if (a == "--chunk")
        o.chunk = count (a, v);
      else if (a == "--out")
        o.out = v;
      else
        fail ("unknown option " + a);
    }
  check (o.chunk >= MIN_CHUNK,
         "--chunk is at least " + std::to_string (MIN_CHUNK));
  check (o.seconds > 0.0 && std::isfinite (o.seconds),
         "--seconds is positive");
}

// The capture, streamed: a clean emitter at two samples a chip, the rate
// converter to the capture rate, the Doppler channel, then noise. The
// converter's and the channel's output lengths vary by a sample from call
// to call, so a stage holds what the next chunk has not taken yet.
class Scene
{
public:
  Scene (const uint8_t *code, const std::vector<uint8_t> &payload, double fc,
         double esn0_db, double seconds, size_t chunk)
      : chunk_ (chunk)
  {
    // The point's derived rates, computed once by the library: the chip
    // rate, the converter's ratio from two samples a chip, and the Doppler
    // ramp in ppm of the carrier. The ramp crosses zero at mid-run.
    const double start_hz = -DP_CCSDS_415_R_ENV_HZ_S * seconds / 2.0;
    const dp_ccsds_415_scene_t s = dp_ccsds_415_scene (fc, 2.0, start_hz);
    const double fs2 = 2.0 * s.chip_rate;
    // The emitter: a continuous DSSS source at two samples a chip, clean
    // (the noise is added after the channel). Its own PN arguments are
    // unused, since its data is the payload set below.
    const int type = WFM_SYNTH_DSSS;
    const double freq_hz = 0.0;             // no carrier offset of its own
    const double clean_db = WFM_SYNTH_SNR_CLEAN; // 100 dB and up: no AWGN
    const int snr_mode = 0;                 // auto; moot with no AWGN
    const uint32_t seed = 0;                // its PRNG: no AWGN, no PN data
    const int sps = 2;                      // samples a chip
    const int pn_length = 15;               // its PN register: unused
    const uint64_t pn_poly = 0;             // 0: the table's MLS polynomial
    const int lfsr = PN_GALOIS;
    const double f_end_hz = 0.0;            // chirps only
    syn_.reset (dp_wfm_synth_create (type, fs2, freq_hz, clean_db, snr_mode,
                                     seed, sps, pn_length, pn_poly, lfsr,
                                     f_end_hz));
    check (syn_ != nullptr, "the emitter opens");
    check (dp_wfm_synth_set_dsss_cont (
               syn_.get (), code, DP_CCSDS_415_SF,
               s.chip_rate / DP_CCSDS_415_SYM, WFM_DSSS_DATA_BITS,
               payload.data (), payload.size ())
               == 0,
           "the emitter takes the payload");
    rc_.reset (dp_RateConverter_create (s.ratio, 0));
    ch_.reset (dp_doppler_channel_create (DP_CCSDS_415_FS, fc, s.start_ppm,
                                          s.rate_ppm_s));
    // Es/N0 over one symbol's FS / SYM samples.
    const double snr_db
        = esn0_db - 10.0 * std::log10 (DP_CCSDS_415_FS / DP_CCSDS_415_SYM);
    awg_.reset (dp_awgn_create (
        1, dp_wfm_awgn_amplitude (static_cast<float> (snr_db), 1.0f)));
    check (rc_ && ch_ && awg_, "the converter, channel and noise open");
    lead_left_ = lead_in ();
    clean_left_ = static_cast<size_t> (seconds * fs2);
    clean_.resize (chunk);
    conv_.resize (2 * chunk + 64);
    stage_.resize (2 * chunk + 64);
    noise_.resize (chunk);
  }

  // Fill x with the next chunk; false once the signal ends inside it.
  bool
  next (std::vector<cf32> &x)
  {
    size_t k = 0;
    while (k < chunk_)
      {
        if (lead_left_)
          {
            const size_t take = std::min (lead_left_, chunk_ - k);
            std::fill (x.begin () + k, x.begin () + k + take, cf32{});
            lead_left_ -= take;
            k += take;
            continue;
          }
        if (pos_ == len_)
          {
            if (!clean_left_)
              return false;
            const size_t n = std::min (clean_left_, chunk_);
            dp_wfm_synth_steps (syn_.get (), c_ptr (clean_), n);
            clean_left_ -= n;
            const size_t m = dp_RateConverter_execute (
                rc_.get (), c_ptr (clean_), n, c_ptr (conv_), conv_.size ());
            len_ = dp_doppler_channel_execute (ch_.get (), c_ptr (conv_), m,
                                               c_ptr (stage_), stage_.size ());
            pos_ = 0;
            continue;
          }
        const size_t take = std::min (len_ - pos_, chunk_ - k);
        std::copy (stage_.begin () + pos_, stage_.begin () + pos_ + take,
                   x.begin () + k);
        pos_ += take;
        k += take;
      }
    dp_awgn_generate (awg_.get (), chunk_, c_ptr (noise_), chunk_);
    for (size_t i = 0; i < chunk_; i++)
      x[i] += noise_[i];
    return true;
  }

  static size_t
  lead_in ()
  {
    return static_cast<size_t> (LEAD_IN_S * DP_CCSDS_415_FS);
  }

private:
  size_t chunk_;
  Owned<dp_wfm_synth_state_t, dp_wfm_synth_destroy> syn_;
  Owned<dp_RateConverter_state_t, dp_RateConverter_destroy> rc_;
  Owned<dp_doppler_channel_state_t, dp_doppler_channel_destroy> ch_;
  Owned<dp_awgn_state_t, dp_awgn_destroy> awg_;
  size_t lead_left_ = 0, clean_left_ = 0, pos_ = 0, len_ = 0;
  std::vector<cf32> clean_, conv_, stage_, noise_;
};

Run::Run (const Options &o, double fc) : o_ (o), fc_ (fc)
{
  char name[32];
  std::snprintf (name, sizeof name, "ccsds415-%.1fGHz", fc / 1e9);
  name_ = name;
  code_ = gold_code ();
  stim_ = stimulus (
      static_cast<size_t> ((o.seconds + LEAD_IN_S) * DP_CCSDS_415_SYM) + 64);
  reader_ = std::make_unique<FrameReader> ();

  // The receiver the library builds at the point, for Es/N0 4 dB.
  const char *why = nullptr;
  rx_.reset (dp_async_dsss_receiver_create_ccsds415 (
      code_.data (), code_.size (), fc, 0.0, true, &why));
  check (rx_ != nullptr, std::string ("the receiver: ") + (why ? why : "?"));

  // Telemetry: every probe the receiver has, under "rx.", and one of this
  // program's own, the chunk's processing time per sample. Probes first:
  // the capture sizes its ring from them.
  tlm_.reset (dp_tlm_create (1 << 12));
  check (tlm_ != nullptr, "the telemetry context opens");
  check (dp_async_dsss_receiver_set_telemetry (rx_.get (), tlm_.get (), "rx",
                                               1)
             == DP_OK,
         "the receiver attaches its probes");
  proc_id_ = dp_tlm_probe (tlm_.get (), "app.proc_ns", 1);
  check (proc_id_ >= 0, "the timing probe registers");

  // The capture: lossless by construction when every boundary is at most
  // one chunk apart, with the sample clock as its time base.
  dp_sample_clock_init (&clock_, DP_CCSDS_415_FS, 0);
  const std::string path = o.out + "/" + name_ + ".tlm";
  cap_.reset (
      dp_tlm_capture_open (tlm_.get (), o.chunk, path.c_str (), &clock_));
  check (cap_ != nullptr, "the capture opens " + path);

  scene_ = std::make_unique<Scene> (code_.data (), stim_.bits, fc, o.esn0_db,
                                    o.seconds, o.chunk);
  x_.resize (o.chunk);
  // The most one call of a chunk can deliver: sized to it, no call holds
  // symbols back or refuses its input (dp_async_dsss_receiver_steps()).
  out_.resize (dp_async_dsss_receiver_steps_max_out (rx_.get (), o.chunk));
}

Run::~Run () = default;

double
Run::elapsed_s () const
{
  return static_cast<double> (n_) / DP_CCSDS_415_FS;
}

double
Run::length_s () const
{
  return o_.seconds + LEAD_IN_S;
}

bool
Run::step ()
{
  if (!scene_->next (x_))
    return false;
  // The boundary: the capture drains the chunk just finished.
  dp_tlm_set_now (tlm_.get (), n_);
  // The timed span is the receiver call and nothing else.
  const uint64_t t0 = dp_mono_ns ();
  const size_t got = dp_async_dsss_receiver_steps (
      rx_.get (), c_ptr (x_), o_.chunk, c_ptr (out_), out_.size ());
  const uint64_t dt = dp_mono_ns () - t0;
  // Sized from the bound, every call takes its chunk; one that did not
  // would mean the bound is wrong. Recorded, not exited on: the TUI must
  // restore the terminal before a check reports, so the finish reports it
  // and the run stops here.
  if (dp_async_dsss_receiver_get_consumed (rx_.get ()) != o_.chunk)
    {
      refused_ = true;
      return false;
    }
  last_ns_ = static_cast<double> (dt) / static_cast<double> (o_.chunk);
  dp_tlm_emit_checked (tlm_.get (), proc_id_, last_ns_);
  total_ns_ += dt;
  worst_ns_ = std::max (worst_ns_, last_ns_);
  st_ = dp_async_dsss_receiver_status (rx_.get ());
  // A forced whole-symbol slip (--drop-symbol, --repeat-symbol): the
  // symbol at that index is dropped, or sent twice, before anything here
  // reads it, as a receiver that slipped would. A test of what the reader
  // and the report do across a slip, not a model of one.
  const size_t from = syms_.size ();
  for (size_t i = 0; i < got; i++)
    {
      // Indexed by the receiver's own symbols, which a drop does not stop.
      const size_t k = rx_syms_++;
      const int copies
          = k == o_.drop_symbol ? 0 : k == o_.repeat_symbol ? 2 : 1;
      // The flags of a receiver searching or refining are not its link's.
      const bool tr = st_.state == ASYNC_DSSS_RX_TRACKING;
      const int up[N_LOCK_FLAGS]
          = { st_.locked, st_.code_locked, st_.carrier_locked,
              st_.demod_carrier_locked, st_.sync_locked };
      for (int c = 0; c < copies; c++)
        {
          syms_.push_back (out_[i]);
          for (size_t q = 0; q < N_LOCK_FLAGS; q++)
            flags_[q].push_back (static_cast<uint8_t> (tr && up[q]));
        }
    }
  emitted_.push_back (syms_.size ());
  // The frames, read from what this chunk decided: outside the timed span.
  reader_->feed (syms_.data () + from, syms_.size () - from);
  n_ += o_.chunk;
  return true;
}

// Where the scored window opens: the latest of the five lock flags'
// sustained symbols, or -1 if any never sustained. The design's rule
// (async-dsss-receiver.md §4.12, "The error-rate window"), through the one
// primitive the certification record opens its window with.
int64_t
Run::window_start () const
{
  const uint8_t *fl[N_LOCK_FLAGS];
  for (size_t q = 0; q < N_LOCK_FLAGS; q++)
    fl[q] = flags_[q].data ();
  const size_t n = flags_[0].size ();
  return dp_ber_lock_all (fl, N_LOCK_FLAGS, n, LOCK_SUSTAIN, LOCK_MIN_FRAC,
                          n, nullptr);
}

Result
Run::finish ()
{
  dp_tlm_set_now (tlm_.get (), n_);
  check (!refused_, "[" + name_
                       + "] a call did not take its chunk: the output "
                         "bound is wrong");
  Result r;
  r.chunks = emitted_.size ();
  r.proc_ns = mean_proc_ns ();
  r.worst_ns = worst_ns_;

  // Complete, or the capture has a hole: close says which.
  check (dp_tlm_capture_close (cap_.get ()) == DP_OK,
         "the capture lost records");
  // Every probe the receiver has, and ours, reached the file: a run that
  // searched, handed over, refined and tracked exercises all of them.
  const size_t probes = dp_tlm_probe_count (tlm_.get ());
  for (size_t i = 0; i < probes; i++)
    {
      const int id = dp_tlm_probe_id_at (tlm_.get (), i);
      check (dp_tlm_emitted (tlm_.get (), id) > 0,
             "[" + name_ + "] probe " + dp_tlm_probe_name (tlm_.get (), id)
                 + " emitted nothing");
    }

  // Score: the window opens where the lock is sustained (window_start()),
  // and the meter finds where the stream sits in the payload from a marker.
  const int64_t lo = window_start ();
  check (lo >= 0, "[" + name_ + "] the five lock flags never all sustained");
  size_t at = 0;
  while (emitted_[at] <= static_cast<size_t> (lo))
    at++;
  r.lock_s = (static_cast<double> (at + 1) * o_.chunk
              - static_cast<double> (Scene::lead_in ()))
             / DP_CCSDS_415_FS;
  Owned<dp_ber_meter_state_t, dp_ber_meter_destroy> meter (
      dp_ber_meter_create (2, 0, 0.0));
  check (meter != nullptr, "the BER meter opens");
  check (dp_ber_meter_set_truth (meter.get (), stim_.bits.data (),
                                 stim_.bits.size ())
             == 0,
         "the meter takes the stimulus");
  // Scoring needs the marker, BER_SYNC_SYMS long, starting LAG_SPAN into
  // the locked stream, and LAG_SPAN more for the alignment's search.
  const size_t need
      = marker_at (stim_, static_cast<size_t> (lo)) + BER_SYNC_SYMS + LAG_SPAN;
  if (need > syms_.size ())
    {
      char b[200];
      std::snprintf (b, sizeof b,
                     "[%s] the scene is too short to score: scoring needs "
                     "%zu symbols, %.2f s, and the scene gave %zu; a longer "
                     "--seconds has them",
                     name_.c_str (), need,
                     static_cast<double> (need) / DP_CCSDS_415_SYM,
                     syms_.size ());
      fail (b);
    }
  check (dp_ber_meter_align (meter.get (), c_ptr (syms_), syms_.size (),
                             marker_at (stim_, static_cast<size_t> (lo)), 0, 0,
                             LAG_SPAN, 0.0),
         "[" + name_ + "] the payload marker is in the locked stream");
  dp_ber_meter_score (meter.get (), c_ptr (syms_), syms_.size (),
                      static_cast<size_t> (lo), syms_.size ());
  const ber_interval_t b = dp_ber_meter_ber (meter.get ());
  r.ber = b.p_hat;
  r.ber_lo = b.lo;
  r.ber_hi = b.hi;
  r.conf = b.conf;
  r.errors = b.errors;
  r.bits = b.symbols;
  r.esn0_db = o_.esn0_db;
  if (o_.errors)
    print_errors (meter.get (), static_cast<size_t> (lo));

  // The frames, against the truth, at the lag the meter detected
  // (symbol i carries stimulus bit i + lag): every period sent whole
  // inside the locked stream must have been read, and each CRC verdict must
  // be what comparing the frame with what was sent says. A frame read
  // where no period begins is a wrong verdict too.
  const long lag = dp_ber_meter_get_lag (meter.get ());
  const auto in_window = [&] (long at, size_t len) {
    return at >= lo && at + static_cast<long> (len) <= static_cast<long> (syms_.size ());
  };
  for (size_t i = 0; i < stim_.at.size (); i++)
    if (in_window (static_cast<long> (stim_.at[i]) - lag, stim_.len[i]))
      r.frames_sent++;
  // With none, the --seconds that would end with the first period that
  // starts in the window: the scene's symbols, less the lead-in's.
  for (size_t i = 0; !r.frames_sent && i < stim_.at.size (); i++)
    if (static_cast<long> (stim_.at[i]) - lag >= lo)
      {
        r.frames_need_s
            = static_cast<double> (stim_.at[i] + stim_.len[i]) / DP_CCSDS_415_SYM;
        break;
      }
  const std::vector<uint8_t> &rx = reader_->bits ();
  for (const FrameReader::Seen &f : reader_->seen ())
    {
      if (!in_window (static_cast<long> (f.at), f.len))
        continue;
      r.frames_read++;
      (f.crc_ok ? r.frames_ok : r.frames_failed)++;
      // The period this frame is: the nearest period start within
      // SLIP_MAX symbols of where the meter's one lag puts it. A receiver
      // that slipped whole symbols moves every later frame by the slip,
      // and the reader follows it, so the shift is a slip to report, not a
      // frame read where none was sent.
      const long t = static_cast<long> (f.at) + lag;
      const long slip = static_cast<long> (SLIP_MAX);
      auto p = std::lower_bound (stim_.at.begin (), stim_.at.end (),
                                 static_cast<size_t> (std::max (t - slip, 0L)));
      auto best = stim_.at.end ();
      for (; p != stim_.at.end () && static_cast<long> (*p) <= t + slip; ++p)
        if (best == stim_.at.end ()
            || std::labs (static_cast<long> (*p) - t)
                   < std::labs (static_cast<long> (*best) - t))
          best = p;
      // A frame read where no period begins is wrong whatever its CRC
      // says: nothing was sent there.
      if (best == stim_.at.end ())
        {
          r.frames_wrong++;
          continue;
        }
      const size_t i = static_cast<size_t> (best - stim_.at.begin ());
      const long shift = static_cast<long> (*best) - t;
      if (shift != 0)
        {
          if (!r.frames_shifted)
            {
              r.shift_at = f.at;
              r.shift_by = shift;
            }
          r.frames_shifted++;
        }
      const size_t tp = *best;
      // Read at a period's start with another length: its length field
      // arrived wrong, and only a CRC that passed it is wrong.
      if (stim_.len[i] != f.len)
        {
          if (f.crc_ok)
            r.frames_wrong++;
          continue;
        }
      bool same = true;
      for (size_t k = 0; same && k < f.len; k++)
        same = (rx[f.at + k] ^ (f.inverted ? 1 : 0)) == stim_.bits[tp + k];
      if (same != f.crc_ok)
        r.frames_wrong++;
    }
  r.reader_slips = reader_->stats ().slips;
  return r;
}

const FrameStats &
Run::frames () const
{
  return reader_->stats ();
}

// Where the scored stream's bit errors fall, at the meter's own detected lag
// and phase (symbol i carries stimulus bit i + lag): the first and the last
// error, the longest run of consecutive errors, and the error rate from the
// first error on. Random errors are scattered with short runs; a slip or an
// inverted stream shows as everything after one point at a rate near 0.5
// or 1. A diagnosis aid, printed, never a check.
void
Run::print_errors (const dp_ber_meter_state_t *meter, size_t lo) const
{
  const long lag = dp_ber_meter_get_lag (meter);
  const cf32 rot = std::polar (1.0f,
                               -static_cast<float> (dp_ber_meter_get_phase (meter)));
  size_t n = 0, errs = 0, first = 0, last = 0, run = 0, longest = 0;
  for (size_t i = lo; i < syms_.size (); i++)
    {
      const long t = static_cast<long> (i) + lag;
      if (t < 0 || static_cast<size_t> (t) >= stim_.bits.size ())
        continue;
      n++;
      const uint8_t bit = (syms_[i] * rot).real () < 0.0f ? 1 : 0;
      if (bit != stim_.bits[static_cast<size_t> (t)])
        {
          if (!errs)
            first = i;
          last = i;
          errs++;
          longest = std::max (longest, ++run);
        }
      else
        run = 0;
    }
  // The rate from the first error on is over the scored symbols from there,
  // the same set n counts.
  size_t after = 0;
  for (size_t i = first; errs && i < syms_.size (); i++)
    {
      const long t = static_cast<long> (i) + lag;
      if (t >= 0 && static_cast<size_t> (t) < stim_.bits.size ())
        after++;
    }
  // The errors in each tenth of the window, to show a rate that moves.
  size_t tenth[10] = {};
  const size_t span = syms_.size () > lo ? syms_.size () - lo : 0;
  for (size_t i = lo; span && i < syms_.size (); i++)
    {
      const long t = static_cast<long> (i) + lag;
      if (t < 0 || static_cast<size_t> (t) >= stim_.bits.size ())
        continue;
      const uint8_t bit = (syms_[i] * rot).real () < 0.0f ? 1 : 0;
      if (bit != stim_.bits[static_cast<size_t> (t)])
        tenth[std::min<size_t> (9, (i - lo) * 10 / span)]++;
    }
  std::printf ("%s errors: %zu in %zu scored symbols from symbol %zu (lag "
               "%ld, phase %.3f rad)",
               name_.c_str (), errs, n, lo, lag,
               dp_ber_meter_get_phase (meter));
  if (errs)
    std::printf ("; first at symbol %zu (+%zu into the window), last at %zu; "
                 "longest run %zu; from the first on, %.3f of symbols are "
                 "errors",
                 first, first - lo, last, longest,
                 static_cast<double> (errs) / static_cast<double> (after));
  std::printf ("\n%s errors by tenth of the window (%zu symbols each):",
               name_.c_str (), span / 10);
  for (const size_t c : tenth)
    std::printf (" %zu", c);
  std::printf ("\n");
}

bool
Run::finish_partial ()
{
  dp_tlm_set_now (tlm_.get (), n_);
  bool ok = true;
  if (refused_)
    {
      std::fprintf (stderr,
                    "FAIL: [%s] a call did not take its chunk: the output "
                    "bound is wrong\n",
                    name_.c_str ());
      ok = false;
    }
  if (dp_tlm_capture_close (cap_.get ()) != DP_OK)
    {
      std::fprintf (stderr, "FAIL: [%s] the capture lost records\n",
                    name_.c_str ());
      ok = false;
    }
  uint64_t emitted = 0;
  const size_t probes = dp_tlm_probe_count (tlm_.get ());
  for (size_t i = 0; i < probes; i++)
    emitted += dp_tlm_emitted (tlm_.get (), dp_tlm_probe_id_at (tlm_.get (), i));
  const size_t held = dp_tlm_capture_count (cap_.get ());
  if (held != emitted)
    {
      std::fprintf (stderr,
                    "FAIL: [%s] the capture holds %zu records of the %llu "
                    "emitted\n",
                    name_.c_str (), held,
                    static_cast<unsigned long long> (emitted));
      ok = false;
    }
  // Lock time, if it was reached: the window is the same as finish()'s.
  const int64_t lo = window_start ();
  std::string lock = "the lock time (not reached)";
  if (lo >= 0)
    {
      size_t at = 0;
      while (emitted_[at] <= static_cast<size_t> (lo))
        at++;
      char b[64];
      std::snprintf (b, sizeof b, "locked %.2f s after arrival",
                     (static_cast<double> (at + 1) * o_.chunk
                      - static_cast<double> (Scene::lead_in ()))
                         / DP_CCSDS_415_FS);
      lock = b;
    }
  std::printf ("%s: stopped at %.2f s of %.2f s by the user; %s; the "
               "full-scene checks (%sBER, the payload marker, the frames) were not "
               "evaluated. Partial checks (capture complete, %zu records, "
               "every call took its chunk): %s\n",
               name_.c_str (), elapsed_s (), length_s (), lo >= 0 ? lock.c_str () : "lock not yet reached",
               lo >= 0 ? "" : "the lock time, ", held, ok ? "held" : "FAILED");
  return ok;
}

bool
report (const std::string &name, const Result &r, size_t chunk)
{
  // The cost, in the vocabulary's terms: the processing time per sample
  // against the sample period, their ratio stated as what it is and what
  // it means, so it cannot be read the wrong way round.
  const double ts = sample_period_ns ();
  const double share = r.proc_ns / ts;
  // The bound: theory's BER at the Es/N0 run less the allowed loss. The
  // check fails only when the meter's exact interval lies wholly above it,
  // so a run too short to tell passes, and a receiver worse than theory by
  // more than the loss fails once the bits scored show it.
  const double bound
      = dp_ber_theory_ber (2, std::pow (10.0, (r.esn0_db - LOSS_DB) / 10.0));
  std::printf ("%s: locked %.2f s after arrival (allocation %.0f s); BER "
               "%.1e (%zu errors in %zu bits; %.0f%% interval %.1e to "
               "%.1e)\n",
               name.c_str (), r.lock_s, DP_CCSDS_415_LOCK_S, r.ber, r.errors,
               r.bits, 100.0 * r.conf, r.ber_lo, r.ber_hi);
  // The loss the rate implies: the Es/N0 the bound needs for it, less the
  // Es/N0 run. None with no errors, which no finite Es/N0 gives.
  const double needs = dp_ber_esn0_db_for_ser (2, r.ber);
  // With no errors there is none to measure; with a rate past the bound at
  // -10 dB (near chance), the library reads none either, and says so with
  // a NaN, which is not "no errors".
  char loss[64] = "none measurable (no errors)";
  if (r.errors && std::isfinite (needs))
    std::snprintf (loss, sizeof loss, "%.2f dB", r.esn0_db - needs);
  else if (r.errors)
    std::snprintf (loss, sizeof loss,
                   "more than %.0f dB (the rate is near chance)",
                   r.esn0_db + 10.0);
  std::printf ("  the bound at Es/N0 %.1f dB less the allowed %.2f dB: %.1e; "
               "the loss this rate implies: %s\n",
               r.esn0_db, LOSS_DB, bound, loss);
  std::printf ("  processing time per sample %.1f ns, sample period %.1f "
               "ns: %.1f%% of the sample period (%.1f times faster than "
               "real time); slowest chunk %.1f ns a sample; %zu chunks of "
               "%zu\n",
               r.proc_ns, ts, 100.0 * share, 1.0 / share, r.worst_ns,
               r.chunks, chunk);
  bool ok = true;
  if (!(r.lock_s <= DP_CCSDS_415_LOCK_S))
    {
      std::fprintf (stderr, "FAIL: [%s] locked after the allocation\n",
                    name.c_str ());
      ok = false;
    }
  std::printf ("  frames: %zu of the %zu sent in the locked stream read; "
               "CRC passed %zu, failed %zu; %zu verdicts the truth "
               "contradicts\n",
               r.frames_read, r.frames_sent, r.frames_ok, r.frames_failed,
               r.frames_wrong);
  // A whole-symbol slip in the receiver: the frames after it are read a
  // few symbols from where the meter's one alignment puts them. Said here
  // as what it is, with what the reader saw on its own.
  if (r.frames_shifted || r.reader_slips)
    std::printf ("  slip: %zu frame(s) read shifted from the first alignment, "
                 "the first by %+ld symbol(s) at symbol %zu; the reader, with "
                 "no truth, re-acquired %zu time(s) after a slip\n",
                 r.frames_shifted, r.frames_shifted ? r.shift_by : 0L,
                 r.shift_at, r.reader_slips);
  if (r.frames_sent == 0)
    {
      std::fprintf (stderr,
                    "FAIL: [%s] no whole frame in the locked stream: the "
                    "first ends %.1f s into the signal, so --seconds %.1f "
                    "or more holds it\n",
                    name.c_str (), r.frames_need_s,
                    std::ceil (r.frames_need_s * 10.0) / 10.0);
      ok = false;
    }
  if (r.frames_read != r.frames_sent)
    {
      std::fprintf (stderr, "FAIL: [%s] %zu frames read of %zu sent\n",
                    name.c_str (), r.frames_read, r.frames_sent);
      ok = false;
    }
  if (r.frames_wrong)
    {
      std::fprintf (stderr, "FAIL: [%s] %zu CRC verdicts the truth "
                            "contradicts\n",
                    name.c_str (), r.frames_wrong);
      ok = false;
    }
  // No bits scored has an interval from 0, which no bound refuses: it
  // fails on its own.
  if (r.bits == 0 || !(r.ber_lo <= bound))
    {
      std::fprintf (stderr,
                    "FAIL: [%s] BER %.2e: its %.0f%% interval (%.2e to "
                    "%.2e) lies above the bound, %.2e\n",
                    name.c_str (), r.ber, 100.0 * r.conf, r.ber_lo,
                    r.ber_hi, bound);
      ok = false;
    }
  return ok;
}

} // namespace ccsds415
// run.hpp -- one run of the async DSSS receiver at the CCSDS 415.1-B-1
// point, a chunk at a time: the loop both front ends drive.
//
// ccsds415 (main.cpp) runs it to the end and prints a summary; ccsds415-tui
// (tui.cpp) runs it a chunk at a time and draws it as it goes. Neither
// computes a measurement of its own: every number either shows comes from
// here, and everything here comes from the library.
#pragma once

#include <doppler/RateConverter/RateConverter_core.h>
#include <doppler/async_dsss_receiver/async_dsss_receiver_core.h>
#include <doppler/awgn/awgn_core.h>
#include <doppler/ber_meter/ber_meter_core.h>
#include <doppler/doppler_channel/doppler_channel_core.h>
#include <doppler/dp_tlm/dp_tlm_core.h>
#include <doppler/dp_tlm_capture/dp_tlm_capture_core.h>
#include <doppler/wfm_synth/wfm_synth_core.h>

#include <array>
#include <cmath>
#include <complex>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>

namespace ccsds415
{

using cf32 = std::complex<float>;

// Every doppler object is created by a function and freed by its destroy
// function; a unique_ptr with that function as its deleter owns it.
template <auto Destroy> struct Deleter
{
  template <class T>
  void
  operator() (T *p) const
  {
    Destroy (p);
  }
};
template <class T, auto Destroy>
using Owned = std::unique_ptr<T, Deleter<Destroy> >;

// The smallest chunk a run takes: any. The output is sized from the
// receiver's own bound for the chunk (see the README, "Chunks").
constexpr size_t MIN_CHUNK = 1;
// The sample period, ns: the cost every chunk is held against.
double sample_period_ns ();

// What a run is. The defaults are the batch binary's; the TUI changes the
// scene's length.
struct Options
{
  std::vector<double> carriers;
  double esn0_db = 10.0; // 6 dB above the point's Es/N0 4 dB
  double seconds = 10.0; // signal after the lead-in: four whole frames
  size_t chunk = 4096;   // samples a push into the receiver
  std::string out = "."; // directory the captures go to
  bool paced = false;    // the TUI's: hold each chunk to real time
  bool snapshot = false; // the TUI's: no terminal, one frame at the end
  bool errors = false;   // print where in the scored stream errors fall
  // A forced whole-symbol slip, for testing: the decided symbol at this
  // index dropped, or repeated (SIZE_MAX: none).
  size_t drop_symbol = SIZE_MAX, repeat_symbol = SIZE_MAX;
};

// Parse argv into o (whose fields hold the defaults); exits on --help or a
// bad option. `tui` adds the TUI's own options to the usage.
void parse (int argc, char **argv, Options &o, bool tui);

// A failed check: the reason on stderr, exit 1.
[[noreturn]] void fail (const std::string &why);
void check (bool ok, const std::string &why);

// What the frame reader has read so far, from the receiver's decided
// symbols alone: no truth. Every count is of whole frames.
struct FrameStats
{
  size_t found = 0;      // frames read: a start sequence, then the length
  size_t crc_ok = 0;     // of those, the FECF's CRC held
  size_t crc_failed = 0; // and did not
  size_t missed = 0;     // no start sequence where the last frame put it
  size_t slips = 0;      // frames found a few symbols from where due
  size_t slip_at = 0;    // the last such frame's start sequence, symbol
  long slip_by = 0;      // and its shift, symbols
  bool tracking = false; // the next start sequence's place is known
  // The last frame read.
  bool any = false;
  unsigned octets = 0, scid = 0, vcid = 0, seq = 0, start_errors = 0;
  bool inverted = false; // read from the complemented stream
};

// What a finished run measured.
struct Result
{
  double lock_s = NAN;   // arrival to the five lock flags sustained
  double esn0_db = NAN;  // the Es/N0 run
  double ber = NAN;      // over the locked stream
  double ber_lo = NAN, ber_hi = NAN; // its exact interval (the meter's)
  double conf = NAN;     // that interval's confidence level
  size_t errors = 0;     // bit errors scored
  size_t bits = 0;       // bits scored
  double proc_ns = 0.0;  // processing time per sample, whole run
  double worst_ns = 0.0; // the slowest chunk's
  size_t chunks = 0;
  // Frames in the locked stream: those sent whole inside it, those read,
  // their CRC verdicts, and the verdicts the truth contradicts.
  size_t frames_sent = 0, frames_read = 0, frames_ok = 0, frames_failed = 0;
  size_t frames_wrong = 0;
  // Frames the truth places a few symbols from the meter's lag: read after
  // a whole-symbol slip. The first's symbol, and its shift.
  size_t frames_shifted = 0, shift_at = 0;
  long shift_by = 0;
  size_t reader_slips = 0; // the slips the reader reported, with no truth
  double frames_need_s = NAN; // with none sent: the --seconds one needs
};

// The summary lines for one carrier, and whether its checks held.
bool report (const std::string &name, const Result &r, size_t chunk);

class Scene;
class FrameReader;

// The stimulus, every period of it, as the bits sent and where each period
// sits in them.
struct Stimulus
{
  std::vector<uint8_t> bits;
  std::vector<size_t> at, len;   // a period's first bit, and its bits
  std::vector<size_t> data_at, data_len; // its data field's
};

// One carrier's run: the scene, the receiver, its telemetry and capture.
class Run
{
public:
  Run (const Options &o, double fc);
  ~Run ();
  Run (const Run &) = delete;
  Run &operator= (const Run &) = delete;

  // Process the next chunk; false once the scene has ended.
  bool step ();
  // Close the capture and score the run: the self-checks (a complete
  // capture, every probe emitted, a sustained lock, the payload found, and
  // every frame sent in the locked stream read, with CRC verdicts the
  // truth agrees with).
  Result finish ();
  // A run stopped before its scene ended (the TUI's q): close the capture
  // and check only what a partial run can answer. The capture closes
  // complete and holds every record emitted so far; no call filled its
  // capacity (step() checks that as it goes). Says why on stderr when a
  // check fails, and prints the line saying which full-scene checks were
  // not evaluated. True when the partial checks hold.
  bool finish_partial ();

  const std::string &
  name () const
  {
    return name_;
  }
  double
  carrier_hz () const
  {
    return fc_;
  }
  // The receiver as status() reports it after the last chunk.
  const async_dsss_receiver_status_t &
  status () const
  {
    return st_;
  }
  // The last chunk's processing time per sample, ns: the receiver call
  // alone.
  double
  last_proc_ns () const
  {
    return last_ns_;
  }
  double
  mean_proc_ns () const
  {
    return n_ ? static_cast<double> (total_ns_) / n_ : 0.0;
  }
  // Seconds of the scene processed, and its length.
  double
  elapsed_s () const;
  double
  length_s () const;
  size_t
  symbols () const
  {
    return syms_.size ();
  }
  // The frames read so far.
  const FrameStats &frames () const;

private:
  const Options &o_;
  double fc_;
  std::string name_;
  std::vector<uint8_t> code_;
  Stimulus stim_;
  std::unique_ptr<FrameReader> reader_;
  Owned<dp_async_dsss_receiver_state_t, dp_async_dsss_receiver_destroy> rx_;
  Owned<dp_tlm_t, dp_tlm_destroy> tlm_;
  Owned<dp_tlm_capture_t, dp_tlm_capture_destroy> cap_;
  dp_sample_clock_t clock_{};
  int proc_id_ = -1;
  std::unique_ptr<Scene> scene_;
  std::vector<cf32> x_, out_, syms_;
  size_t rx_syms_ = 0; // symbols the receiver has emitted
  // Per symbol, the status record's five lock flags, each up only while
  // tracking: symbol, code, carrier, demodulator carrier, sync.
  static constexpr size_t N_LOCK_FLAGS = 5;
  std::array<std::vector<uint8_t>, N_LOCK_FLAGS> flags_;
  std::vector<size_t> emitted_;
  async_dsss_receiver_status_t st_{};
  uint64_t n_ = 0, total_ns_ = 0;
  double last_ns_ = 0.0, worst_ns_ = 0.0;
  bool refused_ = false; // a call did not take its chunk: the run stopped there
  void print_errors (const dp_ber_meter_state_t *meter, size_t lo) const;
  int64_t window_start () const;
};

} // namespace ccsds415
// tui.cpp -- ccsds415-tui: the same run as ccsds415, drawn as it goes.
//
// A second front end over run.cpp's loop, not a second receiver: the scene,
// the receiver, the capture and the checks are the batch binary's. What it
// adds is a terminal display (FTXUI), refreshed at most every 100 ms of
// wall time:
//
//   - cost: the last chunk's processing time per sample and the run's,
//     against the sample period, and the display's own time per refresh,
//     shown apart so it is plainly not what is being measured;
//   - receiver: its state, both lock flags, the symbol-lock metric against
//     its threshold, C/N0, the Doppler and the code rate, as status()
//     reports them: nothing here computes a measurement of its own;
//   - progress through the scene;
//   - frames: what the reader finds in the decided symbols, with no
//     truth: the start sequence searched for or tracked, frames read and
//     their CRC verdicts, and the last frame's header fields read back.
//
// One thread. The timed span in run.cpp is the receiver call alone; the
// pacing sleep and the drawing both fall outside it, and the display never
// holds the receiver up: Loop::RunOnce() draws what is pending and returns.
// By default each chunk is held to real time, so the 30 s scene takes
// 30 s and lock can be watched happening; --unpaced runs it as fast as it
// goes. q quits early, through the same teardown as the scene's end: the
// capture is closed and the checks are reported.
//
// --snapshot needs no terminal: it runs the scene unpaced, then prints the
// last frame as text, so CI can read every panel.
#include "run.hpp"

#include <doppler/timing/timing_core.h>

#include <ftxui/component/component.hpp>
#include <ftxui/component/loop.hpp>
#include <ftxui/component/screen_interactive.hpp>
#include <ftxui/dom/elements.hpp>
#include <ftxui/screen/screen.hpp>

#include <cctype>
#include <chrono>
#include <unistd.h>
#include <cstdio>
#include <memory>
#include <string>
#include <thread>
#include <vector>

namespace
{

using namespace ftxui;

std::string
fmt (const char *f, double v)
{
  char b[48];
  std::snprintf (b, sizeof b, f, v);
  return b;
}

const char *
state_name (int s)
{
  switch (s)
    {
    case ASYNC_DSSS_RX_SEARCHING:
      return "searching";
    case ASYNC_DSSS_RX_REFINING:
      return "refining";
    case ASYNC_DSSS_RX_TRACKING:
      return "tracking";
    case ASYNC_DSSS_RX_IDLE:
      return "idle";
    case ASYNC_DSSS_RX_LOST:
      return "lost";
    default:
      return "?";
    }
}

// The screen's text without its blank last lines: a line is blank when it
// has nothing but spaces outside its escape sequences.
std::string
trimmed (const std::string &screen)
{
  std::vector<std::string> lines;
  size_t from = 0;
  for (size_t nl; (nl = screen.find ('\n', from)) != std::string::npos;
       from = nl + 1)
    lines.push_back (screen.substr (from, nl - from));
  lines.push_back (screen.substr (from));
  const auto blank = [] (const std::string &l) {
    bool esc = false;
    for (const char c : l)
      {
        if (esc)
          esc = !std::isalpha (static_cast<unsigned char> (c));
        else if (c == '\x1b')
          esc = true;
        else if (c != ' ' && c != '\r')
          return false;
      }
    return true;
  };
  while (!lines.empty () && blank (lines.back ()))
    lines.pop_back ();
  std::string out;
  for (const std::string &l : lines)
    out += l + "\n";
  if (!out.empty ())
    out.pop_back ();
  return out;
}

// One labelled value: the label in a fixed column, the value after it.
Element
row (const std::string &label, const std::string &value, int width = 32)
{
  return hbox ({ text (label) | size (WIDTH, EQUAL, width), text (value) });
}

// The whole display for one run, from what the run and the receiver report.
Element
document (const ccsds415::Run &run, double refresh_ms, bool paced,
          bool held = false)
{
  const async_dsss_receiver_status_t &st = run.status ();
  const double ts = ccsds415::sample_period_ns ();
  const double last = run.last_proc_ns (), mean = run.mean_proc_ns ();
  const double done = run.elapsed_s () / run.length_s ();
  const Element cost = window (
      text ("cost"),
      vbox ({
          // Paced, each chunk starts with a cache the sleep let go cold, so
          // the figure reads higher than unpaced: the label says which.
          row (paced ? "processing time per sample (paced)"
                     : "processing time per sample",
               fmt ("%.1f ns", last)),
          row ("  over the run so far", fmt ("%.1f ns", mean)),
          row ("sample period", fmt ("%.1f ns", ts)),
          row ("share of the sample period", fmt ("%.1f %%", 100.0 * mean / ts)),
          row ("times faster than real time",
               fmt ("%.1f", mean > 0.0 ? ts / mean : 0.0)),
          separator (),
          row ("display time per refresh", fmt ("%.2f ms", refresh_ms)),
      }));
  const Element receiver = window (
      text ("receiver"),
      vbox ({
          row ("state", state_name (st.state)),
          row ("code lock", st.code_locked ? "up" : "down"),
          row ("symbol lock", st.locked ? "up" : "down"),
          row ("lock metric", fmt ("%.3f", st.lock_metric)),
          row ("  threshold", fmt ("%.3f", st.lock_threshold)),
          row ("C/N0", fmt ("%.1f dB-Hz", st.cn0_dbhz_est)),
          row ("Doppler", fmt ("%.2f Hz", st.doppler_hz)),
          // The received code rate over the nominal: 1 is no Doppler.
          row ("code rate (received / nominal)", fmt ("%.9f", st.code_rate)),
      }));
  const Element progress = window (
      text ("scene"),
      vbox ({
          row ("carrier", fmt ("%.1f GHz", run.carrier_hz () / 1e9)),
          row ("time", fmt ("%.2f s", run.elapsed_s ())),
          row ("symbols", fmt ("%.0f", static_cast<double> (run.symbols ()))),
          hbox ({ text ("progress ") | size (WIDTH, EQUAL, 32),
                  gauge (static_cast<float> (done))
                      | size (WIDTH, EQUAL, 16) }),
      }));
  // The frames, as the reader finds them in the decided symbols: what a
  // ground station would see, with no truth.
  const ccsds415::FrameStats &fr = run.frames ();
  const auto n = [] (size_t v) { return fmt ("%.0f", static_cast<double> (v)); };
  const auto read_back = [&] (unsigned v) {
    return fr.any ? n (v) : std::string ("none yet");
  };
  // The frames panel's labels are shorter, so its values have room.
  const auto fr_row = [] (const std::string &l, const std::string &v) {
    return row (l, v, 26);
  };
  const Element frames = window (
      text ("frames"),
      vbox ({
          fr_row ("start sequence", fr.tracking ? "tracking" : "searching"),
          fr_row ("frames read", n (fr.found)),
          fr_row ("  CRC passed", n (fr.crc_ok)),
          fr_row ("  CRC failed", n (fr.crc_failed)),
          fr_row ("start sequences missed", n (fr.missed)),
          // A frame found a few symbols from where the last one ended: the
          // receiver slipped whole symbols between them.
          fr_row ("slips", n (fr.slips)),
          fr_row ("  last slip",
               fr.slips ? fmt ("%+.0f", static_cast<double> (fr.slip_by))
                              + " at symbol " + n (fr.slip_at)
                        : std::string ("none")),
          fr_row ("last frame's data",
               fr.any ? n (fr.octets) + " octets" : "none yet"),
          fr_row ("  SCID", read_back (fr.scid)),
          fr_row ("  VCID", read_back (fr.vcid)),
          fr_row ("  frame sequence number", read_back (fr.seq)),
          fr_row ("  polarity",
               fr.any ? (fr.inverted ? "inverted" : "upright") : "none yet"),
      }));
  Elements parts{ text (run.name ()) | bold, hbox ({ cost, receiver }),
                  hbox ({ progress, frames }) };
  if (held)
    parts.push_back (text ("the scene has ended: press q to exit"));
  return vbox (std::move (parts));
}

} // namespace

int
main (int argc, char **argv)
{
  ccsds415::Options o;
  o.seconds = 30.0; // long enough to watch: lock, then the Doppler ramp
  o.paced = true;
  ccsds415::parse (argc, argv, o, true);

  std::vector<std::pair<std::string, ccsds415::Result> > results;
  if (o.snapshot)
    {
      for (const double fc : o.carriers)
        {
          ccsds415::Run run (o, fc);
          while (run.step ())
            {
            }
          // The display's cost here is one render, timed, then drawn
          // again carrying that time.
          // A screen taller than any frame, its blank tail trimmed when
          // printed: Dimension::Fit under-measures two side-by-side windows
          // of different heights and cut the taller one's last row.
          Element doc = document (run, 0.0, false);
          Screen screen
              = Screen::Create (Dimension::Fixed (100), Dimension::Fixed (80));
          const uint64_t t0 = dp_mono_ns ();
          Render (screen, doc);
          const double render_ms
              = static_cast<double> (dp_mono_ns () - t0) / 1e6;
          doc = document (run, render_ms, false);
          screen.Clear ();
          Render (screen, doc);
          std::printf ("%s\n", trimmed (screen.ToString ()).c_str ());
          results.emplace_back (run.name (), run.finish ());
        }
    }
  else
    {
      // The runs outlive the display: a failed check exits the program,
      // and it must not do so while the terminal is in the display's mode.
      std::vector<std::unique_ptr<ccsds415::Run> > runs;
      bool stopped = false; // q came before the last run's scene ended
      auto screen = ScreenInteractive::Fullscreen ();
      ccsds415::Run *cur = nullptr;
      double refresh_ms = 0.0;
      bool quit = false;
      bool held = false; // every scene ended: the last frame stays up
      auto view = Renderer ([&] {
        return cur ? document (*cur, refresh_ms, o.paced, held)
                   : text ("starting");
      });
      auto app = CatchEvent (view, [&] (Event e) {
        if (e == Event::Character ('q'))
          {
            quit = true;
            return true;
          }
        return false;
      });
      {
        Loop loop (&screen, app);
        for (const double fc : o.carriers)
          {
            if (quit)
              break;
            runs.push_back (std::make_unique<ccsds415::Run> (o, fc));
            ccsds415::Run &run = *runs.back ();
            cur = &run;
            const uint64_t start = dp_mono_ns ();
            uint64_t last_draw = 0;
            bool more = true;
            while (!quit && (more = run.step ()))
              {
                // Pacing and drawing are outside the receiver's timed span.
                if (o.paced)
                  {
                    const uint64_t due
                        = start
                          + static_cast<uint64_t> (run.elapsed_s () * 1e9);
                    const uint64_t now = dp_mono_ns ();
                    if (due > now)
                      std::this_thread::sleep_for (
                          std::chrono::nanoseconds (due - now));
                  }
                const uint64_t now = dp_mono_ns ();
                if (now - last_draw >= 100000000u)
                  {
                    screen.PostEvent (Event::Custom); // same thread: a redraw
                    const uint64_t t0 = dp_mono_ns ();
                    loop.RunOnce ();
                    refresh_ms = static_cast<double> (dp_mono_ns () - t0) / 1e6;
                    last_draw = now;
                  }
              }
            stopped = more && quit;
          }
        // Every scene ended: keep the last frame on screen, drawn once more
        // with the hold line, until q.
        // Only on a terminal: with stdin not one, nothing can send the q.
        if (!quit && cur && isatty (STDIN_FILENO))
          {
            held = true;
            screen.PostEvent (Event::Custom);
            while (!quit)
              {
                loop.RunOnce ();
                std::this_thread::sleep_for (std::chrono::milliseconds (50));
              }
          }
        cur = nullptr;
      } // the Loop restores the terminal here, before any check can exit
      // A run the user stopped answers only the partial checks; the runs
      // before it finished their scenes and answer the full ones.
      for (size_t i = 0; i < runs.size (); i++)
        if (stopped && i + 1 == runs.size ())
          {
            if (!runs[i]->finish_partial ())
              return 1;
          }
        else
          results.emplace_back (runs[i]->name (), runs[i]->finish ());
      if (stopped)
        {
          bool ok = true;
          for (const auto &[name, r] : results)
            ok = ccsds415::report (name, r, o.chunk) && ok;
          return ok ? 0 : 1;
        }
    }

  bool ok = !results.empty ();
  for (const auto &[name, r] : results)
    ok = ccsds415::report (name, r, o.chunk) && ok;
  if (!ok)
    return 1;
  std::printf ("OK\n");
  return 0;
}