Files
trx-rs/src/decoders/trx-sstv/src/vis.rs
T
sjg a0b0c0ed81
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
[feat](trx-sstv): decode SSTV pictures
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

237 lines
8.6 KiB
Rust

// 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);
}
}