Compare commits

..
Author SHA1 Message Date
sjgandClaude Opus 5 bf3bcc8a84 [fix](trx-frontend-http): show one rig at a time on the digital modes page
CI / lint (pull_request) Successful in 2m24s
CI / test (pull_request) Successful in 8m34s
CI / test (push) Successful in 7m47s
CI / frontend (pull_request) Successful in 4m28s
CI / reuse (pull_request) Successful in 5s
CI / lint (push) Successful in 2m21s
CI / frontend (push) Successful in 3m37s
CI / reuse (push) Successful in 6s
A client connected to several rigs decodes all of them at once, and the
decode stream carries every rig's traffic to every browser.  The decoder
panels listed all of it: a station a background rig copied on another band
appeared in the APRS list next to the selected rig's, the vessel counts and
the "latest seen" lines counted both, the status lines said "Receiving"
because some other rig was, and the CW pane interleaved two rigs into one
stream of text that read as neither.

The page is about the rig the operator selected — the one whose spectrum is
on screen and whose audio is playing — so each panel now shows what that rig
heard: rows, counts, latest-seen, status, the live picture a WEFAX or SSTV
frame is painting, and the CW pane.

Nothing is dropped on the way in.  The map is the whole station's view, has
its own rig filter, and would empty out if the plugins stopped feeding it, so
the histories still hold every rig and the map still plots them.  That also
means a switch loses nothing: the runtime gained a rerender hook, which the
rig switch calls, and switching back brings the other rig's traffic up again.
The CW pane is the exception — a running stream of text cannot be unpicked
after the fact — so it starts empty on the rig switched to.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-07 08:11:13 +02:00
sjgandClaude Opus 5 86dd36312e [test](trx-frontend-http): type the frequency instead of filling it
CI / lint (pull_request) Successful in 2m20s
CI / test (pull_request) Successful in 8m32s
CI / frontend (pull_request) Successful in 4m27s
CI / reuse (pull_request) Successful in 6s
CI / lint (push) Successful in 2m26s
CI / test (push) Successful in 7m42s
CI / frontend (push) Successful in 3m35s
CI / reuse (push) Successful in 5s
tune-links drove the dial with Playwright's fill(), which writes a value
into the field without a keystroke.  The app arms its guard against its own
refreshes on the first keydown, so a filled field stays unguarded: any state
update landing between the fill and the Enter rewrites the field with the
frequency the radio is already on, and the Enter then re-applies that.  The
window is a few milliseconds wide on a developer's machine and wide enough
to lose on a loaded CI runner, where the test failed claiming the tuning had
landed on the frequency it started from.

Type it the way an operator does: select the field, then send the characters
as keystrokes.  The select arms the guard before a single character changes.

Under CPU throttling that reproduced the failure — 1 in 6 runs with fill(),
on this branch and on main alike — typing came through 8 runs clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-07 02:47:04 +02:00
sjgandClaude Opus 5 15ff686542 [fix](trx-frontend-http): keep the mini views to the rig on screen
CI / lint (pull_request) Successful in 2m23s
CI / test (pull_request) Successful in 8m34s
CI / frontend (pull_request) Failing after 1m32s
CI / reuse (pull_request) Successful in 6s
The decode SSE stream and the history behind it are not rig-scoped: every
rig's decodes reach the browser, each carrying the rig that heard it.  The
panels on the decoder tabs want that — they aggregate the whole station —
but the mini views over the waterfall caption the spectrum underneath, and
they were reading the same unfiltered histories.  A background rig copying
APRS on another band put its frames over the active rig's waterfall.  The
mode gate did not help: it reads the mode of the rig on screen, so those
frames appeared whenever that rig happened to be in PKT.

Filter each overlay on the rig it belongs to, through one shared predicate
that compares a decode's rig_id with the per-tab active rig already driving
the spectrum and the audio.  A decode that names no rig, and a session that
has not learnt its rig list yet, still show everything.

The FTx normalizer was dropping rig_id on the floor, so it now keeps it.
CW needed more than a filter: its lines accumulate character by character,
so two rigs copying at once braided their text into one unreadable line.
Lines in progress are now kept per rig.

The bar repaints in render() move into refreshDecodeBars(), which the rig
switch calls as well — otherwise the outgoing rig's frames stayed on screen
until the next state update — and which finally includes the CW bar.

Closes #49

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-07 00:46:39 +02:00
sjgandClaude Opus 5 b78c4a4dd4 [feat](trx-rs): make spectrum affordable over a slow link
CI / lint (pull_request) Successful in 2m22s
CI / test (pull_request) Successful in 8m36s
CI / frontend (push) Successful in 3m38s
CI / reuse (push) Successful in 6s
CI / frontend (pull_request) Successful in 4m27s
CI / reuse (pull_request) Successful in 6s
CI / lint (push) Successful in 2m21s
CI / test (push) Successful in 7m48s
Spectrum dominates the server↔client connection, and all three things that
govern its cost were working against a poor link.

**It was polled, one round trip per frame.** The client asked for a frame every
50 ms on a dedicated connection and waited for the reply, so the frame rate was
capped at 1/RTT — on a 200 ms link, five frames a second no matter what was
configured.  Add SubscribeSpectrum alongside the existing SubscribeMeter: the
server pushes frames from a per-rig broadcast that rig_task fills only while
somebody is subscribed.  A server too old to know the command answers with an
error and leaves the connection usable, so the client falls back to polling on
the same connection without reconnecting.

**Bins were JSON floats.** 1024 bins spelled out as decimal text is around
10 KB a frame, ~200 KB/s at full rate — while the very next hop, client to
browser, already sends the same information as base64 i8 in about 1.4 KB.  Bins
now travel base64-encoded whole dBFS, the resolution the display draws at
anyway.  Decoding still accepts the old array form.

**Nothing was tunable.** [sdr].spectrum_fft_size and [sdr].spectrum_interval_ms
replace the compile-time FFT size and cadence; [[remotes]].spectrum_interval_ms
lets the client ask for less.  512 bins at 5 frames/s is roughly 3.5 KB/s
against roughly 200 KB/s before.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-07 00:15:50 +02:00
sjgandClaude Opus 5 f396e8f235 [fix](trx-frontend-http): give satellite passes their own page
CI / lint (push) Successful in 2m21s
CI / test (push) Successful in 7m50s
CI / frontend (push) Successful in 3m38s
CI / reuse (push) Successful in 6s
Pass predictions were a third view inside the Weather Satellite Decoder card,
under Digital modes — a planning tool filed behind a decoder toggle, beside the
FT8 and WEFAX panels it has nothing to do with.  Nothing about knowing when a
bird comes over belongs there.

Move them to /satellites, reached from Tools alongside Statistics, Recorder,
Settings and About: occasional destinations that live behind that menu rather
than taking a slot in the operating strip.  Adding a sixth strip button wrapped
the phone nav onto two rows and cost the desktop strip its labels at 1280px, so
the tab is hidden from the strip exactly the way its four peers already are —
the nav is byte-for-byte what it was.

The prediction code moves out of sat.ts into its own plugin that loads with the
page, so the decoder card no longer carries it.  Countdowns stop when the page
is hidden and each visit reloads, since passes go stale while it is closed.
The server grows a /satellites index route so a deep link or a refresh serves
the SPA shell rather than a 404.

Closes #47

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-07 00:06:00 +02:00
sjgandClaude Opus 5 46c9827e8a [fix](trx-config): keep the generated example off the machine that made it
CI / lint (pull_request) Successful in 2m17s
CI / frontend (pull_request) Successful in 3m28s
CI / reuse (pull_request) Successful in 3s
CI / lint (push) Successful in 2m16s
CI / test (pull_request) Successful in 7m50s
CI / frontend (push) Successful in 4m11s
CI / reuse (push) Successful in 9s
CI / test (push) Failing after 17m15s
The example is generated from the config defaults, and [decode_logs].dir
defaults to the running user's cache directory.  So the file rendered
/Users/sjg/Library/Caches/trx-rs/decoders on the machine that generated it and
/root/.cache/trx-rs/decoders in CI, and the up-to-date test failed for everyone
but its author.

Pin dir to an illustrative /var/lib/trx-rs/decoders in the example config;
omitting the key still falls back to the per-user directory.  A new test asserts
the rendered example contains none of this machine's home, cache or config
directories, so the next environment-derived default cannot slip through the
same way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 22:08:06 +02:00
sjgandClaude Opus 5 0fc977f19f [style](trx-config): apply rustfmt
CI / test (pull_request) Failing after 6m0s
CI / lint (pull_request) Successful in 2m18s
CI / frontend (pull_request) Successful in 3m28s
CI / reuse (pull_request) Successful in 2s
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 21:44:17 +02:00
sjgandClaude Opus 5 084f629b5b [docs](trx-rs): record the trx-config crate and its commands
CI / lint (pull_request) Failing after 1s
CI / test (pull_request) Failing after 6m6s
CI / reuse (pull_request) Has been cancelled
CI / frontend (pull_request) Has been cancelled
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 21:39:09 +02:00
sjgandClaude Opus 5 bc63ded583 [feat](trx-config): warn about deprecated configuration keys
Several keys quietly stopped doing what they look like they do, and nothing
said so: [remote] and the flat per-rig sections are ignored outright once
[[remotes]] / [[rigs]] exist, [frontends.rigctl].port and --rigctl-port have
been dead since rig_ports replaced them, [frontends.audio].rig_ports is
superseded by rig_urls, and default_rig_id was renamed to default_rig_name.

Warn once at load, naming the replacement.  Defaults are indistinguishable from
explicit values after deserialization, so the loader now records which key paths
the file actually set and the checks work off that — no warning for a setting
the user never wrote.

The single-rig flat layout is not deprecated: it is the documented simple form,
and only draws a warning when [[rigs]] is silently shadowing it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 21:35:52 +02:00
sjgandClaude Opus 5 cfaeb6ee15 [docs](trx-rs): generate the example config and correct the manual
trx-rs.toml.example was maintained by hand and had fallen well behind: no
[[rigs]], no [[remotes]], no [timeouts], no bandplan or decode-history
settings, and a [frontends.http].default_rig_id that had been renamed.

Generate it from the config structs instead, so a new field shows up the moment
it exists, and add a test that fails when the checked-in copy drifts:

    cargo run -p trx-config --example generate_example

Section comments come from a small table; a section without an entry is still
emitted, so forgetting a comment can never drop a setting from the example.

The manual was wrong about the basics.  It listed five config search paths, none
of which the loader has ever looked at (the real order is ./trx-rs.toml → XDG →
/etc), called --print-config output "fully commented" when it carries no
comments at all, and documented a TRX_PLUGIN_DIRS variable no code reads.  It
also still described [frontends.rigctl].port as the bind port years after
rig_ports replaced it.  Fixed, and the new configuration features are written
up alongside.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 21:32:46 +02:00
sjgandClaude Opus 5 76bcce8c54 [feat](trx-config): let secrets live outside the config file
Tokens and passphrases had exactly one representation: plain text in
trx-rs.toml.  That is awkward for config-management tools, for a config kept in
a private repo, and for anything shared between machines.

Two alternatives:

- ${VAR} anywhere in a config string, expanded from the environment at load.
  An unset variable is an error rather than an empty string — a silently blank
  passphrase is how authentication gets disabled by accident.
- A *_file sibling for every credential: [listen.auth].tokens_file,
  [[remotes]].auth.token_file, [frontends.http.auth].rx_passphrase_file and
  .control_passphrase_file, [frontends.http_json.auth].tokens_file.  Setting
  both forms is an error rather than a guess about which wins.

Plus a nudge: a config file that holds credentials inline and is readable by
group or others gets a warning naming the chmod that fixes it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 21:27:18 +02:00
sjgandClaude Opus 5 88ed3da6cc [feat](trx-server): make the decoder set configurable per rig
Every rig started nine decoders — APRS, HF APRS, CW, FT8, FT4, WSPR, LRPT,
WEFAX, SSTV — whether or not anyone ever looked at the results.  Two rigs on a
Pi meant eighteen decoder tasks chewing CPU for modes the operator does not
run.  Only the SDR virtual channels had a decoder list; the analog path had no
say at all.

Add [decoders] per rig:

    [decoders]
    enabled = ["cw", "ft8", "wspr"]
    output_dir = "/var/lib/trx-rs"

using the same decoder names as [sdr.channels].decoders, so there is one
vocabulary.  enabled defaults to every decoder, so upgrading changes nothing.
An unknown name is a config error rather than a silently ignored entry.

output_dir also replaces the hard-coded cache paths for the decoders that write
images, so SSTV, WEFAX and LRPT output can live somewhere the operator chooses.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 21:22:03 +02:00
sjgandClaude Opus 5 7c69e0de08 [feat](trx-rs): add --check-config to the server and client
Validating a config meant starting the daemon and reading the first error it
died on, fixing that, and repeating.  Add --check-config, which loads the
config through the real loader, reports every problem at once and exits 0/1:

    $ trx-server --check-config --config trx-rs.toml
    trx-rs.toml
      warning: unknown config key 'listen.prot' (did you mean 'listen.port'?)
      error: [general].log_level 'verbose' is invalid (expected one of: ...)
      error: [rig.access].baud must be > 0 for serial access
      error: [audio].frame_duration_ms must be one of: 3, 5, 10, 20, 40, 60
      error: [listen] and rig "default" [audio] would both bind 127.0.0.1:4530

Validation grows validate_all()/validate_resolved_all() alongside the existing
first-error entry points; validate() is now the first element of validate_all().
Sockets are built by one helper shared by startup and the check, so the two
cannot disagree about what --listen overrides.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 21:08:20 +02:00
sjgandClaude Opus 5 fbc4f6e398 [feat](trx-config): add a resolved-config validation phase
Some things can only be checked once CLI overrides have been folded in and the
rig/remote lists are final, so nothing checked them at all:

- The client's per-rig maps (rigctl.rig_ports, audio.rig_urls, audio.rig_ports,
  decode_history_retention_min_by_rig, http.default_rig_name) are keyed by a
  remote's short name.  A typo used to spawn a rigctl listener that injected a
  rig_id no remote answered to, without a word in the log.
- Nothing noticed two listeners claiming one socket.  [listen].port and a rig's
  [audio].port could both be 4530; on the client, http, http_json and each
  rigctl rig port could collide freely.

Add validate_resolved() to both configs, run after argument parsing, plus a
shared socket-conflict check that treats a wildcard address as conflicting with
any address on the same port and ignores port 0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 21:02:26 +02:00
sjgandClaude Opus 5 d42ca4f030 [fix](trx-config): validate every rig, not just the legacy flat one
ServerConfig::validate() checked the flat [rig]/[audio]/[behavior] fields and
gave [[rigs]] entries only an id/audio-port uniqueness pass, and
validate_sdr() returned early unless the *flat* access type was "sdr".  A
multi-rig SDR station therefore got no Nyquist, stream_opus, duplicate-decoder
or tx_enabled checking at all, and a rig entry with frame_duration_ms = 7 or a
missing baud rate started and failed at runtime.

Move the per-rig rules into validate_rig_instance() and validate_sdr_instance()
and run them over resolved_rigs(), which already synthesises the flat layout as
a single entry.  Both layouts now go through the same code, and multi-rig
messages name the rig they came from.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 20:57:59 +02:00
sjgandClaude Opus 5 335922fecc [feat](trx-config): report unknown configuration keys
Every config struct is #[serde(default)], so a misspelled key was dropped in
silence and the setting kept its default.  Writing `prot = 9999` under
[listen] started the server on 4530 without a word.

Collect the ignored key paths with serde_ignored and pair each with the
closest known key at the same level:

    WARN unknown config key 'listen.prot' (did you mean 'listen.port'?)

Warnings by default, so a config written for a newer version still runs on an
older binary; --strict-config makes them fatal for CI.  Logging now starts
before validation so these warnings are actually visible.

trx-configurator --check drops its hand-maintained key lists and re-implemented
range checks in favour of the real loader and validators, so it no longer
passes configs the binaries reject.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 20:55:01 +02:00
sjgandClaude Opus 5 bede2e34fe [fix](trx-config): accept both sectioned and bare config files
trx-configurator wrote standalone configs with [general]/[rig] at the root
while the loader required a [trx-server] section header, so every config the
wizard generated with --type server or --type client was rejected by the
binary it was generated for:

    $ trx-server --config trx-server.toml
    Error: ParseError("trx-server.toml", "missing [trx-server] section")

Teach the loader to fall back to the document root when no section header is
present, so hand-written standalone files keep working, and have the wizard
emit the same sectioned shape --print-config does.  A file carrying only the
*other* component's section still reports the missing section rather than
silently loading defaults.

Round-trip tests now load every document the wizard can generate through the
real loader and validator.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 20:46:59 +02:00
sjgandClaude Opus 5 da58a004fe [refactor](trx-config): extract client/server config into a shared crate
The setup wizard, the server and the client each carried their own idea of
what a valid config looks like: trx-configurator validated with hand-written
toml_edit key lists while the binaries validated with serde plus their own
validate().  Nothing kept the three in sync.

Move ServerConfig, ClientConfig, the section loader, the shared validators and
the endpoint-URL parsing into a new trx-config crate that all three depend on,
so there is one definition of the config to drift from.  The binaries keep a
thin crate::config re-export so their internal paths are unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyX26FCpMQxiBoC7r5K1A7
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 20:44:42 +02:00
sjg 77b283cb78 [fix](trx-frontend-http): size the nav's labels against the screen, not the font
CI / lint (pull_request) Successful in 2m17s
CI / test (pull_request) Successful in 8m23s
CI / frontend (pull_request) Successful in 4m20s
CI / reuse (pull_request) Successful in 3s
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 7m35s
CI / frontend (push) Successful in 3m29s
CI / reuse (push) Successful in 2s
CI cut "Bookmarks" off at 360 px where this machine had ten pixels to
spare.  How wide a platform draws a word varies by more than ten per
cent, so a fixed 0.6rem label is a bet on the machine it was measured
on -- the same bet ui-core's own comment warns about where it explains
why the tab strip reflows by measurement rather than at a width.

The long labels are sized with `clamp(0.46rem, 2.2vw, 0.62rem)` now.  A
tab is a fifth of the viewport, so what fits in it follows the viewport;
tying the label to the same thing leaves better than a fifth of the tab
spare at every phone width, and holds with the text drawn 30% wider than
it is here.

The test asked the wrong question too.  "Does the label fit" is a
question about font metrics, and it will keep answering differently on
different machines.  It now asserts what actually matters: a label stays
inside its own tab, and if it is too long for it, it ends in an ellipsis
rather than being cut through a letter.  Both hold whatever width the
platform draws the words at.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 19:41:45 +02:00
sjg 6284747339 [fix](trx-frontend-http): let the bottom nav's labels fit inside its tabs
CI / lint (pull_request) Successful in 2m17s
CI / test (pull_request) Successful in 8m22s
CI / frontend (pull_request) Failing after 1m46s
CI / reuse (pull_request) Successful in 2s
The bottom nav keeps its labels under the icons -- that is what makes it
navigation rather than five glyphs -- but the labels did not fit the
tabs.  On a 360 px screen "Bookmarks" and "Digital modes" were cut off
mid-word and ran into each other: "Bookmarks igital mode".

The stylesheet already meant to handle it.  Three rules shrink the long
labels, and a rule twenty lines further down sets the size for all of
them; identical specificity, later in the file, so the blanket rule won
and nothing was ever shortened.  Those rules now come after it.

Beyond that, tabs sized themselves to their own labels, so "Map" and
"Digital modes" were given the same room.  They divide the bar evenly
now, which is the shape of every bottom nav, and a label that still runs
long ellipsises rather than being cut through a letter.

"Digital modes" does not fit at any size worth reading, so the nav shows
"Digital" and the button carries the full name as its accessible label;
the short form is hidden from assistive tech, which reads the button's
name instead.

The phone layout test now checks that no label in the nav is cut off at
430, 390 or 360 px, and that the shortened tab still says what it is to
something that reads the page rather than looks at it.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 19:14:31 +02:00
sjg 14ad6e241b [fix](trx-frontend-http): stop the radio controls running off the side of a phone
CI / lint (pull_request) Successful in 2m19s
CI / test (pull_request) Successful in 8m23s
CI / frontend (pull_request) Failing after 1m28s
CI / reuse (pull_request) Successful in 2s
On a 390 px screen the transmit controls were laid out at x=400, off the
side of a tray 354 px wide: present, invisible, and reachable only by a
horizontal scroll with nothing to say it was there.  The page scrolled
sideways by a dozen pixels as well.

Three causes, each in a different place.

A container query at the end of the stylesheet re-imposes `flex-wrap:
wrap` on a narrow tray's rows.  That is right while a row runs left to
right; below the phone breakpoint the row is a column, and wrapping a
column starts a *second column* — which is what put the transmit
controls beside the tray rather than under it.  The rule outranks the
phone one, two classes to its one, and sits later in the file, so it now
excludes itself below that breakpoint rather than being overridden.

The tray is a grid, and a grid column sizes to its content.  One row
wider than the screen — the mode picker, six buttons across — dragged
the whole tray out with it.  `minmax(0, 1fr)` lets the column be as
narrow as the phone and the rows wrap inside it.

The wavelength and signal-strength readouts are given the width of their
column on narrow screens, but with padding on a content box that is the
column's width plus the padding.  Those dozen pixels were the page's
sideways scroll.  They are border-box now.

Also: the rig picker was taking 139 px of a 338 px bar, pushing the rest
of the top bar into the overflow menu.  It is capped and ellipsised on
phones, with the full name still in the menu it opens.

The map's filter bar, collapsed, keeps both its anchors and shrinks
inside them rather than dropping `left` to be sized by shrink-to-fit,
and no longer asks for a compositing layer it does not need.  An
absolutely positioned, backdrop-filtered, composited box sizing itself
from its content is the shape of thing that renders as nothing on an
engine other than the one it was written against — which is what Edge
does with it.  Unverified there: this machine has no Edge to test with.

tests/mobile-layout.mjs holds the page to it at 430, 390 and 360 px: no
sideways scroll, nothing laid out past the right edge, the transmit
controls inside the screen, the rig picker within its cap — and the
collapsed filter bar still on screen with a button to bring the filters
back.

The SSTV panel test stamped its picture with a fixed date, which the
panel's own retention window dropped once that date was a day old.  It
uses a recent stamp now.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 19:06:15 +02:00
sjg 06971ff65c [style](trx-frontend-http): make the spectrum control strip one strip
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 8m28s
CI / frontend (push) Successful in 4m10s
CI / reuse (push) Successful in 3s
The row of controls under the plot held four different control heights,
units as loose text beside the field they belonged to, and a quarter of
its width as a hole in the middle.  Between about 1100 and 1400 px it
came apart: the bandwidth cluster wrapped to two lines while the level
cluster stayed on one, so the two sat at heights that matched neither
each other nor anything else on the page.

Every control stays, in its order, with its name and its behaviour.
This is the styling and the layout.

A field is now one box -- name, value and unit inside a single border --
so a number cannot be read apart from the unit it is in.  Fields,
buttons, the peak-hold select and the contrast slider are one height,
border-box so a button's own border cannot add two pixels to it, and
2.4rem under a coarse pointer where a fingertip needs the room.  The
contrast readout holds a fixed, tabular slot, so the row no longer
twitches between 1.0 and 0.9.

The container wraps and a cluster does not: a cluster that will not fit
drops whole to the next line and starts it left-aligned.  The slack
goes to a spacer rather than to `space-between`, which is what opened
the hole.

Two things this turned up.  The select carries `status-input` for other
layouts' sake, which drew a box inside the field's box.  And the narrow
-screen rules lived in a media query earlier in the file than the rules
they override -- identical specificity, so the later one won and the
phone layout had been overflowing sideways rather than stacking.  The
narrow rules now sit directly after what they override.

The layout test measures the strip at three widths: one height across
every control, no overflow, inside the plot, and clusters either
sharing a line or each having one -- never one floating against the
middle of the other.

docs/Spectrum-Controls-Rework.md records what was wrong and what was
deliberately left alone: the two different Autos, the settings that do
not persist, the one-shot buttons, and Sweet-spot's silence while it
retunes the SDR.  Those are behaviour, and are for another day.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 01:10:26 +02:00
sjg 18107ce07e [feat](trx-rs): receive SSTV pictures end to end
CI / lint (pull_request) Successful in 2m16s
CI / frontend (pull_request) Successful in 4m12s
CI / reuse (pull_request) Successful in 2s
CI / lint (push) Successful in 2m15s
CI / test (pull_request) Successful in 9m37s
CI / test (push) Successful in 7m36s
CI / frontend (push) Failing after 31s
CI / reuse (push) Successful in 3s
Wires the SSTV decoder into the stack, from the audio the server already
has to a panel in the browser that shows the picture arriving.

Server: a decoder task alongside the WEFAX one, running whenever the
decoder is enabled and the rig is in a mode SSTV is sent in.  A finished
picture is written to the cache as a PNG and sent on as a message; the
rows are sent as they decode, so a client can watch two minutes of
Martin M1 fill in rather than waiting for it.  Pictures join the decode
history, are replayed to a client that connects later, and survive a
restart.

Protocol: SetSstvDecodeEnabled and ResetSstvDecoder, a sstv_decode
_enabled flag in the rig state, two audio message types, and Sstv and
SstvProgress on DecodedMessage.  The history stores the message without
its base64 payload -- the picture is already on disk, and a megabyte per
entry is not what a history is for.

Client: pictures land in their own history, and the PNG the server sent
is written to the local cache so /sstv-images/ can serve it back.  That
endpoint and the WEFAX one now share their filename checks rather than
each carrying a copy: no separators, no parent references, .png only.

Web UI: an SSTV sub-tab beside WEFAX, with a live canvas the rows paint
into at the line number they carry, a card for the last picture, and a
filterable history with links to the files.  Rows below the one arriving
are grey rather than black -- not yet received is a different thing from
received as black.  A picture is not a spot, so neither pictures nor
their progress updates reach the decode statistics; that exclusion list
had grown by hand for LRPT and WEFAX and is now one named set.

The decoder crate gains what the server needed to hand a picture on:
to_png, to_png_base64 and save_png, with file names stamped in UTC so
they sort.

Panel behaviour is tested with the plugin runtime: rows painting at
their own line numbers rather than in arrival order, a completed picture
linked by file name alone with no server path in the page, a cut-off
picture reported as partial, clearing, and the toggle following the rig
state.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-06 00:14:59 +02:00
sjg a0b0c0ed81 [feat](trx-sstv): decode SSTV pictures
CI / test (pull_request) Successful in 7m40s
CI / lint (pull_request) Failing after 14m36s
CI / frontend (pull_request) Successful in 3m12s
CI / reuse (pull_request) Successful in 3s
CI / test (push) Successful in 7m32s
CI / frontend (push) Failing after 1m21s
CI / reuse (push) Successful in 2s
CI / lint (push) Successful in 2m16s
A new decoder crate covering the modes SSTV is actually sent in: Martin
M1/M2, Scottie S1/S2/DX, Robot 36/72, PD50 through PD290, and Wraase
SC2-180.  The mode comes from the VIS header every transmission opens
with, so nothing has to be told what is arriving.

Modes are a table rather than code: a list of segments -- sync, gaps,
and one scan per colour channel -- plus a colour model and a geometry.
The decoder reads the offset of each scan straight off that list, which
is what makes fifteen modes cost about as much as one, and a new mode a
table entry.  The segment lists are checked against the published line
durations in a test, because both are transcribed by hand from the same
specification and a digit wrong in one is unlikely to be wrong
identically in the other.

Signal path: band-pass over the SSTV band, Hilbert FIR, instantaneous
frequency by phase difference, then a state machine that walks the
transmission a line at a time.  Each line is looked for where the mode
says it should be and nudged into place by the sync pulse found near
it -- two sound cards never agree exactly, and over the two minutes of a
Martin M1 frame an uncorrected error of a few parts per million shears
the picture visibly.  Rows are emitted as they decode, so a picture can
be watched arriving, which is most of the appeal of the mode.

Four things this cost, each now the reason a piece of it is shaped the
way it is:

The per-sample frequency estimate ripples by ±95 Hz at 1200 Hz, where
the Hilbert approximation is weakest, though its mean is exact.  Pixels
average over their own window and were always right; the VIS bits and
the sync detector classify individual samples and were reading the
ripple.  Both now read short means.  Pixels deliberately still do not,
so edges stay where they are.

Broadband noise cost the whole picture, not part of it: a
phase-difference detector answers whatever is loudest, and there was no
input filter.  Hence the band-pass, which is what every real decoder
does first.

A sync search window shorter than a sync pulse rejected every pulse
arriving late in it, for being short.

The first line's sync search locked onto the VIS stop bit -- 30 ms at
exactly the sync frequency, immediately before the picture starts.  The
header already says where the picture begins, so the first line no
longer searches.

Tests: nine modes are encoded from a test card and decoded back,
compared pixel by pixel, alongside silence around the signal, a
transmission cut off part way, two transmissions back to back, 20 dB of
noise, and a transmitter clock 0.1% fast.  The encoder that produces
those signals reads the same table as the decoder, so a round trip
tests the decoder and not the timings; the timings are held to the
published line durations separately.

Nothing is wired into the server or the web UI yet: this is the decoder
alone.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-05 23:29:52 +02:00
sjg a2c630a92b [feat](trx-frontend-http): put the tuned frequency in the address bar
CI / frontend (pull_request) Successful in 4m3s
CI / reuse (pull_request) Successful in 2s
CI / lint (push) Successful in 2m16s
CI / lint (pull_request) Successful in 2m16s
CI / test (pull_request) Successful in 8m11s
CI / test (push) Successful in 7m20s
CI / frontend (push) Successful in 3m10s
CI / reuse (push) Successful in 2s
A receiver spreads by being linked to, and there was nothing to link to:
the routes carried the tab and nothing else, so "listen to this" could
only ever mean a screenshot and a frequency typed out in a message.

The query string now carries the dial -- rig, frequency, mode and
bandwidth -- in both directions.  Opening a link selects the rig, sets
the mode, tunes, then applies the bandwidth: a mode change brings its
own default bandwidth with it, so an explicit bw has to land after it.
Frequencies are read the way someone writes them by hand (7074k,
14.074M) and written back as whole Hz, so what comes out of the address
bar is the same link in canonical form.

After that the address bar keeps up with the dial, which is what makes
it copyable at any moment rather than only at load.  It is rewritten
with replaceState -- tuning is not navigation, and a swept dial would
otherwise bury the back button.  A link button in the top bar copies
the current link; it folds into the overflow menu when the bar is tight.

Applying a link changes the radio, so an rx session says so instead of
failing control calls one at a time.  A tab listening to a virtual
channel leaves the address alone rather than publishing a frequency the
rig is not on, and bw is skipped in both directions on rigs without
filter control, which would only refuse it.

The fixture pinned every state frame to 100 MHz plus jitter to keep
frames distinct, so no test could observe tuning at all.  The jitter
moves to the S-meter and the fixture echoes set_freq/set_mode/
set_bandwidth, as it already did for squelch.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-05 22:31:12 +02:00
sjg 09634eb851 [fix](trx-frontend-http): tidy up the map's filter bar
CI / lint (pull_request) Successful in 2m21s
CI / test (pull_request) Successful in 8m7s
CI / frontend (push) Successful in 2m57s
CI / reuse (push) Successful in 3s
CI / frontend (pull_request) Successful in 3m47s
CI / reuse (pull_request) Successful in 3s
CI / lint (push) Successful in 2m16s
CI / test (push) Successful in 7m19s
The bar explained itself in prose: "All bands visible by default" sat
between the chips and the next group, taking width the bar could not
spare and reading as a stray line of text. An "All" chip says the same
thing in a chip's width and gives the selection somewhere to be undone.

Band chips also came up dimmed at the very moment every band was on the
map -- an empty selection is no filter at all, so nothing is dimmed
until something is picked. The path toggles drop their "On"/"Off"
suffix, which cost most of a row and only repeated what their own
highlight already said; state moves to aria-pressed and the tooltip.

The rest is alignment. The rule dividing the buttons from the filters
is drawn on the button block's edge, and a centred block left it
floating as a stub beside a two-row bar; stacked, it lay down the left
of a block that sits underneath. The labels sat at their natural
widths, so each row's first control started somewhere different, and
the two pairs of phase buttons differed in width, so the groups after
them missed each other by four pixels. One gutter for every label, one
width for both pairs, and the search field moved last where it can take
the room the fixed-width groups leave.

The map layout test now covers the chips, the divider's height and the
rows' shared start.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-05 21:43:57 +02:00
sjg 90ab7781ad [fix](trx-frontend-http): stop the browser offering saved values for frequency
CI / lint (pull_request) Successful in 2m16s
CI / test (pull_request) Successful in 8m11s
CI / frontend (pull_request) Successful in 3m48s
CI / reuse (pull_request) Successful in 2s
CI / lint (push) Successful in 2m24s
CI / test (push) Successful in 7m23s
CI / frontend (push) Successful in 2m54s
CI / reuse (push) Successful in 3s
The tuned and centre frequency readouts are text inputs, so the browser
keeps what has been typed into them and offers it back in a dropdown --
Edge does this out of the box, dropping stale frequencies from other
sessions over the reading.

Turn autofill off on both, along with autocorrect and spellcheck, which
have no business near a number either.

Fixes #39

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-05 19:36:22 +02:00
sjg 88d04253ca [fix](trx-frontend-http): move the map's fullscreen and filter toggles into the bar
Fullscreen and Hide Filters floated in their own block over the map's
top-right corner, separate from the filter bar they sit beside.

Put them at the right-hand end of the bar, behind a separator. What made
this awkward before is that Hide Filters cannot live inside the thing it
hides, so the collapse now applies to the filters alone: the bar keeps its
two controls and shrinks to them at the map's right edge, leaving the whole
map visible and the way back one click away.

Fixes #38

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-05 19:34:09 +02:00
sjg 08005c5c07 [feat](trx-frontend-http): lay the map filters out as a bar across the top
CI / test (push) Successful in 8m6s
CI / frontend (push) Successful in 3m45s
CI / reuse (push) Successful in 3s
CI / lint (push) Successful in 2m15s
The filters were a 30rem column parked in the bottom-right corner, covering
a third of the map they filter. Lay them out horizontally instead: one row
per group -- label beside its control, thin rules between -- across the top
of the map, spanning ~87% of its width at 1600px and wrapping to a second
row as it narrows.

It starts clear of Leaflet's zoom buttons and stops short of the corner
controls, which stay outside it: the button that hides the filters cannot
live inside the thing it hides. The bottom-left band legend keeps its place.
The sentence explaining the two path toggles would have swallowed the bar,
so it moves to their tooltips and is shown inline only in the stacked
narrow-screen layout.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-05 07:54:21 +02:00
sjg 026f816ddb [fix](trx-frontend-http): replay stored decodes onto the map when it loads
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 8m12s
CI / frontend (push) Successful in 3m40s
CI / reuse (push) Successful in 2s
The map module is lazy: it arrives when the Map tab is first opened, which
is normally long after startup restored the decode history. Until then
aprsMapAddStation, aisMapAddVessel and vdesMapAddPoint are undefined, and
the decoders' `if (lat != null && ... && fn)` guards quietly dropped every
restored position. Nothing replayed them once the module did arrive, so the
map came up empty and filled in only from decodes heard afterwards -- a
station heard once was never plotted at all. A second reload appeared to
fix it because the cached module then loaded early enough to win the race
against the history fetch.

Give DecoderPlugin an optional syncMap(), implement it for APRS, AIS and
VDES over the history each already retains, and have map-core call
trxPluginRuntime.syncMapAll() as it attaches. The add functions are keyed
by callsign, MMSI and point, so replaying updates in place and cannot
duplicate a marker; the replay runs oldest-first so tracks are rebuilt in
the order they happened.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-05 07:34:45 +02:00
sjg d31b6f545f [test](trx-frontend-http): watch the history progress from inside the page
CI / lint (push) Successful in 2m16s
CI / test (push) Successful in 8m18s
CI / frontend (push) Successful in 3m38s
CI / reuse (push) Successful in 2s
The replay-progress check polled the overlay from the test every 100ms.
A replay that starts and finishes between two polls is never sampled, and
the test then reports that no progress was shown at all -- the source of
the intermittent "no progress was shown while the history loaded" failure.

Record the samples from a MutationObserver installed before the page's own
scripts run, so a fast replay is observed rather than missed.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-05 07:10:57 +02:00
sjg 39f551c914 [fix](trx-frontend-http): hold the APRS symbol column open for frames without one
renderLocalAprsSymbol() returns nothing when a packet carries no symbol
table or code, so those rows lost the icon's 24px slot and every column
after it -- callsign, type badge, summary -- slid left against the rows
around them. Frames that do carry a symbol then read as indented.

Render an empty slot of the same size instead, so a list mixing position
reports with messages and telemetry still lines up.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-05 07:10:33 +02:00
sjg 6d25ecdc11 [feat](trx-frontend-http): give the AIS list the same log shape
CI / lint (push) Successful in 2m15s
CI / test (push) Successful in 8m8s
CI / frontend (push) Successful in 3m41s
CI / reuse (push) Successful in 2s
A message was three stacked lines — time and name, then MMSI and route,
then motion, distance, position and age — so a screen held eight of
them.  It is one line now: time, vessel, message type, and what the
message says, opening in place for the MMSI, the channel frequency, the
route, the age, the fix and a jump to the map.  Twenty-two fit where
eight did.

What a message says depends on what it is.  Position reports give the
fix and the motion; the static and voyage reports that carry no fix give
the callsign and where the vessel is bound.  Both fall back to whatever
fields are present rather than showing nothing.

The row vocabulary the APRS list introduced is no longer APRS-specific —
the classes are decode-line and decode-expanded now, shared by both, and
identity sits in fixed columns so the summaries line up down the list
instead of starting wherever the callsign happens to end.  The three
summary cards above the list go the way of the APRS ones.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-04 23:24:09 +02:00
sjg 37987b2779 [feat](trx-frontend-http): make the APRS list a log, and read the payloads
CI / lint (push) Successful in 2m24s
CI / test (push) Successful in 8m12s
CI / frontend (push) Successful in 3m41s
CI / reuse (push) Successful in 2s
A frame was a card five lines tall — timestamp, a meta line, the
information field as it arrived on the air, three buttons, and a Details
panel repeating the four things already on the row — so five frames
filled the panel and the payload was left to be decoded by eye.

A frame is one line now: time, station, type, and what the frame says.
It opens in place for the path, the CRC, the raw field, its bytes and
the actions.  Twenty-one frames fit where five did.

And the information field is read rather than echoed.  Weather reports
give temperature, wind, humidity and pressure; telemetry gives its
sequence and channels; a message gives its addressee and text; a
position gives the fix, course and speed, and the comment the station
wrote.  Anything that cannot be summarised falls back to the raw field,
which is in the expanded view either way.

HF APRS had a copy of the same forty lines of markup, differing by one
badge, so both now build their rows from one function in the shared
module — the CSS is shared between them and this would have broken it
otherwise.  Both headers lose their three summary cards for a line of
counts beside the filters, which frees another fifth of the panel.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-04 23:12:02 +02:00
sjg 67a7bace4e [fix](trx-frontend-http): let the decode lists fill their panel
CI / test (push) Successful in 8m16s
CI / lint (push) Successful in 2m18s
CI / frontend (push) Successful in 3m40s
CI / reuse (push) Successful in 3s
FT8, FT4, FT2 and WSPR size their list against the panel with flex, and
the sidebar layout made the panel a grid item aligned to the start of
its row — sized to its own content.  The lists collapsed to their 120px
minimum with several hundred pixels of the page empty underneath.  The
panel stretches to the row now and the sidebar keeps its own height.

The marine lists were sized a different way, by formula: 100vh minus a
guess at everything above them.  That guess stopped matching the moment
the panel changed shape, so they left a few hundred pixels unused as
well.  They fill the panel like the rest now, and so does CW, which had
a 360px ceiling.

HF APRS had no container styling at all — no scroller, no frame, no
height — so its packets ran down the page.  It gets what the other
packet lists have.

The smoke test measures each list against its panel and requires it to
scroll on its own.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-04 22:49:28 +02:00
sjg b48cc23d6e [fix](trx-frontend-http): keep the rig names through the state stream
CI / lint (push) Successful in 2m19s
CI / test (push) Successful in 8m14s
CI / frontend (push) Successful in 3m47s
CI / reuse (push) Successful in 3s
The picker and the header showed each rig's lowercase id instead of its
configured name.  applyRigList takes the names as a parameter defaulted
to an empty map, and the state-update path passes only the rig ids —
names come from /rigs, not from a state frame — so that call landed on
the default and the body, which treats "an object" as "here are the
names", cleared them.  One frame after load the names were gone for the
rest of the session.  Omitted now means no news rather than no names.

The fixture is why this was invisible: it pushed an identical status
payload every tick and the client skips a frame equal to the last, so
render never ran and neither did the call that did the damage.  Its
event stream varies between frames now, as a real one does.

Which immediately caught a second fault: state frames arrive
continuously, and one sent before the server applied a new squelch
threshold snapped the line back to where it had just been dragged from.
A local change outranks the echo for two seconds, the same idea as the
optimistic frequency guard beside it.  The fixture also records what
/set_sdr_squelch sets and reports it back afterwards — the drag test had
been passing against a server that ignored the write.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-04 22:38:21 +02:00
sjg c1899229a0 [fix](trx-frontend-http): stop the decode history replay giving up at 20s
CI / lint (push) Successful in 2m19s
CI / test (push) Successful in 8m15s
CI / frontend (push) Successful in 3m37s
CI / reuse (push) Successful in 3s
Reloading a second time sometimes showed history the first load did not,
and the safety valve is why: it called one function that both released
the buffered live decodes and tore the history worker down, so any load
where the replay had not finished inside twenty seconds — a large
backlog, a cold cache, a slow link — dropped whatever had not arrived,
without a word.  A reload got another go at it, and the second one is
faster because everything is cached by then.

Those are two separate things now.  At the timeout the live decodes are
released so the panels are not held back, the replay carries on, and the
progress says so.  The fallback's error path retries once and then says
"Decode history unavailable" rather than leaving the operator to guess
whether there was anything to see.

The progress is no longer a scrim.  It was fixed to the whole viewport
with a wash over the page — the waterfall, the decode panels, all of it —
for the length of the replay, which is exactly when there is something
worth watching.  It is a corner card with a bar: indeterminate while the
payload is on the wire, then filling as N of M messages replay.

None of this was reachable from a test.  /decode/history answers in CBOR
and the worker reads the body as CBOR unconditionally, but the fixture
served JSON, so every browser run had been exercising the client's retry
path and never its history path.  It encodes CBOR now, including the
64-bit form the millisecond timestamps need, and decode-flow serves 1200
records and holds the client to restoring all of them on the first load,
showing progress while it does, and never covering the page with it.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-04 22:14:13 +02:00
sjg 84a99a3636 [fix](trx-frontend-http): load the decoders that own the digital modes panels
AIS, VDES and both APRS decoders were listed under the map plugin group
alone, so opening Digital modes and clicking AIS or APRS gave an empty
panel reading "Connected, listening for packets" while the decodes piled
up unprocessed in the plugin runtime.  They appeared only if something
had opened the Map tab first, which flushed the queue.  There is also a
map-data group naming exactly those four that nothing loads: the loader
is called with tab names and no tab is called map-data.

They load with the tab whose panels they fill now.  map-core stays lazy,
since their calls into it are optional and the Map tab can go on paying
for Leaflet by itself.

tests/decode-flow.mjs follows a decode from the wire to the map: an AIS
vessel and an APRS beacon arrive on /decode, and it asserts both panels
fill with the map module confirmed absent, the mini view names the
vessel and offers a pin, following that pin lands on /map centred on the
vessel, and both decoders leave a marker.  Nothing exercised any of this
before — the fixture served an empty decode stream, which is how the map
links came to be broken for every decoder at once.

The fixture stamps decodes as it sends them, since the client prunes
anything outside the retention window, and repeats them, since the views
collapse by vessel and need more than one frame to behave.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-04 21:31:30 +02:00
sjg 84bdf2593c [fix](trx-frontend-http): measure whether the tab bar fits, and watch for it
CI / lint (push) Successful in 2m20s
CI / test (push) Successful in 8m25s
CI / frontend (push) Successful in 3m36s
CI / reuse (push) Successful in 3s
CI put the tab strip 9px into the controls at 1440px with no scaling at
all, on a bar that had every degradation step available to it and used
none of them.  It used none because nothing thought anything was wrong:
the fit test was an arithmetic estimate — identity + nav.scrollWidth +
actions.scrollWidth + a 48px allowance for the gaps — and on a platform
whose fonts run wider than the one it was written on, that allowance no
longer covered what it stands for.  An estimate that says "fits" stops
the ladder before its first rung.

It reads the geometry now: the controls have to stay inside the bar, and
no tab may reach them.  That is the same measurement the test makes, so
the two cannot disagree about any platform's metrics.  The tabs are the
subject rather than the nav's box because the nav shrinks below its
content — the box gets smaller while the tabs keep their width and slide
underneath the controls.

A second fault turned up while probing this: the strip only reflowed on
window resize.  The rig name arriving from the server, the style picker
filling in, a font swapping in wider metrics — each changes what fits
without touching the window, and the bar sat there as it was through all
of them.  A ResizeObserver on the bar and the controls covers those, and
document.fonts.ready covers the swap.

The guard sweeps text scales and adds a station name too long for the
bar, but it should be said plainly: it passes against the old code too.
Nothing here reproduces on this machine — a 4px viewport sweep from 1080
to 1500, three wide font stacks and scales from 1.0 to 3.0 all failed to
make the old estimate lie.  What is fixed is the mechanism that could.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-04 20:32:38 +02:00
sjg c527f20a88 [feat](trx-frontend-http): give digital modes a decoder sidebar
CI / lint (push) Successful in 2m18s
CI / test (push) Successful in 8m15s
CI / frontend (push) Failing after 32s
CI / reuse (push) Successful in 3s
Thirteen decoders in a horizontal strip needed a scroller on anything
but a wide window, and the open one was marked by a single underline
among thirteen.  They are a list down the left now, all visible at once,
each keeping the state dot it already carried, with the panel for the
selected one filling the rest of the width.

No script changed: the sub-tab wiring, the aria roles, the decoder
picker and the state-dot observers all work on the same markup, so this
is layout only.

Below 760px the sidebar gives way to the picker that already existed
there.  That path needed align-content: the tab panel fills the page
height and a grid stretches its rows to match, which handed the picker a
218px row and left a 189px gap under it.

The tab icon was the signal-strength bars, which is what the S-meter
shows two rows above it; a pulse train says digital modes instead.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-04 08:01:22 +02:00
sjg 9f495021f0 [style](trx-frontend-http): name and fence the three audio groups
CI / lint (push) Successful in 2m19s
CI / test (push) Successful in 8m23s
CI / frontend (push) Successful in 3m18s
CI / reuse (push) Successful in 3s
The row carries three unrelated things — how loud it is, whether there
is any audio at all, and how much is arriving — and only the middle one
was named.  Each is a group now: VOLUME over the two sliders, SQL on its
own switch, LEVEL over the meter, with a hairline between each.

The rules are drawn only while the row is one line, measured against the
row rather than the viewport: what fits depends on whether the rig
transmits and whether it has a squelch at all.  A rule divides what sits
either side of it, so once a group wraps the wrap is the division and
the rule would just be a mark at the start of a line — which is what it
was at 900px before this.  The labels carry the grouping on their own
below that width, and the groups stack whole on a phone.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-04 07:46:56 +02:00
sjg 33aa7b807c [style](trx-frontend-http): fence the squelch off from the volume controls
CI / lint (push) Successful in 2m18s
CI / test (push) Successful in 8m18s
CI / frontend (push) Failing after 31s
CI / reuse (push) Successful in 3s
The squelch sat in the audio row on the same gap as everything else, so
it read as a continuation of the volume sliders.  It decides whether
there is audio at all, which is not the same kind of control as how loud
it is, and a hairline says so.

The rule belongs to the squelch block, so it leaves with it on a rig
that has none, and it stands down where the row stacks: there the line
break separates them already and a leading rule would just start a line.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-04 07:36:53 +02:00
sjg 2c56d82a81 [feat](trx-frontend-http): make the SQL label the squelch switch
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 8m13s
CI / frontend (push) Failing after 30s
CI / reuse (push) Successful in 3s
Clicking SQL turns the squelch on and off.  The label and the button
beside it said the same thing twice — one naming the control, the other
reading "On" or "Off" — where the name itself is the obvious target, and
the dot already carries the state: grey when off, green while the gate
passes, amber while it holds.

The pressed state is on the label, so the switch reads the same to a
screen reader as it looks.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 23:41:52 +02:00
sjg 0fc2115973 [fix](trx-frontend-http): make map links work before the map has loaded
The AIS and APRS mini views link each position to the map, and neither
did anything: the map module installs itself lazily, and it was the one
defining window.navigateToAprsMap, so until something had opened the Map
tab the global did not exist.  AIS calls it inline from onclick and
threw "not a function"; APRS guards the call and so failed silently.
The grid links on FT8, FT4, FT2 and WSPR rows went the same way through
navigateToMapLocator.

The app owns both globals now, installed at startup.  They record the
target, switch tabs through navigateToTab — the only path that
materialises the panel from its template, loads the module and updates
the history entry, none of which the module's own hand-rolled tab switch
did — and the target is applied once the module reports ready.

The module keeps the focusing, which is its job, and exposes it as
focusMapPosition and focusMapLocator.

The smoke test now calls the link from a cold page, asserting the map
module is not loaded first so the check cannot pass by accident.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 23:41:09 +02:00
sjg 2c1df75d19 [fix](trx-frontend-http): measure auto squelch from the meter
CI / frontend (push) Successful in 3m16s
CI / reuse (push) Successful in 2s
CI / lint (push) Successful in 2m18s
CI / test (push) Successful in 8m14s
Auto took the spectrum's noise floor and added 6 dB, but the threshold
is compared against the channel level the meter reports, and the two sit
a long way apart: the gap is set by the FFT size and window, the channel
bandwidth, the decimation, and peak-versus-mean statistics.  Measured on
white noise it runs +22.1 dB at 48k/8k/3k, +18.7 dB at 240k/24k/12k and
-1.2 dB at 1.92M/24k/12k — a 23 dB swing across ordinary configurations.
Only the last of those is anywhere near right, so on a narrow span Auto
set the gate some 20 dB below the noise and it never closed.

It now reads the same number the DSP compares: the 20th percentile of
the meter over the last ten seconds, plus 5 dB.  The percentile keeps a
burst of traffic inside the window from dragging the estimate up, and
5 dB clears the meter's own jitter, which measured 0.9-1.6 dB.  Nothing
in it converts between scales, so no part of the signal chain can put it
out again.  With no history yet — a fresh connection, a rig switch — it
listens for a moment rather than refusing.

The fixture gained a streaming /meter, without which there is nothing to
measure, and the spectrum test pins auto to the meter it serves.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 23:32:18 +02:00
sjg aefd36c4b1 [feat](trx-frontend-http): set the squelch on the spectrum, in dB
CI / lint (push) Successful in 2m19s
CI / test (push) Successful in 8m41s
CI / frontend (push) Failing after 31s
CI / reuse (push) Successful in 2s
The threshold is in dB, and since the squelch fix that is the scale the
spectrum axis and the S-meter are labelled in — so the control belongs
on the plot, at the level it gates.  A dashed line spans the spectrum at
its threshold with a grip that reads it out, dragged like the bandwidth
edges, green while the signal is above it and amber while it gates.
Arrow keys move it a dB at a time for anyone not using a mouse.

The audio row keeps a compact version: the dB, an indicator lit from the
same meter the DSP compares against, Auto, and an enable toggle that no
longer doubles as the level.  The slider ran 0-100% over that dB range,
which gave the operator a number with nothing on screen to relate it to,
and zero meant "disabled", so turning the squelch off to listen threw
the threshold away.  Auto now says which level it picked.

Two things the browser could only show once it was on the plot: the grip
landed underneath the split control at the right edge, which swallowed
its pointer, and dragging to the foot of the axis hid the line — and the
grip with it — instead of pinning it where it could be dragged back.

The fixture could not exercise any of this: /audio answered 404, which
hides the audio row and the control inside it, and the status carried no
filter block, which is what tells the client the rig has a squelch at
all.  Both now look like an SDR, and the spectrum test drives the line.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 23:20:19 +02:00
sjg 25b9c31c9b [fix](trx-backend-soapysdr): squelch against the meter, not the post-AGC level
The threshold was compared against the block level measured after the IQ
AGC.  Holding that level at a setpoint is the AGC's entire purpose, so
for every mode that has one — FM, PKT, AIS, AM, SAM, which is to say the
modes anyone squelches — the comparison was against a near-constant.
With FM's 12 dB of gain a weak signal reads some 12 dB hotter than it
is, and the value never had the decimation correction the meter applies
on top of that: around 20 dB adrift at 48k/8k, more as decimation grows.

The threshold arrives in the other scale entirely.  The slider maps its
percentage onto -120..-30 dB and Auto takes the spectrum noise floor
plus 6, both of which are what the meter and the spectrum display show.
So a gate set just above the noise sat open on it.

It now reads last_signal_db, which is already computed each block before
the AGC and corrected for decimation — the same number the meter shows.
The post-AGC measurement had no other consumer.

The test feeds one signal twice and takes the threshold from the
channel's own meter: 6 dB above must gate it, 6 dB below must pass it.
Nothing there depends on the absolute scale, only on the two agreeing.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 23:03:46 +02:00
sjg d68a84f7f9 [chore](trx-client): apply cargo fmt
CI / lint (push) Successful in 2m16s
CI / test (push) Successful in 7m33s
CI / frontend (push) Successful in 3m18s
CI / reuse (push) Successful in 3s
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 22:57:33 +02:00
sjg 4fa191e9b6 [fix](trx-frontend-http): serve the band plan to every session
CI / lint (push) Failing after 1s
CI / test (push) Successful in 8m20s
CI / frontend (push) Failing after 31s
CI / reuse (push) Successful in 3s
/bandplan.json needed the control role.  Route access is decided by
suffix for static assets — .js, .css, .png and so on — and ".json" is
not among them, so the band plan matched nothing and fell through to the
catch-all.  It is compiled into the binary and identical for every user,
so it is public now, like the rest of them.

Two things followed from that.  Read-only sessions never saw a band plan
at all.  And since the page asks for it during startup, the request can
land before the session is established: that 401 was swallowed by an
empty catch and never retried, which is why the allocations sometimes
only appeared after a manual reload.

So the client no longer hides the failure, retries once the auth gate
clears — which is exactly when a startup 401 becomes fixable — and
schedules a draw when the data lands, since the strip is painted from
the spectrum draw and a rig sitting between frames would stay blank.

The fixture can now refuse the first request the way the server did, and
the spectrum layout test holds the client to recovering from it.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 22:50:49 +02:00
sjg c073d03ffb [feat](trx-frontend-http): reorder the controls tray sections
CI / lint (push) Successful in 2m23s
CI / frontend (push) Failing after 31s
CI / reuse (push) Successful in 3s
CI / test (push) Successful in 8m14s
The radio's own settings now come first, then audio, then the scheduler:
Advanced radio controls, Audio controls, Scheduler controls.

The advanced section is not in the markup — ui-core builds it at runtime
and gathers the SDR settings, virtual channel and TX limit rows into it,
appending the result, which put it last however the markup was ordered.
It is inserted ahead of the audio section instead.

The signal readout and the TX meters stay where they are, between the
controls and the sections: they are readouts rather than a section, and
on an SDR the spectrum covers them anyway.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 22:41:08 +02:00
sjg 730f129404 [fix](trx-frontend-http): let the header identity give way before the tabs
CI still put the tab strip into the controls, now at 1100px — the
narrowest bar in the app, since the bookmark gutters take 9.5rem a side
above that width and leave 756px against 871px at 900px.  With the
controls already in the overflow menu and the tabs already down to
icons, nothing else could give, and what gives by default is the strip:
it is the one item allowed to shrink below its content, so its tabs keep
full width and slide under the controls, out of reach.

The identity block takes the squeeze instead, ellipsised.  A clipped
station name is still readable; a destination hidden underneath the
controls is not.

The guard that was supposed to catch this scaled only the tabs and the
controls, not the title and subtitles — which is exactly what runs out
of room — and skipped 900px.  It now scales every piece of text in the
bar and checks all four widths.  Measured across text scales from 1.0 to
3.0 at each width, the bar keeps its 16px allowance everywhere; before
this, 1.6 and above overlapped at 1100px.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 22:40:36 +02:00
sjg f95f3d0104 [feat](trx-frontend-http): centre the radio controls, split off the mode row
CI / lint (push) Successful in 2m19s
CI / test (push) Successful in 8m13s
CI / frontend (push) Failing after 32s
CI / reuse (push) Successful in 3s
The controls every rig has — mode, wheel, tune step, transmit — now sit
as a centred block rather than packed against the left edge.

What the current mode adds moves out from among them: WFM's six controls
stretched the row sideways whenever it was active, pushing the wheel and
the step pickers off centre, and SAM did the same on a smaller scale.
They get a row of their own below a divider, which appears and leaves
with them — an empty one would still take a track and a gap in the tray
and draw its divider under controls it has nothing to do with.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 22:29:31 +02:00
sjg e70e82c8c0 [feat](trx-frontend-http): rebuild the general radio controls row
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 8m8s
CI / frontend (push) Failing after 36s
CI / reuse (push) Successful in 4s
Mode was a full-width select: 483px of the row to display "FM".  The
modes are three or four characters and there are at most twelve, so they
become a segmented group like the Unit and Step Scale pickers beside
them — a third of the width, and one click instead of two.

The <select> stays as the mode's value.  A dozen call sites and several
plugins read #mode.value, so replacing it outright would have reached
much further than a layout change should; it is hidden from sight and
from assistive tech, the buttons write to it, and everything downstream
runs unchanged.  Every writer re-syncs the buttons, the plugins through
a new trxCore.syncModePicker.

The row itself was a grid with a track per column, but the WFM, SAM and
transmit columns are hidden on most rigs, so it ended in some 500px of
hole.  It packs left now.  Same fault one level down: the power buttons
sat in three fixed tracks, so a rig with neither transmit nor lock kept
two empty ones and left its label chip stranded at the far edge.

Unit and Step Scale move out of the frequency row and in beside the
wheel and the +/- they modify, which were some 600px away.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 22:09:08 +02:00
sjg 23cc0db1fa [fix](trx-frontend-http): drop the tabs to icons when the bar runs out of room
CI / test (push) Successful in 8m15s
CI / frontend (push) Failing after 31s
CI / reuse (push) Successful in 2s
CI / lint (push) Successful in 2m17s
CI put the tab strip 9px into the controls at 1440px on a run that
passed locally: its system font is wider, and the bar had no move left
to make.  Controls are moved into the overflow menu until the bar fits,
but once all of them were in the menu nothing else gave — the nav may
shrink below its content, so the tabs kept full width and ran under the
controls, leaving the destinations nearest them unclickable.  Labels
dropping to icons was the other half of the answer, but it hung off a
max-width:1360px media query and so was unavailable at 1440px.

That class now goes on by measurement, as the last step after the menu
is exhausted, which is the same reasoning the controls' own fit test
already uses: how much fits depends on the rig name and on how wide the
platform draws the labels, not on the viewport.  The class is cleared
before measuring so the decision cannot ratchet, and icon widths are
fixed, so it always buys back the labels' width.

Labels now stay put between 1100px and 1360px while they fit, with the
style picker and theme toggle behind the overflow menu instead.

The suite could not have caught this: it passed on the fonts of the
machine that wrote it.  The layout section now repeats its fit check
with the bar's text scaled up, which reproduces a wider system font
anywhere — with this fix reverted it fails on macOS too.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 21:36:55 +02:00
sjg 657f952a2c [fix](trx-frontend-http): hold the strips' place above the spectrum
Tuning across a band edge moved the whole page under the cursor: the
band plan strip is in flow, so a range with no allocations collapsed it
from 18px to nothing and dragged every element below it up (measured at
1600x950: overview top 118 to 100, footer 1026 to 1008).  It now keeps
its height whenever a band plan could be drawn at all, and only gives it
back when the feature is off, has no data, or there is no spectrum.

The bookmark rail gets the same treatment for consistency, though it
never moved anything — it is absolutely positioned over the top of the
overview.  It stays up and blank rather than vanishing.

Which exposes something the rail was already doing wrong: it covers the
top of the plot, and a bare div still takes pointer events, so whenever
bookmarks were in range that band of the overview could not be dragged
or scrolled.  Only the chips are targets now.

tests/spectrum-layout.mjs covers this: it streams spectrum frames, tunes
between a band with bookmarks and allocations and one with neither, and
asserts nothing moves and that the rail lets clicks through.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 21:26:19 +02:00
sjg 1f256cbb68 [refactor](trx-frontend-http): extract the browser test fixture
browser-smoke.mjs carried its static server inline, which made it the
only browser test that could exist: a second one would have had to copy
180 lines of routes to change a single capability flag.  The server
moves to tests/web-fixture.mjs behind startWebFixture(), with the rig's
spectrum support, bookmarks and band plan as options.

Serving a rig with a spectrum matters because that is where the layout
actually lives — the panel, the strips above it and the waterfall are
all gated on filter_controls, and the existing fixture reports a
CAT-only rig, so none of it has ever been rendered under test.

No change to what the smoke test checks.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 21:26:06 +02:00
sjg 92fbdb692c [feat](trx-frontend-http): lay the scheduler controls out in one row
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 8m12s
CI / frontend (push) Failing after 29s
CI / reuse (push) Successful in 3s
The controls were a column — release, then the step buttons, then the
status line, then the entry on air last — which read bottom-up and left
the entry that is actually transmitting furthest from the buttons that
change it.  They now run left to right: step through the entries, hand
the rig back, then the current entry behind a separator.

The separator is a pseudo-element on the current-entry block rather than
an element of its own, because that block is display-toggled whenever
fewer than two entries are active; a standalone rule would be left
hanging with nothing after it.

No ids move, so the enable/disable logic in the scheduler plugin and the
release polling in vchan bind exactly as before.  The smoke test asserts
the row's order, which is also what keeps the separator in place.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 20:58:31 +02:00
sjg b2fbcb318d [fix](trx-frontend-http): stop Tools lighting up on every refresh
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 8m21s
CI / frontend (push) Failing after 30s
CI / reuse (push) Successful in 3s
navigateToTab marked the Tools button by asking whether the destination
tab was displayed, which is the right question at the wrong moment: the
first route navigation runs while the card is still behind the loading
state, where every tab computes to display:none.  Refreshing or deep
linking to any page therefore lit Tools alongside the real destination,
and nothing re-evaluated it once the page appeared.

Membership of the Tools menu answers the same question without needing
anything laid out, and still reads the grouping ui-core installs rather
than a second copy of it.

The smoke fixture now serves the SPA shell for route paths the way the
server's per-tab index handlers do, so a deep link no longer 404s and
the case is testable at all; two of them are asserted.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 20:51:04 +02:00
sjg 44721b579c [fix](trx-frontend-http): fill the map column down to the footer
The windowed map was capped at 75% of the viewport height and at a
width-derived aspect ratio, which left a dead band under it: 69px at
1600x950, and on a 420px-wide phone a 270px map on an 800px screen.
Neither cap was doing useful work now that the stage spans the full
width, so the map fills the column down to the footer instead.

Growing into the footer needs a bound: once the column is tall enough to
push the footer below the fold, using its position would push it further
on every pass, so the bottom edge is clamped to the viewport.  Growth
then consumes the column's spare height and settles in one pass.

Also drops three mapIsFullscreen() branches in the windowed path that
could never be taken — the fullscreen case returns above them.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 20:50:48 +02:00
sjg 889d00007d [feat](trx-frontend-http): box the selected tab instead of underlining it
CI / lint (push) Successful in 2m23s
CI / test (push) Successful in 8m19s
CI / frontend (push) Successful in 3m10s
CI / reuse (push) Successful in 3s
The desktop strip marked the current page with a 2px underline while the
mobile bottom nav already boxed it, so one navigation model looked like
two.  The box now sits on both: a transparent 1px border on the base
reserves it, so switching pages moves no neighbours, and hover fills a
fainter version of the same shape.  Tools carries it too — that button
is marked active for the destinations the strip hides.

Dropping the mobile rule's border-bottom:none, which only existed to
cancel the old desktop underline, closes the bottom edge its active box
had been missing.  The smoke test checks all four edges.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 20:37:31 +02:00
sjg 6f53592041 [feat](trx-frontend-http): rework the page footer
The footer floated in space below the content with no rule to close the
page, its two clusters sat on a text baseline that left the source pill
hanging, and the status hint was a plain line of text a size larger than
the attribution beside it.

Now a hairline closes the page the way .tab-bar opens it, the clusters
centre on one line, and the attribution drops the opacity it stacked on
top of --text-muted, which had put it below a readable contrast ratio.

The status hint becomes a pill with a state dot: green when ready, amber
while a command is in flight, red on connection loss.  The colour comes
from a data-state attribute, so every hint now goes through setPowerHint
instead of assigning textContent directly.  --status-ok carries the
indicator green; .about-status-on picks it up too, which darkens it on
light themes where the old value was barely legible.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 20:37:12 +02:00
sjg 709939f60b [feat](trx-frontend-http): span the map across the full viewport width
The map stage broke out of the centred .card column: negative inline
margins cancel the card's centring offset and its side padding, so the
stage reaches both viewport edges at every width without hardcoding
either value.  Its rounded corners and left/right borders go with it —
edge to edge, the panel reads as a band rather than a floating card.

The browser smoke test now measures the stage against the viewport, and
checks that the full-bleed width does not push the page sideways.

Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 20:36:50 +02:00
sjgandClaude Opus 5 5b7dd493d4 [feat](trx-frontend-http): draw APRS symbols from the sprite sheets
CI / lint (pull_request) Successful in 2m16s
CI / test (pull_request) Successful in 8m12s
CI / frontend (pull_request) Successful in 3m2s
CI / reuse (pull_request) Successful in 3s
CI / lint (push) Successful in 2m24s
CI / test (push) Successful in 7m28s
CI / frontend (push) Successful in 2m11s
CI / reuse (push) Successful in 3s
Resolve a table/code pair to a sprite cell in aprs-shared, and use it
from both the packet lists and the map markers, which had each been
printing the raw symbol character in a bordered box.

A table identifier of / or \ selects the primary or alternate sheet
directly.  Anything else is an overlay character, which the APRS spec
draws on top of the alternate symbol -- so those stack the overlay sheet
over the alternate one rather than picking a sheet.  Codes outside
0x21..0x7E have no cell and keep the old character box.

The sheet URLs stay in the stylesheet so a min-resolution query can swap
in the retina sheets; only the cell offset is computed and set inline.
Map markers share the helper through the plugin chunk, so the map stays
free of any remote symbol fetch.

Verified in a browser against the real stylesheet and sheets: /> is a
car, /_ a WX circle, /& an igate diamond, \n a red triangle, and the
overlays S> and 7# carry their character on the alternate symbol.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018huL1ELyr86yVqfAabtioA
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 19:55:50 +02:00
sjgandClaude Opus 5 02fe492dbf [feat](trx-frontend-http): serve the vendored APRS symbol sprites
Embed the six sheets alongside the other vendored assets and serve them
under /vendor with the same immutable cache headers.

The browser computes a symbol's cell from a 16x6 grid of 24px cells, so
a re-vendored sheet at any other size would shift every station onto a
neighbouring icon -- wrong on every packet, and invisible unless you
know which glyph to expect.  Pin the geometry by parsing each embedded
PNG's IHDR in a test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018huL1ELyr86yVqfAabtioA
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 19:55:50 +02:00
sjgandClaude Opus 5 1bc2c88e2f [chore](trx-rs): vendor the APRS symbol sprite sheets
The web UI had no symbol graphics at all, so a position report rendered
its raw symbol character in a bordered box.  Vendor rev H of the
hessu/aprs-symbols set: three 24px sheets (primary, alternate, and the
overlay characters) plus their retina variants.

The set carries no single license.  Individual symbols are variously
vectorizations of the original WA8LMF bitmaps with unknown terms, new
CC BY-SA work by OH7LZB, public-domain or CC sources, and a handful of
brand logos owned by their companies.  Record that as
LicenseRef-APRS-Symbols with the upstream per-symbol catalogue copied
verbatim, and carry the attribution pointer upstream asks for.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018huL1ELyr86yVqfAabtioA
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 19:36:27 +02:00
sjgandClaude Opus 5 863a6d8fd4 [fix](trx-frontend-http): restore decode history from the stored records
CI / lint (pull_request) Successful in 2m21s
CI / test (pull_request) Successful in 8m19s
CI / frontend (pull_request) Successful in 3m1s
CI / reuse (pull_request) Successful in 2s
CI / lint (push) Successful in 2m16s
CI / test (push) Successful in 7m26s
CI / frontend (push) Successful in 2m11s
CI / reuse (push) Successful in 2s
Replay required every restored record to carry a string `type`, and
stored records do not have one: an AIS entry holds mmsi, lat, lon,
crc_ok and its decoder's own fields, nothing more.  The filter therefore
discarded all of them, and did it silently — the fetch returned its full
payload, the worker decoded it, and no error was logged, so the history
simply never appeared.

That field identifies live SSE frames, which do carry it, which is why
only replay was affected.  History arrives already grouped and the
group's kind is delivered alongside the messages, so `type` was never
needed to route them.  Require only that a record is an object.

Confirmed against a live server: the first restored group is AIS, and
its records expose their decoder fields with `type` undefined.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 18:39:13 +02:00
sjgandClaude Opus 5 b252717f6b [test](trx-frontend-http): serve a realistic decoder registry to the smoke test
CI / lint (pull_request) Successful in 2m18s
CI / test (pull_request) Successful in 7m25s
CI / frontend (pull_request) Successful in 2m10s
CI / reuse (pull_request) Successful in 3s
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 7m26s
CI / frontend (push) Successful in 2m12s
CI / reuse (push) Successful in 3s
The fixture answered /decoders with an empty list, which hid most of the
application from the only test that runs it in a browser.  The decoder
sub-tabs, their panels, the decode toggles and the bookmark decoder
checkboxes are all built from that registry, so the run exercised three
of thirteen sub-tabs and none of the decoder UI.  Finding this needed
route interception, because nothing in the suite could see it.

Serve eleven decoders covering the modes the real registry spans.  The
run now builds 13 sub-tabs and 11 bookmark decoder checkboxes — the same
checkboxes whose construction a recent fix changed without any test
reaching them — and still reports no runtime errors.

It also makes an existing fault observable: at 1100px the decoder
sub-tab bar hides 195px of itself with no scrollbar or fade, the same
silent truncation the top strip had.  No assertion for it here, since
that would fail until the truncation is fixed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 17:46:52 +02:00
sjgandClaude Opus 5 92697b11c5 [feat](trx-frontend-http): mark Tools active for its destinations
CI / test (pull_request) Successful in 8m9s
CI / test (push) Successful in 7m22s
CI / lint (pull_request) Successful in 2m15s
CI / frontend (pull_request) Successful in 3m1s
CI / reuse (pull_request) Successful in 2s
CI / lint (push) Successful in 2m16s
CI / frontend (push) Successful in 2m10s
CI / reuse (push) Successful in 2s
Grouping Statistics, Recorder, Settings and About behind Tools left the
tab strip looking identical on all four: the destination's own button
carries the active class, but the strip hides that button, so nothing
was marked.  The page titles named the page without saying how you got
there.

Mark the Tools button when the active destination is one the strip hides.
That state is read from the button's computed display rather than from a
second copy of the grouping, so the two cannot drift: whatever ui-core
puts in the menu lights up Tools, and a destination promoted back into
the strip stops doing so with no further change.

Tools already carries the tab class, so the existing active styling
applies unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 00:23:17 +02:00
sjgandClaude Opus 5 b409c57296 [test](trx-frontend-http): assert header geometry in the browser smoke test
CI / test (push) Successful in 7m27s
CI / frontend (push) Successful in 3m1s
CI / reuse (push) Successful in 3s
CI / lint (pull_request) Successful in 2m16s
CI / test (pull_request) Successful in 7m24s
CI / frontend (pull_request) Successful in 2m11s
CI / reuse (pull_request) Successful in 2s
CI / lint (push) Successful in 2m15s
Several layout faults shipped while every gate passed, because nothing
looked at geometry: a header whose height tracked the viewport, controls
at four different heights, a tab strip that ran under the controls, and a
dropdown that opened underneath the page.

Assert the invariants behind those at four widths — the header stays one
row, the tabs do not reach the controls, the controls share a height, the
page does not scroll sideways — and that the menu renders with real
dimensions and wins a hit test at its own centre.

The overlap check measures the tabs rather than the strip: with the strip
allowed to overflow, its box shrinks while its content paints across the
controls, so the container's own rect never registers the collision.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 00:18:16 +02:00
sjgandClaude Opus 5 00191c8d7a [fix](trx-frontend-http): serve the Statistics and Bookmarks routes
CI / lint (pull_request) Successful in 2m18s
CI / frontend (pull_request) Successful in 3m1s
CI / reuse (pull_request) Successful in 2s
CI / lint (push) Successful in 2m17s
CI / test (pull_request) Successful in 8m23s
CI / test (push) Successful in 7m28s
CI / frontend (push) Successful in 2m9s
CI / reuse (push) Successful in 2s
The server answers /, /map, /digital-modes, /recorder, /settings and
/about with the application shell, but never had a route for /statistics
or /bookmarks.  Both fell through to the catch-all asset handler, so
reloading on either one downloaded a file instead of reopening the page.
Only in-app navigation worked, which is why it went unnoticed until
Statistics was reachable from the Tools menu.

Add the two missing shell routes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-03 00:03:48 +02:00
sjgandClaude Opus 5 56c363a517 [fix](trx-frontend-http): align the Statistics page and unblock the tab strip
Two faults, both mine, both visible in one screenshot of that page.

#tab-statistics was the only panel with padding of its own, so its title
and content sat 16px inside where every other page begins.  Remove it and
the page lines up with the header and with its siblings.

Removing the tab strip's `overflow-x` left it unable to shrink below its
content, so at around 1280px it ran under the controls: the Map tab sat
beneath the audio button and Tools beneath REC.  Clipping is safe again —
the menus it anchors are reparented to the body when they open — so the
strip can shrink, and the labels now give way to icons at 1360px rather
than 1180px, before it has to clip anything.

Measured at 1280px: 321px of clearance between the strip and the
controls, and the page title at the same left edge as the header.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 23:59:58 +02:00
sjgandClaude Opus 5 5ad91b4ab6 [fix](trx-frontend-http): stop doubling the space under the Statistics title
CI / lint (pull_request) Successful in 2m17s
CI / test (pull_request) Successful in 8m13s
CI / frontend (pull_request) Successful in 3m1s
CI / reuse (pull_request) Successful in 3s
CI / lint (push) Successful in 2m20s
CI / test (push) Successful in 7m33s
CI / frontend (push) Successful in 2m12s
CI / reuse (push) Successful in 3s
The page titles carry a bottom margin, which is what spaces them from the
content on the plain block panels.  #tab-statistics is not one: it is a
flex column with `gap: 1rem`, so the margin landed on top of that gap and
left 28px under the title where every other page had 12px.

Drop the margin on that panel and let its own gap do the spacing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 23:50:03 +02:00
sjgandClaude Opus 5 1843522b45 [feat](trx-frontend-http): give the Tools destinations page titles
CI / lint (pull_request) Successful in 2m21s
CI / test (pull_request) Successful in 8m13s
CI / frontend (pull_request) Successful in 2m59s
CI / reuse (pull_request) Successful in 2s
CI / lint (push) Successful in 2m21s
CI / test (push) Successful in 7m30s
CI / frontend (push) Successful in 2m10s
CI / reuse (push) Successful in 3s
Recorder stated its name; Statistics, Settings and About did not, so one
page in eight carried a title.  The class it used, section-heading, had
no rule behind it either, leaving even that title as a default h2.

Which way to unify follows from the navigation change.  The tab strip
highlights the destination you are on, so Radio, Bookmarks, Digital modes
and Map already say where you are and a title would repeat the strip
while costing vertical space the spectrum wants.  The four destinations
behind Tools get no such highlight — the strip looks the same on all of
them — so those are exactly the pages that have to name themselves.

Give the three that were missing a heading, and style section-heading so
all four match.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 23:46:09 +02:00
sjgandClaude Opus 5 41ddecf5a7 [fix](trx-frontend-http): label the overflow tab Tools and hide its glyph
CI / test (pull_request) Successful in 8m17s
CI / lint (push) Successful in 2m18s
CI / lint (pull_request) Successful in 2m16s
CI / frontend (pull_request) Successful in 3m6s
CI / reuse (pull_request) Successful in 3s
CI / test (push) Successful in 7m25s
CI / frontend (push) Successful in 2m11s
CI / reuse (push) Successful in 3s
The button rendered as "•••More": the dots span carried no styling at
all, so the glyph sat flush against the label instead of behaving like
the icon it is.  Every other tab hides its icon while labels are shown
and swaps to it when they are not; the dots now follow the same rule, so
the button reads "Tools" beside the other labels and becomes the glyph
alone in the icon band.

"More" also said nothing about the destinations behind it.  The menu
holds Statistics, Recorder, Settings and About, so name it Tools and give
the button an aria-label that spells that out.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 23:36:41 +02:00
sjgandClaude Opus 5 b06c37affa [fix](trx-frontend-http): lift the header menus out of the header
CI / lint (pull_request) Successful in 2m24s
CI / test (pull_request) Successful in 8m21s
CI / frontend (pull_request) Successful in 3m5s
CI / reuse (pull_request) Successful in 3s
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 7m36s
CI / frontend (push) Successful in 2m9s
CI / reuse (push) Successful in 3s
Fixed positioning escaped the clipping, but not the stacking: the header
carries `z-index: 2`, which makes it a stacking context, so whatever
z-index a menu inside it carries is confined below level 2.  The spectrum
overlays paint as high as 9600, so both dropdowns opened underneath them.

Reparent each menu to the body when it opens.  Leaving that subtree is
the only way out of an ancestor's stacking context, and the menus are
already positioned in viewport coordinates, so nothing else about them
changes.  The outside-click test now considers the menu as well as its
wrapper, since the two are no longer nested.

Verified by hit testing rather than by inspecting z-index:
elementFromPoint at the open menu's centre returns the menu.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 23:28:39 +02:00
sjgandClaude Opus 5 b4912f5879 [fix](trx-frontend-http): render the header menus above the page
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 7m23s
CI / lint (pull_request) Successful in 2m16s
CI / test (pull_request) Successful in 8m13s
CI / frontend (pull_request) Successful in 2m59s
CI / reuse (pull_request) Successful in 3s
CI / frontend (push) Successful in 2m10s
CI / reuse (push) Successful in 3s
Both header dropdowns were laid out inside the bar rather than over the
page.  The navigation menu opened as an 18px sliver positioned above its
own button, and the overflow menu did not appear at all.

Two causes.  The tab strip kept `overflow-x: auto` from when it scrolled,
which clips an absolutely positioned descendant — and the strip is what
the navigation menu anchors to.  The strip no longer scrolls, since the
occasional destinations moved behind More, so the property and the edge
fade that went with it are both gone.

Anchoring in fixed coordinates at open time addresses the general case:
an absolutely positioned menu is clipped by any scrolling ancestor and
trapped inside whatever stacking context its ancestors create, so it can
be squashed inside the bar or painted underneath page content.  Fixed
coordinates answer to the viewport, and the menu flips above its button
near the bottom edge.

Clearing `right` when setting `left` keeps the menus at their natural
width: the stylesheet pins them to the right of their anchor, and leaving
that in place stretched them across the bar — 845px for a four-item list.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 19:18:47 +02:00
sjgandClaude Opus 5 27f2558193 [feat](trx-frontend-http): one navigation model at every width
CI / test (pull_request) Successful in 8m13s
CI / frontend (pull_request) Successful in 3m0s
CI / reuse (pull_request) Successful in 3s
CI / test (push) Successful in 7m25s
CI / lint (pull_request) Successful in 2m18s
CI / lint (push) Successful in 2m17s
CI / frontend (push) Successful in 2m9s
CI / reuse (push) Successful in 3s
Eight destinations sat flat in the tab strip with equal weight, competing
with the controls for the same row and then scrolling out of reach with
only a fade to say so.  They are not equal: Radio is where an operator
spends nearly all their time, Bookmarks, Digital modes and Map are
operating surfaces, and Statistics, Recorder, Settings and About are
occasional.

The mobile layout already grouped them exactly that way, behind its More
menu, so the application carried two navigation models.  Adopt the mobile
grouping at every width instead of adding a third: four operating tabs
plus More.  The strip no longer scrolls at any width, and the menu keeps
its bottom-sheet placement on mobile while anchoring under its button
elsewhere.

Drop the labels between 701 and 1180px so the tabs degrade to their icons
— which every tab already carries — before the strip could ever need to
hide a destination.

Rename Main to Radio: it is the receiver, not a generic first page, and
the name now says what the destination is rather than where it sits.

Freeing that width also let the style picker and theme toggle return to
the bar inline, leaving only the layout picker in the overflow menu.

Navigating to About in the browser smoke test now goes through More, as a
person would.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 19:12:14 +02:00
sjgandClaude Opus 5 3a9bf1b7ce [fix](trx-frontend-http): drop the rig description from the top bar
CI / test (pull_request) Successful in 8m22s
CI / frontend (pull_request) Successful in 3m1s
CI / reuse (pull_request) Successful in 3s
CI / lint (pull_request) Successful in 2m17s
The header repeated the active rig's hardware string and mode list beside
the rig picker.  With a real SDR that reads

  SoapySDR driver=airspyhf,serial=c852eb5dd23539f8 · RX · SDR filters ·
  LSB · USB · CW · CWR · AM · +7 modes

which is longer than every other control in the bar combined, and it is
already on the About tab in full, split across its Rig, Active rig,
Connection, Modes and VFO rows.

Remove the element and the builder behind it.  Rig switching keeps its
feedback through the existing hint channel rather than by briefly
rewriting a permanent label, and the identity that belongs in a header —
the rig's display name — stays in the left subtitle.

The freed width is not spent: the tab strip now reaches Settings before
it needs to scroll, where it previously faded out during Statistics.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 18:59:28 +02:00
sjgandClaude Opus 5 dd5760c436 [style](trx-frontend-http): fade the scrolled tab strip edge
CI / lint (pull_request) Successful in 2m19s
CI / test (pull_request) Successful in 8m17s
CI / frontend (pull_request) Successful in 3m0s
CI / reuse (pull_request) Successful in 3s
CI / lint (push) Successful in 2m17s
CI / test (push) Successful in 7m33s
CI / frontend (push) Successful in 2m9s
CI / reuse (push) Successful in 3s
The page tabs scroll rather than wrap, so the last visible tab was sliced
mid-word ("Se…" for Settings), which reads as a rendering fault instead of
as an invitation to scroll.

Fade the trailing edge with a mask.  A colour-matched cover gradient is
the usual trick, but the card is transparent, so a cover would have to
track the page background across both themes and all nine styles; a mask
is colour-agnostic.  Only the trailing edge is faded, leaving the first
tab crisp while the strip sits at rest.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 18:48:34 +02:00
sjgandClaude Opus 5 eee3630f04 [feat](trx-frontend-http): compact single-row top bar
The header's height depended on the viewport width, and not even
monotonically: 112px at 1440, 169px at 1100, 131px at 900, 246px at 720.
Both control groups wrapped, so every width produced a different ragged
block — eight page tabs across four rows at 1100px, and action controls
across three.  Four different control heights (32, 34, 45 and 54px) sat
in the same row, the 54px one being the rig picker with its summary
stacked underneath, and on narrow viewports the icon buttons stretched to
fill half the row, rendering a play triangle centred in a 249px box.

Lay both groups out as one row that never wraps.  Controls are a uniform
2rem and no longer stretch, the rig summary sits inline beside its select,
and the page tabs scroll instead of wrapping.  Secondary controls —
layout, style and theme — move into an overflow menu when the bar cannot
hold them, leaving audio, record and the rig picker inline.

Deciding when they no longer fit needs natural widths, not rendered ones:
the nav has min-width 0 and scrolls, so it always shrinks to the leftover
space and always reports scrolling, and the bar reports overflow even when
nothing is clipped.  scrollWidth on the scroll container is its
unconstrained content width, which is what the fit test compares against
the space available.

Measured after the change: 72px at 1440, 1280, 1100, 900 and 480, every
control 32px, nothing clipped at any width.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 18:45:43 +02:00
sjgandClaude Opus 5 b31790ff48 [fix](trx-frontend-http): keep layout sections togglable
CI / lint (pull_request) Successful in 2m21s
CI / frontend (pull_request) Successful in 3m3s
CI / reuse (pull_request) Successful in 3s
CI / test (pull_request) Successful in 8m32s
CI / lint (push) Successful in 2m30s
CI / test (push) Successful in 8m36s
CI / frontend (push) Successful in 2m13s
CI / reuse (push) Successful in 4s
A layout seeds the collapsible sections; it should not hold them there.
applyLayout writes the disclosure state of the advanced, audio and
scheduler sections, and it runs far more often than a layout change:
render() calls applyRigList() for every SSE frame carrying `remotes`,
which calls setActiveRig() unconditionally, which re-applies the layout.

An operator who expanded a section that the selected layout collapses by
default therefore had it shut again within about a second, which read as
the section being locked by the layout — most visibly the scheduler under
Compact.

Write the section state only when the layout actually changes, or the
first time each section appears in the DOM, since the advanced controls
are constructed after the first applyLayout call.  Switching layout still
reseeds every section, so choosing a layout keeps meaning "give me these
defaults".

Verified in Chromium: with Compact selected, activating the scheduler
summary opens the section and it survives both a rig-state refresh and a
repeated applyLayout, while selecting Full still reseeds it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 17:46:56 +02:00
sjgandClaude Opus 5 2f4973ed70 [chore](trx-rs): allow the sccache bind mount on the CI runner
CI / test (pull_request) Successful in 13m51s
CI / frontend (pull_request) Successful in 5m1s
CI / test (push) Successful in 7m43s
CI / frontend (push) Successful in 2m18s
CI / reuse (pull_request) Successful in 4s
CI / lint (pull_request) Successful in 4m22s
CI / lint (push) Successful in 2m23s
CI / reuse (push) Successful in 1m18s
act_runner validates every bind mount against `valid_volumes`, which
defaults to an empty allowlist, so the `-v /var/cache/sccache:/sccache`
in `container.options` was dropped on every job.  The only trace is one
line in the job log — "[/var/cache/sccache] is not a valid volume, will
be ignored" — after which SCCACHE_DIR points at a path that does not
outlive the container, so the shared compilation cache never persisted.

Allow that one path rather than the `**` wildcard: the runner is the only
thing mounting host directories here, and a narrow allowlist keeps a
workflow from mounting arbitrary host paths into a job container.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 16:54:16 +02:00
sjgandClaude Opus 5 26b00608b2 [chore](trx-rs): force-pull the SDK image on the CI runner
CI / lint (pull_request) Failing after 3s
CI / test (pull_request) Failing after 2s
CI / frontend (pull_request) Failing after 28s
CI / reuse (pull_request) Successful in 3s
The workflow references the SDK image by the moving `:latest` tag, and
act_runner skips the pull when a local copy of that tag already exists:
the job log reports `docker pull ... forcePull=false` followed by
`Image exists? true`.  Pushing a rebuilt image therefore changes nothing
until someone pulls on the VM by hand, and the run fails as though the
image never gained the tool that was added to the Containerfile —
`sccache` resolving as "No such file or directory" while the pinned
toolchain from an earlier build of the same tag resolves fine.

Set `force_pull: true` so a pushed image is what actually runs, and
document the manual refresh for runners configured before this change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 16:49:46 +02:00
sjgandClaude Opus 5 c2455bb08c [chore](trx-rs): build the SDK image natively on x86_64 and arm64
CI / reuse (pull_request) Successful in 3s
CI / lint (pull_request) Has been cancelled
CI / test (pull_request) Has been cancelled
CI / frontend (pull_request) Has been cancelled
The sccache release asset is per-architecture and the Containerfile
hardcoded the x86_64 triple, so an arm64 build produced an image whose
sccache binary could not execute.  Everything else in the image — the
Debian base, the build dependencies, Node.js and rustup — already
resolves per architecture, so that one URL was what pinned the image to
amd64 and forced Rosetta or qemu on Apple Silicon.

Resolve the triple from `uname -m`, which reflects the build platform
under plain docker/podman build as well as buildx, unlike the
BuildKit-only TARGETARCH.

Document publishing `:latest` as a manifest list built natively on a host
of each architecture, since a single-architecture tag sends the other
side back to emulation, and note that Apple's `container` CLI needs
Rosetta for its BuildKit helper VM regardless of the target.

Pick the act_runner download by architecture for the same reason.

Verified on arm64: the case arm selects
sccache-v0.8.2-aarch64-unknown-linux-musl, and the installed binary
reports `sccache 0.8.2` running natively.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 12:14:44 +02:00
sjgandClaude Opus 5 22ff1349f3 [chore](trx-rs): run the frontend job in the SDK image
CI / lint (pull_request) Failing after 4s
CI / test (pull_request) Failing after 2s
CI / frontend (pull_request) Failing after 27s
CI / reuse (pull_request) Successful in 5s
The frontend job was added while CI still targeted host-executor runners,
so it never gained the `container:` key the lint and test jobs use.  On
the Docker executor it lands on a bare job container and fails the same
way the Rust jobs did before this branch: `npm` is missing, the Chromium
install shells out to `sudo apt-get`, and `npm run verify-generated`
regenerates the Rust wire contracts, so it needs `cargo` too.

Run it in the SDK image, which already ships Node.js, Chromium at the
path the browser smoke test defaults to, and the pinned Rust toolchain.
Installing Chromium per run is then redundant.

Drop the job's trailing `reuse lint`.  The SDK image deliberately carries
nothing REUSE-related, and the separate `reuse` job lints the whole
repository with the upstream action, generated assets included.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 11:33:02 +02:00
sjg 8b72573521 [chore](trx-rs): add sccache compilation cache
Bake sccache into the SDK image and enable it via RUSTC_WRAPPER in CI and
the devcontainer (not repo-wide, so non-SDK builds are unaffected).

- container/Containerfile: install the sccache musl binary.
- ci.yml: RUSTC_WRAPPER=sccache, CARGO_INCREMENTAL=0, SCCACHE_DIR=/sccache,
  cache size cap, plus a `sccache --show-stats` step per job.
- runner-config.example.yaml: bind-mount /var/cache/sccache into job
  containers so the cache persists across runs and is shared between jobs.
- .devcontainer: enable sccache with a named cache volume.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 11:27:42 +02:00
sjg f64032dcbe [chore](trx-rs): add OpenRC service for act_runner on Alpine
The runner host is Alpine (OpenRC, no systemd). Add an OpenRC init script
for act_runner (supervise-daemon, depends on docker) plus a conf.d
example for running one instance per project, and rewrite the runner
section of the README with Alpine setup steps (apk docker, dedicated user
in the docker group, register, service install).

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 11:27:42 +02:00
sjg 8fd1761688 [chore](trx-rs): use nested SDK image path trx-rs/sdk
Match the image name that was pushed to the registry
(git.haxx.space/sjg/trx-rs/sdk) across the workflow, devcontainer and
README.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 11:27:42 +02:00
sjg 7022f20b76 [chore](trx-rs): shared SDK image for CI and developers
Rework container/ from a host-executor act_runner image into a single
"SDK" build image used everywhere: as the CI job container (Docker
executor) and by developers locally / via .devcontainer. It bakes in a
pinned Rust toolchain and all build dependencies, so CI and every
developer share the exact same rustc/clippy.

- container/Containerfile: SDK image (Debian + deps + pinned Rust + Node).
- rust-toolchain.toml: pin the toolchain to match the image; also ends the
  "CI clippy newer than local" version skew.
- .gitea/workflows/ci.yml: lint/test run inside the SDK image via
  `container:`; reuse returns to fsfe/reuse-action (Docker executor runs
  it as a sibling container, so nothing REUSE-related is baked in).
- .devcontainer/devcontainer.json: dev use of the same image.
- container/runner-config.example.yaml: Docker-executor runner config for
  the CI VM, capped for a 2-thread budget.
- Drop the obsolete host-executor entrypoint/config/Quadlet units.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 11:27:42 +02:00
sjgandClaude Opus 5 0d4c657b97 [fix](trx-frontend-http): route feature bundles through the host contract
CI / lint (pull_request) Failing after 2s
CI / test (pull_request) Failing after 1s
CI / frontend (pull_request) Failing after 41s
CI / reuse (pull_request) Failing after 2s
CI / lint (push) Failing after 2s
CI / test (push) Failing after 2s
CI / frontend (push) Failing after 36s
CI / reuse (push) Failing after 1s
The bookmark fix addressed one instance of a defect the TypeScript
migration left across the feature entries.  app.js stopped being a
classic script, so its top-level declarations are no longer shared
globals, but the converted entries kept reading them as window
properties that nothing publishes.

Restore the broken behavior:

- ais, aprs, hf-aprs read serverLat, serverLon and haversineKm as
  undefined, so every positioned packet rendered an empty distance.
- ais, aprs, hf-aprs, cw, sat, vdes, wefax, wspr called an undefined
  postPath, so clear-history and decoder toggles threw.
- scheduler read authRole as undefined, so the lazy-load path never
  self-initialized and the Settings tab opened an inert scheduler.
- background-decode read authEnabled as undefined, so control gating
  fell back to role-only.
- vchan read fifteen application values and services as undefined:
  mode and bandwidth sync, the out-of-band hint, RX audio restart, and
  the frequency field all silently no-opped on a virtual channel.
- vchan wrapped window.refreshFreqDisplay, capturing an undefined
  original exactly as it did for setRigFrequency, so leaving a channel
  never restored the application's own frequency display.
- _audioChannelOverride was a const that nothing could assign, so RX
  audio always subscribed to the primary channel.
- ftx-family read fmtTime, a helper legacy ft8.js owned locally, so
  decode bar timestamps rendered empty.

Declare the contract once in plugins/host.ts and import it from the
feature entries, rather than restoring globals that
docs/frontend-architecture.md excludes.  trx.state gains jogUnit,
rxActive and audioChannelOverride, and makes lastModeName writable;
trx.core gains the tuning, RDS, WFM, jog and RX audio services the
entries need.  vchan interception moves to an interceptFreqDisplay
service method that refreshFreqDisplay calls, matching the frequency,
mode and bandwidth interception it already registers.

Reading registry-built elements through a strict lookup is the same
defect as in bookmarks: renderTimelineNeedle guards its result, but
schedulerEl throws, so the now-initializing scheduler crashed on the
timeline needle group that its own SVG creates.

Feature tests move onto a shared host fixture, and entries that now
import a common module are bundled through bundleEntry like the other
shared-module entries.  Covers scheduler self-initialization and the
distance path that the bare window reads broke.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 11:20:17 +02:00
sjgandClaude Opus 5 23dbcac5b6 [fix](trx-frontend-http): restore bookmark host contract
CI / lint (pull_request) Failing after 1s
CI / test (pull_request) Failing after 1s
CI / frontend (pull_request) Failing after 42s
CI / reuse (pull_request) Failing after 0s
The TypeScript migration turned app.js from a classic script into an ES
module, so its top-level declarations stopped being shared globals.
bookmarks.ts was converted verbatim and kept reading them as window
properties, which app.ts no longer publishes.

Every bookmark interaction read undefined: the Add Bookmark and Select
All buttons stayed hidden because the auth check saw no authEnabled or
authRole, per-rig scopes were missing from the scope picker and the move
target, decoder checkboxes were never built, and Tune threw on
bridge.postPath before issuing a single request.

Extend the typed window.trx host contract instead of restoring globals,
as docs/frontend-architecture.md closes the standalone window property
list.  trx.state publishes authEnabled; trx.core publishes
setRigFrequency, applyLocalTunedFrequency, armOptimisticFrequency,
syncBandwidthInput, scheduleSpectrumDraw, and onDecoderRegistryReady.

Replace the vchan setRigFrequency wrapper with an interceptFrequency
service method, matching interceptMode and interceptBandwidth.  The
wrapper captured an undefined original and silently dropped every tune;
routing interception through setRigFrequency also restores virtual
channel redirection for the application's own tuning.

Read registry-built elements through bmOptionalEl, since bmEl throws and
the decoder checkboxes and decode toggle buttons are legitimately absent
until the registry arrives.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GdyUjuXejCEfiub675z6cz
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-08-02 10:15:56 +02:00
sjg 695434942f chore: complete TypeScript migration cleanup
CI / lint (pull_request) Failing after 2s
CI / test (pull_request) Failing after 2s
CI / frontend (pull_request) Failing after 42s
CI / reuse (pull_request) Failing after 2s
CI / lint (push) Failing after 2s
CI / test (push) Failing after 1s
CI / frontend (push) Failing after 44s
CI / reuse (push) Failing after 2s
2026-08-01 22:39:37 +02:00
sjg a1a8d1d1d3 test: cover lazy map and rig startup flows 2026-08-01 22:34:22 +02:00
sjg ddb33b6ff3 feat: generate frontend status metadata contract 2026-08-01 22:27:35 +02:00
sjg f87289b129 fix: validate typed frontend startup in Chromium 2026-08-01 22:25:10 +02:00
sjg 812359c744 refactor: enforce typed frontend runtime boundaries 2026-08-01 22:19:50 +02:00
sjg d929ad3bde build: consolidate typed frontend module graph 2026-08-01 21:54:00 +02:00
sjg 8aeca613aa test: add frontend browser startup smoke coverage 2026-08-01 20:19:27 +02:00
sjg ee59d8efdd build: remove JavaScript compatibility mode 2026-08-01 19:28:45 +02:00
sjg ddd151c1ee refactor: convert main frontend application to TypeScript 2026-08-01 19:18:48 +02:00
sjg 5136704826 refactor: extract typed spectrum math 2026-08-01 18:19:02 +02:00
sjg e300cc343d refactor: extract typed auto bandwidth estimator 2026-08-01 17:59:04 +02:00
sjg 1fb196a64e refactor: extract typed navigation routes 2026-08-01 17:18:41 +02:00
sjg c8cc235e88 refactor: extract strict CBOR decoder 2026-08-01 17:04:13 +02:00
sjg ab3fe4bbb7 refactor: extract typed frontend formatters 2026-08-01 16:42:54 +02:00
sjg 40accb9697 refactor: extract typed authentication API 2026-08-01 16:39:52 +02:00
sjg cbca810a30 refactor: extract typed decoder registry 2026-08-01 16:28:39 +02:00
sjg 26a167cb82 refactor: replace feature globals with typed services 2026-08-01 16:05:40 +02:00
sjg 3d49839ed5 build: type-check worker with isolated globals 2026-08-01 15:21:16 +02:00
sjg 26be675242 build: enable frontend module code splitting 2026-08-01 14:40:59 +02:00
sjg 1a42d58075 refactor: embed generated frontend asset directory 2026-08-01 14:39:34 +02:00
sjg 844de809a4 fix: preserve bandplan override lookup 2026-08-01 14:23:29 +02:00
sjg e910e644d5 refactor: extract typed frontend core utilities 2026-08-01 13:48:51 +02:00
sjg 50e07e2715 refactor: add typed frontend bootstrap 2026-08-01 13:43:46 +02:00
sjg 82121491c5 refactor: convert map feature to strict TypeScript 2026-08-01 13:39:41 +02:00
sjg 0338c8b8d2 refactor: convert scheduler to typed module 2026-08-01 13:23:30 +02:00
sjg c7994347e9 refactor: convert bookmarks to typed module 2026-08-01 13:13:52 +02:00
sjg 9fef0ebc7b refactor: route all decoders through plugin runtime 2026-08-01 13:06:38 +02:00
sjg 508cf2ba87 refactor: add typed decoder plugin runtime 2026-08-01 13:02:54 +02:00
sjg 6a83e2e90a refactor: convert virtual channels to TypeScript 2026-08-01 12:57:09 +02:00
sjg fc2f55bab9 refactor: convert satellite scheduler to TypeScript 2026-08-01 12:54:03 +02:00
sjg 4fb65971e4 refactor: convert satellite view to TypeScript 2026-08-01 12:51:22 +02:00
sjg 021d31d780 refactor: share typed APRS plugin contracts 2026-08-01 12:48:33 +02:00
sjg 074c67c7b9 refactor: convert APRS plugin to TypeScript 2026-08-01 12:43:40 +02:00
sjg d93f784aad refactor: convert AIS plugin to TypeScript 2026-08-01 12:39:20 +02:00
sjg ec59908e0d refactor: convert background decode controls to TypeScript 2026-08-01 12:36:27 +02:00
sjg 7251ec276d refactor: convert WEFAX plugin to TypeScript 2026-08-01 12:33:38 +02:00
sjg 0ab0f80986 refactor: convert VDES plugin to TypeScript 2026-08-01 12:30:17 +02:00
sjg 2cbcc23fec refactor: move plugin loading into typed registry 2026-08-01 12:26:29 +02:00
sjg 968fb3ea2d refactor: type the local Leaflet AIS adapter 2026-08-01 12:23:37 +02:00
sjg 5ba3ecf59b refactor: make FT8 family a typed module 2026-08-01 12:21:13 +02:00
sjg 03bdc10b02 refactor: convert CW plugin to TypeScript 2026-08-01 12:18:51 +02:00
sjg d96624be4f refactor: convert WSPR plugin to TypeScript 2026-08-01 12:15:19 +02:00
sjg a5dccd5489 refactor: consolidate FT2 and FT4 plugins in TypeScript 2026-08-01 12:12:27 +02:00
sjg 42e5dc8604 docs: record frontend migration baseline 2026-08-01 12:09:38 +02:00
sjg e6f593b959 refactor: convert screenshot support to TypeScript 2026-08-01 12:08:44 +02:00
sjg 9ac6d7f82c refactor: convert WebGL renderer to TypeScript 2026-08-01 12:07:02 +02:00
sjg a58553ba66 refactor: convert decode history worker to TypeScript 2026-08-01 12:03:19 +02:00
sjg 7442437757 refactor: convert shared UI core to TypeScript 2026-08-01 12:01:07 +02:00
sjg bbc53d56b0 feat: generate typed frontend API contracts 2026-08-01 11:58:09 +02:00
sjg 888f793eb8 build: add frontend TypeScript toolchain 2026-08-01 11:52:47 +02:00
sjg 860760ecfc docs: add TypeScript migration plan 2026-08-01 11:48:20 +02:00
sjg b4ea35baf8 feat(ui): add dedicated audio controls section
CI / lint (pull_request) Failing after 1s
CI / test (pull_request) Failing after 0s
CI / reuse (pull_request) Failing after 0s
CI / lint (push) Failing after 1s
CI / test (push) Failing after 1s
CI / reuse (push) Failing after 0s
2026-08-01 11:32:34 +02:00
sjg 508ed8a8e7 feat(ui): separate scheduler controls subsection
CI / lint (pull_request) Failing after 1s
CI / test (pull_request) Failing after 2s
CI / reuse (pull_request) Failing after 2s
CI / lint (push) Failing after 0s
CI / test (push) Failing after 1s
CI / reuse (push) Failing after 1s
2026-08-01 11:28:51 +02:00
sjg d9fc623ef4 fix(ui): simplify operator layout picker
CI / lint (push) Failing after 1s
CI / test (push) Failing after 0s
CI / reuse (push) Failing after 0s
CI / lint (pull_request) Failing after 2s
CI / test (pull_request) Failing after 2s
CI / reuse (pull_request) Failing after 1s
2026-08-01 11:25:32 +02:00
sjg 53736ef750 fix(ui): hide SDR power and align header controls
CI / lint (pull_request) Failing after 1s
CI / test (pull_request) Failing after 2s
CI / reuse (pull_request) Failing after 1s
2026-08-01 11:23:57 +02:00
sjg 6566eae2c7 fix(ui): keep workspace and rig context visible
CI / lint (pull_request) Failing after 1s
CI / test (pull_request) Failing after 1s
CI / reuse (pull_request) Failing after 1s
CI / lint (push) Failing after 0s
CI / test (push) Failing after 0s
CI / reuse (push) Failing after 1s
2026-08-01 11:19:31 +02:00
sjg f3eeddff7c fix(ui): close mobile overlays predictably 2026-08-01 11:18:37 +02:00
sjg 1540ca5b4e test(ui): cover shared component behavior 2026-08-01 11:17:17 +02:00
sjg e449704fd2 feat(ui): explain unavailable workspaces 2026-08-01 11:16:03 +02:00
sjg af74430551 fix(ui): make rig switching atomic and visible 2026-08-01 11:15:39 +02:00
sjg d07dbdc645 feat(ui): focus broadcast workspace on reception 2026-08-01 11:14:10 +02:00
sjg d07a627508 feat(ui): remember workspaces per rig 2026-08-01 11:13:21 +02:00
sjg 9fbf90ee91 feat(ui): explain operator workspace choices 2026-08-01 11:12:33 +02:00
sjg d393b3cefc feat(ui): drive workspaces from rig capabilities 2026-08-01 11:11:47 +02:00
sjg 35a492ec95 fix(ui): gate broadcast layout on rig capability
CI / lint (pull_request) Failing after 2s
CI / test (pull_request) Failing after 2s
CI / reuse (pull_request) Failing after 2s
CI / lint (push) Failing after 1s
CI / test (push) Failing after 3s
CI / reuse (push) Failing after 1s
2026-08-01 11:05:45 +02:00
sjg b20da5c541 style(ui): polish shared interaction components
CI / lint (pull_request) Failing after 1s
CI / test (pull_request) Failing after 1s
CI / reuse (pull_request) Failing after 2s
CI / lint (push) Failing after 2s
CI / test (push) Failing after 1s
CI / reuse (push) Failing after 2s
2026-08-01 10:43:29 +02:00
sjg a0bdaa2c4b feat(ui): improve radio operator experience
CI / lint (pull_request) Failing after 1s
CI / test (pull_request) Failing after 1s
CI / reuse (pull_request) Failing after 1s
CI / lint (push) Failing after 1s
CI / test (push) Failing after 1s
CI / reuse (push) Failing after 0s
2026-08-01 02:24:47 +02:00
sjg 6676b66993 [fix](trx-frontend): account for WFM interference in auto bandwidth
CI / lint (pull_request) Failing after 1s
CI / test (pull_request) Failing after 1s
CI / reuse (pull_request) Failing after 0s
CI / lint (push) Failing after 0s
CI / test (push) Failing after 1s
CI / reuse (push) Failing after 1s
2026-08-01 02:07:32 +02:00
sjg 412651d612 [fix](trx-frontend): narrow weak WFM to 60 kHz
CI / lint (push) Failing after 1s
CI / test (push) Failing after 2s
CI / reuse (push) Failing after 1s
2026-08-01 02:04:14 +02:00
sjg d347b493d9 [fix](trx-frontend): make auto bandwidth modulation-aware 2026-08-01 02:04:14 +02:00
sjg 39e59dca96 [fix](trx-server): gate test-only history imports
CI / lint (pull_request) Failing after 1s
CI / test (pull_request) Failing after 1s
CI / reuse (pull_request) Failing after 1s
CI / lint (push) Failing after 3s
CI / test (push) Failing after 2s
CI / reuse (push) Failing after 1s
2026-08-01 01:55:33 +02:00
sjg 5654520901 [fix](workspace): clear build and clippy warnings
CI / lint (push) Failing after 1s
CI / test (push) Failing after 1s
CI / reuse (push) Failing after 1s
2026-08-01 01:52:08 +02:00
sjg ff75fcc692 [refactor](trx-server): extract decoder history store
CI / lint (pull_request) Failing after 2s
CI / test (pull_request) Failing after 2s
CI / reuse (pull_request) Failing after 1s
CI / lint (push) Failing after 2s
CI / test (push) Failing after 2s
CI / reuse (push) Failing after 1s
2026-08-01 01:45:19 +02:00
sjg 4728b578ae [refactor](trx-server): extract history policy 2026-08-01 01:44:26 +02:00
sjg 7db7fad9b0 [refactor](trx-frontend): define module service boundaries 2026-08-01 01:44:26 +02:00
sjg 830f7299fe [fix](trx-frontend): vendor Opus decoder 2026-08-01 01:44:26 +02:00
sjg 061738a63b [fix](trx-frontend): serialize plugin loading
CI / lint (push) Failing after 1s
CI / test (push) Failing after 1s
CI / reuse (push) Failing after 1s
2026-08-01 01:43:50 +02:00
sjg e8bd97655f [fix](trx-server): offload history persistence
CI / reuse (push) Failing after 1s
CI / lint (push) Failing after 2s
CI / test (push) Failing after 2s
2026-08-01 01:43:47 +02:00
sjg 7d0b36450d [fix](trx-server): persist all decoder histories
CI / reuse (push) Failing after 1s
CI / lint (pull_request) Failing after 3s
CI / test (pull_request) Failing after 1s
CI / reuse (pull_request) Failing after 2s
CI / lint (push) Failing after 1s
CI / test (push) Failing after 1s
2026-08-01 01:23:36 +02:00
Stan Grams b12c83e8b5 [fix](trx-frontend): preload AIS map icons
CI / lint (pull_request) Failing after 6s
CI / test (pull_request) Failing after 2s
CI / reuse (pull_request) Failing after 1s
CI / lint (push) Failing after 1s
CI / test (push) Failing after 2s
CI / reuse (push) Failing after 0s
2026-08-01 01:14:07 +02:00
sjg ff4e2a5c5d [chore](trx-rs): install reuse with charset-normalizer extra
CI / lint (pull_request) Successful in 9m35s
CI / reuse (pull_request) Failing after 5s
CI / lint (push) Successful in 8m40s
CI / test (pull_request) Successful in 29m0s
CI / reuse (push) Failing after 5s
CI / test (push) Successful in 14m28s
The runner image's `reuse` failed to import (NoEncodingModuleError): it
needs an encoding-detection backend, which the bare `reuse` install does
not provide and which libmagic/`file` is not present to satisfy. Install
`reuse[charset-normalizer]` so the reuse job can run in the image.

Rebuild the runner image and recreate the containers to pick this up.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-18 23:57:38 +02:00
sjg 2ef9f80fc1 [chore](trx-rs): drop redundant CI setup steps for baked runner image
CI / lint (pull_request) Successful in 9m14s
CI / reuse (pull_request) Failing after 6s
CI / test (pull_request) Successful in 15m15s
The host-executor runners run jobs inside one container that already has
the Rust toolchain and all build dependencies baked in, so the per-job
`apt-get install` and rustup steps were redundant. Worse, with two jobs
running concurrently in the same runner they collided on the dpkg lock
("Could not get lock /var/lib/dpkg/lock-frontend").

Remove the system-dependency, rustup and cache steps; jobs now run cargo
directly. The cargo registry persists in the long-lived runner container.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-18 23:33:42 +02:00
sjg 6fe549e34e [chore](trx-rs): run reuse lint directly instead of Docker action
CI / test (pull_request) Failing after 52s
CI / reuse (pull_request) Failing after 3s
CI / lint (pull_request) Successful in 3m34s
The host-executor runners have no Docker daemon, so fsfe/reuse-action
(a Docker action) fails with "Cannot connect to the Docker daemon". Call
the reuse CLI directly; it is baked into the runner image.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-18 13:24:26 +02:00
sjg 406a8f86b1 [chore](trx-rs): add Podman act_runner CI deployment
CI / lint (pull_request) Successful in 2m43s
CI / test (pull_request) Successful in 3m20s
CI / reuse (pull_request) Successful in 7s
CI / lint (push) Successful in 2m36s
CI / test (push) Successful in 2m35s
CI / reuse (push) Failing after 4s
Add container/: a rootless Podman + systemd (Quadlet) setup to run
per-project Gitea Actions runners on one host instead of VMs. Uses the
host executor with a purpose-built image that bakes in the Rust toolchain
and all build dependencies (opus, alsa, soapysdr, clang), so CI runs skip
the per-run install and cold soapysdr-sys build.

Includes the runner Containerfile, first-boot registration entrypoint,
act_runner config template, two Quadlet units (trx-rs + a second project),
and a README covering build, registration, the required host-executor
workflow tweak, and tuning.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-18 12:45:53 +02:00
sjg 4b17b4ac1d [style](trx-ftx): use iterators in LDPC single-index loops
CI / lint (pull_request) Successful in 2m35s
CI / test (pull_request) Successful in 3m22s
CI / reuse (pull_request) Successful in 7s
CI / lint (push) Successful in 2m34s
CI / test (push) Successful in 3m26s
CI / reuse (push) Successful in 7s
clippy needless_range_loop (rust 1.97) flagged the loops in ldpc_check
and ldpc_decode that use a range only to index one array. Replace them
with iterator/enumerate forms. The belief-propagation loops that index
several arrays by the same variable are left as-is (not flagged).

Behaviour is unchanged; the transformations are index-for-index
equivalent. Verified the lib compiles and is clippy-clean; the crate's
LDPC tests run in the CI test job (they need a dev-dependency not
available in the local offline sandbox).

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-18 10:43:01 +02:00
sjg 977f7b709e [style](trx-ais): drop redundant u32 cast
CI / lint (pull_request) Failing after 2m28s
CI / test (pull_request) Successful in 3m23s
CI / reuse (pull_request) Successful in 7s
get_uint returns Option<u32>, so `? as u32` is an unnecessary same-type
cast flagged by clippy under -D warnings (rust 1.97).

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-18 10:28:55 +02:00
sjg a2838b06a2 [style](trx-ftx): fix clippy question_mark and collapsible_match
CI / lint (pull_request) Failing after 2m22s
CI / test (pull_request) Successful in 3m27s
CI / reuse (pull_request) Successful in 8s
CI runs a newer clippy (1.97) than was available locally, which flagged
three lints in trx-ftx not caught earlier:

- question_mark: replace the Some/None match in CallsignHashTable::lookup
  with `self.entries[idx].as_ref()?`
- collapsible_match: fold the nested `if` in text.rs char/nchar into match
  guards on the AlphanumSpaceSlash arm

Behaviour is unchanged; verified clean with nightly clippy (1.93).

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-18 09:25:12 +02:00
sjg c6cd661676 [style](trx-rs): fix clippy warnings for -D warnings CI
CI / lint (pull_request) Failing after 4m14s
CI / test (pull_request) Successful in 15m22s
CI / reuse (pull_request) Successful in 7s
The CI lint job runs clippy with -D warnings, which surfaced a set of
existing warnings across decoders, the client, and the soapysdr backend.
Resolve them so the workspace is clean under the enforced lint level:

- collapsible_match / identity_op / needless_range_loop / same_item_push
  in trx-rds, trx-wspr, trx-vdes, trx-wefax, trx-aprs (mostly tests)
- field_reassign_with_default -> struct-update syntax in trx-client config
  tests
- assign_op_pattern, useless vec!, and test-module ordering picked up by
  cargo clippy --fix in trx-client and the soapysdr WFM tests

No behaviour changes; all affected crates' tests pass.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-17 23:49:12 +02:00
sjg bf08c7ebc0 [chore](trx-rs): install libclang for soapysdr-sys in CI
CI / lint (pull_request) Failing after 4m7s
CI / reuse (pull_request) Has been cancelled
CI / test (pull_request) Has been cancelled
soapysdr-sys builds bindings with bindgen, which needs libclang at build
time. Add clang and libclang-dev to the system dependencies so the
soapysdr backend (a default feature) compiles under CI.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-17 23:30:49 +02:00
sjg c7470acc1c [chore](trx-rs): fix Rust PATH handling in CI
CI / lint (pull_request) Failing after 3m18s
CI / reuse (pull_request) Has been cancelled
CI / test (pull_request) Has been cancelled
The Set up Rust step wrote the cargo bin dir to GITHUB_PATH, which does
not help within the same step and is not relied upon across steps on the
Gitea act_runner. Prepend $HOME/.cargo/bin to PATH directly in the setup
and each cargo step instead, so rustup and cargo resolve regardless of
GITHUB_PATH support.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-17 23:25:21 +02:00
sjg bcde03de38 [docs](trx-rs): track improvement areas in aidocs/wip.md
CI / lint (pull_request) Failing after 31s
CI / reuse (pull_request) Successful in 35s
CI / test (pull_request) Failing after 29s
Record the three-tier improvement backlog (infrastructure, robustness,
product) with a per-item progress status column, so the work discovered
in the July 2026 repo scan is tracked. Register aidocs/** in REUSE.toml
alongside docs/**.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-17 21:21:57 +02:00
sjg 63d46562c7 [chore](trx-rs): add Gitea Actions CI pipeline
Introduce CI running on push to main and pull requests. Three jobs:
lint (rustfmt check + clippy with -D warnings), test (build and test the
workspace with --locked), and REUSE compliance. Installs the required
system libraries (opus, alsa, soapysdr) and caches the cargo registry
and target directory.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-17 21:21:57 +02:00
sjg e575b3b365 [docs](trx-rs): adopt kernel-style AI attribution trailers
Replace the guidance to credit LLM usage via 'Co-authored-by:' with the
Linux kernel convention. Co-Authored-By and Co-Developed-By are reserved
for human authors (who must also sign off); AI/LLM assistance is
disclosed with an Assisted-By: trailer instead.

Apply the new policy to this commit as a worked example.

Assisted-By: Claude Code (claude-opus-4)
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-17 21:10:09 +02:00
sjgandClaude Opus 4.8 2121817c04 [style](trx-frontend-http): refine web UI design system and a11y
Introduce a shared design-token layer and apply it to the web
frontend for a more consistent, readable, and accessible feel.
Pure CSS plus one HTML block; no app.js behaviour changes, and the
existing multi-theme (style x light/dark) system is preserved.

- Add spacing, type, radius and motion tokens to :root.
- Fix undefined --surface consumed by .controls-tray, which dropped
  the panel background entirely; it now resolves per theme.
- Set body line-height and font smoothing; collapse near-duplicate
  font sizes onto canonical scale steps.
- Rebuild the auth gate with classes and replace hardcoded colours
  (#ff6b6b, #9aa4b5) with theme variables so it renders correctly in
  every theme.
- Add an opacity fade on tab switches, gated by prefers-reduced-motion.
- Extend focus-visible rings to the spectrum canvas, tabindex controls
  and links.
- Add a self-theming --accent-text token to lift accent-coloured text
  (links, active tab) to WCAG AA without altering brand fills.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NFpGtGTWUEYXLwZeZs2RAV
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-07-17 20:57:43 +02:00
sjgandClaude Opus 4.7 d0bd38d7df [docs](trx-frontend-http): point footer repo link to Gitea
Repoint the web UI footer link to git.haxx.space/sjg/trx-rs, swap the
GitHub octocat mark for a host-neutral git-branch icon, and relabel to
"trx-rs source".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-05-18 00:06:45 +02:00
sjgandClaude Opus 4.7 bf9617e24d [docs](trx-rs): migrate wiki links from GitHub to Gitea
Point README wiki/repo URLs at git.haxx.space/sjg/trx-rs (the new
primary upstream); same /wiki/<Page> path scheme as before.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-05-18 00:05:29 +02:00
sjgandClaude Opus 4.7 3c235fce5e [chore](trx-rs): REUSE 3.3 compliance, drop GitHub wiki workflow
Add a root REUSE.toml annotating docs, repo metadata, logos, vendored
Leaflet (BSD-2-Clause) and the DSEG14 font (OFL-1.1) instead of
per-file headers; add LICENSES/OFL-1.1.txt. reuse lint: compliant.

Also remove .github/workflows/wiki.yml: the project moved off GitHub
to a self-hosted Gitea, so the GitHub Actions wiki-publishing workflow
no longer runs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-05-18 00:05:24 +02:00
sjg ba48de2d30 Initial commit
Sync docs to Wiki / wiki (push) Has been cancelled
Signed-off-by: Stan Grams <sjg@haxx.space>
2026-05-17 23:25:14 +02:00
365 changed files with 56098 additions and 13145 deletions
+4
View File
@@ -1,3 +1,7 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: GPL-2.0-or-later
# Enable CPU optimizations for better performance
# Set target-cpu to native to use all available CPU features on the build machine
+22
View File
@@ -0,0 +1,22 @@
{
"name": "trx-rs SDK",
"image": "git.haxx.space/sjg/trx-rs/sdk:latest",
"workspaceFolder": "/work",
"workspaceMount": "source=${localWorkspaceFolder},target=/work,type=bind",
"mounts": [
"source=trx-rs-sccache,target=/sccache,type=volume"
],
"containerEnv": {
"RUSTC_WRAPPER": "sccache",
"CARGO_INCREMENTAL": "0",
"SCCACHE_DIR": "/sccache"
},
"customizations": {
"vscode": {
"extensions": [
"rust-lang.rust-analyzer",
"tamasfe.even-better-toml"
]
}
}
}
+89
View File
@@ -0,0 +1,89 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: GPL-2.0-or-later
# CI for the Docker-executor runner (VM). The lint, test and frontend jobs run
# inside the shared trx-rs SDK image (container/Containerfile), which bakes in
# the pinned Rust toolchain, Node.js, Chromium and all build dependencies. The
# reuse job uses the upstream Docker action, which the Docker executor launches
# as a sibling container.
name: CI
on:
push:
branches: [main]
pull_request:
env:
CARGO_TERM_COLOR: always
# sccache: shared compilation cache persisted on the runner host (see the
# -v mount in runner-config.example.yaml). CARGO_INCREMENTAL=0 because
# sccache cannot cache incremental artifacts.
RUSTC_WRAPPER: sccache
CARGO_INCREMENTAL: "0"
SCCACHE_DIR: /sccache
SCCACHE_CACHE_SIZE: "20G"
jobs:
lint:
runs-on: ubuntu-latest
container: git.haxx.space/sjg/trx-rs/sdk:latest
steps:
- uses: actions/checkout@v4
- name: rustfmt
run: cargo fmt --all -- --check
- name: clippy
run: cargo clippy --workspace --all-targets --all-features -- -D warnings
- name: sccache stats
if: always()
run: sccache --show-stats
test:
runs-on: ubuntu-latest
container: git.haxx.space/sjg/trx-rs/sdk:latest
steps:
- uses: actions/checkout@v4
- name: Build
run: cargo build --workspace --all-targets --locked
- name: Test
run: cargo test --workspace --locked
- name: sccache stats
if: always()
run: sccache --show-stats
frontend:
runs-on: ubuntu-latest
container: git.haxx.space/sjg/trx-rs/sdk:latest
defaults:
run:
working-directory: src/trx-client/trx-frontend/trx-frontend-http/frontend
steps:
- uses: actions/checkout@v4
- name: Cache npm downloads
uses: actions/cache@v4
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('src/trx-client/trx-frontend/trx-frontend-http/frontend/package-lock.json') }}
restore-keys: |
npm-${{ runner.os }}-
- name: Install locked frontend dependencies
run: npm ci
- name: Type-check
run: npm run typecheck
- name: Lint
run: npm run lint
- name: Test
run: npm test
# Chromium comes from the SDK image at the path the smoke test defaults
# to, so there is nothing to install here.
- name: Browser smoke test
run: npm run test:browser
- name: Verify generated assets
run: npm run verify-generated
reuse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: fsfe/reuse-action@v5
-39
View File
@@ -1,39 +0,0 @@
name: Sync docs to Wiki
on:
push:
branches: [main]
paths:
- 'docs/**'
workflow_dispatch:
permissions:
contents: write
jobs:
wiki:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Checkout wiki
uses: actions/checkout@v4
with:
repository: ${{ github.repository }}.wiki
path: wiki
token: ${{ secrets.GITHUB_TOKEN }}
- name: Sync docs to wiki
run: |
rsync -av --delete --exclude='.git' docs/ wiki/
cd wiki
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add -A
if git diff --cached --quiet; then
echo "No wiki changes to commit."
else
git commit -m "Sync docs from ${GITHUB_SHA::8}"
git push
fi
+3
View File
@@ -21,6 +21,9 @@ Cargo.lock
coverage/
benchmarks/
# Frontend dependencies
**/node_modules/
# Env
.env
.env.*
+8 -1
View File
@@ -24,6 +24,12 @@ cargo test -p trx-core
./target/release/trx-server --print-config > trx-server.toml
./target/release/trx-client --print-config > trx-client.toml
# Validate a config without starting anything (reports every problem)
./target/release/trx-server --check-config --config trx-rs.toml
# Regenerate trx-rs.toml.example after changing a config struct
cargo run -p trx-config --example generate_example
# Run server
./target/release/trx-server --config trx-server.toml
# or via CLI args:
@@ -41,7 +47,8 @@ This is a Cargo workspace. All crates live under `src/`:
src/
trx-core/ # Core types, traits, state machine, controller (~3,500 LOC)
trx-protocol/ # Client↔server protocol DTOs, auth, codec, mapping (~1,100 LOC)
trx-app/ # Shared application helpers (config paths, logging init)
trx-app/ # Shared application helpers (logging init, name normalization)
trx-config/ # Client + server config structs, loader, validators (~2,500 LOC)
trx-reporting/ # PSKReporter UDP uplink + APRS-IS TCP uplink (~1,150 LOC)
trx-server/ # Server binary: rig_task, audio pipeline, listener (~3,700 LOC)
trx-backend/ # Backend abstraction trait + factory + dummy
+21 -1
View File
@@ -18,7 +18,7 @@ When contributing to the project, please follow these guidelines:
- Use a maximum of 80 characters per line.
- Use a blank line between the commit message and the body.
- Sign your commits with `git commit -s`.
- Explicitly mark LLM usage in commit messages with 'Co-authored-by:'.
- Disclose AI/LLM assistance with an `Assisted-By:` trailer (see below).
Use the format below for commit titles:
[<type>](<crate>): <description>
@@ -39,3 +39,23 @@ Allowed types:
- chore: build or maintenance changes
Write isolated commits for each crate.
## Attribution trailers
This project follows the Linux kernel convention for crediting work.
The `Co-Authored-By:` and `Co-Developed-By:` trailers name **people** who
authored the change. They are reserved for humans, and every person named
this way must also add their own `Signed-off-by:` line. Never use these
trailers for tools, assistants, or bots.
When a commit was produced with help from an AI assistant or LLM,
disclose it with an `Assisted-By:` trailer naming the tool (and model,
where relevant). The human committer remains the author of record and
takes responsibility for the change through `Signed-off-by:`.
Example:
Assisted-By: Claude Code (claude-opus-4)
Co-Authored-By: Jane Developer <jane@example.com>
Signed-off-by: Your Name <you@example.com>
Generated
+81 -4
View File
@@ -2412,6 +2412,16 @@ dependencies = [
"syn",
]
[[package]]
name = "serde_ignored"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798"
dependencies = [
"serde",
"serde_core",
]
[[package]]
name = "serde_json"
version = "1.0.149"
@@ -2645,6 +2655,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
"winapi-util",
]
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -3022,10 +3041,6 @@ dependencies = [
name = "trx-app"
version = "0.1.0"
dependencies = [
"dirs",
"serde",
"thiserror 2.0.18",
"toml",
"tracing",
"tracing-subscriber",
]
@@ -3106,6 +3121,7 @@ dependencies = [
"toml",
"tracing",
"trx-app",
"trx-config",
"trx-core",
"trx-frontend",
"trx-frontend-http",
@@ -3115,6 +3131,23 @@ dependencies = [
"uuid",
]
[[package]]
name = "trx-config"
version = "0.1.0"
dependencies = [
"dirs",
"serde",
"serde_ignored",
"tempfile",
"thiserror 2.0.18",
"toml",
"toml_edit 0.22.27",
"tracing",
"trx-core",
"trx-decode-log",
"trx-reporting",
]
[[package]]
name = "trx-configurator"
version = "0.1.0"
@@ -3123,13 +3156,16 @@ dependencies = [
"dialoguer",
"tempfile",
"tokio-serial",
"toml",
"toml_edit 0.22.27",
"trx-config",
]
[[package]]
name = "trx-core"
version = "0.1.0"
dependencies = [
"base64",
"flate2",
"reqwest",
"serde",
@@ -3137,6 +3173,7 @@ dependencies = [
"sgp4",
"tokio",
"tracing",
"ts-rs",
"uuid",
]
@@ -3168,6 +3205,7 @@ dependencies = [
"serde_json",
"tokio",
"trx-core",
"trx-protocol",
"uuid",
]
@@ -3177,6 +3215,7 @@ version = "0.1.0"
dependencies = [
"actix-web",
"actix-ws",
"base64",
"brotli 7.0.0",
"bytes",
"dirs",
@@ -3193,6 +3232,7 @@ dependencies = [
"trx-core",
"trx-frontend",
"trx-protocol",
"ts-rs",
"uuid",
]
@@ -3236,6 +3276,7 @@ dependencies = [
"serde",
"serde_json",
"trx-core",
"ts-rs",
]
[[package]]
@@ -3260,6 +3301,7 @@ dependencies = [
name = "trx-server"
version = "0.1.0"
dependencies = [
"base64",
"bytes",
"chrono",
"clap",
@@ -3279,12 +3321,14 @@ dependencies = [
"trx-app",
"trx-aprs",
"trx-backend",
"trx-config",
"trx-core",
"trx-cw",
"trx-decode-log",
"trx-ftx",
"trx-protocol",
"trx-reporting",
"trx-sstv",
"trx-vdes",
"trx-wefax",
"trx-wspr",
@@ -3292,6 +3336,16 @@ dependencies = [
"uuid",
]
[[package]]
name = "trx-sstv"
version = "0.1.0"
dependencies = [
"base64",
"png",
"tracing",
"trx-core",
]
[[package]]
name = "trx-vdes"
version = "0.1.0"
@@ -3330,6 +3384,29 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "ts-rs"
version = "12.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "756050066659291d47a554a9f558125db17428b073c5ffce1daf5dcb0f7231d8"
dependencies = [
"thiserror 2.0.18",
"ts-rs-macros",
"uuid",
]
[[package]]
name = "ts-rs-macros"
version = "12.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d90eea51bc7988ef9e674bf80a85ba6804739e535e9cab48e4bb34a8b652aa"
dependencies = [
"proc-macro2",
"quote",
"syn",
"termcolor",
]
[[package]]
name = "typenum"
version = "1.20.0"
+1 -1
View File
@@ -1,3 +1,3 @@
SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
SPDX-License-Identifier: BSD-2-Clause
SPDX-License-Identifier: GPL-2.0-or-later
+3 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[workspace]
members = [
@@ -12,11 +12,13 @@ members = [
"src/decoders/trx-ftx",
"src/decoders/trx-rds",
"src/decoders/trx-vdes",
"src/decoders/trx-sstv",
"src/decoders/trx-wefax",
"src/decoders/trx-wspr",
"src/trx-core",
"src/trx-protocol",
"src/trx-app",
"src/trx-config",
"src/trx-reporting",
"src/trx-server",
"src/trx-server/trx-backend",
-143
View File
@@ -1,143 +0,0 @@
# Fix Plan
Current state analysis of trx-rs as of 2026-04-08.
## Overall Assessment
The codebase is in good shape. Clippy is clean, no `unsafe` code, no TODO/FIXME markers,
robust error handling throughout. One broken test and several untested crates are the
main weak spots.
---
## P0 — Broken Test
### 1. `test_toggle_ft8_decode` returns 500 instead of 200
**Location:** `src/trx-client/trx-frontend/trx-frontend-http/src/api/mod.rs:1016`
**Root cause:** The handler `toggle_ft8_decode` (decoder.rs:353) requires
`context: web::Data<Arc<FrontendRuntimeContext>>` for multi-rig state resolution.
The test registers `state_rx` and `rig_tx` but not `context`, so actix-web returns 500
(missing app data). A `make_context()` helper already exists at line 757 but is unused
by this test.
**Fix:** Add `.app_data(web::Data::new(make_context()))` to the test's `App` builder
(line 1036-1041). ~1 line change.
**Impact:** This is the only failing test in the entire suite (50 pass, 1 fail).
---
## P1 — Test Coverage Gaps
### 2. trx-aprs decoder — 0 tests (596 LOC)
**Location:** `src/decoders/trx-aprs/src/lib.rs`
Bell 202 AFSK demodulator + AX.25 HDLC frame parser + CRC-16 validation.
No `#[cfg(test)]` module at all.
**Suggested tests:**
- CRC-16 computation on known frames
- HDLC flag detection and bit-unstuffing
- Full frame decode from synthetic AFSK audio (1200 baud sine pairs)
- Rejection of corrupted frames (bad CRC, truncated)
### 3. trx-decode-log — 0 tests (226 LOC)
**Location:** `src/decoders/trx-decode-log/src/lib.rs`
JSON Lines file writer with date-based rotation. Pure I/O wrapper.
**Suggested tests:**
- Write + read-back round-trip in a tempdir
- Date rotation triggers new file creation
- Flush error logging (mock writer)
### 4. trx-reporting — partial tests (1,065 LOC across 2 files)
**Location:** `src/trx-reporting/src/pskreporter.rs` (582 LOC),
`src/trx-reporting/src/aprsfi.rs` (483 LOC)
Both files have `#[cfg(test)]` modules but coverage is limited to serialization.
Network behavior (reconnect, rate-limit, batching) is untested.
**Suggested tests:**
- PSKReporter UDP datagram encoding round-trip
- APRS-IS login line formatting
- Spot batching and dedup logic (unit-testable without network)
---
## P2 — Code Quality
### 5. `audio.rs` is 4,000 LOC
**Location:** `src/trx-server/src/audio.rs`
Houses all decoder task launchers (FT8, FT4, FT2, APRS, AIS, VDES, CW, WSPR, LRPT,
WEFAX). Each launcher follows the same pattern. The file is coherent but large.
**Suggested improvement:** Extract decoder launchers into a `decoders/` submodule
within trx-server, one file per decoder family (e.g., `ftx.rs`, `aprs.rs`, `wefax.rs`).
Keep the audio pipeline and capture logic in `audio.rs`.
### 6. `scheduler.rs` is 1,585 LOC
**Location:** `src/trx-client/trx-frontend/trx-frontend-http/src/scheduler.rs`
Mixes grayline computation, timespan matching, satellite pass prediction, and the
scheduler state machine. Well-tested but dense.
**Suggested improvement:** Extract grayline and satellite pass logic into separate
modules (these are pure functions with no HTTP dependencies).
---
## P3 — Minor
### 7. `#[allow(dead_code)]` in soapysdr backend (4 annotations)
**Locations:**
- `vchan_impl.rs:66,87``fixed_slot_count`, `process_pair`
- `real_iq_source.rs:20``device`
- `demod.rs:113` — lifetime anchor
All documented as intentional (lifetime anchors / reserved capacity). No action needed
unless the fields can be converted to `PhantomData` or `_`-prefixed without breaking
semantics.
### 8. FrontendRuntimeContext test helper duplication risk
**Location:** `src/trx-client/trx-frontend/trx-frontend-http/src/api/mod.rs:757`
`make_context()` and `spawn_rig_responder()` are good helpers but only used by some
tests. As new endpoint tests are added, ensure they consistently use these helpers to
avoid repeating the `test_toggle_ft8_decode` bug.
---
## Implementation Order
```mermaid
gantt
title Fix Plan
dateFormat X
axisFormat %s
section P0
Fix test_toggle_ft8_decode :p0, 0, 1
section P1
Add trx-aprs tests :p1a, 1, 3
Add trx-decode-log tests :p1b, 1, 2
Expand trx-reporting tests :p1c, 1, 3
section P2
Split audio.rs decoder launchers :p2a, 3, 5
Extract scheduler pure functions :p2b, 3, 5
```
P0 is a one-line fix. P1 items are independent and can be parallelized. P2 items are
refactors that should wait until P1 tests provide regression safety.
+338
View File
@@ -0,0 +1,338 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Moe Ghoul>, 1 April 1989
Moe Ghoul, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+434
View File
@@ -0,0 +1,434 @@
APRS symbol set (https://github.com/hessu/aprs-symbols)
=========================================================
Verbatim copy of the upstream COPYRIGHT.md, retrieved 2026-08-03 from
https://github.com/hessu/aprs-symbols. The set has no single SPDX license:
individual symbols carry different terms, summarized below. Attribution
requirement from the upstream README: "If you use this symbol set, please
provide a pointer to the source (http://github.com/hessu/aprs-symbols/)."
---
Copyright and licensing information
======================================
This is a collection of vectorized symbols for use on the APRS system.
The copyright status of this collection is a bit complicated, since the
symbols come from various sources, each having different copyright owners.
Most of the vectorized symbols are loosely based on the low-resolution
"standard" bitmap symbol set as distributed by Stephen Smith, WA8LMF. That
set is used by most APRS software around the world. The low resolution of
those symbols does not allow direct vector conversion, so I've drawn new
symbols in a similar layout. The vector versions try to mimic the original
appearance and colours, with the intention of keeping the set recognizable
and familiar to existing users. In some cases the vector versions are
probably similar enough to the originals, so that they cannot be considered
"original work" by myself. In some of these cases, the originals are
probably also mimicking someone else's design.
The original symbols do not come with any information on their licensing.
They've been distributed with a lot of APRS software over time, but I don't
know who designed which symbol originally. Most likely all of them are
drawn by one of:
* Roger Barker, G4IDE, "original set provided with UI-View" (SK)
* Steve Dimse, KH4G, "U.S. customary set"
* Stephen Smith, WA8LMF
The Adobe Illustrator (.ai) file contains a copy of the original bitmaps
as a hidden layer, just for reference.
Some symbols I obtained from other sources, such as Wikipedia. In those
cases I picked SVG versions which allow commercial reuse (source known, and
the work is placed on public domain, or with a CC license which allows
adaptation and commercial reuse).
Some symbols are vectorized versions of product or brand logos. The
copyright of those is owned by the respective companies (Apple, Microsoft,
Kenwood), and each of those may have some opinions on how the logos are
used. Please check for yourself if you can use them or not.
In the list below I try to summarize the licensing status for each symbol.
Shorthand notation for common licensing status
-------------------------------------------------
* *VEC-OH7LZB* - Vectorized by OH7LZB, based on original APRS symbol set
* Source of original bitmap: http://wa8lmf.net/aprs/APRS_symbols.htm
* Original designer of individual symbol unknown at this time, but one of:
* Roger Barker, G4IDE
* Steve Dimse, KH4G
* Stephen Smith, WA8LMF
* Vectorized versions are designed to look similar
* Licensing: Unknown
* *OH7LZB* - Original vector design by Heikki Hannikainen, OH7LZB
* Different enough (by author's opinion) to make it a new original work,
instead of a copy of the old symbol
* License: CC BY-SA 2.0
* https://creativecommons.org/licenses/by-sa/2.0/
Primary table
----------------
* /! - Police station
* VEC-OH7LZB
* /# - Digipeater / Green star with D in middle
* VEC-OH7LZB
* /$ - Telephone
* VEC-OH7LZB
* /% - DX cluster
* VEC-OH7LZB
* /& - HF gateway
* VEC-OH7LZB
* /' - Small aircraft
* https://openclipart.org/detail/27182/topdown-airplane-view
* Author: Wirelizard (Brian Burger)
* With color and some other small tuning added by OH7LZB
* PD: https://openclipart.org/share
* /( - Mobile satellite station
* OH7LZB
* /) - Wheelchair, handicapped
* PD wheelchair symbol
* Vectorized from bitmap by OH7LZB
* /* - Snowmobile
* https://openclipart.org/detail/15849/snowmobile
* Author: Mystica (https://openclipart.org/user-detail/mystica)
* PD: https://openclipart.org/share
* /+ - Red Cross
* VEC-OH7LZB
* /, - Boy Scouts
* VEC-OH7LZB
* /- - House
* VEC-OH7LZB
* /. - Red X
* VEC-OH7LZB
* // - Red dot
* VEC-OH7LZB
* /0 to /9 - Numbered circles
* VEC-OH7LZB
* Fire
* http://commons.wikimedia.org/wiki/File:FireIcon.svg
* Author: Piotr Jaworski
* PD: I, the copyright holder of this work, release this work into the public domain. This applies worldwide.
* Tent
* https://openclipart.org/detail/174933/green-tent-by-stamps-174933
* Author: stamps
* PD: https://openclipart.org/share
* Motorcycle
* http://commons.wikimedia.org/wiki/File:MUTCD_W8-15P.svg
* This file is in the public domain because it comes from the Manual on
Uniform Traffic Control Devices, sign number W8-15P, which states
specifically on page I-1 that: Any traffic control device design or
application provision contained in this Manual shall be considered to
be in the public domain. Traffic control devices contained in this
Manual shall not be protected by a patent, trademark, or copyright,
except for the Interstate Shield and any other items owned by FHWA.
* Colour version by OH7LZB
* /= - Railroad engine
* http://commons.wikimedia.org/wiki/File:Icon_train.svg
* Author: http://en.wikipedia.org/wiki/User:Richtom80
* CC-BY-SA-2.5,2.0,1.0
* /> - Car
* OH7LZB
* /? - File server
* https://openclipart.org/detail/163717/file-server-by-lyte
* Author: lyte
* PD: https://openclipart.org/share
* /@ - Hurricane predicted path
* VEC-OH7LZB
* /A - Aid station
* VEC-OH7LZB
* Mail (BBS)
* https://openclipart.org/detail/29268/yellow-mail-by-rg1024-29268
* Author: rg1024
* PD: https://openclipart.org/share
* /C - Canoe
* https://openclipart.org/detail/179047/red-canoe-by-rambo-tribble-179047
* https://openclipart.org/detail/179041/canoe-paddle-by-rambo-tribble-179041
* Author: Rambo Tribble
* PD: I, the copyright holder of this work, release this work into the public domain. This applies worldwide.
* /E - Eyeball
* http://commons.wikimedia.org/wiki/File:Blue_eye.svg
* PD: "This file is from the Open Clip Art Library, which released it explicitly into the public domain"
* PD: https://openclipart.org/share
* /F - Tractor
* https://openclipart.org/detail/191654/farm-tractor-by-tmjbeary-191654
* Author: tmjbeary
* PD: https://openclipart.org/share
* /G - Grid square, 3 by 3
* VEC-OH7LZB
* /H - Hotel
* VEC-OH7LZB
* /I - TCP/IP
* VEC-OH7LZB
* /K - School
* OH7LZB
* /L - PC user
* OH7LZB
* /M - Mac apple
* Apple
* /N - NTS
* VEC-OH7LZB
* /O - Hot air balloon
* OH7LZB
* /P - Police
* OH7LZB
* /R - RV
* OH7LZB
* /S - Space Shuttle
* https://openclipart.org/detail/814/space-shuttle-by-johnny_automatic
* PD: Published by the NASA, in "The Brain in Space"
* /T - SSTV
* https://openclipart.org/detail/48997/flat-screen-by-rg1024
* Author: rg1024
* Adjusted by OH7LZB
* PD: https://openclipart.org/share
* /U - Bus
* OH7LZB
* /V - ATV, amateur television
* https://openclipart.org/detail/48997/flat-screen-by-rg1024
* Author: rg1024
* Adjusted by OH7LZB
* PD: https://openclipart.org/share
* /W - Wx, Weather service site
* VEC-OH7LZB
* /X - Helicopter
* OH7LZB
* /Y - Sailboat
* OH7LZB
* /Z - Windows flag
* Microsoft
* /[ - Human
* VEC-OH7LZB
* /\ - DF triangle
* VEC-OH7LZB
* /] - Mailbox, post office, letter
* /^ - Large aircraft
* https://openclipart.org/detail/183204/plane-red-by-sketchartist-183204
* Author: SketchArtist
* PD: https://openclipart.org/share
* /_ - Weather station
* VEC-OH7LZB
* /` - Satellite dish
* OH7LZB
* /a - Ambulance
* OH7LZB
* /b - Bicycle
* http://commons.wikimedia.org/wiki/File:Bicycle_evolution-numbers.svg
* Author: Wikipedia user: Al2
* CC BY 3.0
* /c - Incident command post
* VEC-OH7LZB
* /d - Fire station
* VEC-OH7LZB
* /e - Horse, equestrian
* https://openclipart.org/detail/142627/horse-riding-lesson-by-olku
* Author: OlKu
* PD: https://openclipart.org/share
* /f - Fire truck
* OH7LZB
* /g - Hang glider
* OH7LZB
* /h - Hospital
* VEC-OH7LZB
* /i - IOTA, islands on the air
* http://commons.wikimedia.org/wiki/File:Palm_Island_R.svg
* PI
* /j - Jeep
* OH7LZB
* /k - Truck
* OH7LZB
* /l - Laptop
* OH7LZB
* /m - Mic-E repeater
* VEC-OH7LZB
* /n - Node, black bulls-eye
* VEC-OH7LZB
* /o - Emergency operations center
* VEC-OH7LZB
* /p - Dog(e)
* OH7LZB
* /q - Grid square, 2 by 2
* VEC-OH7LZB
* /r - Repeater tower
* OH7LZB
* /s - Ship, power boat
* OH7LZB
* /t - Truck stop
* VEC-OH7LZB
* /u - Semi-trailer truck, 18-wheeler
* OH7LZB
* /v - Van
* OH7LZB
* /w - Water station
* VEC-OH7LZB
* /x - X / Unix
* https://commons.wikimedia.org/wiki/File:X11.svg
* PD
* /y - House, yagi antenna
* VEC-OH7LZB
* /z - Shelter
* VEC-OH7LZB
Secondary table
------------------
* Emergency
* VEC-OH7LZB
* Numbered digipeater / Green star
* VEC-OH7LZB
* Bank
* VEC-OH7LZB
* Numbered gateway / Black diamond
* VEC-OH7LZB
* Crash site
* OH7LZB
* Cloudy
* OH7LZB
* MEO
* VEC-OH7LZB
* Snowflake
* http://commons.wikimedia.org/wiki/File:Snowflake_01.svg
* Author: Wikipedia user: Amada44
* Public Domain
* Church
* VEC-OH7LZB
* Girl Scout
* VEC-OH7LZB
* Looks slightly like the common USA girl scouts logos. Should be different
enough to not infringe on "Girl Scouts of the USA" copyrights.
* Home (HF antenna)
* VEC-OH7LZB
* Unknown position
* VEC-OH7LZB
* Destination
* VEC-OH7LZB
* Numbered circle
* VEC-OH7LZB
* Petrol Station
* OH7LZB
* Hail
* VEC-OH7LZB
* Park
* VEC-OH7LZB
* Gale Flag
* VEC-OH7LZB
* Red car from above
* OH7LZB
* Info Kiosk
* VEC-OH7LZB
* Hurricane
* OH7LZB
* Numbered white box
* VEC-OH7LZB
* Snow blowing
* VEC-OH7LZB
* Coast Guard
* VEC-OH7LZB
* Drizzle
* VEC-OH7LZB
* Smoke / Chimney
* VEC-OH7LZB
* Freezing rain
* VEC-OH7LZB
* Snow Shwr
* VEC-OH7LZB
* Haze
* VEC-OH7LZB
* Rain Shower
* VEC-OH7LZB
* Lightning
* OH7LZB
* "Kenwood radio"
* Kenwood logo, vectorized
* "Lighthouse"
* CC BY-SA 2.0
* http://wiki.openstreetmap.org/wiki/File:Lighthouse.svg
* Nav Buoy
* OH7LZB
* Rocket
* http://www.clker.com/clipart-gglkuglug.html
* PD according to clker.com license
* Parking
* VEC-OH7LZB
* Earthquake, Restaurant
* VEC-OH7LZB
* Satellite
* OH7LZB
* Thunderstorm
* OH7LZB
* Sunny
* OH7LZB
* VORTAC, Numbered WXS
* VEC-OH7LZB
* Pharmacy Rx
* OH7LZB
* Wall Cloud
* OH7LZB
* Numbered plane
* https://openclipart.org/detail/183204/plane-red-by-sketchartist-183204
* Author: SketchArtist
* PD: https://openclipart.org/share
* Numbered WX Station
* VEC-OH7LZB
* Rain
* Source: http://commons.wikimedia.org/wiki/File:Heavy-rain-shower-transparent.svg
* Author: Wikipedia user: Peepo
* Public Domain
* With modifications by OH7LZB
* Numbered diamond
* VEC-OH7LZB
* Dust blowing
* NA
* Numbered civil defence
* VEC-OH7LZB
* DX spot
* VEC-OH7LZB
* Sleet
* NA
* Funnel Cloud
* NA
* Gale
* VEC-OH7LZB
* Store
* https://openclipart.org/detail/89299/cart-medium-by-martins.bruvelis
* Author: martins.bruvelis
* Public Domain
* Adjustments by OH7LZB
* Numbered black box
* VEC-OH7LZB
* Work zone / Excavator
* Based on http://www.clker.com/clipart-292480.html PNG version
* Vectorized and colors adjusted by OH7LZB
* PD according to clker.com documentation, uploader KURSVEIAL
* SUV
* OH7LZB
* Milepost, Numbered triangle, Circle sm
* VEC-OH7LZB
* Partly cloudy
* OH7LZB
* Restrooms, Numbered boat
* VEC-OH7LZB
* Tornado (also used in Funnel cloud, Skywarn)
* https://openclipart.org/detail/104887/tornado-by-laabadon
* Author: Laabadon
* Public Domain
* Numbered truck
* OH7LZB
* Numbered van
* OH7LZB
* Flooding
* NA
* Sky warn, Numbered shelter, fog
* VEC-OH7LZB
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+43
View File
@@ -0,0 +1,43 @@
SIL OPEN FONT LICENSE
Version 1.1 - 26 February 2007
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
+29 -10
View File
@@ -5,7 +5,7 @@
A modular amateur radio control stack written in Rust.
[![License](https://img.shields.io/badge/license-BSD--2--Clause-blue.svg)](LICENSES)
[![License](https://img.shields.io/badge/license-GPL--2.0--or--later-blue.svg)](LICENSES)
</div>
@@ -64,9 +64,15 @@ brew install soapysdr
```
</details>
See [Build Requirements](https://github.com/sgrams/trx-rs/wiki/User-Manual#build-requirements)
See [Build Requirements](https://git.haxx.space/sjg/trx-rs/wiki/User-Manual#build-requirements)
in the wiki for details on each library.
> **Note:** `cmake` is required even when a system Opus library is installed.
> The `audiopus_sys` crate probes for Opus via `pkg-config`; if it is not found
> (or `pkg-config` is unavailable), it falls back to compiling a vendored copy
> of Opus with CMake. A missing `cmake` therefore fails the build with
> `is cmake not installed?` rather than a missing-Opus error.
### 2. Build
```bash
@@ -87,13 +93,17 @@ The wizard walks you through rig selection, serial port detection, audio
settings, and frontend options, then writes `trx-server.toml` and
`trx-client.toml`.
Alternatively, generate example configs and edit them by hand:
Alternatively, copy `trx-rs.toml.example` — a commented example covering every
setting — and edit it by hand:
```bash
./target/release/trx-server --print-config > trx-server.toml
./target/release/trx-client --print-config > trx-client.toml
cp trx-rs.toml.example trx-rs.toml
./target/release/trx-server --check-config --config trx-rs.toml
```
`--check-config` reports everything wrong with a config without starting
anything. `--print-config` prints the same settings without comments.
### 4. Run
```bash
@@ -101,6 +111,9 @@ Alternatively, generate example configs and edit them by hand:
./target/release/trx-client --config trx-client.toml
```
A single `trx-rs.toml` can configure both: the server reads its `[trx-server]`
section and the client reads `[trx-client]`.
Open the configured HTTP frontend address in a browser (default `http://localhost:8080`).
## How It Works
@@ -127,12 +140,18 @@ a unified set of frontends.
| Resource | Description |
|----------|-------------|
| [User Manual](https://github.com/sgrams/trx-rs/wiki/User-Manual) | Configuration, features, and usage |
| [Architecture](https://github.com/sgrams/trx-rs/wiki/Architecture) | System design, crate layout, data flow, and internals |
| [Optimization Guidelines](https://github.com/sgrams/trx-rs/wiki/Optimization-Guidelines) | Performance guidelines for the real-time DSP pipeline |
| [Planned Features](https://github.com/sgrams/trx-rs/wiki/Planned-Features) | Roadmap and design notes |
| [User Manual](https://git.haxx.space/sjg/trx-rs/wiki/User-Manual) | Configuration, features, and usage |
| [Architecture](https://git.haxx.space/sjg/trx-rs/wiki/Architecture) | System design, crate layout, data flow, and internals |
| [Optimization Guidelines](https://git.haxx.space/sjg/trx-rs/wiki/Optimization-Guidelines) | Performance guidelines for the real-time DSP pipeline |
| [Planned Features](https://git.haxx.space/sjg/trx-rs/wiki/Planned-Features) | Roadmap and design notes |
| [Contributing](CONTRIBUTING.md) | Commit conventions, workflow, and code style |
## License
BSD-2-Clause. See [`LICENSES`](LICENSES) for bundled third-party license files.
GPL-2.0-or-later. See [`LICENSES`](LICENSES) for the full license text and
bundled third-party license files. Bundled third-party components retain their
original licenses: Leaflet is BSD-2-Clause, DSEG is OFL-1.1, and opus-decoder
is MIT. The APRS symbol sprites come from
[hessu/aprs-symbols](https://github.com/hessu/aprs-symbols); their per-symbol
copyright status is catalogued in
[`LICENSES/LicenseRef-APRS-Symbols.txt`](LICENSES/LicenseRef-APRS-Symbols.txt).
+74
View File
@@ -0,0 +1,74 @@
version = 1
# Project-owned files without an in-file SPDX header (docs, config,
# repo metadata, logos, and bespoke web assets).
[[annotations]]
path = [
".gitattributes",
".gitignore",
"CLAUDE.md",
"CONTRIBUTING.md",
"README.md",
"trx-rs.toml.example",
"docs/**",
"aidocs/**",
"container/**",
".devcontainer/**",
"src/decoders/trx-ftx/README.md",
"src/decoders/trx-wxsat/README.md",
"assets/trx-logo.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/trx-favicon.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/trx-logo.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/bandplan.json",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/generated/**",
"src/trx-client/trx-frontend/trx-frontend-http/frontend/package.json",
"src/trx-client/trx-frontend/trx-frontend-http/frontend/package-lock.json",
"src/trx-client/trx-frontend/trx-frontend-http/frontend/tsconfig.json",
"src/trx-client/trx-frontend/trx-frontend-http/frontend/tsconfig.worker.json",
]
SPDX-FileCopyrightText = "2026 Stan Grams <sjg@haxx.space>"
SPDX-License-Identifier = "GPL-2.0-or-later"
# Vendored Leaflet 1.9.4 (https://leafletjs.com), distributed under BSD-2-Clause.
[[annotations]]
path = [
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/leaflet.js",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/leaflet.css",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/layers.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/layers-2x.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/marker-icon.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/marker-icon-2x.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/marker-shadow.png",
]
SPDX-FileCopyrightText = "2010-2023 Vladimir Agafonkin, 2010-2011 CloudMade"
SPDX-License-Identifier = "BSD-2-Clause"
# Vendored DSEG14 font (https://github.com/keshikan/DSEG), SIL OFL 1.1.
[[annotations]]
path = ["src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/dseg14-classic-latin-400-normal.woff2"]
SPDX-FileCopyrightText = "2020 The DSEG Authors (https://github.com/keshikan/DSEG)"
SPDX-License-Identifier = "OFL-1.1"
# Vendored opus-decoder 0.7.11 browser build
# (https://github.com/eshaz/wasm-audio-decoders), MIT.
# SHA-256: fd73ee0a9c8a5e233c0b88234df14f46003ad89bb4ba27435bc8714db2a6dc62
[[annotations]]
path = ["src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/opus-decoder-0.7.11.min.js"]
SPDX-FileCopyrightText = "2021-2025 Ethan Halsall"
SPDX-License-Identifier = "MIT"
# Vendored APRS symbol sprites (https://github.com/hessu/aprs-symbols), rev H.
# The set has no single upstream license -- individual symbols carry different
# terms, catalogued in LICENSES/LicenseRef-APRS-Symbols.txt. Upstream asks that
# users point back to https://github.com/hessu/aprs-symbols/.
[[annotations]]
path = [
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/aprs-symbols-24-0.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/aprs-symbols-24-1.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/aprs-symbols-24-2.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/aprs-symbols-24-0-2x.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/aprs-symbols-24-1-2x.png",
"src/trx-client/trx-frontend/trx-frontend-http/assets/web/vendor/aprs-symbols-24-2-2x.png",
]
SPDX-FileCopyrightText = "Heikki Hannikainen OH7LZB and the APRS symbol set authors (https://github.com/hessu/aprs-symbols)"
SPDX-License-Identifier = "LicenseRef-APRS-Symbols"
+89
View File
@@ -0,0 +1,89 @@
# Work In Progress — Project Improvement Areas
Living tracker for engineering-infrastructure and hardening work identified
during a July 2026 repo scan. The architecture-level backlog
(`docs/Improvement-Areas.md`, P0P3) is closed; these items focus on the
tooling, robustness, and product concerns *around* the code.
Status legend: **Done** · **In progress** · **Not started**
| # | Tier | Area | Status |
|----|------|------|--------|
| 1 | 1 — Infrastructure | Gitea Actions CI (fmt, clippy, test, REUSE) | In progress |
| 2 | 1 — Infrastructure | Supply-chain & lint governance (cargo-deny/audit, MSRV, `[workspace.lints]`) | Not started |
| 3 | 1 — Infrastructure | Release & deployment (container image, systemd units, binary releases) | Not started |
| 4 | 2 — Robustness | Panic-resilience audit (harden ~495 unwrap/expect/panic sites) | Not started |
| 5 | 2 — Robustness | `unsafe` SIMD safety scaffolding (`# Safety` docs, scalar↔SIMD equivalence tests) | Not started |
| 6 | 2 — Robustness | DSP performance benchmarks (criterion, guard optimization gains) | Not started |
| 7 | 2 — Robustness | Test-coverage measurement & gap-filling (llvm-cov; CAT backends, server tasks) | Not started |
| 8 | 3 — Product | Frontend modularization & tooling (split `app.js` into ES modules, ESLint, JS tests) | Not started |
| 9 | 3 — Product | Runtime observability (`/health`, Prometheus metrics) | Not started |
| 10 | 3 — Product | Documentation freshness & consolidation (reconcile `docs/` with code) | Not started |
## Tier 1 — Infrastructure gaps
### 1. Gitea Actions CI
No `.gitea/` / `.github/` / Woodpecker workflows exist, despite 768 tests.
Add a workflow running `cargo fmt --check`, `cargo clippy -D warnings`,
`cargo build`/`cargo test`, and REUSE lint on push + pull_request.
System deps: `pkg-config cmake libopus-dev libasound2-dev libsoapysdr-dev`
(the `soapysdr` backend is a default feature).
Notes for the runner: assumes an `act_runner` registered with an
`ubuntu-latest` label and GitHub-action proxying enabled (used by
`actions/checkout`, `actions/cache`, `fsfe/reuse-action`). `clippy` runs
with `-D warnings`; core crates are already clean, but if the first full
`--all-features` run surfaces warnings in a less-travelled crate, fix them
(preferred) or temporarily soften that step.
### 2. Supply-chain & lint governance
No `deny.toml`, `cargo audit`, `rustfmt.toml`/`clippy.toml`, declared MSRV,
or `[workspace.lints]`. Add dependency auditing to CI, pin an MSRV
(`rust-version`), and centralize lint policy in the workspace manifest.
### 3. Release & deployment
No `Dockerfile`, systemd units, packaging, or release automation (only
`script/dummy-server.sh`). Add a container image, example systemd units for
`trx-server`/`trx-client`, and a tag-triggered static-binary release job.
## Tier 2 — Robustness & correctness
### 4. Panic-resilience audit
495 `unwrap()`/`expect()`/`panic!` sites, 11 in the hottest server files
(`audio.rs`, `rig_task.rs`). A panic there can drop a rig task or the
process. Convert hot-path panics to error propagation / graceful
degradation; reserve `expect` for documented invariants.
### 5. `unsafe` SIMD safety scaffolding
13 `unsafe` blocks (AVX2 DSP). Add `# Safety` docs stating invariants,
confirm runtime feature detection is tested, and add property tests
asserting SIMD output matches the scalar fallback across random inputs.
### 6. DSP performance benchmarks
`docs/Optimization-Guidelines.md` documents NCO/polyphase/AVX2 gains, but no
`criterion` benches guard them. Add benches for the demod/resample/FFT hot
paths so regressions surface as numbers.
### 7. Test-coverage measurement & gap-filling
67 of 146 Rust files have no test module. Protocol is well covered; backends
(CAT BCD/ASCII encoding), `listener.rs`, and `config.rs` look thin. Wire up
`cargo-llvm-cov` and target the CAT backends and server tasks first.
## Tier 3 — Product & maintainability
### 8. Frontend modularization & tooling
`app.js` is 8,760 lines and `map-core.js` 3,515, with no modules, linter, or
tests. Keeping vanilla HTML+JS (no framework), split into native ES modules
by concern, add ESLint + Prettier, and add `node:test` unit tests for pure
logic (frequency formatting, unit math, decode parsing).
### 9. Runtime observability
`tracing` is set up, but there is no `/health` endpoint or metrics
instrumentation. Add health/readiness endpoints and Prometheus-format
metrics (decode rates, reconnects, audio underruns, per-rig state).
### 10. Documentation freshness & consolidation
`docs/` (13 files) is mostly dated 2026-03-29 while code moved into July, and
mixes planning artifacts with reference docs. Reconcile against current code,
separate "plans" from "reference," and fold still-true content into the
canonical docs.
+68
View File
@@ -0,0 +1,68 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: GPL-2.0-or-later
# trx-rs SDK / build image.
#
# Single source of truth for the build environment. Used two ways:
# * CI — as the job container for the lint/test jobs (Docker executor).
# * Dev — run locally or via .devcontainer for a reproducible toolchain.
#
# Pinning the Rust version here (and in rust-toolchain.toml) means CI and every
# developer share the exact same rustc/clippy, so "works locally, fails in CI"
# cannot happen.
FROM docker.io/library/debian:bookworm-slim
# Keep in sync with rust-toolchain.toml.
ARG RUST_VERSION=1.97.1
ARG NODE_MAJOR=20
ENV DEBIAN_FRONTEND=noninteractive \
RUSTUP_HOME=/usr/local/rustup \
CARGO_HOME=/usr/local/cargo \
PATH=/usr/local/cargo/bin:/usr/local/bin:/usr/bin:/bin
# Build dependencies (mirror README's manual instructions).
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates curl git \
build-essential pkg-config cmake clang libclang-dev \
libopus-dev libasound2-dev libsoapysdr-dev chromium \
&& rm -rf /var/lib/apt/lists/*
# Node.js — JS-based actions (actions/checkout, actions/cache) run *inside*
# the job container under the Docker executor, so node must be present.
RUN curl -fsSL https://deb.nodesource.com/setup_${NODE_MAJOR}.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
&& rm -rf /var/lib/apt/lists/*
# Pinned Rust toolchain, installed world-readable so any UID the runner or a
# devcontainer uses can invoke cargo.
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --no-modify-path \
--default-toolchain "${RUST_VERSION}" --profile minimal \
--component rustfmt --component clippy \
&& chmod -R a+rwX "$RUSTUP_HOME" "$CARGO_HOME"
# sccache — shared compilation cache. Enabled at build time via
# RUSTC_WRAPPER (see the CI workflow and .devcontainer), not repo-wide, so
# non-SDK builds are unaffected. musl build is static and runs anywhere.
#
# The release asset is per-architecture, so resolve it from `uname -m` rather
# than hardcoding one triple: everything else in this image is arch-agnostic,
# and a pinned x86_64 URL is what forces an amd64 build (and Rosetta or qemu)
# on an arm64 host. `uname -m` reflects the build platform under plain
# docker/podman build as well as buildx, unlike the BuildKit-only TARGETARCH.
ARG SCCACHE_VERSION=0.8.2
RUN set -eux; \
case "$(uname -m)" in \
x86_64) sccache_arch=x86_64 ;; \
aarch64|arm64) sccache_arch=aarch64 ;; \
*) echo "unsupported architecture for sccache: $(uname -m)" >&2; exit 1 ;; \
esac; \
sccache_dist="sccache-v${SCCACHE_VERSION}-${sccache_arch}-unknown-linux-musl"; \
curl -fsSL "https://github.com/mozilla/sccache/releases/download/v${SCCACHE_VERSION}/${sccache_dist}.tar.gz" \
| tar -xz -C /tmp; \
install -m755 "/tmp/${sccache_dist}/sccache" /usr/local/bin/sccache; \
rm -rf /tmp/sccache-*
WORKDIR /work
+193
View File
@@ -0,0 +1,193 @@
<!--
SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
SPDX-License-Identifier: GPL-2.0-or-later
-->
# trx-rs SDK image
A single container image that is the canonical build environment for trx-rs,
used **both** by CI and by developers. It bakes in the pinned Rust toolchain
(matching `rust-toolchain.toml`) and every build dependency, so the compiler
and `clippy` are identical everywhere — no "works on my machine".
| File | Purpose |
|------|---------|
| `Containerfile` | The SDK image (Debian + build deps + pinned Rust + Node + git). |
| `runner-config.example.yaml` | Example act_runner config for the CI VM (Docker executor). |
## Build and publish
Nothing in the image is architecture-specific: the base image, the Debian build
dependencies, Node.js, `rustup` and the `sccache` release all resolve per
architecture, so the same `Containerfile` builds natively on x86_64 and arm64.
Single architecture — the tag then only works on the architecture you built it
on:
```bash
# from the repo root
podman build -t git.haxx.space/sjg/trx-rs/sdk:latest container
podman login git.haxx.space
podman push git.haxx.space/sjg/trx-rs/sdk:latest
```
**Both architectures without emulation.** The CI runner is x86_64 and Apple
Silicon developer machines are arm64, so `:latest` has to be a manifest list —
a single-architecture tag makes the other side fall back to Rosetta or qemu.
Build each half natively on a host of that architecture, then join them:
```bash
# on an x86_64 host
podman build --platform linux/amd64 -t git.haxx.space/sjg/trx-rs/sdk:latest-amd64 container
podman push git.haxx.space/sjg/trx-rs/sdk:latest-amd64
# on an arm64 host
podman build --platform linux/arm64 -t git.haxx.space/sjg/trx-rs/sdk:latest-arm64 container
podman push git.haxx.space/sjg/trx-rs/sdk:latest-arm64
# from either, once both are pushed
podman manifest create git.haxx.space/sjg/trx-rs/sdk:latest \
git.haxx.space/sjg/trx-rs/sdk:latest-amd64 \
git.haxx.space/sjg/trx-rs/sdk:latest-arm64
podman manifest push --all git.haxx.space/sjg/trx-rs/sdk:latest
```
Building both from one machine is a single command
(`podman build --platform linux/amd64,linux/arm64 --manifest ...`), but the
foreign half runs under emulation and is slow — the two-host flow above is
what keeps every build native.
Tag with the Rust version too (e.g. `:1.97.1`) if you want reproducible pins.
Make the package **public** (Gitea → Packages → the image → Settings) so the CI
runner and developers can pull it without credentials. If you keep it private,
add `credentials:` under the workflow's `container:` and log the runner into the
registry.
Pushing a rebuilt image is not enough on its own: `:latest` is a moving tag, and
act_runner reuses whatever it cached the first time unless `force_pull: true` is
set (see `runner-config.example.yaml`). Without it the job log says
`Image exists? true` and the run behaves as though the image were never
rebuilt — a tool added to the `Containerfile` reads as missing from the image.
Either set `force_pull`, or refresh the VM's copy by hand:
```bash
docker pull git.haxx.space/sjg/trx-rs/sdk:latest
docker run --rm git.haxx.space/sjg/trx-rs/sdk:latest sccache --version
```
### macOS note
Apple's `container` CLI builds through a BuildKit helper VM that is configured
with Rosetta whether or not the target is x86_64, so `container build` fails
with *"Rosetta is not installed"* on a clean machine. That is a property of the
builder, not of this image — `container run` works natively without it. Either
install Rosetta once (`softwareupdate --install-rosetta`, after which an arm64
build still produces a native arm64 image), or build with Podman, whose arm64
BuildKit needs no emulation.
## Developer use
Reproducible one-off build, no local toolchain needed:
```bash
podman run --rm -it -v "$PWD":/work -w /work \
git.haxx.space/sjg/trx-rs/sdk:latest \
cargo build --release
```
Or open the repo in the image via VS Code / JetBrains "Reopen in Container"
(`.devcontainer/devcontainer.json` points at the same image).
Building outside the container? `rust-toolchain.toml` pins the same rustc, so
`rustup` installs the matching toolchain automatically.
## CI use
`.gitea/workflows/ci.yml` runs the `lint`, `test` and `frontend` jobs *inside*
this image via the `container:` key, so they skip all setup and go straight to
`cargo` and `npm`. The frontend job needs three things from the image beyond
Rust: Node.js for the toolchain, Chromium at `/usr/bin/chromium` for the
browser smoke test, and `cargo``npm run verify-generated` regenerates the
Rust wire contracts before checking for drift.
The `reuse` job stays on the upstream `fsfe/reuse-action` (a Docker action the
Docker executor launches as a sibling container) — nothing REUSE-related is
baked into the SDK, and it lints the whole repository, so no job runs its own
licence check.
## Compilation cache (sccache)
The SDK image ships [`sccache`](https://github.com/mozilla/sccache). It is
enabled via `RUSTC_WRAPPER=sccache` in CI and the devcontainer (not repo-wide,
so plain `cargo` builds outside the SDK are unaffected).
- **CI** persists the cache on the runner host — create the dir once:
`mkdir -p /var/cache/sccache`. It is bind-mounted into each job container at
`/sccache` (see `runner-config.example.yaml`), so cache survives across runs
and is shared between the lint/test jobs and both projects.
- **Devcontainer** uses a named volume (`trx-rs-sccache`).
- Check effectiveness with `sccache --show-stats` (the CI jobs print it).
`CARGO_INCREMENTAL=0` is set wherever sccache is on, since sccache cannot cache
incremental artifacts.
## CI runner (Alpine / OpenRC)
The runner uses the **Docker executor** (not the host executor): per-job
container isolation and standard `ubuntu-latest` semantics. `act_runner` runs
as an OpenRC service. Files provided:
| File | Purpose |
|------|---------|
| `act_runner.openrc` | OpenRC init script (`supervise-daemon`, depends on docker). |
| `act_runner.confd.example` | Per-instance `conf.d` settings for multi-runner hosts. |
**Cap the thread budget.** In a VM, pin its vCPUs to specific host threads
(libvirt/KVM):
```xml
<vcpu placement='static'>2</vcpu>
<cputune>
<vcpupin vcpu='0' cpuset='4'/>
<vcpupin vcpu='1' cpuset='5'/>
</cputune>
```
On bare metal, the `container.options: "--cpus=2"` and `capacity: 1` in
`runner-config.example.yaml` already bound each runner.
**Set it up:**
```bash
# 1. Docker + a dedicated user with socket access
apk add docker docker-cli
rc-update add docker default && rc-service docker start
adduser -S -D -H -h /var/lib/act_runner act
addgroup act docker
# 2. act_runner binary (static Go build, works on musl)
# Upstream publishes per-architecture builds; pick the host's.
case "$(uname -m)" in x86_64) arch=amd64 ;; aarch64) arch=arm64 ;; esac
curl -fsSL -o /usr/local/bin/act_runner \
"https://gitea.com/gitea/act_runner/releases/download/v0.2.11/act_runner-0.2.11-linux-${arch}"
chmod +x /usr/local/bin/act_runner
# 3. Config + register one runner per project (scope keeps their jobs apart)
install -Dm644 container/runner-config.example.yaml /etc/act_runner/trx-rs.yaml
install -d -o act /var/lib/act_runner/trx-rs
su act -s /bin/sh -c 'cd /var/lib/act_runner/trx-rs && \
act_runner register --no-interactive \
--instance https://git.haxx.space --token <TOKEN> \
--name trx-rs-ci \
--labels "ubuntu-latest:docker://catthehacker/ubuntu:act-latest"'
# 4. OpenRC service (repeat the symlink+conf.d for the second project)
install -m755 container/act_runner.openrc /etc/init.d/act_runner
ln -s act_runner /etc/init.d/act_runner.trx-rs
install -m644 container/act_runner.confd.example /etc/conf.d/act_runner.trx-rs
rc-update add act_runner.trx-rs default
rc-service act_runner.trx-rs start
```
Check it with `rc-service act_runner.trx-rs status` and
`tail -f /var/log/act_runner.trx-rs.log`.
+14
View File
@@ -0,0 +1,14 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Per-instance settings for an act_runner OpenRC service.
# Copy to /etc/conf.d/<service-name>, e.g. /etc/conf.d/act_runner.trx-rs
# (the name must match the /etc/init.d/ symlink).
# User that runs the daemon. Must be a member of the `docker` group.
runner_user="act"
# Per-instance state dir (holds the .runner registration) and config file,
# so two runners on one host stay independent.
runner_dir="/var/lib/act_runner/trx-rs"
runner_config="/etc/act_runner/trx-rs.yaml"
+44
View File
@@ -0,0 +1,44 @@
#!/sbin/openrc-run
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
# SPDX-License-Identifier: GPL-2.0-or-later
#
# OpenRC service for a Gitea act_runner (Docker executor) on Alpine.
#
# Install as /etc/init.d/act_runner (chmod +x). Single instance uses
# /etc/act_runner/config.yaml. For one runner per project, symlink this script
# and add a matching conf.d file:
#
# ln -s act_runner /etc/init.d/act_runner.trx-rs
# cp container/act_runner.confd.example /etc/conf.d/act_runner.trx-rs
# $EDITOR /etc/conf.d/act_runner.trx-rs # set runner_dir / runner_config
# rc-update add act_runner.trx-rs default
# rc-service act_runner.trx-rs start
description="Gitea Actions runner"
: "${runner_user:=act}"
: "${runner_dir:=/var/lib/act_runner}"
: "${runner_config:=/etc/act_runner/config.yaml}"
command="/usr/local/bin/act_runner"
command_args="daemon --config ${runner_config}"
# No group given, so supplementary groups (incl. docker) are initialised.
command_user="${runner_user}"
directory="${runner_dir}"
supervisor="supervise-daemon"
respawn_delay=5
respawn_max=0
pidfile="/run/${RC_SVCNAME}.pid"
output_log="/var/log/${RC_SVCNAME}.log"
error_log="/var/log/${RC_SVCNAME}.log"
depend() {
need docker
use net dns
}
start_pre() {
checkpath -d -m 0750 -o "${runner_user}" "${runner_dir}"
checkpath -f -m 0640 -o "${runner_user}" "${output_log}"
}
+47
View File
@@ -0,0 +1,47 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Example act_runner config for the Docker-executor runner that lives in the
# CI VM. This is NOT the SDK image — it configures the runner that launches
# per-job containers (including the trx-rs SDK image referenced by the
# workflow's `container:` key). Copy to the VM and pass with
# `act_runner daemon --config`.
log:
level: info
runner:
file: .runner
# One concurrent job. With one runner per project on a 2-vCPU VM this keeps
# total CI usage at ~2 threads.
capacity: 1
timeout: 3h
# Docker executor: no ":host" suffix. Maps runs-on labels to base images
# (the workflow overrides these per job via `container:`).
labels:
- "ubuntu-latest:docker://catthehacker/ubuntu:act-latest"
cache:
enabled: true
container:
# Cap every job container's CPU so CI stays within the 2-thread budget even
# if capacity is raised later. The -v mount persists the sccache cache on the
# host (create it first: `mkdir -p /var/cache/sccache`), matching SCCACHE_DIR
# in the workflow.
options: "--cpus=2 -v /var/cache/sccache:/sccache"
# act_runner rejects every bind mount unless it is listed here — the default
# is an empty allowlist, so the -v above is dropped with only a
# "[...] is not a valid volume, will be ignored" line in the job log, and
# SCCACHE_DIR then points at a directory that does not outlive the job.
valid_volumes:
- /var/cache/sccache
# Reuse the host VM's Docker network for the built-in cache/artifact server.
network: "host"
# The workflow pulls the SDK image by the moving `:latest` tag. Without this
# the runner logs "Image exists? true" and reuses whatever it cached the
# first time, so pushing a rebuilt image has no effect until someone pulls
# on the VM by hand — which looks like the image is missing a tool it in
# fact has. The extra registry round-trip per job is nothing next to a build.
force_pull: true
+6 -2
View File
@@ -1,9 +1,13 @@
# RDS Parameter Tuning — Work in Progress
# RDS Parameter Tuning Notes
*Decoder tuning rationale for `trx-rds`. Recorded 2026-03-27; reflects the
shipped parameter set. Kept as a reference for why these constants were chosen —
not an open work item.*
## Goal
Maximum sensitivity (weak-signal decode) with zero false positive PI decodes.
## Changes Made
## Changes Applied
### `src/decoders/trx-rds/src/lib.rs`
+116
View File
@@ -0,0 +1,116 @@
# Spectrum Controls — Visual Rework
The strip between the spectrum and the radio controls (`#spectrum-controls`)
holds eight controls in two groups. This proposes how it should *look*.
Every control stays, in its current order, with its current name and its
current behaviour. Nothing here changes what a button does, what commits when,
or what is stored. It is a styling and layout change.
*Status: implemented. Kept as the record of what was changed and why.*
---
## What it looks like now
```
Bandwidth [ 12 ] kHz [Set] [Auto BW] [Sweet-spot] Peak Hold [2 s] Floor [-115] dB Range [90] dB [Auto] Contrast [——●——] 1.0
```
Four problems, all of them visual:
**1. Four different control heights on one line.** The bare number inputs, the
buttons, the `select` and the range slider are each sized by their own rule, so
nothing shares a baseline and the row reads as a pile rather than a strip.
**2. Units are loose text.** `kHz`, `dB`, `dB` and the contrast value `1.0` are
text nodes sitting outside the control they belong to, separated from it by a
gap the same size as the gap between unrelated controls. The eye has to work
out which number owns which unit.
**3. A quarter of the strip is a hole.** `justify-content: space-between` puts
about 250 px of nothing in the middle at 1600 px, and the two groups read as
two unrelated things because the only thing between them is emptiness.
**4. The groups stagger between 1100 and 1400 px.** The bandwidth group wraps
to two lines while the level group stays on one, so the level group floats at a
height of its own, aligned with neither line of the group beside it. This is
the worst of it, and it happens at a common window width.
Two smaller things: 24 px controls are below any touch-target guideline, and
the contrast readout has no fixed width, so the row twitches as the value
changes between `1.0` and `0.9`.
## Proposed
**One control height, units inside their field, and a rule where the clusters
meet.**
- **A field is one box.** Label, value and unit share a single bordered box —
`Bandwidth │ 12.0 │ kHz` — so a number and its unit can never be read apart.
Fields, buttons, the peak-hold select and the contrast slider are all 1.7 rem
tall, on 44 px targets under a coarse pointer.
- **A rule, not a hole.** The two clusters are separated by a thin vertical
rule with normal spacing either side. The slack goes to a flexible spacer, so
the strip is left-aligned rather than pushed apart.
- **A cluster never splits.** Each cluster is `nowrap`; the container wraps. If
a cluster does not fit on the line it drops whole to the next one,
left-aligned with the one above. No staggering, at any width.
- **Rules fall away at line starts.** A cluster that begins a line has no rule
hanging off its left edge.
- **The contrast readout gets a fixed, tabular slot**, so the row is still.
Below the existing mobile breakpoint the strip already stacks; the same field
component applies there, which is most of what makes it look deliberate.
## What this does not change
`Set` stays. `Auto BW` and `Auto` keep their names, even though they mean
different things — that is a naming question, not a styling one. Sweet-spot
stays where it is and keeps its behaviour. Nothing gains or loses persistence.
Nothing moves into a popover, and no control is hidden behind a click.
Those are all worth arguing about separately; a note of them is at the end of
this file so the arguments are not lost.
## Implementation
One pass, no behaviour touched:
1. `.spectrum-field` and `.spectrum-btn` in `style.css`, replacing the six
per-id rules (`#spectrum-bw-input`, `#spectrum-floor-input`,
`#spectrum-range-input`, `#spectrum-bw-label`, `#spectrum-floor-label`,
`#spectrum-range-label`) that currently repeat the same declarations.
2. Markup in `index.html`: the loose `kHz` / `dB` text nodes move inside their
label, which keeps every id and every event handler exactly where it is.
3. `#spectrum-controls` becomes a wrapping flex row with a spacer;
`#spectrum-bw-row` and `#spectrum-level-row` become `nowrap` clusters with a
left rule.
4. The mobile block in the media query drops the rules it no longer needs.
`app.ts` is not touched. Every id survives, so the existing handlers, the
`spectrum-layout.mjs` geometry test and the broadcast-layout highlight all keep
working.
### Tests
Extend `spectrum-layout.mjs`, which already measures this area:
- Every control in the strip shares one height, at 1600, 1200 and 900 px.
- No two clusters sit at different vertical offsets on the same line — the
staggering bug, asserted directly.
- The strip never overflows its container and never overlaps the hint line.
---
## Noted for later, not proposed here
Behavioural observations from reading the code, kept so they are not lost:
- `Auto BW` (filter) and `Auto` (display scaling) are both called Auto, 600 px
apart.
- `Floor`, `Range` and `Contrast` are not persisted; `Peak Hold` is.
- `Auto` and `Auto BW` are one-shot: no state, nothing to turn off.
- `Sweet-spot` retunes the SDR and waits up to 1.4 s per candidate centre, with
no busy indication.
- Contrast resets on a double-click that nothing advertises.
+232 -22
View File
@@ -17,30 +17,61 @@ frontends.
## Configuration
Both `trx-server` and `trx-client` use TOML configuration files. Use
`--print-config` to generate a fully commented example.
Both `trx-server` and `trx-client` read TOML. The server takes its settings
from the `[trx-server]` section and the client from `[trx-client]`, so one
`trx-rs.toml` can configure both — or each may live in its own file with the
section header left off.
`trx-rs.toml.example` in the repository root is a complete, commented example
generated from the config definitions themselves. `--print-config` prints the
same settings without the comments.
### File Locations
**trx-server** lookup order:
1. `--config <FILE>`
2. `./trx-server.toml`
3. `~/.trx-server.toml`
4. `~/.config/trx-rs/server.toml`
5. `/etc/trx-rs/server.toml`
Both binaries use the same lookup order:
**trx-client** lookup order:
1. `--config <FILE>`
2. `./trx-client.toml`
3. `~/.config/trx-rs/client.toml`
4. `/etc/trx-rs/client.toml`
2. `./trx-rs.toml`
3. `~/.config/trx-rs/trx-rs.toml`
4. `/etc/trx-rs/trx-rs.toml`
CLI arguments override config file values.
### Environment Variables
### Checking a Config
- `TRX_PLUGIN_DIRS`: additional plugin directories (path-separated), used by
both server and client.
`--check-config` loads the file, reports every problem it finds — unknown keys,
invalid values, listeners fighting over a port — and exits without starting
anything:
```bash
trx-server --check-config --config trx-rs.toml
trx-client --check-config --config trx-rs.toml
```
Unknown keys are warnings by default, so a config written for a newer version
still runs on an older binary. `--strict-config` makes them fatal.
`trx-configurator --check <FILE>` runs the same checks.
### Environment Variables and Secrets
Any string in the config may reference an environment variable as `${VAR}`;
an unset variable is an error rather than an empty value.
Credentials can be kept out of the config entirely by pointing at a file
instead. Every secret has a `*_file` sibling — set one or the other, never
both:
| Inline key | File key | Contents |
|------------|----------|----------|
| `[listen.auth].tokens` | `tokens_file` | one token per line |
| `[[remotes]].auth.token` | `token_file` | the token |
| `[frontends.http.auth].rx_passphrase` | `rx_passphrase_file` | the passphrase |
| `[frontends.http.auth].control_passphrase` | `control_passphrase_file` | the passphrase |
| `[frontends.http_json.auth].tokens` | `tokens_file` | one token per line |
Blank lines and `#` comments are ignored in the list files. A config that holds
credentials inline and is readable by group or others is flagged at startup.
### Server Options
@@ -96,6 +127,7 @@ CLI arguments override config file values.
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `tokens` | string[] | `[]` | Allowed auth tokens (empty = no auth) |
| `tokens_file` | string | — | Read tokens from this file, one per line |
#### `[audio]`
@@ -121,6 +153,13 @@ When audio is enabled, at least one of `rx_enabled` or `tx_enabled` must be true
| `sample_rate` | u32 | `1920000` | IQ capture rate in Hz |
| `bandwidth` | u32 | `1500000` | Hardware IF filter bandwidth in Hz |
| `center_offset_hz` | i64 | `100000` | Offset from dial to avoid DC spur |
| `spectrum_fft_size` | usize | `1024` | Spectrum FFT bins; power of two, 1288192 |
| `spectrum_interval_ms` | u64 | `50` | How often a spectrum frame is pushed to subscribed clients |
Spectrum is the largest thing on the client connection. On a slow or
high-latency link, halving `spectrum_fft_size` halves the bytes per frame (at
half the frequency resolution) and raising `spectrum_interval_ms` sends fewer of
them; see [Spectrum over a slow link](#spectrum-over-a-slow-link).
#### `[sdr.gain]`
@@ -197,6 +236,29 @@ Notes:
Files are appended in JSON Lines format. Supported date tokens: `%YYYY%`,
`%MM%`, `%DD%` (UTC).
#### `[decoders]`
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | string[] | all decoders | Decoders to run for this rig |
| `output_dir` | string | `"$XDG_CACHE_HOME/trx-rs"` | Base directory for decoders that write images |
Valid decoder names: `aprs`, `aprs_hf`, `ais`, `cw`, `ft2`, `ft4`, `ft8`,
`lrpt`, `sstv`, `vdes`, `wefax`, `wspr` — the same names `[[sdr.channels]]`
uses. An unrecognised name is a config error.
Every decoder runs by default, which costs real CPU on a small machine. On a
station that only works digital modes, listing just what you use is worth it:
```toml
[decoders]
enabled = ["ft8", "ft4", "wspr"]
```
`sstv`, `wefax` and `lrpt` write images into a subdirectory of `output_dir`
named after the decoder. `ais` and `vdes` additionally require an SDR channel
configured to feed them.
#### Multi-Rig Configuration
Use `[[rigs]]` arrays instead of the flat `[rig]` section for multi-rig setups:
@@ -240,12 +302,32 @@ Rigs without an explicit `id` get auto-generated IDs like `ft817_0`, `soapysdr_1
|-------|------|---------|-------------|
| `url` | string | — | Server address (e.g. `localhost:4530`) |
| `poll_interval_ms` | u64 | `750` | State poll interval |
| `spectrum_interval_ms` | u64 | `50` | Spectrum frame interval; also settable per `[[remotes]]` entry |
#### `[remote.auth]`
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `token` | string | — | Auth token (must not be empty if set) |
| `token_file` | string | — | Read the token from this file instead |
#### `[[remotes]]`
Preferred over the single `[remote]` section: one entry per rig, each mapping a
short name to a server and an optional server-side rig id.
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `name` | string | — | Short name used everywhere in the client |
| `url` | string | — | Server address (`host:port`) |
| `rig_id` | string | — | Rig id on a multi-rig server |
| `auth.token` | string | — | Auth token |
| `auth.token_file` | string | — | Read the token from this file instead |
| `poll_interval_ms` | u64 | `750` | State poll interval |
The `name` is the key used by `default_rig_name`, `rigctl.rig_ports`,
`audio.rig_urls`, `audio.rig_ports` and `decode_history_retention_min_by_rig`.
A name in any of those maps that no remote answers to is a config error.
#### `[frontends.http]`
@@ -254,6 +336,31 @@ Rigs without an explicit `id` get auto-generated IDs like `ft817_0`, `soapysdr_1
| `enabled` | bool | `true` | Enable web UI |
| `listen` | ip | `127.0.0.1` | Bind address |
| `port` | u16 | `8080` | Bind port |
| `default_rig_name` | string | — | Remote selected on startup |
| `initial_map_zoom` | u8 | `10` | Starting zoom for the APRS map |
| `show_sdr_gain_control` | bool | `true` | Expose the RF gain control |
| `bandplan_enabled` | bool | `true` | Show the bandplan strip |
| `bandplan_region` | string | `"iaru_r1"` | `iaru_r1`, `iaru_r2`, or `iaru_r3` |
| `decode_history_retention_min` | u64 | `1440` | Decode history retention |
| `decode_history_retention_min_by_rig` | table | `{}` | Per-remote retention override |
| `spectrum_coverage_margin_hz` | u32 | `50000` | Centre-retune guard margin |
| `spectrum_usable_span_ratio` | f32 | `0.92` | Usable fraction of the sampled span |
#### `[frontends.http.auth]`
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `false` | Require a passphrase |
| `rx_passphrase` | string | — | Passphrase granting receive-only access |
| `rx_passphrase_file` | string | — | Read it from this file instead |
| `control_passphrase` | string | — | Passphrase granting full control |
| `control_passphrase_file` | string | — | Read it from this file instead |
| `tx_access_control_enabled` | bool | `true` | Hide TX from unauthenticated users |
| `session_ttl_min` | u64 | `480` | Session lifetime |
| `cookie_secure` | bool | `false` | Set Secure on the session cookie (needs HTTPS) |
| `cookie_same_site` | string | `"Lax"` | `Strict`, `Lax`, or `None` |
With `enabled = true`, at least one passphrase must be set.
#### `[frontends.rigctl]`
@@ -261,7 +368,11 @@ Rigs without an explicit `id` get auto-generated IDs like `ft817_0`, `soapysdr_1
|-------|------|---------|-------------|
| `enabled` | bool | `false` | Enable Hamlib rigctl |
| `listen` | ip | `127.0.0.1` | Bind address |
| `port` | u16 | `4532` | Bind port |
| `rig_ports` | table | `{}` | Remote name → local port; one listener each |
One listener is started per `rig_ports` entry, each routing to its rig, so
`rig_ports` must name at least one remote when the frontend is enabled. The
older single `port` key and `--rigctl-port` are ignored.
#### `[frontends.http_json]`
@@ -271,13 +382,17 @@ Rigs without an explicit `id` get auto-generated IDs like `ft817_0`, `soapysdr_1
| `listen` | ip | `127.0.0.1` | Bind address |
| `port` | u16 | `0` | Bind port (0 = ephemeral) |
| `auth.tokens` | string[] | `[]` | Allowed auth tokens |
| `auth.tokens_file` | string | — | Read tokens from this file, one per line |
#### `[frontends.audio]`
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `true` | Enable audio client |
| `server_port` | u16 | `4531` | Server audio port |
| `server_url` | string | — | Audio endpoint for every remote |
| `rig_urls` | table | `{}` | Remote name → audio URL (wins over `server_url`) |
| `server_port` | u16 | `4531` | Fallback port when no URL is configured |
| `rig_ports` | table | `{}` | Remote name → port; superseded by `rig_urls` |
| `bridge.enabled` | bool | `false` | Enable local CPAL audio bridge |
| `bridge.rx_output_device` | string | — | Local playback device |
| `bridge.tx_input_device` | string | — | Local capture device |
@@ -287,16 +402,111 @@ Rigs without an explicit `id` get auto-generated IDs like `ft817_0`, `soapysdr_1
The bridge is intended for WSJT-X integration via virtual audio devices (ALSA
loopback on Linux, BlackHole on macOS).
### Spectrum over a slow link
Spectrum dominates the server↔client connection: everything else is a few
hundred bytes, a frame is a few kilobytes. Three things govern what it costs.
**Frames are pushed, not polled.** The client subscribes and the server sends
frames at `[sdr].spectrum_interval_ms`. Polling cost a round trip per frame, so
the rate was capped at 1/RTT — on a 200 ms link you could not exceed 5 frames a
second however often the client asked. Clients fall back to polling
automatically against a server too old to stream.
**Bins travel as whole dBFS.** They are base64-encoded `i8` on the wire, about
an eighth of the JSON array of floats they used to be, at the resolution the
display draws anyway.
**Both ends have a rate, and the slower one wins.** The server pushes no faster
than `[sdr].spectrum_interval_ms`; the client asks for no more than
`[[remotes]].spectrum_interval_ms`.
For a link that struggles, start here:
```toml
[trx-server.sdr]
spectrum_fft_size = 512 # half the bins, half the bytes
spectrum_interval_ms = 200 # 5 frames/s instead of 20
[[trx-client.remotes]]
name = "remote-site"
url = "radio.example.com:4530"
spectrum_interval_ms = 200
```
That is roughly 0.7 KB per frame at 5 frames/s — about 3.5 KB/s, against
roughly 200 KB/s for 1024 float bins at 20 frames/s.
### CLI Override Summary
**trx-server:**
`--config`, `--print-config`, `--rig`, `--access`, `--callsign`, `--listen`,
`--port`. SDR options are file-only.
`--config`, `--print-config`, `--check-config`, `--strict-config`, `--rig`,
`--access`, `--callsign`, `--listen`, `--port`. SDR options are file-only.
**trx-client:**
`--config`, `--print-config`, `--url`, `--token`, `--poll-interval`,
`--frontend`, `--http-listen`, `--http-port`, `--rigctl-listen`,
`--rigctl-port`, `--http-json-listen`, `--http-json-port`, `--callsign`.
`--config`, `--print-config`, `--check-config`, `--strict-config`, `--url`,
`--token`, `--poll-interval`, `--rig-id`, `--frontend`, `--http-listen`,
`--http-port`, `--rigctl-listen`, `--http-json-listen`, `--http-json-port`,
`--callsign`.
`--listen` on the server overrides the bind address of both the control
listener and every rig's audio listener.
---
## Multiple Rigs in the Web UI
A client connected to several rigs decodes all of them at once, whichever one
is on screen. The rig picker in the header decides which rig the UI is about,
and each page answers that differently:
| Page | Shows |
|------|-------|
| Radio | The selected rig: its spectrum, its audio, and the mini decode views over the waterfall. |
| Digital Modes | The selected rig: every decoder panel, its counts and its status line. |
| Map | The whole station — every rig's positions, with the map's own rig filter to narrow it. |
| Statistics | The whole station, including the per-rig comparison. |
Switching rigs repaints the radio and digital modes pages for the rig now
selected. Nothing is lost by switching: the traffic other rigs heard is still
held, and switching back brings it up again. The one exception is the CW pane,
which is a single running stream of copied text rather than a list of frames,
so it starts empty on the rig you switch to.
Each browser tab keeps its own selection, so two tabs can watch two rigs.
---
## Tune Links
Every page of the web UI carries what the radio is doing in its address, so the
URL in the address bar is always a link someone else can open:
```
http://receiver.example:8080/?rig=sdr&f=14074000&mode=USB&bw=3000
```
| Parameter | Meaning |
|-----------|---------|
| `f` | Frequency. Hz by default; `7074k` and `14.074M` also work. |
| `mode` | Demodulation mode, e.g. `USB`, `CW`, `WFM`. |
| `bw` | Filter bandwidth in Hz. Ignored by rigs without filter control. |
| `rig` | Rig to select first, by id, on a multi-rig client. |
Opening such a link selects the rig, sets the mode, tunes, and applies the
bandwidth, in that order — a mode change carries its own default bandwidth, so
an explicit `bw` is applied last. Anything the rig cannot do (an unknown mode,
a frequency outside its range) is reported and the rest of the link still
applies. All four parameters are optional.
The link button in the top bar copies the current link to the clipboard. The
address bar itself is updated as you tune, using `replaceState`, so sweeping
the dial does not fill the browser's history.
Applying a link changes the radio, so it needs the `control` role; an `rx`
session opens the page and says the link was not applied. Links describe the
rig's own dial — while a tab is listening to a virtual channel the address is
left as it was, rather than publishing a frequency the rig is not on.
---
+87
View File
@@ -0,0 +1,87 @@
<!--
SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
SPDX-License-Identifier: GPL-2.0-or-later
-->
# Frontend architecture
The HTTP frontend is a strict TypeScript application built with esbuild. Rust
embeds deterministic JavaScript output from `assets/web/generated`; Cargo does
not run Node.js or contact the network.
## Runtime graph
`frontend/src/bootstrap.ts` is the only first-party script referenced by the
HTML document. Its imports establish startup order for WebGL support, shared UI
services, decoder dispatch, the local Leaflet AIS adapter, and the application
coordinator. Leaflet and the Opus decoder remain isolated vendored scripts.
Feature entries under `frontend/src/plugins` are ESM bundles. The typed plugin
loader imports them by feature group and keeps expensive map, scheduling, and
decoder behavior lazy. Shared code is emitted as content-hashed chunks. The
decode-history worker is an independent entry compiled against Web Worker
globals.
Dependencies point from application and feature code toward `core` and `api`.
`api/generated.ts` contains Rust wire formats; `api/client.ts` and focused
parsers validate untrusted HTTP, SSE, WebSocket, and worker data before it is
used as typed application state.
## Browser host contract
Separate lazy bundles cannot share module instances with the stable application
entry, so they use three intentional host namespaces:
| Global | Purpose | Mutation policy |
| --- | --- | --- |
| `window.trx` | Application state, core services, and feature registrations | The root is frozen; lazy features may register only their documented `modules.*` service. |
| `window.trxPluginRuntime` | Typed decoder registration and message dispatch | Runtime object is installed once; plugins register lifecycle handlers through its API. |
| `window.trxUi` | Notifications, confirmations, tab accessibility, and control presentation | Installed once by `ui-core.ts`; consumers call methods but do not replace them. |
`frontend/src/plugins/host.ts` declares the typed view of `window.trx.state`
and `window.trx.core` that feature bundles consume. Feature entries import it
instead of re-deriving the contract, so a service that moves out of the
application entry is added in one place. Application state that a feature needs
belongs in `trx.state`, and shared behavior belongs in `trx.core`; a feature
that has to intercept application behavior registers a `modules.*` method the
application calls, as the virtual-channel entry does for tuning, mode,
bandwidth, and frequency display.
The WebGL adapter exposes `createTrxWebGlRenderer`, `trxParseCssColor`,
`trxHslToRgba`, and `trxClearCssColorCache` for the application bundle. Leaflet
adds `L.TrxAisTrackSymbol` and `L.trxAisTrackSymbol` to the vendored Leaflet
namespace.
The following transitional properties are explicitly part of the lazy-feature
host contract and are declared in `app.ts`: `lastSpectrumData`, `lastFreqHz`,
`currentBandwidthHz`, `ft8BaseHz`, `getDecodeHistoryRetentionMs`,
`applyDecodeHistoryRetention`, `getDecodeRigMeta`, `renderRdsOverlays`,
`buildAisVesselUrl`, `trxScheduleUiFrameJob`,
`takeSchedulerControlForDecoderDisable`, `navigateToTab`, `_syncRecorderState`,
and `refreshRdsUi`. Optional callbacks owned by lazy features are
`refreshCwTonePicker`, `updateFt8RfDisplay`, `clearSatPredictionDom`,
`syncWefaxToggle`, `updateAisBar`, `updateVdesBar`, `updateAprsBar`,
`updateFt8Bar`, `updateSatLiveState`, `applyCwAutoUi`, and
`applyCwAutoUiFromServer`.
This list is closed: new standalone mutable `window` properties are not an
accepted integration mechanism. Extend an existing typed service or introduce
an imported interface instead. Removing transitional properties as feature
boundaries become directly importable remains preferable.
## Build and verification
The generated directory is removed before every build, preventing orphaned
compatibility bundles. Stable feature entry names are allowlisted by the Rust
asset manifest; shared chunks use content hashes. The generic Rust handler
rejects unknown names and unsupported MIME types and serves embedded assets
with compression, ETags, and immutable caching.
CI installs from `package-lock.json`, caches only npm downloads, type-checks the
window and worker environments separately, lints, runs unit and DOM tests,
starts the application in Chromium, regenerates Rust contracts and bundles,
checks for drift, and runs REUSE validation after generation.
See `frontend/src/README.md` for local commands and
`docs/ts-migration-plan.md` for the migration decisions and completion gates.
+5 -1
View File
@@ -7,7 +7,11 @@ trx-rs web frontend (`trx-frontend-http`). The frontend is a single-page
application served as embedded static assets (gzip-compressed with ETag
caching) from the Actix-Web server.
## Current asset inventory
## Historical asset inventory
This inventory records the frontend before the TypeScript migration. The
first-party JavaScript copies listed here have since been replaced by strict
TypeScript source and deterministic output under `assets/web/generated`.
| File | Lines | Size |
|------|------:|-----:|
+50
View File
@@ -0,0 +1,50 @@
<!--
SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
SPDX-License-Identifier: GPL-2.0-or-later
-->
# TypeScript migration baseline
This baseline records the browser architecture at the start of the migration.
It is intentionally historical; generated output sizes are tracked separately
by the deterministic frontend build.
## Startup order
The initial document loads these scripts in order:
1. `/vendor/opus-decoder-0.7.11.min.js`
2. `/vendor/leaflet.js`
3. `/leaflet-ais-tracksymbol.js`
4. `/webgl-renderer.js`
5. `/ui-core.js`
6. `/app.js`
Decoder and feature scripts are then loaded lazily by the inline loader in
`index.html`. The frontend smoke test locks the core ordering and rejects
remote script or stylesheet URLs.
## Source measurements
At baseline, first-party JavaScript comprised 23 files and approximately
776 KiB. The largest sources were:
| Source | Bytes |
|---|---:|
| `app.js` | 337,111 |
| `map-core.js` | 131,899 |
| `plugins/scheduler.js` | 60,883 |
| `plugins/bookmarks.js` | 30,543 |
| `plugins/sat.js` | 22,541 |
| `plugins/vchan.js` | 20,195 |
| `webgl-renderer.js` | 18,993 |
The migrated source snapshot contained 123 distinct direct `window.*`
assignments. These are compatibility callbacks, shared state, and plugin entry
points. New TypeScript code must not add to that set; the typed plugin registry
and explicit services replace it over the course of the migration.
All production scripts, stylesheets, fonts, icons, and map assets were already
served from local embedded routes. The automated startup test ensures no
remote runtime script or stylesheet dependency is introduced.
+586
View File
@@ -0,0 +1,586 @@
<!--
SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
SPDX-License-Identifier: GPL-2.0-or-later
-->
# TypeScript Migration Plan
> **Scope**: `src/trx-client/trx-frontend/trx-frontend-http/`
>
> **Status**: Complete (2026-08-01)
## Implementation result
The migration was completed on `feat/typescript-frontend-migration`. The
baseline and phased sections below are retained as the decision record; their
descriptions of JavaScript files and classic loading refer to the pre-migration
state.
Completion evidence:
- all first-party browser sources are strict `.ts` files, checked by separate
DOM and Web Worker TypeScript projects with no JavaScript compatibility mode
or suppression directives;
- `bootstrap.ts` is the single first-party HTML entry and esbuild represents
startup order, lazy feature imports, shared hashed chunks, and the worker in
its module graph;
- obsolete source and generated compatibility JavaScript was removed;
- Rust generates rig, status, capability, decoder, and flattened frontend
metadata contracts into `api/generated.ts`; runtime guards validate HTTP,
SSE, WebSocket, and worker boundaries;
- the generic embedded-asset handler serves a build-generated allowlist with
constrained MIME types, compression, ETags, immutable caching, and no file
system lookup;
- intentional browser host namespaces and transitional lazy-feature properties
are documented in `docs/frontend-architecture.md`;
- CI uses locked npm dependencies, caches npm downloads rather than
`node_modules`, runs strict type checking and linting, unit/DOM/worker tests,
Chromium startup coverage, generated-output drift checks, and REUSE after
generation;
- Cargo continues to consume committed generated assets without invoking Node
or requiring network access.
The final local gate ran `npm ci`, type checking, linting, 30 frontend tests,
the Chromium smoke flow (startup, auth gate, audio controls, rig switching, map
initialization, and navigation), generated-contract and bundle verification,
workspace formatting, Clippy with warnings denied, all-target builds, workspace
tests, and REUSE 3.3 validation.
## 1. Decision
Migrating the web frontend to TypeScript is worthwhile, provided it is used to
remove implicit contracts and global coupling. Renaming JavaScript files to
`.ts` without changing their boundaries would add tooling without delivering
the main safety benefits.
The migration must be incremental. Every intermediate commit and pull request
must leave the frontend buildable and usable.
## 2. Baseline State
The frontend currently contains roughly 21,700 lines of first-party
JavaScript. Its largest components include:
- `app.js`: approximately 8,900 lines;
- `map-core.js`: approximately 3,500 lines;
- `plugins/scheduler.js`: approximately 1,500 lines;
- `plugins/bookmarks.js`: approximately 800 lines;
- `plugins/vchan.js`: approximately 560 lines.
Important characteristics of the current architecture are:
- scripts are embedded individually into the Rust binary with `include_str!`;
- the Rust HTTP server exposes an explicit route for each asset;
- plugins are loaded dynamically as classic scripts;
- script order is significant;
- modules communicate through `window.*`, `window.trx`, callbacks, and shared
mutable state;
- the main HTML file contains the plugin loader;
- a Web Worker is loaded through a fixed URL;
- Cargo builds do not require Node.js;
- CI images contain Node.js, but CI currently runs only Rust and REUSE checks;
- Leaflet, Opus decoder, fonts, images, and other vendored assets are local.
These constraints make a big-bang rewrite unnecessarily risky.
## 3. Goals
The migration should:
1. Create checked contracts between Rust responses and browser code.
2. Replace global callbacks with explicit module interfaces.
3. Split `app.js` by responsibility.
4. Make rig, capability, decoder, scheduler, audio, and spectrum state explicit.
5. Preserve lazy loading for expensive features.
6. Add frontend type checking, linting, and automated tests to CI.
7. Keep ordinary Cargo builds independent of Node.js and network access.
8. Preserve existing browser behavior throughout the migration.
## 4. Non-Goals
The migration will not initially:
- introduce a UI framework;
- redesign the user interface;
- convert vendored JavaScript to TypeScript;
- change REST, SSE, WebSocket, or worker protocols unless required to make an
existing contract unambiguous;
- make `build.rs` install packages or download frontend dependencies;
- convert all of `app.js` in one pull request.
## 5. Target Layout
```text
trx-frontend-http/
├── frontend/
│ ├── package.json
│ ├── package-lock.json
│ ├── tsconfig.json
│ ├── tsconfig.worker.json
│ ├── build.mjs
│ ├── src/
│ │ ├── bootstrap.ts
│ │ ├── api/
│ │ │ ├── client.ts
│ │ │ └── generated.ts
│ │ ├── core/
│ │ │ ├── dom.ts
│ │ │ ├── events.ts
│ │ │ ├── settings.ts
│ │ │ └── state.ts
│ │ ├── features/
│ │ │ ├── audio/
│ │ │ ├── bookmarks/
│ │ │ ├── map/
│ │ │ ├── navigation/
│ │ │ ├── radio/
│ │ │ ├── recorder/
│ │ │ ├── scheduler/
│ │ │ └── spectrum/
│ │ ├── decoders/
│ │ ├── workers/
│ │ └── legacy/
│ │ └── global-bridge.ts
│ └── tests/
└── assets/web/
├── generated/
├── vendor/
├── index.html
├── style.css
└── themes.css
```
The exact feature directories may evolve, but dependencies should point from
features toward `core` and `api`, never from `core` back into features.
## 6. Tooling
Use TypeScript for type checking and esbuild for bundling. A framework-specific
development server is not needed.
Recommended compiler baseline:
```json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"useUnknownInCatchVariables": true,
"noEmit": true,
"lib": ["ES2022", "DOM"]
}
}
```
Worker code should use a separate configuration with `WebWorker` rather than
`DOM` globals.
The package scripts should provide at least:
```text
npm run typecheck
npm run lint
npm test
npm run build
npm run verify-generated
```
Pin dependencies in `package-lock.json`. New package and generated files must
carry or inherit valid REUSE licensing information.
## 7. Cargo and Asset Integration
Cargo must remain usable on machines without Node.js. Do not invoke `npm`
automatically from `build.rs`.
The initial integration should work as follows:
1. TypeScript and JavaScript sources live under `frontend/src`.
2. esbuild writes browser-ready output under `assets/web/generated`.
3. Generated browser output is committed to the repository.
4. Rust embeds generated output, not TypeScript source.
5. CI rebuilds the frontend and fails if committed output is stale.
During early phases, retain the existing public URLs, including:
```text
/app.js
/ui-core.js
/map-core.js
/scheduler.js
/decode-history-worker.js
```
Keeping these URLs stable avoids coupling the first migration phases to changes
in HTML loading, authentication rules, caching, or Rust routing.
After modules and code splitting are established, replace the explicit list of
Rust constants and handlers with an embedded generated-asset directory. The
server must still enforce an allowlist, correct MIME types, cache headers, and
path traversal protection.
## 8. Rust-to-TypeScript Contracts
Generate TypeScript definitions from Rust wire types instead of maintaining
parallel handwritten representations.
Initial candidates include:
- `RigState`, `RigInfo`, and `RigCapabilities`;
- the `/rigs` response;
- decoder registry entries;
- scheduler configuration and status;
- filter and spectrum state;
- recorder responses;
- SSE update payloads;
- decoded-message variants;
- WebSocket control and status messages.
A generator such as `ts-rs` can produce
`frontend/src/api/generated.ts`. Generated definitions should describe only
wire formats. UI state and view models should remain handwritten.
CI must regenerate these definitions and fail when the working tree changes.
Serde renames, tagged enums, optional fields, flattened values, and numeric
ranges must be checked explicitly during the initial generator integration.
TypeScript types do not validate data at runtime. Critical compatibility
boundaries should retain focused runtime checks for missing or malformed data,
particularly when clients and servers may run different versions.
## 9. Target Module Contracts
Plugins should eventually implement an explicit interface rather than assigning
callbacks to `window`:
```ts
interface TrxPlugin {
readonly id: string;
initialize(context: PluginContext): void | Promise<void>;
dispose?(): void;
}
interface PluginContext {
api: TrxApi;
events: TrxEventBus;
navigation: NavigationService;
notifications: NotificationService;
state: ReadonlyRadioState;
}
```
During the transition, `legacy/global-bridge.ts` may expose the minimum globals
required by unmigrated scripts. The bridge must shrink as migration progresses;
new feature code must not add new global callbacks.
State should be divided by responsibility rather than replaced by one large
typed global:
```ts
interface RadioState {
activeRigId: string | null;
capabilities: RigCapabilities | null;
connection: ConnectionState;
frequencyHz: number | null;
mode: RigMode | null;
bandwidthHz: number | null;
}
interface AudioState {
rx: AudioStreamState;
tx: AudioStreamState;
volume: VolumeState;
}
interface DecoderState {
registry: DecoderDescriptor[];
status: ReadonlyMap<DecoderId, DecoderStatus>;
}
```
Commands should receive a rig ID explicitly. They must not infer their target
from mutable global selection state after an asynchronous operation begins.
## 10. Migration Phases
### Phase 0: Baseline and Measurements
- Record current asset names, sizes, and load order.
- Add a browser startup smoke test.
- Record existing global symbols and plugin callbacks.
- Confirm that generated bundles do not introduce remote runtime dependencies.
**Exit criterion:** current behavior and asset loading have an automated
baseline.
### Phase 1: Tooling Scaffold
- Add the frontend package, lockfile, TypeScript configuration, and esbuild.
- Allow existing JavaScript as build input without type checking it globally.
- Produce fixed-name outputs matching current URLs.
- Add frontend commands and CI checks.
- Document local frontend development commands.
**Exit criterion:** existing JavaScript passes through the frontend build with
no runtime changes, and CI detects stale generated output.
### Phase 2: Generated API Types
- Add Rust-to-TypeScript type generation.
- Generate the first status, rig, capability, and decoder contracts.
- Introduce a typed fetch/post client and typed SSE decoding boundary.
- Keep narrow runtime guards at compatibility boundaries.
**Exit criterion:** new API consumers cannot use untyped response objects.
### Phase 3: Core Browser Services
Convert or create:
- DOM lookup helpers;
- notifications and confirmations;
- settings and per-rig preferences;
- navigation;
- the event bus;
- application state stores;
- plugin registry and loader.
Convert `ui-core.js` as the first strict TypeScript entry.
**Exit criterion:** shared UI behavior is TypeScript, tested, and does not add
new globals.
### Phase 4: Independent Leaf Modules
Convert lower-coupling code first:
1. WebGL renderer;
2. decode-history worker;
3. screenshot support;
4. FT2 and FT4;
5. WSPR;
6. CW and other decoder views.
Workers must be separate build entries.
**Exit criterion:** each converted module has typed inputs, outputs, and tests.
### Phase 5: Plugin Loading
- Move the inline loader out of `index.html`.
- Replace classic-script injection with typed dynamic imports.
- Register plugins through `TrxPlugin`.
- Preserve lazy loading by tab and feature.
- Remove the corresponding global callbacks after each plugin migrates.
**Exit criterion:** plugin dependencies and loading order are represented by the
module graph rather than implicit script order.
### Phase 6: Split the Main Application
Extract `app.js` by responsibility:
1. authentication and API transport;
2. rig enumeration and switching;
3. radio commands and capabilities;
4. audio streaming;
5. spectrum state and rendering;
6. decode history;
7. recorder;
8. keyboard shortcuts;
9. application bootstrap.
Do not split by arbitrary line ranges. Each extraction must establish an
explicit interface and remove the corresponding globals.
**Exit criterion:** the bootstrap file composes services and features but does
not contain their implementations.
### Phase 7: High-Coupling Features
Convert the remaining large features after the core contracts are stable:
- scheduler and satellite scheduler;
- bookmarks;
- virtual channels;
- map and map-backed statistics;
- remaining decoder plugins.
**Exit criterion:** no first-party classic scripts or untyped plugin callbacks
remain.
### Phase 8: Asset-Server Consolidation
- Enable code splitting and hashed chunks.
- Embed the generated asset directory in Rust.
- Serve generated assets through a generic, allowlisted handler.
- Add appropriate immutable caching for hashed output.
- Retain stable handling for HTML and version metadata.
- Remove obsolete fixed-asset constants and handlers.
**Exit criterion:** Rust no longer needs a source edit for every generated
frontend chunk.
### Phase 9: Strictness and Cleanup
- Remove `allowJs`.
- Remove the legacy global bridge.
- Enable all selected strict compiler and lint rules.
- Remove obsolete generated compatibility bundles.
- Update architecture and contributor documentation.
**Exit criterion:** all first-party frontend source is strict TypeScript and the
browser runtime exposes only intentionally documented globals.
## 11. Testing Strategy
Frontend CI should run:
```sh
npm ci
npm run typecheck
npm run lint
npm test
npm run build
git diff --exit-code -- assets/web/generated frontend/src/api/generated.ts
```
Testing should cover four layers:
1. **Pure unit tests** for bandwidth calculations, formatting, state changes,
capability decisions, and message routing.
2. **DOM component tests** for dialogs, tabs, workspace selection, rig
switching, and collapsible control sections.
3. **Worker tests** for decode-history pruning, batching, and message formats.
4. **Browser smoke tests** for startup, authentication gating, plugin loading,
navigation, rig switching, audio controls, and map initialization.
The existing dependency-free `ui-core` test can remain during the scaffold
phase. It should be moved to the standard TypeScript test runner once that
runner is established.
## 12. CI Changes
Add a dedicated frontend job rather than hiding frontend work inside the Cargo
jobs. The job should:
- use the Node.js version provided by the runner image;
- run with `npm ci`, never a mutable install;
- cache the npm download cache, not `node_modules`;
- type-check, lint, test, and build;
- verify generated artifacts and Rust-generated types are current;
- run REUSE validation after generated files are produced.
Rust lint and test jobs should continue to consume committed generated assets.
## 13. Pull Request Strategy
Use small, independently reversible pull requests. A recommended sequence is:
1. tooling and unchanged JavaScript build;
2. generated Rust wire types and typed API client;
3. `ui-core` conversion;
4. worker and WebGL conversion;
5. decoder plugin conversions in small groups;
6. plugin registry and dynamic imports;
7. one `app.js` responsibility per PR;
8. scheduler, bookmarks, and map conversions;
9. generic embedded asset serving;
10. removal of JavaScript compatibility mode.
Every PR should include:
- runtime behavior preserved or intentionally documented;
- frontend type checking and tests;
- strict Rust formatting and Clippy;
- generated-artifact drift verification;
- no newly introduced undocumented `window` globals;
- no remote runtime asset dependency.
## 14. Risks and Mitigations
### Superficial Conversion
**Risk:** globals receive declarations but remain coupled and mutable.
**Mitigation:** require every converted module to expose explicit inputs and
outputs and remove at least the globals it replaces.
### Cargo Becomes Dependent on Node
**Risk:** builds fail on systems without Node or network access.
**Mitigation:** commit deterministic generated output and keep npm outside
`build.rs`.
### Script-Order Regressions
**Risk:** switching to modules changes execution timing and scope.
**Mitigation:** retain current public entries initially, then replace script
loading only after the plugin registry is in place.
### Unreviewable `app.js` Rewrite
**Risk:** a large conversion is difficult to review, test, or bisect.
**Mitigation:** extract one responsibility at a time and keep bootstrap working
after every extraction.
### Rust and Browser Contracts Drift
**Risk:** TypeScript compiles against stale wire definitions.
**Mitigation:** generate types from Rust and enforce a clean working tree after
generation in CI.
### Generated Asset Noise
**Risk:** committed bundles make reviews noisy.
**Mitigation:** separate source and generated commits when useful, include
source maps, and require deterministic output.
### Bundle or Startup Regression
**Risk:** bundling loads too much code eagerly.
**Mitigation:** record the current baseline, preserve feature-level lazy loads,
and track entry/chunk sizes in CI.
## 15. Initial Proof of Concept
The first implementation PR should be deliberately limited to:
1. adding the frontend package and locked toolchain;
2. building existing JavaScript to fixed-name generated output;
3. adding frontend CI and drift checks;
4. generating initial rig/status TypeScript definitions;
5. introducing the typed API client;
6. converting `ui-core.js` to strict TypeScript;
7. preserving every existing asset URL and observable behavior.
This proof of concept is the decision gate for the remainder of the migration.
If it materially improves contract safety without making Cargo development
unwieldy, continue with the phased plan. If it does not, the repository can
retain the tooling and the converted core without committing to a full rewrite.
## 16. Completion Criteria
The migration is complete when:
- all first-party browser source is strict TypeScript;
- vendor files remain isolated and declared through narrow type adapters;
- Rust wire types generate their browser contracts;
- no feature depends on accidental script ordering;
- no undocumented mutable `window` callbacks remain;
- `app.js` has been replaced by a small typed bootstrap and feature modules;
- frontend type checking, linting, unit tests, component tests, browser smoke
tests, and generated-output checks run in CI;
- Cargo builds remain possible without Node.js or network access;
- production assets remain local, embedded, cacheable, and reproducible.
+11
View File
@@ -0,0 +1,11 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Pins the Rust toolchain for reproducible builds. Keep in sync with the
# SDK image (container/Containerfile, ARG RUST_VERSION). rustup honours this
# automatically for local builds outside the SDK container.
[toolchain]
channel = "1.97.1"
components = ["rustfmt", "clippy"]
Executable → Regular
+4
View File
@@ -1,4 +1,8 @@
#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: GPL-2.0-or-later
# Run trx-server with the dummy backend for development and testing.
set -euo pipefail
+1 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-ais"
+2 -2
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Basic AIS GMSK/HDLC decoder.
//!
@@ -243,7 +243,7 @@ fn parse_frame(frame: RawFrame, channel: &str) -> Option<AisMessage> {
let message_type = get_uint(&bits, 0, 6)? as u8;
let repeat = get_uint(&bits, 6, 2)? as u8;
let mmsi = get_uint(&bits, 8, 30)? as u32;
let mmsi = get_uint(&bits, 8, 30)?;
let mut msg = AisMessage {
rig_id: None,
+1 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-aprs"
+5 -5
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Bell 202 AFSK demodulator + AX.25/APRS decoder.
//!
@@ -638,7 +638,7 @@ mod tests {
for (i, &ch) in b"N0CALL".iter().enumerate() {
addr[i] = ch << 1;
}
addr[6] = (0 << 1) | 1; // SSID=0, last=true
addr[6] = 1; // SSID=0, last=true
let decoded = decode_ax25_address(&addr, 0);
assert_eq!(decoded.call, "N0CALL");
@@ -652,7 +652,7 @@ mod tests {
for (i, &ch) in b"SP2SJG".iter().enumerate() {
addr[i] = ch << 1;
}
addr[6] = (5 << 1) | 0; // SSID=5, last=false
addr[6] = 5 << 1; // SSID=5, last=false
let decoded = decode_ax25_address(&addr, 0);
assert_eq!(decoded.call, "SP2SJG");
@@ -667,7 +667,7 @@ mod tests {
for (i, &ch) in b"W1AW ".iter().enumerate() {
addr[i] = ch << 1;
}
addr[6] = (0 << 1) | 1;
addr[6] = 1;
let decoded = decode_ax25_address(&addr, 0);
assert_eq!(decoded.call, "W1AW");
@@ -691,7 +691,7 @@ mod tests {
for &ch in src_bytes.as_bytes().iter().take(6) {
frame.push(ch << 1);
}
frame.push((0 << 1) | 1); // SSID=0, last=true
frame.push(1); // SSID=0, last=true
// Control + PID
frame.push(0x03); // UI frame
frame.push(0xF0); // No layer-3 protocol
+1 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-cw"
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Goertzel-based CW (Morse code) decoder.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-decode-log"
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Server-side decoder file logging (APRS / CW / FT8 / WSPR).
//!
+1 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-ftx"
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Open-addressing hash table for callsign lookup during FTx decoding.
//!
@@ -160,8 +160,7 @@ impl CallsignHashTable {
let mut idx = start_idx;
loop {
match &self.entries[idx] {
Some(entry) => {
let entry = self.entries[idx].as_ref()?;
let stored = (entry.hash & HASH22_MASK) >> shift;
if stored == target {
return Some(entry.callsign.clone());
@@ -171,9 +170,6 @@ impl CallsignHashTable {
return None;
}
}
None => return None,
}
}
}
/// Age all entries and remove those older than `max_age`.
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
use super::protocol::{FTX_LDPC_K_BYTES, FTX_LDPC_M, FTX_LDPC_N};
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
use super::protocol::{FT8_CRC_POLYNOMIAL, FT8_CRC_WIDTH};
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Candidate search, shared decode helpers, and dispatcher functions for FTx decoding.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Shared LDPC encoding functions used by all FTx protocols.
+13 -13
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Pure Rust LDPC decoder for FTx protocols.
//!
@@ -42,8 +42,8 @@ pub(crate) fn ldpc_check(codeword: &[u8; FTX_LDPC_N]) -> i32 {
for m in 0..FTX_LDPC_M {
let mut x: u8 = 0;
let num_rows = FTX_LDPC_NUM_ROWS[m] as usize;
for i in 0..num_rows {
x ^= codeword[FTX_LDPC_NM[m][i] as usize - 1];
for &nm in FTX_LDPC_NM[m].iter().take(num_rows) {
x ^= codeword[nm as usize - 1];
}
if x != 0 {
errors += 1;
@@ -81,11 +81,11 @@ pub fn ldpc_decode(
for j in 0..FTX_LDPC_M {
let num_rows = FTX_LDPC_NUM_ROWS[j] as usize;
let m_row = j * FTX_LDPC_N;
for ii1 in 0..num_rows {
let i1 = FTX_LDPC_NM[j][ii1] as usize - 1;
for &nm1 in FTX_LDPC_NM[j].iter().take(num_rows) {
let i1 = nm1 as usize - 1;
let mut a = 1.0f32;
for ii2 in 0..num_rows {
let i2 = FTX_LDPC_NM[j][ii2] as usize - 1;
for &nm2 in FTX_LDPC_NM[j].iter().take(num_rows) {
let i2 = nm2 as usize - 1;
if i2 != i1 {
a *= fast_tanh(-m_matrix[m_row + i2] / 2.0f32);
}
@@ -97,8 +97,8 @@ pub fn ldpc_decode(
// Hard decisions
for i in 0..FTX_LDPC_N {
let mut l = codeword[i];
for j in 0..3 {
l += e_matrix[(FTX_LDPC_MN[i][j] as usize - 1) * FTX_LDPC_N + i];
for &mn in FTX_LDPC_MN[i].iter().take(3) {
l += e_matrix[(mn as usize - 1) * FTX_LDPC_N + i];
}
plain[i] = if l > 0.0 { 1 } else { 0 };
}
@@ -113,12 +113,12 @@ pub fn ldpc_decode(
// Update m[][] from e[][]
for i in 0..FTX_LDPC_N {
for ji1 in 0..3 {
let j1 = FTX_LDPC_MN[i][ji1] as usize - 1;
for (ji1, &mn1) in FTX_LDPC_MN[i].iter().enumerate().take(3) {
let j1 = mn1 as usize - 1;
let mut l = codeword[i];
for ji2 in 0..3 {
for (ji2, &mn2) in FTX_LDPC_MN[i].iter().enumerate().take(3) {
if ji1 != ji2 {
let j2 = FTX_LDPC_MN[i][ji2] as usize - 1;
let j2 = mn2 as usize - 1;
l += e_matrix[j2 * FTX_LDPC_N + i];
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! FTx message pack/unpack logic.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Common types, constants, and shared functions used across all FTx protocols.
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Windowed FFT waterfall/spectrogram engine for FTx decoding.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! OSD-1/OSD-2 CRC-guided bit-flip decoder for the (174,91) LDPC code.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
/// FTx protocol variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+3 -7
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Character table lookup and string utility functions for FTx message
//! encoding/decoding.
@@ -64,11 +64,9 @@ pub fn charn(mut c: i32, table: CharTable) -> char {
return EXTRAS[c as usize];
}
}
CharTable::AlphanumSpaceSlash => {
if c == 0 {
CharTable::AlphanumSpaceSlash if c == 0 => {
return '/';
}
}
_ => {}
}
@@ -116,11 +114,9 @@ pub fn nchar(c: char, table: CharTable) -> Option<i32> {
'?' => return Some(n + 4),
_ => {}
},
CharTable::AlphanumSpaceSlash => {
if c == '/' {
CharTable::AlphanumSpaceSlash if c == '/' => {
return Some(n);
}
}
_ => {}
}
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Top-level FTx decoder matching the `trx-ft8` public API.
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Per-symbol FFT and multi-scale bit metrics extraction.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! FT2-specific waterfall sync scoring and likelihood extraction.
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Frequency-domain downsampling via IFFT.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! FT2 pipeline orchestration.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! 2D sync scoring with complex Costas reference waveforms.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! FT4-specific sync scoring, likelihood extraction, and tone encoding.
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! FT8-specific sync scoring, likelihood extraction, and tone encoding.
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
pub mod common;
mod decoder;
+1 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-rds"
+13 -28
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
use std::f32::consts::{PI, SQRT_2, TAU};
use std::sync::Arc;
@@ -632,33 +632,18 @@ impl Candidate {
}
let segment = usize::from((block_b & 0x0003) as u8);
let di = ((block_b >> 2) & 0x1) != 0;
match segment {
0 => {
if self.state.dynamic_pty != Some(di) {
self.state.dynamic_pty = Some(di);
let di_flag = Some(di);
let slot = match segment {
0 => &mut self.state.dynamic_pty,
1 => &mut self.state.compressed,
2 => &mut self.state.artificial_head,
3 => &mut self.state.stereo,
_ => unreachable!("segment is masked to two bits"),
};
if *slot != di_flag {
*slot = di_flag;
changed = true;
}
}
1 => {
if self.state.compressed != Some(di) {
self.state.compressed = Some(di);
changed = true;
}
}
2 => {
if self.state.artificial_head != Some(di) {
self.state.artificial_head = Some(di);
changed = true;
}
}
3 => {
if self.state.stereo != Some(di) {
self.state.stereo = Some(di);
changed = true;
}
}
_ => {}
}
let [b0, b1] = block_d.to_be_bytes();
self.ps_bytes[segment * 2] = sanitize_text_byte(b0);
self.ps_bytes[segment * 2 + 1] = sanitize_text_byte(b1);
@@ -1458,9 +1443,9 @@ mod tests {
}
// BPSK modulate onto the 57 kHz subcarrier.
for t in 0..n {
for (t, sample) in shaped.iter_mut().enumerate().take(n) {
let phase = TAU * RDS_SUBCARRIER_HZ * t as f32 / sample_rate;
shaped[t] *= phase.cos();
*sample *= phase.cos();
}
shaped
}
+14
View File
@@ -0,0 +1,14 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-sstv"
version.workspace = true
edition = "2021"
[dependencies]
trx-core = { path = "../../trx-core" }
base64 = "0.22"
png = "0.17"
tracing = "0.1"
@@ -0,0 +1,91 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//! Encode a test card, decode it back, write both as PNGs to a directory.
//!
//! `cargo run -p trx-sstv --example round_trip_png -- /tmp/out`
use trx_sstv::encode::{encode, Frame};
use trx_sstv::mode::mode_for_vis;
use trx_sstv::{ImageCanvas, SstvConfig, SstvDecoder, SstvEvent};
fn main() {
let dir = std::env::args().nth(1).unwrap_or_else(|| ".".into());
for vis in [44u8, 60, 12, 8, 95] {
let mode = mode_for_vis(vis).expect("mode in table");
let (w, h) = (usize::from(mode.width), usize::from(mode.height));
let mut rgb = vec![0u8; w * h * 3];
for y in 0..h {
for x in 0..w {
let at = (y * w + x) * 3;
let (r, g, b) = if y < h / 3 {
[
(255u8, 255u8, 255u8),
(255, 255, 0),
(0, 255, 255),
(0, 255, 0),
(255, 0, 255),
(255, 0, 0),
(0, 0, 255),
(0, 0, 0),
][x * 8 / w]
} else if y < 2 * h / 3 {
let t = (x * 255 / w) as u8;
(t, 255 - t, ((y * 255) / h) as u8)
} else {
// Diagonal stripes: a line-timing error shows up as a kink.
if ((x + y) / 16) % 2 == 0 {
(240, 240, 40)
} else {
(20, 20, 90)
}
};
rgb[at] = r;
rgb[at + 1] = g;
rgb[at + 2] = b;
}
}
let name = mode.name.replace(' ', "-");
let mut sent = ImageCanvas::new(w, h);
for y in 0..h {
sent.put_row(y, &rgb[y * w * 3..(y + 1) * w * 3]);
}
std::fs::write(
format!("{dir}/{name}-sent.png"),
sent.to_png().expect("png"),
)
.expect("write");
let frame = Frame {
width: w,
height: h,
rgb: &rgb,
};
let mut audio = encode(mode, &frame, 48_000);
audio.extend(std::iter::repeat_n(0.0, 4800));
let mut decoder = SstvDecoder::new(48_000, SstvConfig::default());
let mut got = None;
for block in audio.chunks(1024) {
for event in decoder.process_samples(block) {
if let SstvEvent::Complete(image) = event {
got = Some(image);
}
}
}
let image = got.expect("no image decoded");
let mut canvas = ImageCanvas::new(w, h);
for y in 0..h {
canvas.put_row(y, &image.rgb[y * w * 3..(y + 1) * w * 3]);
}
std::fs::write(
format!("{dir}/{name}-decoded.png"),
canvas.to_png().expect("png"),
)
.expect("write");
println!(
"{}: {} lines, complete={}",
mode.name, image.lines, image.complete
);
}
}
+17
View File
@@ -0,0 +1,17 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//! SSTV decoder configuration.
/// Settings for [`crate::decoder::SstvDecoder`].
#[derive(Debug, Clone, Default)]
pub struct SstvConfig {
/// VIS code of a mode to assume when no header is heard, so tuning in
/// part-way through a transmission still produces a picture. `None` means
/// wait for a header, which is the safe default: guessing wrong yields a
/// convincing image of nothing.
pub force_mode: Option<u8>,
/// Directory for saved PNGs. `None` keeps images in memory only.
pub output_dir: Option<String>,
}
+659
View File
@@ -0,0 +1,659 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//! The decoder: audio in, pictures out.
//!
//! Reception is a small state machine. It listens for a VIS header, and once
//! one names a mode it walks the transmission a line at a time, sampling each
//! scan at the offsets the mode's segment list gives. Every line is looked for
//! at the time the mode says it should arrive, then nudged into place by the
//! sync pulse actually found near it — a transmitter's clock and a receiver's
//! sound card never agree exactly, and over two minutes of Martin M1 an
//! uncorrected error of a few parts per million visibly shears the picture.
//!
//! Rows are emitted as they are decoded so a picture can be watched arriving,
//! which is most of the appeal of the mode.
use crate::config::SstvConfig;
use crate::demod::FreqDemod;
use crate::image::ImageCanvas;
use crate::mode::{level_from_hz, mode_for_vis, Channel, ColorModel, SstvMode};
use crate::vis::find_vis;
/// Anything below this is the sync pulse rather than picture: black is 1500 Hz
/// and sync is 1200 Hz, so the line sits between them.
const SYNC_THRESHOLD_HZ: f32 = 1350.0;
/// How much of the signal to keep while hunting for a header. A header is 940
/// ms; two seconds leaves room for one to straddle several blocks of audio.
const SEARCH_HISTORY_MS: f64 = 2000.0;
/// From the start bit to the end of the stop bit: ten 30 ms cells. A header
/// search must never retire a stretch shorter than this, or a start bit split
/// across two blocks of audio is dismissed on half a view of it.
const HEADER_SPAN_MS: f64 = 330.0;
/// How far from its predicted position a line's sync pulse is looked for.
const SYNC_SEARCH_MS: f64 = 12.0;
/// Fraction of the observed timing error applied to the next line. Damped,
/// because a sync pulse found in noise is worth less than the prediction.
const SYNC_CORRECTION: f64 = 0.45;
/// Consecutive lines with no sync pulse anywhere near the prediction before
/// the transmission is taken to have ended.
const MISSING_SYNC_LIMIT: u32 = 8;
/// What the decoder has to say.
#[derive(Debug, Clone)]
pub enum SstvEvent {
/// A header was decoded and reception has begun.
Started {
vis: u8,
mode: &'static str,
width: u16,
height: u16,
},
/// One image row is ready, as RGB triples.
Row { line: u16, rgb: Vec<u8> },
/// Reception finished — at the bottom of the frame, or because the signal
/// went away. Carries the picture either way.
Complete(SstvImage),
}
/// A received picture.
#[derive(Debug, Clone)]
pub struct SstvImage {
pub vis: u8,
pub mode: &'static str,
pub width: u16,
pub height: u16,
/// Rows actually received, which is the height only if it ran to the end.
pub lines: u16,
/// Whether the whole frame arrived.
pub complete: bool,
/// RGB triples, `width * height * 3` bytes. Rows never received are grey.
pub rgb: Vec<u8>,
/// When reception started, in milliseconds since the epoch.
pub started_ms: i64,
}
impl SstvImage {
/// The picture as a canvas, for saving or encoding.
pub fn canvas(&self) -> ImageCanvas {
let width = usize::from(self.width);
let mut canvas = ImageCanvas::new(width, usize::from(self.height));
for (y, row) in self.rgb.chunks(width * 3).enumerate() {
canvas.put_row(y, row);
}
canvas
}
/// The picture as PNG bytes.
pub fn to_png(&self) -> Result<Vec<u8>, String> {
self.canvas().to_png()
}
/// The picture as a base64 PNG, for the journey to a client.
pub fn to_png_base64(&self) -> Result<String, String> {
self.canvas().to_png_base64()
}
/// Write the picture into `dir`, named for when and where it arrived.
pub fn save_png(
&self,
dir: &std::path::Path,
freq_hz: u64,
) -> Result<std::path::PathBuf, String> {
self.canvas()
.save_png(dir, freq_hz, self.mode, &stamp(self.started_ms))
}
}
/// `YYYYMMDDTHHMMSSZ` for a millisecond timestamp, for file names that sort.
fn stamp(ms: i64) -> String {
let secs = ms.div_euclid(1000);
let (days, rest) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
let (year, month, day) = civil_from_days(days);
let (hour, minute, second) = (rest / 3600, (rest % 3600) / 60, rest % 60);
format!("{year:04}{month:02}{day:02}T{hour:02}{minute:02}{second:02}Z")
}
/// Days since the Unix epoch to a calendar date (Howard Hinnant's algorithm).
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
enum State {
/// Listening for a header.
Searching,
Receiving(Box<Reception>),
}
struct Reception {
mode: &'static SstvMode,
canvas: ImageCanvas,
/// Absolute sample index at which the next transmitted line begins.
next_line: f64,
/// Next image row to write.
row: u16,
started_ms: i64,
missing_syncs: u32,
/// Set until the first line has been decoded. A VIS header ends exactly
/// where the picture begins, so the first line is already aligned — and a
/// search would find the header's own 30 ms stop bit, which is at the sync
/// frequency and sits immediately before the picture.
first_line: bool,
/// Robot 36 sends one chroma channel per line and expects the decoder to
/// carry the other over from the line before.
last_chroma_r: Option<Vec<u8>>,
last_chroma_b: Option<Vec<u8>>,
}
pub struct SstvDecoder {
sample_rate: u32,
config: SstvConfig,
demod: FreqDemod,
/// Instantaneous frequency, one entry per audio sample. Delayed by the
/// demodulator's group delay, which is constant and so shifts the whole
/// stream — header and lines alike — without disturbing their spacing.
freqs: Vec<f32>,
/// Absolute index of `freqs[0]`, so positions survive the buffer being
/// trimmed.
base: u64,
/// Absolute index the header search has already covered.
searched_to: u64,
state: State,
}
impl SstvDecoder {
pub fn new(sample_rate: u32, config: SstvConfig) -> Self {
Self {
sample_rate,
config,
demod: FreqDemod::new(sample_rate),
freqs: Vec::new(),
base: 0,
searched_to: 0,
state: State::Searching,
}
}
/// Whether a picture is currently arriving.
pub fn is_receiving(&self) -> bool {
matches!(self.state, State::Receiving(_))
}
/// Feed a block of mono audio. Returns whatever it produced.
pub fn process_samples(&mut self, samples: &[f32]) -> Vec<SstvEvent> {
self.demod.process_into(samples, &mut self.freqs);
let mut events = Vec::new();
loop {
let progressed = match self.state {
State::Searching => self.try_start(&mut events),
State::Receiving(_) => self.try_line(&mut events),
};
if !progressed {
break;
}
}
self.trim();
events
}
/// Abandon a reception in progress, returning the picture so far.
pub fn reset(&mut self) -> Vec<SstvEvent> {
let mut events = Vec::new();
if let State::Receiving(reception) = std::mem::replace(&mut self.state, State::Searching) {
events.push(SstvEvent::Complete(finish(&reception)));
}
self.demod.reset();
self.freqs.clear();
self.base = 0;
self.searched_to = 0;
events
}
/// Look for a header, or for a bare sync pulse when the mode is forced.
fn try_start(&mut self, events: &mut Vec<SstvEvent>) -> bool {
let from = self.searched_to.saturating_sub(self.base) as usize;
if from >= self.freqs.len() {
return false;
}
if let Some(hit) = find_vis(&self.freqs, self.sample_rate, from) {
if let Some(mode) = mode_for_vis(hit.code) {
self.begin(mode, self.base + hit.image_start as u64, events);
return true;
}
// A header that parses but names a mode this decoder does not know
// is still a header: skip past it rather than finding it again.
tracing::debug!(vis = hit.code, "SSTV: unsupported mode");
self.searched_to = self.base + hit.image_start as u64;
return true;
}
// Tuning in mid-transmission means no header to find. With a mode
// named in the configuration, the first sync pulse is enough to start.
if let Some(mode) = self.config.force_mode.and_then(mode_for_vis) {
if let Some(sync) = self.find_sync(from, self.freqs.len(), mode) {
let line_start = (self.base + sync as u64) as f64
- ms_to_samples(mode.sync_offset_ms, self.sample_rate);
self.begin_at(mode, line_start.max(0.0), events);
return true;
}
}
// Nothing yet. Rewind the cursor by a header's worth of samples before
// marking the buffer searched: audio arrives in blocks of a few
// milliseconds, so the search regularly runs over a start bit that is
// only half here. Advancing past it would retire the header for good
// on the strength of a partial view of it.
let unsearchable = ms_to_samples(HEADER_SPAN_MS, self.sample_rate) as u64;
let end = self.base + self.freqs.len() as u64;
self.searched_to = self.searched_to.max(end.saturating_sub(unsearchable));
false
}
fn begin(&mut self, mode: &'static SstvMode, image_start: u64, events: &mut Vec<SstvEvent>) {
self.begin_at(mode, image_start as f64, events);
}
fn begin_at(&mut self, mode: &'static SstvMode, line_start: f64, events: &mut Vec<SstvEvent>) {
events.push(SstvEvent::Started {
vis: mode.vis,
mode: mode.name,
width: mode.width,
height: mode.height,
});
self.state = State::Receiving(Box::new(Reception {
mode,
canvas: ImageCanvas::new(usize::from(mode.width), usize::from(mode.height)),
next_line: line_start,
row: 0,
started_ms: now_ms(),
missing_syncs: 0,
first_line: true,
last_chroma_r: None,
last_chroma_b: None,
}));
}
/// Decode one transmitted line, if all of it has arrived.
fn try_line(&mut self, events: &mut Vec<SstvEvent>) -> bool {
let State::Receiving(reception) = &mut self.state else {
return false;
};
let mode = reception.mode;
let line_samples = ms_to_samples(mode.line_ms, self.sample_rate);
let margin = ms_to_samples(SYNC_SEARCH_MS, self.sample_rate);
let start = reception.next_line;
// Enough for the line's own scans, and for the sync search to reach as
// far ahead as it looks — no further. Demanding the search margin past
// the end of every line would cost the last line of every picture,
// which is exactly where the transmission stops.
let sync_reach = start + ms_to_samples(mode.sync_offset_ms, self.sample_rate) + margin;
let end = (start + line_samples).max(sync_reach);
let available = (self.base + self.freqs.len() as u64) as f64;
if end > available {
return false;
}
// The line may begin before what is still buffered if the caller fed a
// huge block; nothing can be done about that but skip forward.
if start < self.base as f64 {
reception.next_line = self.base as f64;
return true;
}
// Line up on the sync pulse near where this line is predicted to be.
let expected_sync = start + ms_to_samples(mode.sync_offset_ms, self.sample_rate);
let from = (expected_sync - margin).max(self.base as f64) as u64;
let to = (expected_sync + margin) as u64;
let searching = !matches!(&self.state, State::Receiving(r) if r.first_line);
let found = if searching {
self.find_sync_between(from, to, mode)
} else {
None
};
let State::Receiving(reception) = &mut self.state else {
return false;
};
let start = match found {
Some(sync_at) => {
reception.missing_syncs = 0;
let error = sync_at as f64 - expected_sync;
reception.next_line += error * SYNC_CORRECTION;
reception.next_line
}
None if reception.first_line => start,
None => {
reception.missing_syncs += 1;
start
}
};
if reception.missing_syncs >= MISSING_SYNC_LIMIT {
let image = finish(reception);
self.state = State::Searching;
self.searched_to = self.base + self.freqs.len() as u64;
events.push(SstvEvent::Complete(image));
return true;
}
// Sample every scan of the line, then colour the rows.
let mut scans: Vec<(Channel, Vec<u8>)> = Vec::new();
for (channel, offset_ms, ms) in mode.scans() {
let pixels = mode.scan_pixels(channel);
let at = start + ms_to_samples(offset_ms, self.sample_rate);
let values = sample_scan(&self.freqs, self.base, at, ms, pixels, self.sample_rate);
scans.push((channel, values));
}
let State::Receiving(reception) = &mut self.state else {
return false;
};
let rows = compose_rows(reception, &scans);
for (offset, row) in rows.into_iter().enumerate() {
let line = reception.row + offset as u16;
reception.canvas.put_row(usize::from(line), &row);
events.push(SstvEvent::Row { line, rgb: row });
}
reception.first_line = false;
reception.row += mode.lines_per_transmission;
reception.next_line += line_samples;
if reception.row >= mode.height {
let image = finish(reception);
self.state = State::Searching;
self.searched_to = self.base + self.freqs.len() as u64;
events.push(SstvEvent::Complete(image));
}
true
}
/// First sync pulse of about the right length in `freqs[from..to]`,
/// as an index of its leading edge.
///
/// Works on a smoothed copy of the window: a sync pulse is 1200 Hz, where
/// the raw per-sample estimate swings by ±95 Hz, so single samples cross
/// and re-cross the threshold throughout a pulse and no run is ever long
/// enough. Pixels are sampled from the raw signal, where averaging over
/// the pixel does the same job without blurring across its edges.
fn find_sync(&self, from: usize, to: usize, mode: &SstvMode) -> Option<usize> {
let want = sync_ms(mode);
let min_run = (ms_to_samples(want, self.sample_rate) * 0.6) as usize;
// A sync pulse ends. Silence and a dead carrier demodulate to near
// zero, which is below the threshold too, and without an upper bound a
// decoder left running on an empty channel finds sync everywhere and
// fills the picture with noise it invented.
let max_run = (ms_to_samples(want, self.sample_rate) * 3.0) as usize;
let to = to.min(self.freqs.len());
if from >= to {
return None;
}
// Reach past the end of the search window by a whole pulse: a sync
// starting at the last moment the window allows still has to be
// measurable to its full length, or it is rejected for being short and
// the line it belongs to goes unaligned.
let pad = ms_to_samples(want + 2.0, self.sample_rate) as usize;
let window_from = from.saturating_sub(pad);
let window_to = (to + pad).min(self.freqs.len());
let smoothed = crate::demod::smooth(
&self.freqs[window_from..window_to],
ms_to_samples(1.0, self.sample_rate) as usize,
);
let mut i = from - window_from;
let scan_to = to - window_from;
while i < scan_to {
if smoothed[i] >= SYNC_THRESHOLD_HZ {
i += 1;
continue;
}
let mut run = 0;
while i + run < smoothed.len() && smoothed[i + run] < SYNC_THRESHOLD_HZ {
run += 1;
}
if run >= min_run && run <= max_run {
return Some(window_from + i);
}
i += run.max(1);
}
None
}
/// As [`Self::find_sync`], over an absolute index range.
fn find_sync_between(&self, from: u64, to: u64, mode: &SstvMode) -> Option<u64> {
let from = from.saturating_sub(self.base) as usize;
let to = to.saturating_sub(self.base) as usize;
if from >= self.freqs.len() {
return None;
}
self.find_sync(from, to, mode)
.map(|at| self.base + at as u64)
}
/// Drop what is behind the decoder, so a long reception does not grow the
/// buffer without bound.
fn trim(&mut self) {
let keep_from = match &self.state {
State::Searching => {
let history = ms_to_samples(SEARCH_HISTORY_MS, self.sample_rate) as u64;
(self.base + self.freqs.len() as u64).saturating_sub(history)
}
State::Receiving(reception) => {
let margin = ms_to_samples(SYNC_SEARCH_MS * 2.0, self.sample_rate) as u64;
(reception.next_line as u64).saturating_sub(margin)
}
};
if keep_from <= self.base {
return;
}
let drop = (keep_from - self.base) as usize;
if drop >= self.freqs.len() {
self.freqs.clear();
} else {
self.freqs.drain(..drop);
}
self.base = keep_from;
self.searched_to = self.searched_to.max(self.base);
}
}
/// The sync pulse length of a mode, read out of its own segment list.
fn sync_ms(mode: &SstvMode) -> f64 {
mode.segments
.iter()
.find_map(|segment| match segment {
crate::mode::Segment::Sync(ms) => Some(*ms),
_ => None,
})
.unwrap_or(9.0)
}
/// Milliseconds since the epoch, for stamping a picture with when it arrived.
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as i64
}
fn ms_to_samples(ms: f64, sample_rate: u32) -> f64 {
ms / 1000.0 * f64::from(sample_rate)
}
/// Average the frequency across each pixel's window and turn it into a level.
///
/// The middle 60% of the window is used: a pixel's edges carry the
/// demodulator's transition from the pixel before, and including them smears
/// every edge in the picture.
fn sample_scan(
freqs: &[f32],
base: u64,
start: f64,
ms: f64,
pixels: usize,
sample_rate: u32,
) -> Vec<u8> {
let mut out = Vec::with_capacity(pixels);
let width = ms_to_samples(ms, sample_rate) / pixels as f64;
for x in 0..pixels {
let pixel_start = start + width * x as f64;
let from = (pixel_start + width * 0.2 - base as f64).max(0.0) as usize;
let to = ((pixel_start + width * 0.8 - base as f64).max(0.0) as usize).min(freqs.len());
// A pixel narrower than a sample still has to produce one.
let (from, to) = if to > from {
(from, to)
} else {
let at = (pixel_start - base as f64).max(0.0) as usize;
(
at.min(freqs.len().saturating_sub(1)),
(at + 1).min(freqs.len()),
)
};
if to <= from {
out.push(0);
continue;
}
let window = &freqs[from..to];
let mean = window.iter().sum::<f32>() / window.len() as f32;
out.push(level_from_hz(mean));
}
out
}
/// Turn one line's scans into image rows.
fn compose_rows(reception: &mut Reception, scans: &[(Channel, Vec<u8>)]) -> Vec<Vec<u8>> {
let mode = reception.mode;
let width = usize::from(mode.width);
let find = |channel: Channel| scans.iter().find(|(c, _)| *c == channel).map(|(_, v)| v);
match mode.color {
ColorModel::Rgb => {
let red = find(Channel::Red);
let green = find(Channel::Green);
let blue = find(Channel::Blue);
let mut row = vec![0u8; width * 3];
for x in 0..width {
row[x * 3] = red.and_then(|c| c.get(x).copied()).unwrap_or(0);
row[x * 3 + 1] = green.and_then(|c| c.get(x).copied()).unwrap_or(0);
row[x * 3 + 2] = blue.and_then(|c| c.get(x).copied()).unwrap_or(0);
}
vec![row]
}
ColorModel::YCrCb => {
let luma = find(Channel::LumaOdd).cloned().unwrap_or_default();
let cr = find(Channel::ChromaR).cloned().unwrap_or_default();
let cb = find(Channel::ChromaB).cloned().unwrap_or_default();
vec![ycrcb_row(&luma, &cr, &cb, width)]
}
ColorModel::YCrCbAlternating => {
// This line carries one chroma channel; the other is the one from
// the line before, which is what the mode expects a decoder to do.
let luma = find(Channel::LumaOdd).cloned().unwrap_or_default();
let chroma = find(Channel::ChromaAlternating)
.cloned()
.unwrap_or_default();
if reception.row.is_multiple_of(2) {
reception.last_chroma_r = Some(chroma);
} else {
reception.last_chroma_b = Some(chroma);
}
let neutral = vec![128u8; luma.len().max(1) / 2];
let cr = reception
.last_chroma_r
.clone()
.unwrap_or_else(|| neutral.clone());
let cb = reception.last_chroma_b.clone().unwrap_or(neutral);
vec![ycrcb_row(&luma, &cr, &cb, width)]
}
ColorModel::YCrCbPaired => {
let odd = find(Channel::LumaOdd).cloned().unwrap_or_default();
let even = find(Channel::LumaEven).cloned().unwrap_or_default();
let cr = find(Channel::ChromaR).cloned().unwrap_or_default();
let cb = find(Channel::ChromaB).cloned().unwrap_or_default();
vec![
ycrcb_row(&odd, &cr, &cb, width),
ycrcb_row(&even, &cr, &cb, width),
]
}
}
}
/// One RGB row from luminance and chrominance, stretching the chroma scans
/// across the width when they are narrower than it.
fn ycrcb_row(luma: &[u8], cr: &[u8], cb: &[u8], width: usize) -> Vec<u8> {
let mut row = vec![0u8; width * 3];
let pick = |channel: &[u8], x: usize| -> f32 {
if channel.is_empty() {
return 128.0;
}
let at = x * channel.len() / width.max(1);
f32::from(channel[at.min(channel.len() - 1)])
};
for x in 0..width {
let y = if luma.is_empty() {
0.0
} else {
let at = x * luma.len() / width.max(1);
f32::from(luma[at.min(luma.len() - 1)])
};
let (r, g, b) = ycrcb_to_rgb(y, pick(cr, x), pick(cb, x));
row[x * 3] = r;
row[x * 3 + 1] = g;
row[x * 3 + 2] = b;
}
row
}
/// The inverse of the studio-swing conversion SSTV encoders use.
fn ycrcb_to_rgb(y: f32, cr: f32, cb: f32) -> (u8, u8, u8) {
let r = 298.082 * y / 256.0 + 408.583 * cr / 256.0 - 222.921;
let g = 298.082 * y / 256.0 - 100.291 * cb / 256.0 - 208.120 * cr / 256.0 + 135.576;
let b = 298.082 * y / 256.0 + 516.412 * cb / 256.0 - 276.836;
(
r.clamp(0.0, 255.0) as u8,
g.clamp(0.0, 255.0) as u8,
b.clamp(0.0, 255.0) as u8,
)
}
fn finish(reception: &Reception) -> SstvImage {
SstvImage {
vis: reception.mode.vis,
mode: reception.mode.name,
width: reception.mode.width,
height: reception.mode.height,
lines: reception.canvas.filled_rows() as u16,
complete: reception.row >= reception.mode.height,
rgb: reception.canvas.rgb().to_vec(),
started_ms: reception.started_ms,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn file_stamps_are_utc_and_sort_in_time_order() {
// Known instants, checked against `date -u -r <secs>`.
assert_eq!(stamp(0), "19700101T000000Z");
assert_eq!(stamp(1_000_000_000_000), "20010909T014640Z");
assert_eq!(stamp(1_770_000_000_000), "20260202T024000Z");
// Sorting the names sorts the pictures.
assert!(stamp(1_770_000_000_000) < stamp(1_770_000_001_000));
}
}
+297
View File
@@ -0,0 +1,297 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//! Instantaneous frequency estimation.
//!
//! SSTV carries every pixel as a frequency between 1500 and 2300 Hz, and every
//! line boundary as a 1200 Hz pulse, so one measurement serves the whole
//! decoder: the frequency of the signal at each sample. A Hilbert transform
//! FIR forms the analytic signal and the phase difference between consecutive
//! samples gives the frequency.
//!
//! The same approach drives the WEFAX decoder, which maps the result straight
//! to luminance. Here the frequency itself is the output, because the VIS
//! header and the sync detector read tones far outside the pixel band.
//!
//! Block-based linear processing, per `docs/Optimization-Guidelines.md`: the
//! FIR runs over a contiguous `[tail | samples]` buffer so the inner loop is
//! straight indexing the compiler can vectorise.
use std::f32::consts::PI;
/// Taps for the Hilbert transform FIR. Odd, so the delay is a whole sample.
const HILBERT_TAPS: usize = 65;
/// Group delay of the FIR, in samples.
const HILBERT_DELAY: usize = HILBERT_TAPS / 2;
/// Taps for the input band-pass. Long enough to be worth having, short enough
/// that its delay is a couple of milliseconds.
const BANDPASS_TAPS: usize = 127;
/// The band SSTV lives in: sync at 1200 Hz, black at 1500, white at 2300.
const BAND_LOW_HZ: f32 = 900.0;
const BAND_HIGH_HZ: f32 = 2700.0;
/// Produces instantaneous frequency in Hz from real audio samples.
pub struct FreqDemod {
/// Band-pass, applied first. A phase-difference frequency detector answers
/// whatever is loudest, so hiss outside the SSTV band steers the estimate
/// even when the signal is much stronger — the picture tears rather than
/// grows grainy. Every real decoder filters to the band first.
bandpass: Vec<f32>,
bandpass_tail: Vec<f32>,
coeffs: [f32; HILBERT_TAPS],
/// The last `HILBERT_TAPS - 1` input samples, priming the next block.
tail: Vec<f32>,
prev_i: f32,
prev_q: f32,
/// `sample_rate / 2π`, the constant turning phase step into Hz.
hz_per_radian: f32,
}
impl FreqDemod {
pub fn new(sample_rate: u32) -> Self {
Self {
bandpass: design_bandpass_fir(sample_rate),
bandpass_tail: vec![0.0; BANDPASS_TAPS - 1],
coeffs: design_hilbert_fir(),
tail: vec![0.0; HILBERT_TAPS - 1],
prev_i: 0.0,
prev_q: 0.0,
hz_per_radian: sample_rate as f32 / (2.0 * PI),
}
}
/// Band-pass a block, carrying the filter's state across the seam.
fn filter(&mut self, samples: &[f32]) -> Vec<f32> {
let taps = BANDPASS_TAPS;
let tail_len = taps - 1;
let mut work = Vec::with_capacity(tail_len + samples.len());
work.extend_from_slice(&self.bandpass_tail);
work.extend_from_slice(samples);
let mut out = Vec::with_capacity(samples.len());
for i in 0..samples.len() {
let window = &work[i..i + taps];
let mut acc = 0.0f32;
for k in 0..taps {
acc += self.bandpass[k] * window[taps - 1 - k];
}
out.push(acc);
}
let work_len = work.len();
self.bandpass_tail
.copy_from_slice(&work[work_len - tail_len..]);
out
}
/// Frequency in Hz for each input sample, appended to `out`.
///
/// Output is delayed by the FIR's group delay, which is constant and so
/// affects only the absolute timing of the whole stream, not the spacing
/// between the events in it.
pub fn process_into(&mut self, samples: &[f32], out: &mut Vec<f32>) {
if samples.is_empty() {
return;
}
let samples = self.filter(samples);
let samples = samples.as_slice();
let taps = HILBERT_TAPS;
let tail_len = taps - 1;
let mut work = Vec::with_capacity(tail_len + samples.len());
work.extend_from_slice(&self.tail);
work.extend_from_slice(samples);
out.reserve(samples.len());
for i in 0..samples.len() {
let window = &work[i..i + taps];
let mut q = 0.0f32;
for k in 0..taps {
q += self.coeffs[k] * window[taps - 1 - k];
}
// In phase with the quadrature output: the input, delayed by the
// FIR's own group delay.
let i_val = window[HILBERT_DELAY];
// f = |arg(z[n] · conj(z[n-1]))| · fs / 2π
let di = i_val * self.prev_i + q * self.prev_q;
let dq = q * self.prev_i - i_val * self.prev_q;
out.push(dq.atan2(di).abs() * self.hz_per_radian);
self.prev_i = i_val;
self.prev_q = q;
}
let work_len = work.len();
self.tail.copy_from_slice(&work[work_len - tail_len..]);
}
pub fn reset(&mut self) {
self.bandpass_tail.fill(0.0);
self.tail.fill(0.0);
self.prev_i = 0.0;
self.prev_q = 0.0;
}
}
/// Boxcar mean over `window` samples, centred, returning one value per input.
///
/// The per-sample estimate ripples — badly at the low end of the band, where
/// the Hilbert approximation is weakest: a clean 1200 Hz tone reads anywhere
/// between 1110 and 1300 Hz sample to sample, though its mean is exact. Pixels
/// are averaged over their own window and so come out right regardless, but
/// anything that classifies a single sample by frequency — the VIS bits, the
/// sync pulses — has to look at a mean or it is reading the ripple.
pub fn smooth(freqs: &[f32], window: usize) -> Vec<f32> {
let window = window.max(1);
if freqs.is_empty() {
return Vec::new();
}
// Prefix sums in f64: a minute of audio is three million samples, and a
// running f32 total drifts long before that.
let mut prefix = Vec::with_capacity(freqs.len() + 1);
prefix.push(0.0f64);
for &freq in freqs {
prefix.push(prefix[prefix.len() - 1] + f64::from(freq));
}
let half = window / 2;
(0..freqs.len())
.map(|i| {
// Shrinks at the ends rather than reaching past them.
let from = i.saturating_sub(half);
let to = (i + window - half).min(freqs.len());
((prefix[to] - prefix[from]) / (to - from) as f64) as f32
})
.collect()
}
/// Windowed-sinc band-pass over the SSTV band, Hamming-windowed and
/// linear-phase, so every frequency in the band is delayed alike.
fn design_bandpass_fir(sample_rate: u32) -> Vec<f32> {
let sr = sample_rate as f64;
let low = f64::from(BAND_LOW_HZ) / sr;
let high = (f64::from(BAND_HIGH_HZ) / sr).min(0.499);
let m = (BANDPASS_TAPS - 1) as f64;
let mid = m / 2.0;
let sinc = |x: f64| {
if x.abs() < 1e-9 {
1.0
} else {
(std::f64::consts::PI * x).sin() / (std::f64::consts::PI * x)
}
};
let mut coeffs = Vec::with_capacity(BANDPASS_TAPS);
for i in 0..BANDPASS_TAPS {
let n = i as f64 - mid;
// Difference of two low-passes is a band-pass.
let ideal = 2.0 * high * sinc(2.0 * high * n) - 2.0 * low * sinc(2.0 * low * n);
let window = 0.54 - 0.46 * (2.0 * std::f64::consts::PI * i as f64 / m).cos();
coeffs.push((ideal * window) as f32);
}
coeffs
}
/// Type III FIR approximating a 90° phase shift: h[n] = 2/(πn) for odd n,
/// Blackman-windowed. Independent of sample rate, so the decoder can run at
/// whatever rate the audio arrives in.
fn design_hilbert_fir() -> [f32; HILBERT_TAPS] {
let mut coeffs = [0.0f32; HILBERT_TAPS];
let m = (HILBERT_TAPS - 1) as f64;
let mid = m / 2.0;
for (i, coeff) in coeffs.iter_mut().enumerate() {
let n = i as f64 - mid;
let ni = n.round() as i64;
if ni != 0 && ni % 2 != 0 {
let h = 2.0 / (std::f64::consts::PI * n);
let w = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / m).cos()
+ 0.08 * (4.0 * std::f64::consts::PI * i as f64 / m).cos();
*coeff = (h * w) as f32;
}
}
coeffs
}
#[cfg(test)]
mod tests {
use super::*;
fn tone(freq: f32, sample_rate: u32, samples: usize) -> Vec<f32> {
(0..samples)
.map(|n| (2.0 * PI * freq * n as f32 / sample_rate as f32).sin())
.collect()
}
/// Measured on the settled part of the output: the first `HILBERT_TAPS`
/// samples are the filter filling up.
fn measure(freq: f32, sample_rate: u32) -> f32 {
let mut demod = FreqDemod::new(sample_rate);
let mut out = Vec::new();
demod.process_into(
&tone(freq, sample_rate, sample_rate as usize / 10),
&mut out,
);
let settled = &out[HILBERT_TAPS * 2..];
settled.iter().sum::<f32>() / settled.len() as f32
}
#[test]
fn reads_the_tones_sstv_is_made_of() {
for rate in [8000u32, 11025, 44100, 48000] {
for freq in [1200.0f32, 1500.0, 1900.0, 2300.0] {
let measured = measure(freq, rate);
assert!(
(measured - freq).abs() < 5.0,
"{rate} Hz: {freq} Hz tone measured as {measured:.1} Hz",
);
}
}
}
/// Blocks are whatever size the audio pipeline hands over, and a tone that
/// straddles two of them must not produce a discontinuity at the seam.
#[test]
fn block_boundaries_do_not_disturb_the_estimate() {
let rate = 48_000;
let samples = tone(1900.0, rate, 9600);
let mut whole = FreqDemod::new(rate);
let mut expected = Vec::new();
whole.process_into(&samples, &mut expected);
let mut split = FreqDemod::new(rate);
let mut actual = Vec::new();
for chunk in samples.chunks(137) {
split.process_into(chunk, &mut actual);
}
assert_eq!(actual.len(), expected.len());
for (i, (a, b)) in actual.iter().zip(&expected).enumerate() {
assert!((a - b).abs() < 0.01, "sample {i}: {a} vs {b}");
}
}
#[test]
fn follows_a_step_between_tones_within_a_pixel() {
let rate = 48_000;
let mut samples = tone(1500.0, rate, 4800);
samples.extend(tone(2300.0, rate, 4800));
let mut demod = FreqDemod::new(rate);
let mut out = Vec::new();
demod.process_into(&samples, &mut out);
// Well before the step it reads black; well after it, white. The step
// itself takes the filter's length to pass through.
let before = out[4800 - 200..4800 - 100].iter().sum::<f32>() / 100.0;
let after = out[4800 + 200..4800 + 300].iter().sum::<f32>() / 100.0;
assert!(
(before - 1500.0).abs() < 10.0,
"before the step: {before:.1} Hz"
);
assert!(
(after - 2300.0).abs() < 10.0,
"after the step: {after:.1} Hz"
);
}
}
+238
View File
@@ -0,0 +1,238 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//! Turning an image into an SSTV signal.
//!
//! This exists so the decoder can be held to a picture rather than to a
//! description of one: the tests encode a known image, decode the audio back
//! and compare. Nothing in the receive path uses it.
//!
//! It is written to the same mode table the decoder reads, which makes a
//! round-trip a test of the decoder and not of the timings — the timings are
//! checked separately, against the published line durations, in [`crate::mode`].
use crate::mode::{Channel, Segment, SstvMode, BLACK_HZ, SYNC_HZ, WHITE_HZ};
/// A stretch of constant tone.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Tone {
pub hz: f32,
pub ms: f64,
}
/// Frequency for an 8-bit level: the inverse of [`crate::mode::level_from_hz`].
pub fn hz_from_level(level: u8) -> f32 {
BLACK_HZ + (WHITE_HZ - BLACK_HZ) * f32::from(level) / 255.0
}
/// The tones of a VIS header announcing `vis`.
pub fn vis_tones(vis: u8) -> Vec<Tone> {
let mut tones = vec![
Tone {
hz: 1900.0,
ms: 300.0,
},
Tone {
hz: 1200.0,
ms: 10.0,
},
Tone {
hz: 1900.0,
ms: 300.0,
},
Tone {
hz: 1200.0,
ms: 30.0,
}, // start bit
];
let mut ones = 0;
for bit in 0..7 {
let set = vis & (1 << bit) != 0;
if set {
ones += 1;
}
tones.push(Tone {
hz: if set { 1100.0 } else { 1300.0 },
ms: 30.0,
});
}
// Even parity over the seven data bits.
tones.push(Tone {
hz: if ones % 2 == 1 { 1100.0 } else { 1300.0 },
ms: 30.0,
});
tones.push(Tone {
hz: 1200.0,
ms: 30.0,
}); // stop bit
tones
}
/// RGB source for the encoder: `width * height * 3` bytes.
pub struct Frame<'a> {
pub width: usize,
pub height: usize,
pub rgb: &'a [u8],
}
impl Frame<'_> {
fn pixel(&self, x: usize, y: usize) -> (u8, u8, u8) {
let x = x.min(self.width.saturating_sub(1));
let y = y.min(self.height.saturating_sub(1));
let at = (y * self.width + x) * 3;
(self.rgb[at], self.rgb[at + 1], self.rgb[at + 2])
}
/// The colour components SSTV actually sends, for a pixel.
fn ycrcb(&self, x: usize, y: usize) -> (u8, u8, u8) {
let (r, g, b) = self.pixel(x, y);
let (r, g, b) = (f32::from(r), f32::from(g), f32::from(b));
let y_val = 16.0 + (0.003_906 * ((65.738 * r) + (129.057 * g) + (25.064 * b)));
let cr = 128.0 + (0.003_906 * ((112.439 * r) + (-94.154 * g) + (-18.285 * b)));
let cb = 128.0 + (0.003_906 * ((-37.945 * r) + (-74.494 * g) + (112.439 * b)));
(
y_val.clamp(0.0, 255.0) as u8,
cr.clamp(0.0, 255.0) as u8,
cb.clamp(0.0, 255.0) as u8,
)
}
}
/// Encode `frame` in `mode`, returning the tones of the whole transmission.
pub fn encode_tones(mode: &SstvMode, frame: &Frame<'_>) -> Vec<Tone> {
let mut tones = vis_tones(mode.vis);
let per_line = usize::from(mode.lines_per_transmission);
let transmissions = usize::from(mode.height) / per_line;
for transmission in 0..transmissions {
let top = transmission * per_line;
for segment in mode.segments {
match *segment {
Segment::Sync(ms) => tones.push(Tone { hz: SYNC_HZ, ms }),
Segment::Gap(ms) => tones.push(Tone { hz: BLACK_HZ, ms }),
Segment::Scan { channel, ms } => {
// A chroma scan carries fewer pixels than the image is
// wide, and takes proportionally less time per pixel.
let pixels = mode.scan_pixels(channel);
let pixel_ms = ms / pixels as f64;
for x in 0..pixels {
let level = channel_level(mode, frame, channel, x, top, transmission);
tones.push(Tone {
hz: hz_from_level(level),
ms: pixel_ms,
});
}
}
}
}
}
tones
}
fn channel_level(
mode: &SstvMode,
frame: &Frame<'_>,
channel: Channel,
x: usize,
top: usize,
transmission: usize,
) -> u8 {
match channel {
Channel::Red => frame.pixel(x, top).0,
Channel::Green => frame.pixel(x, top).1,
Channel::Blue => frame.pixel(x, top).2,
Channel::LumaOdd => frame.ycrcb(x, top).0,
Channel::LumaEven => frame.ycrcb(x, top + 1).0,
Channel::ChromaR => chroma(mode, frame, x, top, true),
Channel::ChromaB => chroma(mode, frame, x, top, false),
// Robot 36 sends R-Y on odd transmitted lines and B-Y on even ones.
Channel::ChromaAlternating => chroma(mode, frame, x, top, transmission.is_multiple_of(2)),
}
}
/// Chroma scans are half the width of the image in the Robot modes, so each
/// value covers two pixels; PD averages the two image lines of the pair too.
fn chroma(mode: &SstvMode, frame: &Frame<'_>, x: usize, top: usize, want_cr: bool) -> u8 {
let scale = usize::from(mode.width) / mode.scan_pixels(Channel::ChromaR).max(1);
let x0 = x * scale;
let mut total = 0u32;
let mut count = 0u32;
let rows = usize::from(mode.lines_per_transmission);
for row in 0..rows {
for dx in 0..scale {
let (_, cr, cb) = frame.ycrcb(x0 + dx, top + row);
total += u32::from(if want_cr { cr } else { cb });
count += 1;
}
}
(total / count.max(1)) as u8
}
/// Render tones to audio at `sample_rate`, with continuous phase so the
/// demodulator sees no step at a tone boundary that isn't in the signal.
pub fn render(tones: &[Tone], sample_rate: u32) -> Vec<f32> {
let sr = f64::from(sample_rate);
let mut out =
Vec::with_capacity((tones.iter().map(|t| t.ms).sum::<f64>() / 1000.0 * sr) as usize);
let mut phase = 0.0f64;
// Each tone's *end* is rounded to a sample, rather than its length: a
// pixel of 25.5 samples rounded up on its own puts a whole line 600
// samples late by the end of it, which is a timing error no receiver
// should have to chase and no transmitter would produce.
let mut elapsed_ms = 0.0f64;
let mut emitted = 0usize;
for tone in tones {
elapsed_ms += tone.ms;
let end = (elapsed_ms / 1000.0 * sr).round() as usize;
let samples = end.saturating_sub(emitted);
emitted = end;
let step = 2.0 * std::f64::consts::PI * f64::from(tone.hz) / sr;
for _ in 0..samples {
out.push(phase.sin() as f32);
phase += step;
if phase > std::f64::consts::TAU {
phase -= std::f64::consts::TAU;
}
}
}
out
}
/// Encode a frame straight to audio.
pub fn encode(mode: &SstvMode, frame: &Frame<'_>, sample_rate: u32) -> Vec<f32> {
render(&encode_tones(mode, frame), sample_rate)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mode::{level_from_hz, mode_for_vis};
#[test]
fn levels_survive_the_trip_through_frequency() {
for level in [0u8, 1, 64, 128, 200, 255] {
assert_eq!(level_from_hz(hz_from_level(level)), level);
}
}
#[test]
fn a_transmission_lasts_as_long_as_the_mode_says() {
let mode = mode_for_vis(44).expect("Martin M1");
let rgb = vec![128u8; 320 * 256 * 3];
let frame = Frame {
width: 320,
height: 256,
rgb: &rgb,
};
let audio = encode(mode, &frame, 48_000);
// Header plus 256 lines, within a line of the published duration.
let header_s = 0.94;
let expected = header_s + mode.frame_secs();
let actual = audio.len() as f64 / 48_000.0;
assert!(
(actual - expected).abs() < mode.line_ms / 1000.0,
"encoded {actual:.2} s, expected {expected:.2} s",
);
}
}
+150
View File
@@ -0,0 +1,150 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//! Assembling decoded lines into an image, and getting it out of the process.
//!
//! Rows arrive one at a time and the picture is worth looking at before it is
//! finished, so the assembler holds a full-size RGB canvas from the start and
//! fills it in. An unfinished frame is grey below the last decoded row rather
//! than black, which reads as "not here yet" instead of "received as black".
use std::path::{Path, PathBuf};
use base64::Engine;
/// Value the canvas starts at: mid-grey, for rows not yet received.
const UNWRITTEN: u8 = 96;
pub struct ImageCanvas {
width: usize,
height: usize,
rgb: Vec<u8>,
/// Highest row index written, plus one.
filled_rows: usize,
}
impl ImageCanvas {
pub fn new(width: usize, height: usize) -> Self {
Self {
width,
height,
rgb: vec![UNWRITTEN; width * height * 3],
filled_rows: 0,
}
}
pub fn width(&self) -> usize {
self.width
}
pub fn height(&self) -> usize {
self.height
}
/// Rows written so far.
pub fn filled_rows(&self) -> usize {
self.filled_rows
}
/// Write one row of RGB triples. Rows past the bottom of the image are
/// dropped: a transmission that runs long is not a reason to grow.
pub fn put_row(&mut self, y: usize, row: &[u8]) {
if y >= self.height {
return;
}
let at = y * self.width * 3;
let take = row.len().min(self.width * 3);
self.rgb[at..at + take].copy_from_slice(&row[..take]);
self.filled_rows = self.filled_rows.max(y + 1);
}
pub fn row(&self, y: usize) -> Option<&[u8]> {
if y >= self.height {
return None;
}
let at = y * self.width * 3;
Some(&self.rgb[at..at + self.width * 3])
}
pub fn rgb(&self) -> &[u8] {
&self.rgb
}
/// Encode the canvas as a PNG.
pub fn to_png(&self) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
{
let mut encoder = png::Encoder::new(&mut out, self.width as u32, self.height as u32);
encoder.set_color(png::ColorType::Rgb);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder
.write_header()
.map_err(|e| format!("PNG header: {e}"))?;
writer
.write_image_data(&self.rgb)
.map_err(|e| format!("PNG data: {e}"))?;
}
Ok(out)
}
/// The PNG, base64-encoded for the journey to a browser.
pub fn to_png_base64(&self) -> Result<String, String> {
Ok(base64::engine::general_purpose::STANDARD.encode(self.to_png()?))
}
/// Write the PNG into `dir`, named for when and where it was received.
pub fn save_png(
&self,
dir: &Path,
freq_hz: u64,
mode_name: &str,
stamp: &str,
) -> Result<PathBuf, String> {
std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
let slug: String = mode_name
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
let path = dir.join(format!("SSTV_{stamp}_{freq_hz}_{slug}.png"));
std::fs::write(&path, self.to_png()?)
.map_err(|e| format!("write {}: {e}", path.display()))?;
Ok(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rows_land_where_they_are_put_and_the_rest_stays_unwritten() {
let mut canvas = ImageCanvas::new(4, 3);
canvas.put_row(1, &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
assert_eq!(canvas.row(1).unwrap()[0..3], [1, 2, 3]);
assert_eq!(canvas.row(0).unwrap()[0], UNWRITTEN);
assert_eq!(canvas.filled_rows(), 2);
}
#[test]
fn a_row_past_the_bottom_is_dropped_rather_than_growing_the_image() {
let mut canvas = ImageCanvas::new(2, 2);
canvas.put_row(9, &[1, 2, 3, 4, 5, 6]);
assert_eq!(canvas.filled_rows(), 0);
assert_eq!(canvas.rgb().len(), 2 * 2 * 3);
}
#[test]
fn encodes_a_png_a_decoder_can_read_back() {
let mut canvas = ImageCanvas::new(2, 2);
canvas.put_row(0, &[255, 0, 0, 0, 255, 0]);
let png_bytes = canvas.to_png().expect("png");
let decoder = png::Decoder::new(png_bytes.as_slice());
let mut reader = decoder.read_info().expect("png info");
let mut buf = vec![0; reader.output_buffer_size()];
let info = reader.next_frame(&mut buf).expect("png frame");
assert_eq!((info.width, info.height), (2, 2));
assert_eq!(&buf[0..6], &[255, 0, 0, 0, 255, 0]);
assert!(!canvas.to_png_base64().expect("base64").is_empty());
}
}
+36
View File
@@ -0,0 +1,36 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//! SSTV (Slow-Scan Television) decoder.
//!
//! Pure Rust, covering Martin, Scottie, Robot, PD and Wraase SC2-180, with the
//! mode taken from the VIS header that precedes every transmission. Rows are
//! emitted as they arrive so a picture can be watched building up.
//!
//! ```no_run
//! use trx_sstv::{SstvConfig, SstvDecoder, SstvEvent};
//!
//! let mut decoder = SstvDecoder::new(48_000, SstvConfig::default());
//! # let audio: Vec<f32> = Vec::new();
//! for event in decoder.process_samples(&audio) {
//! match event {
//! SstvEvent::Started { mode, .. } => println!("receiving {mode}"),
//! SstvEvent::Row { line, .. } => println!("line {line}"),
//! SstvEvent::Complete(image) => println!("{} lines", image.lines),
//! }
//! }
//! ```
pub mod config;
pub mod decoder;
pub mod demod;
pub mod encode;
pub mod image;
pub mod mode;
pub mod vis;
pub use config::SstvConfig;
pub use decoder::{SstvDecoder, SstvEvent, SstvImage};
pub use image::ImageCanvas;
pub use mode::{mode_for_vis, SstvMode, MODES};
+615
View File
@@ -0,0 +1,615 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//! SSTV mode table: what a VIS code means in timings, geometry and colour.
//!
//! Every mode transmits a line as a sequence of *segments* — a sync pulse, a
//! porch or separator at a fixed tone, and one scan per colour channel. The
//! decoder needs only the segment layout and the offset of each scan within
//! the line, so that is what a [`SstvMode`] is: a list of segments plus the
//! rules for turning the scans back into pixels.
//!
//! Timings follow the published mode specifications (JL Barber, N7CXI,
//! "Proposal for SSTV Mode Specifications", 2000), which is the same table
//! MMSSTV, QSSTV and slowrx work from.
/// Tone that marks a line boundary, in Hz.
pub const SYNC_HZ: f32 = 1200.0;
/// Tone for black, in Hz.
pub const BLACK_HZ: f32 = 1500.0;
/// Tone for white, in Hz.
pub const WHITE_HZ: f32 = 2300.0;
/// What a scan segment carries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channel {
Red,
Green,
Blue,
/// Luminance for the odd (first) image line of the pair.
LumaOdd,
/// Luminance for the even (second) image line of a PD pair.
LumaEven,
/// R-Y chrominance.
ChromaR,
/// B-Y chrominance.
ChromaB,
/// Robot 36 alternates R-Y and B-Y between transmitted lines: odd lines
/// carry R-Y, even lines B-Y, and each is held over both.
ChromaAlternating,
}
/// One piece of a transmitted line.
#[derive(Debug, Clone, Copy)]
pub enum Segment {
/// Sync pulse at [`SYNC_HZ`].
Sync(f64),
/// Porch, separator or gap at a fixed tone; the tone itself is not decoded.
Gap(f64),
/// A scan carrying pixels for one channel.
Scan { channel: Channel, ms: f64 },
}
impl Segment {
pub fn duration_ms(&self) -> f64 {
match *self {
Segment::Sync(ms) | Segment::Gap(ms) => ms,
Segment::Scan { ms, .. } => ms,
}
}
}
/// How the scans of a line become pixels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorModel {
/// Scans are red, green and blue directly (Martin, Scottie, Wraase).
Rgb,
/// Y plus one alternating chroma channel per line (Robot 36).
YCrCbAlternating,
/// Y, R-Y and B-Y in every line (Robot 72).
YCrCb,
/// Two image lines per transmitted line: Y odd, R-Y, B-Y, Y even (PD).
YCrCbPaired,
}
/// A decodable SSTV mode.
#[derive(Debug, Clone)]
pub struct SstvMode {
/// VIS code as sent in the header.
pub vis: u8,
/// Human-readable name, e.g. "Martin M1".
pub name: &'static str,
/// Pixels across.
pub width: u16,
/// Image lines in a full frame.
pub height: u16,
/// Transmitted line duration in milliseconds.
pub line_ms: f64,
/// Segments in transmission order.
pub segments: &'static [Segment],
pub color: ColorModel,
/// Image lines produced by one transmitted line (2 for PD, otherwise 1).
pub lines_per_transmission: u16,
/// Offset from the start of a line to the leading edge of its sync pulse.
/// Zero for most modes; Scottie sends the sync in the middle of the line,
/// so a line detected at its sync starts before it.
pub sync_offset_ms: f64,
}
impl SstvMode {
/// Total of every segment, which must equal [`SstvMode::line_ms`].
pub fn segments_ms(&self) -> f64 {
self.segments.iter().map(Segment::duration_ms).sum()
}
/// Start offset, in milliseconds from the line start, of each scan.
pub fn scans(&self) -> Vec<(Channel, f64, f64)> {
let mut out = Vec::new();
let mut at = 0.0;
for segment in self.segments {
if let Segment::Scan { channel, ms } = *segment {
out.push((channel, at, ms));
}
at += segment.duration_ms();
}
out
}
/// Pixels carried by a scan of this channel.
///
/// Chroma is sent at half the width in the Robot modes — the eye takes
/// colour more coarsely than brightness, and the saving is what makes 36
/// seconds possible. PD sends chroma at full width and saves its time by
/// sharing one pair of chroma scans between two image lines instead.
pub fn scan_pixels(&self, channel: Channel) -> usize {
let width = usize::from(self.width);
match channel {
Channel::ChromaR | Channel::ChromaB | Channel::ChromaAlternating
if self.color != ColorModel::YCrCbPaired =>
{
width / 2
}
_ => width,
}
}
/// Seconds a full frame takes to send.
pub fn frame_secs(&self) -> f64 {
self.line_ms * f64::from(self.height) / f64::from(self.lines_per_transmission) / 1000.0
}
}
// ---------------------------------------------------------------------------
// Martin — sync, porch, then green, blue, red, each followed by a separator.
// ---------------------------------------------------------------------------
const MARTIN_M1: &[Segment] = &[
Segment::Sync(4.862),
Segment::Gap(0.572),
Segment::Scan {
channel: Channel::Green,
ms: 146.432,
},
Segment::Gap(0.572),
Segment::Scan {
channel: Channel::Blue,
ms: 146.432,
},
Segment::Gap(0.572),
Segment::Scan {
channel: Channel::Red,
ms: 146.432,
},
Segment::Gap(0.572),
];
const MARTIN_M2: &[Segment] = &[
Segment::Sync(4.862),
Segment::Gap(0.572),
Segment::Scan {
channel: Channel::Green,
ms: 73.216,
},
Segment::Gap(0.572),
Segment::Scan {
channel: Channel::Blue,
ms: 73.216,
},
Segment::Gap(0.572),
Segment::Scan {
channel: Channel::Red,
ms: 73.216,
},
Segment::Gap(0.572),
];
// ---------------------------------------------------------------------------
// Scottie — the sync pulse sits between the blue and red scans, so a line
// starts one separator before the green scan and the sync of the *previous*
// line is what marks it.
// ---------------------------------------------------------------------------
const SCOTTIE_S1: &[Segment] = &[
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::Green,
ms: 138.240,
},
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::Blue,
ms: 138.240,
},
Segment::Sync(9.0),
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::Red,
ms: 138.240,
},
];
const SCOTTIE_S2: &[Segment] = &[
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::Green,
ms: 88.064,
},
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::Blue,
ms: 88.064,
},
Segment::Sync(9.0),
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::Red,
ms: 88.064,
},
];
const SCOTTIE_DX: &[Segment] = &[
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::Green,
ms: 345.6,
},
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::Blue,
ms: 345.6,
},
Segment::Sync(9.0),
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::Red,
ms: 345.6,
},
];
/// Scottie's sync arrives after the green and blue scans: 1.5 + 138.24 + 1.5 +
/// 138.24 for S1, and the equivalent for the others.
const fn scottie_sync_offset(scan_ms: f64) -> f64 {
1.5 + scan_ms + 1.5 + scan_ms
}
// ---------------------------------------------------------------------------
// Robot — luminance plus chrominance, the chroma scans at half the width.
// ---------------------------------------------------------------------------
const ROBOT_36: &[Segment] = &[
Segment::Sync(9.0),
Segment::Gap(3.0),
Segment::Scan {
channel: Channel::LumaOdd,
ms: 88.0,
},
Segment::Gap(4.5),
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::ChromaAlternating,
ms: 44.0,
},
];
const ROBOT_72: &[Segment] = &[
Segment::Sync(9.0),
Segment::Gap(3.0),
Segment::Scan {
channel: Channel::LumaOdd,
ms: 138.0,
},
Segment::Gap(4.5),
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::ChromaR,
ms: 69.0,
},
Segment::Gap(4.5),
Segment::Gap(1.5),
Segment::Scan {
channel: Channel::ChromaB,
ms: 69.0,
},
];
// ---------------------------------------------------------------------------
// PD — one transmitted line carries two image lines: the luminance of both,
// with a single pair of chroma scans shared between them.
// ---------------------------------------------------------------------------
macro_rules! pd_segments {
($name:ident, $scan:expr) => {
const $name: &[Segment] = &[
Segment::Sync(20.0),
Segment::Gap(2.08),
Segment::Scan {
channel: Channel::LumaOdd,
ms: $scan,
},
Segment::Scan {
channel: Channel::ChromaR,
ms: $scan,
},
Segment::Scan {
channel: Channel::ChromaB,
ms: $scan,
},
Segment::Scan {
channel: Channel::LumaEven,
ms: $scan,
},
];
};
}
pd_segments!(PD_50, 91.520);
pd_segments!(PD_90, 170.240);
pd_segments!(PD_120, 121.600);
pd_segments!(PD_160, 195.584);
pd_segments!(PD_180, 183.040);
pd_segments!(PD_240, 244.672);
pd_segments!(PD_290, 228.800);
// ---------------------------------------------------------------------------
// Wraase SC2-180 — red, green, blue in that order after one porch.
// ---------------------------------------------------------------------------
const WRAASE_SC2_180: &[Segment] = &[
Segment::Sync(5.5225),
Segment::Gap(0.5),
Segment::Scan {
channel: Channel::Red,
ms: 235.0,
},
Segment::Scan {
channel: Channel::Green,
ms: 235.0,
},
Segment::Scan {
channel: Channel::Blue,
ms: 235.0,
},
];
/// Every mode this decoder knows, in VIS order.
pub static MODES: &[SstvMode] = &[
SstvMode {
vis: 8,
name: "Robot 36",
width: 320,
height: 240,
line_ms: 150.0,
segments: ROBOT_36,
color: ColorModel::YCrCbAlternating,
lines_per_transmission: 1,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 12,
name: "Robot 72",
width: 320,
height: 240,
line_ms: 300.0,
segments: ROBOT_72,
color: ColorModel::YCrCb,
lines_per_transmission: 1,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 40,
name: "Martin M2",
width: 320,
height: 256,
line_ms: 226.798,
segments: MARTIN_M2,
color: ColorModel::Rgb,
lines_per_transmission: 1,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 44,
name: "Martin M1",
width: 320,
height: 256,
line_ms: 446.446,
segments: MARTIN_M1,
color: ColorModel::Rgb,
lines_per_transmission: 1,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 55,
name: "Wraase SC2-180",
width: 320,
height: 256,
line_ms: 711.0225,
segments: WRAASE_SC2_180,
color: ColorModel::Rgb,
lines_per_transmission: 1,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 56,
name: "Scottie S2",
width: 320,
height: 256,
line_ms: 277.692,
segments: SCOTTIE_S2,
color: ColorModel::Rgb,
lines_per_transmission: 1,
sync_offset_ms: scottie_sync_offset(88.064),
},
SstvMode {
vis: 60,
name: "Scottie S1",
width: 320,
height: 256,
line_ms: 428.22,
segments: SCOTTIE_S1,
color: ColorModel::Rgb,
lines_per_transmission: 1,
sync_offset_ms: scottie_sync_offset(138.240),
},
SstvMode {
vis: 76,
name: "Scottie DX",
width: 320,
height: 256,
line_ms: 1050.3,
segments: SCOTTIE_DX,
color: ColorModel::Rgb,
lines_per_transmission: 1,
sync_offset_ms: scottie_sync_offset(345.6),
},
SstvMode {
vis: 93,
name: "PD50",
width: 320,
height: 256,
line_ms: 388.16,
segments: PD_50,
color: ColorModel::YCrCbPaired,
lines_per_transmission: 2,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 94,
name: "PD290",
width: 800,
height: 616,
line_ms: 937.28,
segments: PD_290,
color: ColorModel::YCrCbPaired,
lines_per_transmission: 2,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 95,
name: "PD120",
width: 640,
height: 496,
line_ms: 508.48,
segments: PD_120,
color: ColorModel::YCrCbPaired,
lines_per_transmission: 2,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 96,
name: "PD180",
width: 640,
height: 496,
line_ms: 754.24,
segments: PD_180,
color: ColorModel::YCrCbPaired,
lines_per_transmission: 2,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 97,
name: "PD240",
width: 640,
height: 496,
line_ms: 1000.768,
segments: PD_240,
color: ColorModel::YCrCbPaired,
lines_per_transmission: 2,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 98,
name: "PD160",
width: 512,
height: 400,
line_ms: 804.416,
segments: PD_160,
color: ColorModel::YCrCbPaired,
lines_per_transmission: 2,
sync_offset_ms: 0.0,
},
SstvMode {
vis: 99,
name: "PD90",
width: 320,
height: 256,
line_ms: 703.04,
segments: PD_90,
color: ColorModel::YCrCbPaired,
lines_per_transmission: 2,
sync_offset_ms: 0.0,
},
];
/// Look a mode up by the VIS code that announced it.
pub fn mode_for_vis(vis: u8) -> Option<&'static SstvMode> {
MODES.iter().find(|mode| mode.vis == vis)
}
/// Map an instantaneous frequency to an 8-bit level: 1500 Hz is black, 2300 Hz
/// white. Frequencies outside the band clamp rather than wrap, so a sync pulse
/// that lands inside a scan reads as black instead of as bright noise.
pub fn level_from_hz(hz: f32) -> u8 {
let level = (hz - BLACK_HZ) * (255.0 / (WHITE_HZ - BLACK_HZ));
level.clamp(0.0, 255.0).round() as u8
}
#[cfg(test)]
mod tests {
use super::*;
// The segment list and the published line time are two statements of the
// same fact, entered by hand from the specification. If a digit is wrong in
// one it is unlikely to be wrong identically in the other.
#[test]
fn segments_add_up_to_the_published_line_time() {
for mode in MODES {
let sum = mode.segments_ms();
assert!(
(sum - mode.line_ms).abs() < 0.001,
"{}: segments total {:.4} ms, line time says {:.4} ms",
mode.name,
sum,
mode.line_ms,
);
}
}
#[test]
fn vis_codes_are_unique_and_resolvable() {
for mode in MODES {
assert_eq!(mode_for_vis(mode.vis).map(|m| m.name), Some(mode.name));
}
let mut codes: Vec<u8> = MODES.iter().map(|m| m.vis).collect();
codes.sort_unstable();
let count = codes.len();
codes.dedup();
assert_eq!(codes.len(), count, "two modes claim the same VIS code");
}
#[test]
fn every_mode_scans_enough_channels_for_its_colour_model() {
for mode in MODES {
let scans = mode.scans();
let expected = match mode.color {
ColorModel::Rgb => 3,
ColorModel::YCrCbAlternating => 2,
ColorModel::YCrCb => 3,
ColorModel::YCrCbPaired => 4,
};
assert_eq!(
scans.len(),
expected,
"{} has {} scans",
mode.name,
scans.len()
);
}
}
// Frame durations are what operators know these modes by — the number in
// the name is the number of seconds.
#[test]
fn frame_durations_match_the_names() {
for (vis, secs) in [(8u8, 36.0), (12, 72.0), (93, 50.0), (99, 90.0), (95, 126.0)] {
let mode = mode_for_vis(vis).expect("mode in table");
let actual = mode.frame_secs();
assert!(
(actual - secs).abs() < 1.5,
"{} takes {:.1} s, expected about {:.0} s",
mode.name,
actual,
secs,
);
}
}
#[test]
fn levels_span_black_to_white_and_clamp_outside() {
assert_eq!(level_from_hz(BLACK_HZ), 0);
assert_eq!(level_from_hz(WHITE_HZ), 255);
assert_eq!(level_from_hz(1900.0), 128);
assert_eq!(level_from_hz(SYNC_HZ), 0, "a sync pulse must read as black");
assert_eq!(level_from_hz(3000.0), 255);
}
}
+236
View File
@@ -0,0 +1,236 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//! VIS header detection.
//!
//! Every transmission announces its mode in a fixed preamble:
//!
//! | Part | Tone | Duration |
//! |------|------|----------|
//! | Leader | 1900 Hz | 300 ms |
//! | Break | 1200 Hz | 10 ms |
//! | Leader | 1900 Hz | 300 ms |
//! | Start bit | 1200 Hz | 30 ms |
//! | 7 data bits, LSB first | 1100 Hz = 1, 1300 Hz = 0 | 30 ms each |
//! | Even parity | as above | 30 ms |
//! | Stop bit | 1200 Hz | 30 ms |
//!
//! The detector looks for the start bit standing behind a leader, reads the
//! eight bits that follow, and checks the parity. Parity is the only integrity
//! check the header has, so a code that fails it is discarded rather than
//! guessed at — decoding 114 seconds of Martin M1 as Scottie DX produces a
//! convincing-looking image of nothing.
/// Tone durations, in milliseconds.
const BIT_MS: f64 = 30.0;
const LEADER_MS: f64 = 300.0;
/// How far a tone may sit from its nominal frequency and still be recognised.
/// Wide enough for a rig tuned a little off, narrow enough that 1100, 1200,
/// 1300 and 1900 Hz stay distinct.
const TONE_TOLERANCE_HZ: f32 = 60.0;
const LEADER_HZ: f32 = 1900.0;
const START_HZ: f32 = 1200.0;
const ONE_HZ: f32 = 1100.0;
const ZERO_HZ: f32 = 1300.0;
/// A VIS header found in the stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VisHit {
/// The code, which names the mode.
pub code: u8,
/// Index just past the stop bit: where the image itself begins.
pub image_start: usize,
}
fn near(freq: f32, target: f32) -> bool {
(freq - target).abs() <= TONE_TOLERANCE_HZ
}
/// Mean frequency over the middle 60% of a bit cell, which keeps the filter's
/// transitions at either edge out of the measurement.
fn bit_frequency(freqs: &[f32], start: f64, samples_per_bit: f64) -> Option<f32> {
let from = (start + samples_per_bit * 0.2).round() as usize;
let to = (start + samples_per_bit * 0.8).round() as usize;
if to <= from || to > freqs.len() {
return None;
}
let window = &freqs[from..to];
Some(window.iter().sum::<f32>() / window.len() as f32)
}
/// Search `freqs` for a VIS header, starting at `from`.
///
/// Returns the first header whose parity checks out. `freqs` is instantaneous
/// frequency in Hz, one entry per audio sample.
pub fn find_vis(freqs: &[f32], sample_rate: u32, from: usize) -> Option<VisHit> {
let sr = f64::from(sample_rate);
// Header tones are 10 ms at the shortest, so a millisecond of averaging
// costs nothing and takes the demodulator's ripple — ±95 Hz at 1200 Hz —
// out of tones that are 100 Hz apart.
let smoothed = crate::demod::smooth(freqs, (sr / 1000.0).round() as usize);
let freqs = smoothed.as_slice();
let samples_per_bit = BIT_MS / 1000.0 * sr;
let leader_samples = (LEADER_MS / 1000.0 * sr) as usize;
// The start bit must be at least this long to be one.
let min_start_run = (samples_per_bit * 0.7) as usize;
// A leader has to precede the start bit. Half of one is enough evidence,
// and asking for less than the full 300 ms means the search still works on
// a buffer that begins part-way through the header.
let leader_needed = leader_samples / 2;
// The bits themselves may run to the very end of what has arrived so far;
// reading them is what decides whether there is enough, not this bound.
let mut i = from.max(leader_needed);
while i < freqs.len() {
if !near(freqs[i], START_HZ) {
i += 1;
continue;
}
// Measure the run of start tone.
let mut run = 0usize;
while i + run < freqs.len() && near(freqs[i + run], START_HZ) {
run += 1;
}
if run < min_start_run {
i += run.max(1);
continue;
}
// What came before it: the leader. Sampled rather than scanned in
// full, since only its identity matters, not its exact length.
let leader_from = i - leader_needed;
let leader_hits = freqs[leader_from..i]
.iter()
.step_by(16)
.filter(|&&f| near(f, LEADER_HZ))
.count();
let leader_total = freqs[leader_from..i].iter().step_by(16).count();
if leader_total == 0 || (leader_hits as f64) < 0.7 * leader_total as f64 {
i += run;
continue;
}
// Bits follow the start bit, which the run just measured. Use the run's
// own end rather than a nominal offset, so a start bit stretched or
// clipped by the filter does not shift every bit after it.
let bits_start = (i + run) as f64;
let mut bits = [false; 8];
let mut readable = true;
for (index, bit) in bits.iter_mut().enumerate() {
let at = bits_start + samples_per_bit * index as f64;
match bit_frequency(freqs, at, samples_per_bit) {
Some(freq) if near(freq, ONE_HZ) => *bit = true,
Some(freq) if near(freq, ZERO_HZ) => *bit = false,
_ => {
readable = false;
break;
}
}
}
if !readable {
i += run;
continue;
}
// Seven data bits, LSB first, then even parity over them.
let code = bits[..7]
.iter()
.enumerate()
.fold(0u8, |acc, (index, &set)| acc | (u8::from(set) << index));
let ones = bits[..7].iter().filter(|&&b| b).count() + usize::from(bits[7]);
if ones % 2 != 0 {
i += run;
continue;
}
// Past the stop bit is the image.
let image_start = (bits_start + samples_per_bit * 9.0).round() as usize;
return Some(VisHit { code, image_start });
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::encode::{vis_tones, Tone};
fn freqs_from_tones(tones: &[Tone], sample_rate: u32) -> Vec<f32> {
let mut out = Vec::new();
for tone in tones {
let samples = (tone.ms / 1000.0 * f64::from(sample_rate)).round() as usize;
out.extend(std::iter::repeat_n(tone.hz, samples));
}
out
}
#[test]
fn reads_every_code_the_mode_table_knows() {
for mode in crate::mode::MODES {
let freqs = freqs_from_tones(&vis_tones(mode.vis), 48_000);
let hit = find_vis(&freqs, 48_000, 0)
.unwrap_or_else(|| panic!("{} header not found", mode.name));
assert_eq!(
hit.code, mode.vis,
"{} decoded as VIS {}",
mode.name, hit.code
);
}
}
#[test]
fn the_image_starts_after_the_stop_bit() {
let sample_rate = 48_000;
let freqs = freqs_from_tones(&vis_tones(44), sample_rate);
let hit = find_vis(&freqs, sample_rate, 0).expect("header");
// Header is 300 + 10 + 300 ms of leader and break, then ten 30 ms bits.
let expected = ((300.0 + 10.0 + 300.0 + 300.0) / 1000.0 * f64::from(sample_rate)) as usize;
let slack = sample_rate as usize / 100; // 10 ms
assert!(
hit.image_start.abs_diff(expected) < slack,
"image starts at {}, expected about {expected}",
hit.image_start,
);
}
#[test]
fn a_header_with_broken_parity_is_not_a_header() {
let sample_rate = 48_000;
let mut tones = vis_tones(44);
// Flip the parity bit alone: seven data bits still say Martin M1, but
// nothing now vouches for them.
let parity = tones.len() - 2;
tones[parity].hz = if tones[parity].hz == ONE_HZ {
ZERO_HZ
} else {
ONE_HZ
};
let freqs = freqs_from_tones(&tones, sample_rate);
assert_eq!(find_vis(&freqs, sample_rate, 0), None);
}
#[test]
fn tones_without_a_leader_are_not_a_header() {
let sample_rate = 48_000;
let mut tones = vis_tones(44);
// Same bits, but the leader before them is a pixel-band tone — which is
// what a passing image looks like.
tones[0].hz = 2000.0;
tones[2].hz = 2000.0;
let freqs = freqs_from_tones(&tones, sample_rate);
assert_eq!(find_vis(&freqs, sample_rate, 0), None);
}
#[test]
fn a_header_part_way_into_the_buffer_is_still_found() {
let sample_rate = 48_000;
let mut freqs = vec![1750.0f32; sample_rate as usize]; // a second of picture
freqs.extend(freqs_from_tones(&vis_tones(60), sample_rate));
let hit = find_vis(&freqs, sample_rate, 0).expect("header");
assert_eq!(hit.code, 60);
}
}
+384
View File
@@ -0,0 +1,384 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later
//! Decode what was encoded, and compare the pictures.
//!
//! A decoder for a picture format can only really be tested against a picture.
//! These tests build a test card, transmit it in each mode through the
//! encoder, and hold the decoder to what comes back — pixel by pixel, with a
//! tolerance that accounts for the round trip through frequency and, for the
//! colour modes, through a chroma channel at half the width.
//!
//! What this does not test is the timing table itself: the encoder reads the
//! same numbers as the decoder, so a wrong line duration would cancel out.
//! That is checked in `mode.rs` against the published line times instead.
use trx_sstv::encode::{encode, Frame};
use trx_sstv::mode::mode_for_vis;
use trx_sstv::{SstvConfig, SstvDecoder, SstvEvent, SstvImage};
const SAMPLE_RATE: u32 = 48_000;
/// A test card with something for every part of the decoder to get wrong:
/// vertical colour bars catch channels swapped or shifted, the horizontal
/// gradient catches a line-timing drift, and the corner blocks catch a picture
/// that arrives upside down or mirrored.
fn test_card(width: usize, height: usize) -> Vec<u8> {
let mut rgb = vec![0u8; width * height * 3];
let bars: [(u8, u8, u8); 8] = [
(255, 255, 255),
(255, 255, 0),
(0, 255, 255),
(0, 255, 0),
(255, 0, 255),
(255, 0, 0),
(0, 0, 255),
(0, 0, 0),
];
for y in 0..height {
for x in 0..width {
let at = (y * width + x) * 3;
let (r, g, b) = if y < height / 2 {
bars[x * bars.len() / width]
} else {
let ramp = (x * 255 / width.max(1)) as u8;
let down = (y * 255 / height.max(1)) as u8;
(ramp, down, 255 - ramp)
};
rgb[at] = r;
rgb[at + 1] = g;
rgb[at + 2] = b;
}
}
// Corner marks: red top-left, blue bottom-right.
for y in 0..height.min(8) {
for x in 0..width.min(8) {
let at = (y * width + x) * 3;
rgb[at] = 255;
rgb[at + 1] = 0;
rgb[at + 2] = 0;
}
}
for y in height.saturating_sub(8)..height {
for x in width.saturating_sub(8)..width {
let at = (y * width + x) * 3;
rgb[at] = 0;
rgb[at + 1] = 0;
rgb[at + 2] = 255;
}
}
rgb
}
/// Run audio through the decoder in blocks the size a sound card delivers.
///
/// A little silence is fed after the signal, as a receiver that keeps
/// listening supplies: the demodulator is a filter, so the last millisecond of
/// any transmission needs the samples after it before it can be read.
fn decode(audio: &[f32]) -> (Vec<SstvImage>, usize) {
let mut tail = audio.to_vec();
tail.extend(std::iter::repeat_n(0.0, SAMPLE_RATE as usize / 20));
let audio = tail.as_slice();
let mut decoder = SstvDecoder::new(SAMPLE_RATE, SstvConfig::default());
let mut images = Vec::new();
let mut rows = 0;
for block in audio.chunks(1024) {
for event in decoder.process_samples(block) {
match event {
SstvEvent::Row { .. } => rows += 1,
SstvEvent::Complete(image) => images.push(image),
SstvEvent::Started { .. } => {}
}
}
}
(images, rows)
}
/// Mean absolute error per colour channel between two same-sized images.
fn mean_error(a: &[u8], b: &[u8]) -> f64 {
assert_eq!(a.len(), b.len());
let total: u64 = a
.iter()
.zip(b)
.map(|(x, y)| u64::from(x.abs_diff(*y)))
.sum();
total as f64 / a.len() as f64
}
/// Error over the part of the picture away from channel edges, where a decoder
/// that is a pixel out on a hard colour boundary would otherwise dominate.
fn interior_error(mode_width: usize, height: usize, sent: &[u8], got: &[u8]) -> f64 {
let mut total = 0u64;
let mut count = 0u64;
for y in 2..height.saturating_sub(2) {
for x in 4..mode_width.saturating_sub(4) {
// Skip the columns where the bars change, which is where a
// half-pixel timing difference shows up as a whole-colour error.
if x % (mode_width / 8) < 3 {
continue;
}
let at = (y * mode_width + x) * 3;
for channel in 0..3 {
total += u64::from(sent[at + channel].abs_diff(got[at + channel]));
count += 1;
}
}
}
total as f64 / count.max(1) as f64
}
fn round_trip(vis: u8, tolerance: f64) {
let mode = mode_for_vis(vis).expect("mode in table");
let width = usize::from(mode.width);
let height = usize::from(mode.height);
let sent = test_card(width, height);
let frame = Frame {
width,
height,
rgb: &sent,
};
let audio = encode(mode, &frame, SAMPLE_RATE);
let (images, rows) = decode(&audio);
assert_eq!(
images.len(),
1,
"{}: expected one picture, got {}",
mode.name,
images.len()
);
let image = &images[0];
assert!(
image.complete,
"{}: reception did not reach the bottom",
mode.name
);
assert_eq!(image.mode, mode.name);
assert_eq!(
image.lines, mode.height,
"{}: {} of {} lines",
mode.name, image.lines, mode.height
);
assert_eq!(
rows, height,
"{}: emitted {rows} rows for {height} lines",
mode.name
);
let error = interior_error(width, height, &sent, &image.rgb);
assert!(
error < tolerance,
"{}: mean error {error:.1} levels, tolerance {tolerance:.1}",
mode.name,
);
}
#[test]
fn martin_m1_round_trips() {
round_trip(44, 6.0);
}
#[test]
fn martin_m2_round_trips() {
round_trip(40, 8.0);
}
#[test]
fn scottie_s1_round_trips() {
round_trip(60, 6.0);
}
#[test]
fn scottie_s2_round_trips() {
round_trip(56, 8.0);
}
#[test]
fn wraase_sc2_180_round_trips() {
round_trip(55, 6.0);
}
// The colour-difference modes lose chroma resolution by design, so the bars
// bleed into one another at their edges; the tolerance is on the interior.
#[test]
fn robot_72_round_trips() {
round_trip(12, 14.0);
}
#[test]
fn robot_36_round_trips() {
// One chroma channel per line, the other carried over from the line
// before, so alternate lines are a line stale in one channel.
round_trip(8, 26.0);
}
#[test]
fn pd90_round_trips() {
round_trip(99, 14.0);
}
#[test]
fn pd120_round_trips() {
round_trip(95, 14.0);
}
/// Silence before and after is the normal case — a receiver is not started at
/// the instant the transmission does.
#[test]
fn survives_silence_around_the_transmission() {
let mode = mode_for_vis(44).expect("Martin M1");
let (width, height) = (usize::from(mode.width), usize::from(mode.height));
let sent = test_card(width, height);
let frame = Frame {
width,
height,
rgb: &sent,
};
let mut audio = vec![0.0f32; SAMPLE_RATE as usize * 2];
audio.extend(encode(mode, &frame, SAMPLE_RATE));
audio.extend(std::iter::repeat_n(0.0, SAMPLE_RATE as usize));
let (images, _) = decode(&audio);
assert_eq!(
images.len(),
1,
"expected one picture from a transmission in silence"
);
assert!(images[0].complete);
}
/// A transmission cut off part-way is what a fade or a shut-down transmitter
/// produces. The lines that did arrive are worth keeping.
#[test]
fn a_truncated_transmission_still_yields_its_lines() {
let mode = mode_for_vis(44).expect("Martin M1");
let (width, height) = (usize::from(mode.width), usize::from(mode.height));
let sent = test_card(width, height);
let frame = Frame {
width,
height,
rgb: &sent,
};
let full = encode(mode, &frame, SAMPLE_RATE);
// Two thirds of the picture, then silence for long enough that the decoder
// stops waiting for the rest.
let mut audio = full[..full.len() * 2 / 3].to_vec();
audio.extend(std::iter::repeat_n(0.0, SAMPLE_RATE as usize * 5));
let (images, _) = decode(&audio);
assert_eq!(
images.len(),
1,
"a cut-off transmission produced no picture"
);
let image = &images[0];
assert!(
!image.complete,
"a two-thirds transmission reported as complete"
);
assert!(
image.lines > mode.height / 2 && image.lines < mode.height,
"{} lines of {} arrived",
image.lines,
mode.height,
);
// What did arrive is the top of the picture, and it is right.
let rows = usize::from(image.lines).saturating_sub(4);
let error = mean_error(&sent[..width * rows * 3], &image.rgb[..width * rows * 3]);
assert!(
error < 12.0,
"the lines that arrived are wrong: mean error {error:.1}"
);
}
/// Two pictures back to back: the decoder has to finish the first and pick up
/// the header of the second.
#[test]
fn decodes_a_second_transmission_after_the_first() {
let mode = mode_for_vis(40).expect("Martin M2");
let (width, height) = (usize::from(mode.width), usize::from(mode.height));
let sent = test_card(width, height);
let frame = Frame {
width,
height,
rgb: &sent,
};
let one = encode(mode, &frame, SAMPLE_RATE);
let mut audio = one.clone();
audio.extend(std::iter::repeat_n(0.0, SAMPLE_RATE as usize / 2));
audio.extend(one);
let (images, _) = decode(&audio);
assert_eq!(
images.len(),
2,
"expected two pictures, got {}",
images.len()
);
assert!(
images.iter().all(|image| image.complete),
"a picture did not finish"
);
}
/// Noise on the signal is the normal condition on HF. The picture should
/// degrade, not fall apart.
#[test]
fn decodes_through_noise() {
let mode = mode_for_vis(44).expect("Martin M1");
let (width, height) = (usize::from(mode.width), usize::from(mode.height));
let sent = test_card(width, height);
let frame = Frame {
width,
height,
rgb: &sent,
};
let clean = encode(mode, &frame, SAMPLE_RATE);
// Deterministic pseudo-noise at about 20 dB below the signal.
let mut seed = 0x5eed_1234u32;
let noisy: Vec<f32> = clean
.iter()
.map(|sample| {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let noise = (seed >> 8) as f32 / f32::from(u16::MAX) / 256.0 - 0.5;
sample + noise * 0.2
})
.collect();
let (images, _) = decode(&noisy);
assert_eq!(images.len(), 1, "noise cost the whole picture");
let image = &images[0];
assert!(image.complete, "noise cost the bottom of the picture");
let error = interior_error(width, height, &sent, &image.rgb);
assert!(error < 20.0, "mean error through noise {error:.1} levels");
}
/// The sound card that plays the signal and the one that records it never
/// agree exactly. A part-per-thousand error is far worse than reality and the
/// picture should still stand up.
#[test]
fn tolerates_a_transmitter_clock_that_runs_fast() {
let mode = mode_for_vis(44).expect("Martin M1");
let (width, height) = (usize::from(mode.width), usize::from(mode.height));
let sent = test_card(width, height);
let frame = Frame {
width,
height,
rgb: &sent,
};
// Encoding at a slightly different rate and decoding at 48 kHz is exactly
// a clock error: every duration is stretched by the same factor.
let audio = encode(mode, &frame, 48_048);
let (images, _) = decode(&audio);
assert_eq!(images.len(), 1, "a 0.1% clock error cost the picture");
let error = interior_error(width, height, &sent, &images[0].rgb);
assert!(
error < 12.0,
"mean error with a fast clock {error:.1} levels"
);
}
+1 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-vdes"
+2 -4
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! CRC-16 for VDES link-layer frames.
//!
@@ -134,9 +134,7 @@ mod tests {
.flat_map(|&b| (0..8).rev().map(move |i| (b >> i) & 1))
.collect();
// Append wrong CRC
for _ in 0..16 {
bits.push(0);
}
bits.resize(bits.len() + 16, 0);
assert!(!check_crc16(&bits));
}
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! VDES 100 kHz decoder for VDE-TER (ITU-R M.2092-1).
//!
+3 -3
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! VDES link-layer frame parsing per ITU-R M.2092-1.
//!
@@ -346,8 +346,8 @@ mod tests {
write_bits(&mut bits, 12, 32, 123456); // source_id
write_bits(&mut bits, 44, 11, 20); // data_count = 20
// Fill some payload
for i in 55..75 {
bits[i] = (i % 2) as u8;
for (i, bit) in bits.iter_mut().enumerate().take(75).skip(55) {
*bit = (i % 2) as u8;
}
append_crc(&mut bits);
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Turbo FEC decoder for VDES TER-MCS-1 (100 kHz channel).
//!
+1 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-wefax"
+1 -5
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! WEFAX decoder configuration.
@@ -19,9 +19,6 @@ pub struct WefaxConfig {
pub output_dir: Option<String>,
/// Whether to emit line-by-line progress events.
pub emit_progress: bool,
/// Whether to continuously track and correct sample-clock drift
/// (line-to-line cross-correlation) to remove image slant.
pub slant_correction: bool,
}
impl Default for WefaxConfig {
@@ -33,7 +30,6 @@ impl Default for WefaxConfig {
deviation_hz: 400.0,
output_dir: None,
emit_progress: true,
slant_correction: true,
}
}
}
+38 -111
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Top-level WEFAX decoder state machine.
//!
@@ -43,26 +43,11 @@ const LINE_CORR_NOISE_THRESHOLD: f32 = 0.2;
/// fldigi's line-to-line correlation check for automatic stop.
const LINE_CORR_NOISE_LINES: u32 = 30;
/// Pearson correlation above which adjacent lines are considered good
/// evidence of real image content. Used to verify unverified auto-starts.
const LINE_CORR_IMAGE_THRESHOLD: f32 = 0.5;
/// Number of consecutive well-correlated lines that verify an unverified
/// reception (i.e. an auto-start from variance detection). Low enough to
/// engage quickly on real imagery.
const VERIFY_HIGH_CORR_STREAK: u32 = 5;
/// Maximum number of scan lines the verifier waits for before giving up on
/// an unverified reception. Roughly 20 s at 120 LPM. If no high-correlation
/// streak appears by then, the buffered content is dropped and we return
/// to Idle without saving anything.
const VERIFY_TIMEOUT_LINES: u32 = 40;
/// Maximum number of scan-line-equivalent sample windows to wait for phasing
/// lock before falling through to Receiving (unverified). Typical WEFAX
/// phasing lasts ~30 s; if the phasing detector hasn't converged by then
/// we give up on alignment and let the correlation verifier decide whether
/// the content that follows is a real image. At 120 LPM this is ~30 s.
/// lock before falling through to Receiving. Typical WEFAX phasing lasts
/// ~30 s; if the phasing detector hasn't converged by then we give up on
/// alignment and let the carrier-loss watchdog decide whether the content
/// that follows is real imagery. At 120 LPM this is ~30 s.
const PHASING_TIMEOUT_LINES: u32 = 60;
/// WEFAX decoder output event.
@@ -117,18 +102,10 @@ pub struct WefaxDecoder {
/// `LINE_CORR_NOISE_LINES` the decoder auto-finalizes the in-progress
/// image (carrier dropped / tx ended without an APT stop tone).
low_corr_lines: u32,
/// `true` once the current reception has been confirmed to contain real
/// image content. Set immediately for phasing-driven entries (the APT
/// start tone + phasing pulses already proved the signal); set later
/// by the correlation verifier for variance-driven auto-starts.
verified: bool,
/// Rolling count of consecutive well-correlated lines, used to confirm
/// an unverified reception.
high_corr_streak: u32,
/// Number of luminance samples processed while in `State::Phasing`.
/// When this exceeds the equivalent of `PHASING_TIMEOUT_LINES` lines,
/// the decoder falls through to Receiving (unverified) so a noisy or
/// partial phasing signal doesn't wedge the state machine.
/// the decoder falls through to Receiving so a noisy or partial
/// phasing signal doesn't wedge the state machine.
phasing_samples: u64,
/// Current rig dial frequency in Hz (for image filenames).
freq_hz: u64,
@@ -157,8 +134,6 @@ impl WefaxDecoder {
signal_detect_count: 0,
signal_detect_buf: Vec::with_capacity(INTERNAL_RATE as usize / 2),
low_corr_lines: 0,
verified: false,
high_corr_streak: 0,
phasing_samples: 0,
freq_hz: 0,
mode: String::new(),
@@ -267,7 +242,7 @@ impl WefaxDecoder {
.as_millis() as i64,
);
self.signal_detect_buf.clear();
events.push(self.transition_to_receiving(ioc, lpm, 0, false));
events.push(self.transition_to_receiving(ioc, lpm, 0));
break;
}
@@ -297,12 +272,12 @@ impl WefaxDecoder {
if let Some(ref mut phasing) = self.phasing {
if let Some(offset) = phasing.process(&luminance) {
events.push(self.transition_to_receiving(ioc, lpm, offset, true));
events.push(self.transition_to_receiving(ioc, lpm, offset));
} else {
// Phasing timeout: if alignment doesn't converge in
// ~PHASING_TIMEOUT_LINES lines, fall through to
// Receiving (unverified) and let the correlation
// verifier decide.
// Receiving and let the carrier-loss watchdog decide
// whether the content that follows is real imagery.
self.phasing_samples += luminance.len() as u64;
let spl = WefaxConfig::samples_per_line(lpm, INTERNAL_RATE) as u64;
if self.phasing_samples >= spl * PHASING_TIMEOUT_LINES as u64 {
@@ -310,7 +285,7 @@ impl WefaxDecoder {
ioc,
lpm, "WEFAX: phasing timeout — falling through to receiving"
);
events.push(self.transition_to_receiving(ioc, lpm, 0, false));
events.push(self.transition_to_receiving(ioc, lpm, 0));
}
}
}
@@ -327,66 +302,36 @@ impl WefaxDecoder {
// Feed luminance to line slicer.
let mut carrier_lost = false;
let mut verify_failed = false;
if let Some(ref mut slicer) = self.slicer {
let new_lines = slicer.process(&luminance);
for line in new_lines {
if let Some(ref mut image) = self.image {
// Line-to-line Pearson correlation classifies the
// new line as image-like, noise-like, or flat.
// fldigi-style: real imagery has highly correlated
// adjacent lines; pure noise does not.
// Carrier-loss watchdog: real imagery has highly
// correlated adjacent lines; pure noise does not.
// After LINE_CORR_NOISE_LINES consecutive low-
// correlation lines we finalize (fldigi-style
// automatic stop).
if let Some(r) = image.correlation_with_last(&line) {
if r >= LINE_CORR_IMAGE_THRESHOLD {
self.high_corr_streak += 1;
self.low_corr_lines = 0;
if !self.verified
&& self.high_corr_streak >= VERIFY_HIGH_CORR_STREAK
{
self.verified = true;
debug!(
lines = image.line_count(),
"WEFAX: reception verified from line correlation"
);
}
} else if r < LINE_CORR_NOISE_THRESHOLD {
if r < LINE_CORR_NOISE_THRESHOLD {
self.low_corr_lines += 1;
self.high_corr_streak = 0;
trace!(
r = format!("{:.3}", r),
count = self.low_corr_lines,
"WEFAX low line-correlation"
);
} else {
// Middle zone — reset high streak, hold
// low-corr counter.
self.high_corr_streak = 0;
self.low_corr_lines = 0;
}
}
// Flat lines (correlation == None) don't advance
// either counter — solid bands in real imagery
// shouldn't be scored as noise OR as evidence.
// the counter but also don't reset it — an image
// with a solid band surrounded by noise still
// trips the watchdog once the noise resumes.
image.push_line(line);
let count = image.line_count();
// Unverified timeout: if we got here from a
// variance auto-start and line correlation never
// took hold, the "signal" wasn't real WEFAX.
// Abandon without saving.
if !self.verified && count >= VERIFY_TIMEOUT_LINES {
debug!(
lines = count,
"WEFAX: failed to verify image content — abandoning"
);
verify_failed = true;
break;
}
// Carrier-loss watchdog — only active once the
// reception has been verified (otherwise it
// double-counts with the verify timeout).
if self.verified && self.low_corr_lines >= LINE_CORR_NOISE_LINES {
if self.low_corr_lines >= LINE_CORR_NOISE_LINES {
debug!(
lines = count,
"WEFAX: line correlation lost — auto-finalizing image"
@@ -418,15 +363,6 @@ impl WefaxDecoder {
}
}
if verify_failed {
// Drop buffered content without saving — this was a
// false auto-start (tone, noise burst, etc.).
self.image = None;
self.reception_start_ms = None;
self.transition_to_idle();
return events;
}
if carrier_lost {
events.extend(self.finalize_image(ioc, lpm));
self.transition_to_idle();
@@ -465,8 +401,6 @@ impl WefaxDecoder {
self.signal_detect_count = 0;
self.signal_detect_buf.clear();
self.low_corr_lines = 0;
self.verified = false;
self.high_corr_streak = 0;
self.phasing_samples = 0;
events
}
@@ -522,30 +456,13 @@ impl WefaxDecoder {
self.state_event("Phasing", ioc, lpm)
}
fn transition_to_receiving(
&mut self,
ioc: u16,
lpm: u16,
phase_offset: usize,
verified: bool,
) -> WefaxEvent {
debug!(
ioc,
lpm, phase_offset, verified, "WEFAX: entering receiving"
);
fn transition_to_receiving(&mut self, ioc: u16, lpm: u16, phase_offset: usize) -> WefaxEvent {
debug!(ioc, lpm, phase_offset, "WEFAX: entering receiving");
let ppl = WefaxConfig::pixels_per_line(ioc) as usize;
self.slicer = Some(LineSlicer::with_slant(
lpm,
ioc,
INTERNAL_RATE,
phase_offset,
self.config.slant_correction,
));
self.slicer = Some(LineSlicer::new(lpm, ioc, INTERNAL_RATE, phase_offset));
self.image = Some(ImageAssembler::new(ppl));
self.tone_detector.reset();
self.low_corr_lines = 0;
self.verified = verified;
self.high_corr_streak = 0;
self.state = State::Receiving { ioc, lpm };
self.state_event("Receiving", ioc, lpm)
}
@@ -559,8 +476,6 @@ impl WefaxDecoder {
self.signal_detect_count = 0;
self.signal_detect_buf.clear();
self.low_corr_lines = 0;
self.verified = false;
self.high_corr_streak = 0;
self.phasing_samples = 0;
}
@@ -574,12 +489,23 @@ impl WefaxDecoder {
let ppl = WefaxConfig::pixels_per_line(ioc);
let mut path_str = None;
let mut png_data = None;
// Save PNG if output directory is configured.
if let Some(ref dir) = self.config.output_dir {
let output_path = PathBuf::from(dir);
match image.save_png(&output_path, self.freq_hz, &self.mode) {
Ok(p) => {
// Read back the PNG bytes for remote client transfer.
match std::fs::read(&p) {
Ok(bytes) => {
png_data =
Some(base64::engine::general_purpose::STANDARD.encode(&bytes));
}
Err(e) => {
eprintln!("WEFAX: failed to read PNG for transfer: {}", e);
}
}
path_str = Some(p.to_string_lossy().into_owned());
}
Err(e) => {
@@ -597,6 +523,7 @@ impl WefaxDecoder {
ioc,
pixels_per_line: ppl,
path: path_str,
png_data,
complete: true,
}));
}
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! FM discriminator for WEFAX demodulation.
//!
+14 -7
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Image buffer and PNG encoding for WEFAX decoded images.
@@ -144,9 +144,15 @@ impl ImageAssembler {
}
debug_assert_eq!(img_data.len(), expected_bytes);
writer
.write_image_data(&img_data)
.map_err(|e| format!("write PNG data ({} bytes, {}x{}): {}", img_data.len(), width, height, e))?;
writer.write_image_data(&img_data).map_err(|e| {
format!(
"write PNG data ({} bytes, {}x{}): {}",
img_data.len(),
width,
height,
e
)
})?;
// Explicitly finish the writer (writes IEND). Relying on Drop
// alone swallows any I/O error and can yield a truncated file.
@@ -268,7 +274,8 @@ mod tests {
// Pseudo-random noise vs gradient — correlation should be low.
let noise: Vec<u8> = (0..256)
.map(|i| ((i * 1103515245 + 12345) as u32 >> 8 & 0xff) as u8)
.map(|i| (i as u32).wrapping_mul(1_103_515_245).wrapping_add(12_345))
.map(|value| ((value >> 8) & 0xff) as u8)
.collect();
let r = asm.correlation_with_last(&noise).expect("r");
assert!(
@@ -368,8 +375,8 @@ mod tests {
let (y, m, d, h, mi, _) = unix_to_utc(1775055000);
assert_eq!(y, 2026);
// Just verify reasonable values without asserting exact date.
assert!(m >= 1 && m <= 12);
assert!(d >= 1 && d <= 31);
assert!((1..=12).contains(&m));
assert!((1..=31).contains(&d));
assert!(h < 24);
assert!(mi < 60);
}
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! WEFAX (Weather Facsimile) decoder.
//!
+9 -257
View File
@@ -1,27 +1,15 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Line slicer: pixel clock recovery and line buffer assembly.
//!
//! Once the phasing detector has established a line-start phase offset,
//! the line slicer accumulates demodulated luminance samples and extracts
//! complete image lines at the configured LPM rate.
//!
//! When `slant_correction` is enabled, the slicer tracks line-to-line
//! drift via cross-correlation with the previous line and nudges the
//! extraction cursor by ±`MAX_DRIFT_SAMPLES` per line. This compensates
//! for the small mismatch between the transmitter's and receiver's
//! sample clocks that would otherwise skew the assembled image.
use crate::config::WefaxConfig;
/// Maximum per-line drift (in samples at the internal rate) searched for
/// when slant correction is enabled. At 120 LPM / 11025 Hz there are
/// ~5512 samples per line, so ±6 samples is ~0.1% drift per line — more
/// than enough for any real-world sample-clock mismatch.
const MAX_DRIFT_SAMPLES: usize = 6;
/// Line slicer for WEFAX image assembly.
pub struct LineSlicer {
/// Samples per line at the internal sample rate.
@@ -30,34 +18,14 @@ pub struct LineSlicer {
pixels_per_line: usize,
/// Phase offset in samples from the phasing detector.
phase_offset: usize,
/// Accumulated luminance samples. While `slant_correction` is on,
/// the buffer anchor is the *start of the previous line* (so the
/// first `samples_per_line` samples are the reference for drift
/// tracking). Without slant correction the anchor is simply the
/// start of the next line to extract.
/// Accumulated luminance samples.
buffer: Vec<f32>,
/// Whether we have aligned to the phase offset yet.
aligned: bool,
/// Whether a reference (previous) line is held at the buffer anchor.
has_reference: bool,
/// Enable line-to-line drift tracking.
slant_correction: bool,
/// Cumulative drift applied so far (samples). Diagnostic.
pub(crate) total_drift: i64,
}
impl LineSlicer {
pub fn new(lpm: u16, ioc: u16, sample_rate: u32, phase_offset: usize) -> Self {
Self::with_slant(lpm, ioc, sample_rate, phase_offset, true)
}
pub fn with_slant(
lpm: u16,
ioc: u16,
sample_rate: u32,
phase_offset: usize,
slant_correction: bool,
) -> Self {
let samples_per_line = WefaxConfig::samples_per_line(lpm, sample_rate);
let pixels_per_line = WefaxConfig::pixels_per_line(ioc) as usize;
@@ -65,11 +33,8 @@ impl LineSlicer {
samples_per_line,
pixels_per_line,
phase_offset,
buffer: Vec::with_capacity(samples_per_line * 3),
buffer: Vec::with_capacity(samples_per_line * 2),
aligned: false,
has_reference: false,
slant_correction,
total_drift: 0,
}
}
@@ -90,58 +55,17 @@ impl LineSlicer {
self.aligned = true;
}
let spl = self.samples_per_line;
if !self.slant_correction {
// Simple fixed-period extraction.
// Extract complete lines (single drain at the end to avoid O(n²)).
let mut offset = 0;
while offset + spl <= self.buffer.len() {
let line_samples = &self.buffer[offset..offset + spl];
while offset + self.samples_per_line <= self.buffer.len() {
let line_samples = &self.buffer[offset..offset + self.samples_per_line];
let pixels = self.resample_line(line_samples);
lines.push(pixels);
offset += spl;
offset += self.samples_per_line;
}
if offset > 0 {
self.buffer.drain(..offset);
}
return lines;
}
// Slant-corrected extraction.
let max_shift = MAX_DRIFT_SAMPLES;
// Bootstrap: the very first line has no previous reference.
// Extract it naively and keep it in the buffer as the reference.
if !self.has_reference {
if self.buffer.len() < spl {
return lines;
}
let first = self.buffer[0..spl].to_vec();
let pixels = self.resample_line(&first);
lines.push(pixels);
self.has_reference = true;
// Do NOT drain: the first `spl` samples remain as the
// reference for the next line's drift search.
}
// Subsequent lines: for each iteration, buffer[0..spl] is the
// reference line, and we search for the best starting position
// of the NEXT line in the range [spl - max_shift, spl + max_shift].
while self.buffer.len() >= 2 * spl + max_shift {
let prev = &self.buffer[0..spl];
let (best_d, _best_r) =
search_best_shift(prev, &self.buffer, spl, max_shift);
let start = (spl as i32 + best_d) as usize;
let next_line = self.buffer[start..start + spl].to_vec();
let pixels = self.resample_line(&next_line);
lines.push(pixels);
// Advance the anchor to the start of the line we just
// emitted — it becomes the reference for the next iteration.
self.buffer.drain(..start);
self.total_drift += best_d as i64;
}
lines
}
@@ -150,16 +74,9 @@ impl LineSlicer {
self.pixels_per_line
}
/// Samples per line at the internal rate (for diagnostics).
pub fn samples_per_line(&self) -> usize {
self.samples_per_line
}
pub fn reset(&mut self) {
self.buffer.clear();
self.aligned = false;
self.has_reference = false;
self.total_drift = 0;
}
/// Resample a line's worth of luminance samples to the target pixel count
@@ -190,82 +107,6 @@ impl LineSlicer {
}
}
/// Search for the drift `d ∈ [-max_shift, +max_shift]` that maximises
/// the Pearson correlation between `reference` and
/// `buffer[spl+d .. spl+d+spl]`.
///
/// Returns `(best_d, best_r)`. A correlation-peak deadband prefers
/// `d = 0` when the peak is only marginally better than at zero, which
/// keeps tracking stable on quiet lines.
fn search_best_shift(
reference: &[f32],
buffer: &[f32],
spl: usize,
max_shift: usize,
) -> (i32, f32) {
debug_assert!(buffer.len() >= 2 * spl + max_shift);
debug_assert_eq!(reference.len(), spl);
// Pre-compute reference mean + variance.
let n = spl as f32;
let mean_r = reference.iter().sum::<f32>() / n;
let mut var_r = 0.0f32;
for &v in reference {
let d = v - mean_r;
var_r += d * d;
}
// Guard against a flat reference line — drift tracking is useless.
const MIN_VAR: f32 = 32.0;
if var_r < MIN_VAR {
return (0, 0.0);
}
let ms = max_shift as i32;
let mut best_d = 0i32;
let mut best_r = f32::NEG_INFINITY;
let mut r_at_zero = 0.0f32;
for d in -ms..=ms {
let start = (spl as i32 + d) as usize;
let candidate = &buffer[start..start + spl];
let mean_c = candidate.iter().sum::<f32>() / n;
let mut var_c = 0.0f32;
let mut cov = 0.0f32;
for (i, &v) in candidate.iter().enumerate() {
let dr = reference[i] - mean_r;
let dc = v - mean_c;
cov += dr * dc;
var_c += dc * dc;
}
let r = if var_c < MIN_VAR {
// Skip flat candidate slices.
f32::NEG_INFINITY
} else {
cov / (var_r.sqrt() * var_c.sqrt())
};
if d == 0 {
r_at_zero = r;
}
if r > best_r {
best_r = r;
best_d = d;
}
}
// Deadband: if the peak is only marginally better than `d = 0`,
// stick with zero. This avoids per-line jitter when drift is small.
const DEADBAND: f32 = 0.01;
if r_at_zero.is_finite() && best_r - r_at_zero < DEADBAND {
return (0, r_at_zero);
}
(best_d, best_r)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -278,8 +119,7 @@ mod tests {
let spl = WefaxConfig::samples_per_line(lpm, sr);
let ppl = WefaxConfig::pixels_per_line(ioc) as usize;
// Slant correction off for deterministic line count.
let mut slicer = LineSlicer::with_slant(lpm, ioc, sr, 0, false);
let mut slicer = LineSlicer::new(lpm, ioc, sr, 0);
// Feed exactly 3 lines worth of white.
let samples = vec![1.0f32; spl * 3];
let lines = slicer.process(&samples);
@@ -296,7 +136,7 @@ mod tests {
let sr = 11025;
let spl = WefaxConfig::samples_per_line(lpm, sr);
let mut slicer = LineSlicer::with_slant(lpm, ioc, sr, 0, false);
let mut slicer = LineSlicer::new(lpm, ioc, sr, 0);
// Feed a linear ramp from 0.0 to 1.0.
let samples: Vec<f32> = (0..spl).map(|i| i as f32 / spl as f32).collect();
let lines = slicer.process(&samples);
@@ -305,92 +145,4 @@ mod tests {
assert!(lines[0][0] < 5);
assert!(lines[0].last().copied().unwrap_or(0) > 250);
}
/// Synthesise a noisy-ish gradient line that repeats with a small
/// per-line offset, simulating a sample-clock mismatch. The slant
/// tracker should follow the drift.
#[test]
fn slant_tracker_follows_drift() {
let lpm = 120;
let ioc = 576;
let sr = 11025;
let spl = WefaxConfig::samples_per_line(lpm, sr);
// Build a signal where each real line is `spl + 3` samples long
// (i.e. transmitter clock is slower than expected → positive drift
// of +3 samples per line). The content needs high-frequency
// structure for a few-sample shift to be detectable against the
// deadband.
let true_line_len = spl + 3;
let mut signal: Vec<f32> = Vec::new();
let base: Vec<f32> = (0..true_line_len)
.map(|i| {
// Pseudo-random-but-repeatable content with a narrow
// bright stripe — sharp features make sub-line shifts
// easy to localise.
let x = ((i as u32).wrapping_mul(2654435761)) >> 16;
let noise = (x & 0xff) as f32 / 255.0;
let stripe = if i == true_line_len / 3 { 1.0 } else { 0.0 };
0.3 + 0.4 * noise + stripe
})
.collect();
// 20 lines, each identical.
for _ in 0..20 {
signal.extend_from_slice(&base);
}
let mut slicer = LineSlicer::with_slant(lpm, ioc, sr, 0, true);
let lines = slicer.process(&signal);
// Expect ~ (20*true_line_len - spl) / (spl+drift) lines with
// drift absorbing the extra 2 samples per line.
assert!(
lines.len() >= 15,
"slant-corrected slicer produced only {} lines",
lines.len()
);
// Should have tracked positive drift.
assert!(
slicer.total_drift > 0,
"expected positive drift, got {}",
slicer.total_drift
);
// Roughly +3 per line (after the first bootstrap line); allow wide tolerance.
let per_line = slicer.total_drift as f32 / (lines.len() - 1) as f32;
assert!(
per_line > 1.5 && per_line < 4.0,
"per-line drift {:.2} out of range (total {}, lines {})",
per_line,
slicer.total_drift,
lines.len()
);
}
#[test]
fn slant_tracker_deadband_on_no_drift() {
let lpm = 120;
let ioc = 576;
let sr = 11025;
let spl = WefaxConfig::samples_per_line(lpm, sr);
// Perfectly aligned lines → drift should stay at zero.
let line: Vec<f32> = (0..spl)
.map(|i| {
let t = i as f32 / spl as f32;
0.5 + 0.4 * (t * 9.0 * std::f32::consts::PI).sin()
})
.collect();
let mut signal = Vec::new();
for _ in 0..10 {
signal.extend_from_slice(&line);
}
let mut slicer = LineSlicer::with_slant(lpm, ioc, sr, 0, true);
let _ = slicer.process(&signal);
// Deadband should keep drift at 0.
assert_eq!(
slicer.total_drift, 0,
"no drift expected for identical lines"
);
}
}
+3 -5
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Phasing signal detector and line-start alignment for WEFAX.
//!
@@ -161,10 +161,8 @@ mod tests {
for line_idx in 0..20 {
let mut line = vec![1.0f32; spl];
for j in pulse_start..pulse_start + pw {
if j < spl {
line[j] = 0.0;
}
for slot in line.iter_mut().skip(pulse_start).take(pw) {
*slot = 0.0;
}
let result = det.process(&line);
if let Some(offset) = result {
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Polyphase rational resampler: 48000 Hz → 11025 Hz.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! APT tone detector for WEFAX start/stop signals.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-wspr"
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
use crate::protocol;
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
mod decoder;
mod protocol;
+4 -4
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
/// Decoded WSPR message payload.
#[derive(Debug, Clone)]
@@ -483,7 +483,7 @@ mod tests {
let c4 = idx27(b'T');
let c5 = idx27(b' ');
let n1 = ((c0 * 36 + c1) * 10 + c2) * 27u32.pow(3) + c3 * 27u32.pow(2) + c4 * 27 + c5;
let m1 = (179 - 10 * 5 - 2) * 180 + 10 * 13 + 0; // FN20
let m1 = (179 - 10 * 5 - 2) * 180 + 10 * 13; // FN20 (final term is 0)
let power_code = 37u32;
let mut input_bits = [0u8; NBITS];
@@ -530,8 +530,8 @@ mod tests {
fn interleave_deinterleave_roundtrip() {
// Create a sequence of distinguishable values
let mut original = [0u8; NSYMS];
for i in 0..NSYMS {
original[i] = (i % 256) as u8;
for (i, slot) in original.iter_mut().enumerate() {
*slot = (i % 256) as u8;
}
let interleaved = interleave(&original);
+1 -1
View File
@@ -1,6 +1,6 @@
# SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
#
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-License-Identifier: GPL-2.0-or-later
[package]
name = "trx-wxsat"
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Shared PNG image encoding for weather satellite decoders.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! Weather satellite image decoders.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! CCSDS CADU (Channel Access Data Unit) frame synchronisation and extraction.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! QPSK demodulator for Meteor-M LRPT.
//!
+1 -1
View File
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: BSD-2-Clause
// SPDX-License-Identifier: GPL-2.0-or-later
//! MCU (Minimum Coded Unit) assembly and multi-channel image composition.
//!

Some files were not shown because too many files have changed in this diff Show More