# Architecture
## Design Goal
Rasterwave models analog image protocols as bounded, ordered state machines.
It must accept arbitrary PCM chunk sizes, emit useful rows before EOF, and
produce the same samples/events when driven one sample at a time or in one
large call.
## SSTV Receive Path
```text
caller PCM
-> streaming linear rate conversion (12 kHz working rate)
-> quadrature downmix around 1900 Hz
-> two-stage low-pass + complex phase-difference FM demodulation
-> parallel VIS header and sync-pulse detectors
-> candidate/confirmation policy
-> robust line-clock regression
-> family row decoder
-> borrowed LineReady events
```
The acquisition frequency ring is fixed at eight seconds. It allows a VIS
candidate to be confirmed by later sync pulses without discarding the early
rows. Once locked, the decoder reuses fixed line and channel scratch buffers.
VIS parity alone is not enough under low SNR: a corrupted word can still have
valid even parity and name another supported mode. Rasterwave reports the VIS
candidate first, then requires compatible sync width and repeated line period
before emitting `ImageStarted`.
No-VIS inference is stricter. Six compatible pulses are scored against the
mode catalog. If line timing cannot distinguish modes such as Martin M1/M3 or
Scottie S1/S3, only `ModeCandidate` is emitted. A caller may then lock a manual
mode; the library does not choose arbitrarily.
## Frequency And Clock Tracking
Frequency offset is estimated relative to the 1900 Hz leader and refined from
1200 Hz sync pulses. All pixel frequencies use the same estimate.
Clock drift is distinct from carrier offset. Compatible sync edges receive a
line index that can skip missed pulses. A least-squares fit over the latest
eight `(line_index, sample_position)` points updates samples-per-line and
re-anchors the next line boundary from the fitted phase only when:
- slope is within +/-2000 ppm of the profile;
- at least four points exist;
- residual RMS is below the sync-jitter threshold.
Line boundaries use a cumulative fractional deadline. They never round every
row independently.
## Row Revisions
Robot 36 alternates red-difference and blue-difference chroma. An even row can
be displayed immediately with neutral missing chroma (`Provisional`). The next
radio row then produces a revised final even row and a final odd row. Consumers
must key rows by `(image_id, line_index, revision)`.
## Transmit Path
The encoder stores the source raster, mode state, oscillator recurrence, and a
single cumulative sample deadline. It creates tone or pixel segments lazily and
fills caller memory directly. The oscillator is phase-continuous across pixels,
segments, and caller chunk boundaries.
The optional transmission envelope is a separate ordered state machine around
that raster. It can prepend QSSTV calibration tones and append a silence gap,
FSK/CW station ID, and final guard. The legacy constructor selects an empty
envelope, while progress snapshots expose exact raster sample boundaries for
monitoring and loopback decoders.
## Radiofax Boundary
Radiofax shares PCM, oscillator, demodulation, and raster primitives with SSTV
but has a separate protocol state machine:
```text
APT selection -------------------> phasing/IOC/LPM lock -> image rows
configured IOC + phasing-only ---> phasing/IOC/LPM lock -> image rows
IOC is not a fixed image size. The built-in square-sampling policy derives a
full line width, while page height remains open until stop or a configured
limit. The encoder and decoder use the complete `round(pi * IOC)` image line.
APT and suspected stop samples are held until
the control pattern is confirmed so they are not exposed as image pixels.
The default acquisition path detects IOC from APT and WMO line rates from
phasing. Phasing-only acquisition requires the IOC in `FaxDecoderConfig`; an
LPM outside the automatically inferred WMO set must also be configured. An
image-only stream has no timing or horizontal-phase acquisition marker and is
not acquired automatically.
Parameterized FM and AM subcarriers share the framing state machine. Receive
configuration must name the modulation expected on the input. Low target-carrier
level or coherence for the configured interval ends an active page as partial
instead of allowing silence or wideband noise to synthesize more rows. A caller
with receiver-specific squelch evidence may set the coherence threshold to zero
and end the page explicitly at its integration boundary.
## Radiofax Clock Recovery
Radiofax timing has two independent errors: line-period error produces a
progressive slant, while line-phase error produces a constant circular shift.
The decoder models both with `line_start(n) = phase + n * period`.
Phasing edges are retained in a bounded 64-point history. Median interval and
phase statistics reject threshold jitter before a confidence-gated clock is
accepted. The page start is projected onto that fitted grid, so the expected
phasing duration cannot introduce a separate horizontal offset. Rejected
phasing cycles invalidate pending untrusted measurements instead of allowing a
stale period to start a page.
Continuous fax paper has two explicit timing paths. Before a protocol lock, it
emits immediate `NominalPaper` rows. A trusted phasing capture uses the fitted
period directly and emits `Calibrated` rows; image content is not allowed to
retime that segment. For a mid-image join, a separate bounded image-content
tracker may publish a sparse affine model only after at least five consistent
observations over a long span. It freezes on large innovations and never treats
ordinary image structure as protocol evidence.
`correct_fax_paper` applies only to nominal rows. It evaluates sparse timing
models with slope-continuous interpolation and a four-sample fractional-delay
filter, so integer shifts remain exact and necessary fractional correction does
not receive a second linear blur. Consumers must not apply this transform to
rows whose basis is already `Calibrated`.
## RTTY Modem
RTTY is a separate text modem in `rtty`. It shares the crate's threading and
memory rules but no raster state.
Transmit: `RttyEncoder` keeps a queue of not-yet-committed characters and a
queue of scheduled bit spans. A character is committed (and reported through
`drain_rendered`) only when the bit queue runs empty, so at most one character
of waveform is scheduled ahead of the samples already returned and everything
else stays retractable. Shift codes are inserted automatically; after a space
in figures case the shift is treated as unknown so receivers with
unshift-on-space stay correct. An empty buffer sends diddles in the current
case (LTRS, or FIGS while in figures) or mark.
Bit boundaries come from a cumulative fractional sample clock, so output is
identical for any read chunk size. `abort` ends the output after the release
ramp (5 ms by default) from the current position, also inside the tail that
`finish` scheduled.
Receive: a noise blanker removes short impulses (an excursion above six times
the running RMS that ends within 3 ms; longer excursions are level changes and
re-seed the estimate). Input is then mixed by the tone-pair centre and
decimated with one FIR to a baseband rate of at least 1.5 kHz. Each tone is
mixed to DC and matched filtered (0.6 x baud cutoff, two bit periods). Tone
levels are decision directed: the "on" level of a tone is averaged over 2 bits
while it dominates, so the threshold follows selective fading, and its "off"
(noise) level over 16 bits while the other tone dominates. Optimal ATC and
clipped Kahn ratio-squared decisions are scaled to log-likelihood ratios by the
off level (mark-only and space-only lanes are optional).
Every lane and polarity runs its own framer and combiner, forming an
independent character stream. A framer opens a hypothesis at each
mark-to-space edge preceded by mark and predicts the next start bit after each
valid frame (flywheel). A combiner resolves overlapping hypotheses by
confidence, weighted by a chain prior: while characters arrive back to back,
hypotheses that do not start one frame after the previous character are
penalised. The decoder emits only the active stream and switches, with
hysteresis and duplicate suppression, to the stream with the best combination
of chaining and mean confidence. This is the "several complete decoders side
by side" approach: Kahn wins on stationary and flat-fading channels, ATC when
the tones are unbalanced (selective fading, multipath notches), and the
reversed stream when the signal is upside down.
Character confidence is the all-bits-correct probability on a log scale where
2^-7 maps to zero. The squelch compares it with a threshold; a stream that
neither chains nor decodes confidently additionally requires a strong
character. Lock (and therefore AFC adaptation) follows the smoothed confidence
of emitted characters; while unlocked AFC decays back to zero. Lock decay and
AFC run on a fixed 100 ms tick independent of the report interval.
`tests/rtty_channels.rs` measures character error rate under seeded AWGN,
impulse noise, selective and flat Rayleigh fading, two-path multipath, carrier
interference and an adjacent RTTY signal, and pins quality floors.
Level estimators start as plain means of the samples seen so far and become
exponential averages once they have seen their time constant; decisions are
scaled only by a noise floor that rests on at least one bit of samples. Digital
silence carries no noise floor, so the levels are frozen while it lasts and
until the matched filters have refilled (a receiver muted to zero during a
transmission comes back with the levels it had before). After construction, a
discontinuity or silence only strong characters pass for 24 bits.
`RttySignal::snr_db` is measured in the power domain from the matched-filter
outputs at the bit centres (the middle 40% of each bit) of the characters the
active stream frames, squelched ones included. Only data bits whose neighbours
carry the same tone are used, so the other filter sees noise alone rather than
leakage from adjacent bits: the keyed filter gives signal plus noise, the other
filter noise, both tones contribute in proportion to how long they are keyed,
and the ratio is referred from the matched filters' equivalent noise bandwidth
(Σh²/(Σh)² times the baseband rate) to 3 kHz. The sums decay by 0.85 per
measured character. This tracks the true SNR within about 1 dB from -12 to
+40 dB on white noise; characters framed from noise alone read about -13 to
-16 dB. `mark_db` and `space_db` remain the fast decision-directed on/off level
ratios, which inter-symbol leakage caps near 15-16 dB.
`set_lanes` keeps surviving streams, `retune` to a new shift and
`mark_discontinuity` emit characters already demodulated before resetting, and
streams are resolved in global start-time order so switching the active stream
never drops or reorders output.
Shift (LTRS/FIGS) state is applied only to characters that pass the squelch
(shift codes need half its threshold), so noise cannot flip the case of later
text.
### Channel Scanner
`RttyChannelScanner` finds RTTY signals anywhere in an audio passband. The
input goes into a ring buffer that serves both the spectral analysis and the
pre-roll of new channel decoders. Every hop (a quarter of the FFT length) a
Hann-windowed radix-2 FFT with bins of roughly 10 to 16 Hz (the power of two
nearest to `sample_rate / 12.5`; 1024 points and 11.7 Hz at 12 kHz) produces
three-bin band powers, which are kept for the last 1.5 s.
Every 500 ms (a fixed number of hops) the scanner evaluates candidate centres
on a half-bin grid for each configured shift. For the two tone positions it
computes the time mean, variance and covariance of the band power and a local
noise floor (20th percentile of the mean band power within 400 Hz). The score
multiplies three ramps:
- anti-correlation: an FSK transmitter moves its energy between mark and space,
so the correlation coefficient of the two band powers approaches -1. Two
carriers give about 0, the harmonics of a voice or any amplitude-modulated
pair are positively correlated;
- presence: the weaker tone must stand above its local noise floor;
- keying index: the anti-covariance relative to the product of the two tone
powers above noise. It is independent of SNR for a keyed signal and near
zero for steady carriers even when numerical noise makes their correlation
meaningless.
Local maxima of the anti-covariance give candidate centres, refined by
parabolic interpolation, and non-maximum suppression across shifts keeps the
strongest. Detections are tracked: a candidate is reported (and gets an id and
a decoder) after two consecutive updates at `min_score`, survives while
detections reach 60% of it, and is removed three seconds after the last match.
Centre, score and SNR are smoothed per update; a decoder is re-centred when the
tracked centre moves more than 15 Hz. When all `max_channels` slots are used a
new candidate replaces the weakest channel only with a 0.25 score advantage.
Each channel decoder uses the scanner's profile with the detected shift, mark
on the lower tone and auto-reverse; `reversed` reports the polarity it found
while locked. Characters are buffered and released with the channel list, so
the whole event stream is a function of the input samples only and does not
depend on chunking. Steady-state work allocates only the vectors handed out in
events.
## Threading And Future Node.js Binding
The core exposes synchronous methods taking `&mut self`. This is the correct
primitive for a future Promise API:
```text
JS handle -> per-handle serial work queue -> owned Rust codec session
-> owned events back to JS
```
Different handles can run on a Node worker pool. Work for one handle must stay
ordered. The core does not embed Tokio, a thread pool, an `Arc<Mutex<_>>`, or a
Node-API dependency.
Borrowed events are the zero-copy Rust path. A binding must copy
`DecodeEventRef` with `to_owned()` before crossing an asynchronous boundary.
## Memory Invariants
- no mutable process-global codec state;
- acquisition history has fixed capacity;
- locked SSTV audio buffers retain only pending rows;
- radiofax retains bounded phasing history plus bounded stop/fade evidence;
- owned complete images are created only when the caller asks to retain them;
- no `unsafe` code in the core crate.