use std::f64::consts::PI;
use super::decoder::{RttyCharacter, RttyDecodeEvent, RttyDecoder, RttyDecoderConfig};
use super::dsp::{Complex, Fft};
use super::profile::{RttyProfile, RttyTones, validate_sample_rate};
use crate::{Error, Result};
const TARGET_BIN_HZ: f64 = 12.5;
const WINDOW_SECONDS: f64 = 1.5;
const UPDATE_SECONDS: f64 = 0.5;
const PREROLL_SECONDS: f64 = 2.0;
const CONFIRM_UPDATES: u32 = 2;
const DROP_SECONDS: f64 = 3.0;
const KEEP_FRACTION: f64 = 0.6;
const CENTER_ALPHA: f64 = 0.35;
const SCORE_ALPHA: f64 = 0.5;
const EVICT_MARGIN: f64 = 0.25;
const RETUNE_HZ: f64 = 15.0;
const NOISE_PERCENTILE: f64 = 0.2;
const NOISE_SPAN_HZ: f64 = 400.0;
const RHO_RAMP: (f64, f64) = (0.35, 0.75);
const PRESENCE_RAMP: (f64, f64) = (0.3, 1.2);
const KEYING_RAMP: (f64, f64) = (0.04, 0.15);
const MAX_SHIFTS: usize = 8;
const MAX_CHANNELS: usize = 32;
const CHANNEL_REPORT_SECONDS: f64 = 0.25;
#[derive(Clone, Debug, PartialEq)]
pub struct RttyScannerConfig {
pub shifts_hz: Vec<f32>,
pub min_hz: f32,
pub max_hz: f32,
pub max_channels: usize,
pub min_score: f32,
pub profile: RttyProfile,
}
impl Default for RttyScannerConfig {
fn default() -> Self {
Self {
shifts_hz: vec![170.0],
min_hz: 300.0,
max_hz: 2_900.0,
max_channels: 8,
min_score: 0.5,
profile: RttyProfile::RTTY_45_170,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct RttyScanChannel {
pub id: u32,
pub center_hz: f32,
pub shift_hz: f32,
pub score: f32,
pub snr_db: f32,
pub reversed: bool,
pub locked: bool,
}
impl RttyScanChannel {
#[must_use]
pub fn tones(&self) -> RttyTones {
RttyTones::from_center(
f64::from(self.center_hz),
f64::from(self.shift_hz),
self.reversed,
)
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum RttyScanEvent {
Channels {
sample: u64,
channels: Vec<RttyScanChannel>,
},
Text {
sample: u64,
channel_id: u32,
characters: Vec<RttyCharacter>,
},
Removed {
sample: u64,
channel_id: u32,
},
}
#[derive(Clone, Copy, Debug)]
struct Detection {
center_hz: f64,
shift_hz: f64,
score: f64,
snr_db: f64,
}
#[derive(Debug)]
struct ShiftGrid {
shift_hz: f64,
first_center_hz: f64,
step_hz: f64,
objective: Vec<f64>,
score: Vec<f64>,
snr_db: Vec<f64>,
}
#[derive(Debug)]
struct Channel {
decoder: RttyDecoder,
tuned_center_hz: f64,
locked: bool,
reversed: bool,
characters: Vec<RttyCharacter>,
}
impl Channel {
fn push(&mut self, samples: &[f32]) {
let Self {
decoder,
locked,
reversed,
characters,
..
} = self;
let _ = decoder.push_f32(samples, &mut |event| {
Self::on_event(event, locked, reversed, characters);
});
}
fn finish(&mut self) {
let Self {
decoder,
locked,
reversed,
characters,
..
} = self;
decoder.finish(&mut |event| Self::on_event(event, locked, reversed, characters));
}
fn retune(&mut self, tones: RttyTones) {
let Self {
decoder,
locked,
reversed,
characters,
..
} = self;
let _ = decoder.retune(tones, &mut |event| {
Self::on_event(event, locked, reversed, characters);
});
}
fn on_event(
event: RttyDecodeEvent,
locked: &mut bool,
reversed: &mut bool,
characters: &mut Vec<RttyCharacter>,
) {
match event {
RttyDecodeEvent::Character(character) => characters.push(character),
RttyDecodeEvent::Signal(signal) => {
*locked = signal.locked;
if signal.locked {
*reversed = signal.reversed;
}
}
}
}
}
#[derive(Debug)]
struct Track {
id: Option<u32>,
center_hz: f64,
shift_hz: f64,
score: f64,
snr_db: f64,
hits: u32,
last_seen: u64,
matched: bool,
channel: Option<Box<Channel>>,
}
impl Track {
fn snapshot(&self, id: u32) -> RttyScanChannel {
let (reversed, locked) = self
.channel
.as_ref()
.map_or((false, false), |channel| (channel.reversed, channel.locked));
RttyScanChannel {
id,
center_hz: self.center_hz as f32,
shift_hz: self.shift_hz as f32,
score: self.score as f32,
snr_db: self.snr_db as f32,
reversed,
locked,
}
}
}
#[derive(Debug)]
pub struct RttyChannelScanner {
config: RttyScannerConfig,
sample_rate: u32,
fft: Fft,
window: Vec<f64>,
spectrum: Vec<Complex>,
hop: usize,
until_hop: usize,
history: Vec<f32>,
history_pos: usize,
history_len: usize,
preroll: usize,
input_index: u64,
bin_hz: f64,
first_bin: usize,
band_count: usize,
bands: Vec<f32>,
window_frames: usize,
frames: u64,
frames_per_update: usize,
until_update: usize,
update_index: u64,
drop_updates: u64,
noise_span: usize,
mean: Vec<f64>,
noise: Vec<f64>,
scratch: Vec<f64>,
grids: Vec<ShiftGrid>,
detections: Vec<Detection>,
tracks: Vec<Track>,
track_capacity: usize,
next_id: u32,
finished: bool,
}
impl RttyChannelScanner {
pub fn new(sample_rate: u32, config: RttyScannerConfig) -> Result<Self> {
validate_sample_rate(sample_rate)?;
validate_config(&config, sample_rate)?;
let rate = f64::from(sample_rate);
let fft_size = 1_usize << (rate / TARGET_BIN_HZ).log2().round() as u32;
let bin_hz = rate / fft_size as f64;
let hop = fft_size / 4;
let hop_seconds = hop as f64 / rate;
let window_frames = ((WINDOW_SECONDS / hop_seconds).round() as usize).max(8);
let frames_per_update = ((UPDATE_SECONDS / hop_seconds).round() as usize).max(1);
let update_seconds = frames_per_update as f64 * hop_seconds;
let drop_updates = (DROP_SECONDS / update_seconds).ceil() as u64;
let first_bin = ((f64::from(config.min_hz) / bin_hz).floor() as usize)
.saturating_sub(1)
.max(1);
let last_bin =
((f64::from(config.max_hz) / bin_hz).ceil() as usize + 1).min(fft_size / 2 - 2);
let band_count = last_bin - first_bin + 1;
let grids = config
.shifts_hz
.iter()
.map(|&shift| {
let shift = f64::from(shift);
let step_hz = bin_hz / 2.0;
let first_center_hz = f64::from(config.min_hz) + shift / 2.0;
let span = f64::from(config.max_hz) - f64::from(config.min_hz) - shift;
let count = (span / step_hz).floor() as usize + 1;
ShiftGrid {
shift_hz: shift,
first_center_hz,
step_hz,
objective: vec![0.0; count],
score: vec![0.0; count],
snr_db: vec![0.0; count],
}
})
.collect();
let window = (0..fft_size)
.map(|n| 0.5 - 0.5 * (2.0 * PI * n as f64 / fft_size as f64).cos())
.collect();
let preroll = (PREROLL_SECONDS * rate).round() as usize;
let history_len = preroll.max(fft_size);
let noise_span = ((NOISE_SPAN_HZ / bin_hz).round() as usize).max(4);
let track_capacity = 2 * config.max_channels + 8;
Ok(Self {
sample_rate,
fft: Fft::new(fft_size),
window,
spectrum: vec![Complex::ZERO; fft_size],
hop,
until_hop: hop,
history: vec![0.0; history_len],
history_pos: 0,
history_len,
preroll,
input_index: 0,
bin_hz,
first_bin,
band_count,
bands: vec![0.0; window_frames * band_count],
window_frames,
frames: 0,
frames_per_update,
until_update: frames_per_update,
update_index: 0,
drop_updates,
noise_span,
mean: vec![0.0; band_count],
noise: vec![0.0; band_count],
scratch: Vec::with_capacity(2 * noise_span + 1),
grids,
detections: Vec::with_capacity(track_capacity),
tracks: Vec::with_capacity(track_capacity),
track_capacity,
next_id: 1,
finished: false,
config,
})
}
#[must_use]
pub fn config(&self) -> &RttyScannerConfig {
&self.config
}
#[must_use]
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
#[must_use]
pub fn samples_consumed(&self) -> u64 {
self.input_index
}
#[must_use]
pub fn bin_hz(&self) -> f64 {
self.bin_hz
}
#[must_use]
pub fn channels(&self) -> Vec<RttyScanChannel> {
let mut channels: Vec<RttyScanChannel> = self
.tracks
.iter()
.filter_map(|track| track.id.map(|id| track.snapshot(id)))
.collect();
channels.sort_by(|a, b| a.center_hz.total_cmp(&b.center_hz));
channels
}
pub fn push_f32(
&mut self,
samples: &[f32],
sink: &mut impl FnMut(RttyScanEvent),
) -> Result<()> {
if self.finished {
return Err(Error::DecoderFinished);
}
if samples.iter().any(|sample| !sample.is_finite()) {
return Err(Error::NonFiniteSample);
}
self.process(samples, sink);
Ok(())
}
pub fn push_i16(
&mut self,
samples: &[i16],
sink: &mut impl FnMut(RttyScanEvent),
) -> Result<()> {
if self.finished {
return Err(Error::DecoderFinished);
}
let mut buffer = [0.0_f32; 512];
for chunk in samples.chunks(buffer.len()) {
for (out, &sample) in buffer.iter_mut().zip(chunk) {
*out = f32::from(sample) / 32_768.0;
}
self.process(&buffer[..chunk.len()], sink);
}
Ok(())
}
pub fn finish(&mut self, sink: &mut impl FnMut(RttyScanEvent)) {
if self.finished {
return;
}
for track in &mut self.tracks {
if let Some(channel) = track.channel.as_mut() {
channel.finish();
}
}
self.emit(sink);
self.finished = true;
}
pub fn reset(&mut self) {
let next_id = self.next_id;
if let Ok(fresh) = Self::new(self.sample_rate, self.config.clone()) {
*self = fresh;
self.next_id = next_id;
}
}
fn process(&mut self, mut samples: &[f32], sink: &mut impl FnMut(RttyScanEvent)) {
while !samples.is_empty() {
let take = samples.len().min(self.until_hop);
let (segment, rest) = samples.split_at(take);
self.store_history(segment);
for track in &mut self.tracks {
if let Some(channel) = track.channel.as_mut() {
channel.push(segment);
}
}
self.input_index += take as u64;
self.until_hop -= take;
if self.until_hop == 0 {
self.until_hop = self.hop;
self.frame(sink);
}
samples = rest;
}
}
fn store_history(&mut self, mut segment: &[f32]) {
while !segment.is_empty() {
let room = self.history_len - self.history_pos;
let take = room.min(segment.len());
self.history[self.history_pos..self.history_pos + take]
.copy_from_slice(&segment[..take]);
self.history_pos = (self.history_pos + take) % self.history_len;
segment = &segment[take..];
}
}
fn frame(&mut self, sink: &mut impl FnMut(RttyScanEvent)) {
let size = self.fft.size();
let (older, newer) = recent(&self.history, self.history_pos, size);
for ((slot, &sample), &weight) in self
.spectrum
.iter_mut()
.zip(older.iter().chain(newer))
.zip(&self.window)
{
*slot = Complex::new(f64::from(sample) * weight, 0.0);
}
self.fft.forward(&mut self.spectrum);
let row = (self.frames % self.window_frames as u64) as usize;
let bands = &mut self.bands[row * self.band_count..(row + 1) * self.band_count];
let scale = 1.0 / (size as f64 * size as f64);
let power = |bin: usize| self.spectrum[bin].norm_sqr() * scale;
for (index, band) in bands.iter_mut().enumerate() {
let bin = self.first_bin + index;
*band = (power(bin - 1) + power(bin) + power(bin + 1)) as f32;
}
self.frames += 1;
self.until_update -= 1;
if self.until_update == 0 {
self.until_update = self.frames_per_update;
self.update(sink);
}
}
fn update(&mut self, sink: &mut impl FnMut(RttyScanEvent)) {
self.update_index += 1;
self.detections.clear();
let frames = self.frames.min(self.window_frames as u64) as usize;
if frames * 2 >= self.window_frames {
self.analyze(frames);
}
self.track(sink);
self.emit(sink);
}
fn analyze(&mut self, frames: usize) {
let count = self.band_count;
let rows = &self.bands[..frames * count];
self.mean.fill(0.0);
for row in rows.chunks_exact(count) {
for (mean, &value) in self.mean.iter_mut().zip(row) {
*mean += f64::from(value);
}
}
let inverse = 1.0 / frames as f64;
for mean in &mut self.mean {
*mean *= inverse;
}
for index in 0..count {
let low = index.saturating_sub(self.noise_span);
let high = (index + self.noise_span + 1).min(count);
self.scratch.clear();
self.scratch.extend_from_slice(&self.mean[low..high]);
let rank = ((self.scratch.len() - 1) as f64 * NOISE_PERCENTILE).round() as usize;
let (_, value, _) = self.scratch.select_nth_unstable_by(rank, f64::total_cmp);
self.noise[index] = *value;
}
let keep = (KEEP_FRACTION * f64::from(self.config.min_score)).max(1e-6);
let reference_hz = 3_000.0 / self.bin_hz;
for grid in &mut self.grids {
for (j, ((objective, score), snr_db)) in grid
.objective
.iter_mut()
.zip(grid.score.iter_mut())
.zip(grid.snr_db.iter_mut())
.enumerate()
{
let center = grid.first_center_hz + j as f64 * grid.step_hz;
let low = position(center - grid.shift_hz / 2.0, self.bin_hz, self.first_bin);
let high = position(center + grid.shift_hz / 2.0, self.bin_hz, self.first_bin);
let stats = pair_stats(rows, count, low, high);
let noise_low = lerp(&self.noise, low).max(1e-30);
let noise_high = lerp(&self.noise, high).max(1e-30);
let excess_low = stats.mean_a - noise_low;
let excess_high = stats.mean_b - noise_high;
let floor_a = (1e-3 * stats.mean_a).powi(2) + 1e-60;
let floor_b = (1e-3 * stats.mean_b).powi(2) + 1e-60;
let rho = stats.cov / ((stats.var_a + floor_a) * (stats.var_b + floor_b)).sqrt();
let presence = (excess_low / noise_low).min(excess_high / noise_high);
let keying = -stats.cov
/ (excess_low.max(1e-30 + 1e-3 * noise_low)
* excess_high.max(1e-30 + 1e-3 * noise_high));
let s_rho = ramp(-rho, RHO_RAMP);
let s_presence = ramp(presence, PRESENCE_RAMP);
let s_keying = ramp(keying, KEYING_RAMP);
*score = s_rho * s_presence.min(s_keying);
*objective = -stats.cov / (noise_low * noise_high);
let signal = excess_low.max(0.0) + excess_high.max(0.0);
let noise_bin = (noise_low + noise_high) / 6.0;
*snr_db = 10.0 * (signal.max(1e-30) / (noise_bin * reference_hz)).log10();
}
let len = grid.objective.len();
for j in 0..len {
let value = grid.objective[j];
let left = if j > 0 {
grid.objective[j - 1]
} else {
f64::NEG_INFINITY
};
let right = if j + 1 < len {
grid.objective[j + 1]
} else {
f64::NEG_INFINITY
};
if value <= 0.0 || value < right || value <= left {
continue;
}
let score = grid.score[j]
.max(if j > 0 { grid.score[j - 1] } else { 0.0 })
.max(if j + 1 < len { grid.score[j + 1] } else { 0.0 });
if score < keep {
continue;
}
let offset = if left.is_finite() && right.is_finite() {
let curvature = left - 2.0 * value + right;
if curvature < 0.0 {
(0.5 * (left - right) / curvature).clamp(-0.5, 0.5)
} else {
0.0
}
} else {
0.0
};
self.detections.push(Detection {
center_hz: grid.first_center_hz + (j as f64 + offset) * grid.step_hz,
shift_hz: grid.shift_hz,
score,
snr_db: grid.snr_db[j],
});
}
}
self.detections.sort_by(|a, b| {
b.score
.total_cmp(&a.score)
.then(a.center_hz.total_cmp(&b.center_hz))
});
let mut kept = 0;
for index in 0..self.detections.len() {
let candidate = self.detections[index];
let overlaps = self.detections[..kept].iter().any(|other| {
(other.center_hz - candidate.center_hz).abs()
< 0.6 * other.shift_hz.max(candidate.shift_hz)
});
if !overlaps && kept < self.track_capacity {
self.detections[kept] = candidate;
kept += 1;
}
}
self.detections.truncate(kept);
}
fn track(&mut self, sink: &mut impl FnMut(RttyScanEvent)) {
let now = self.update_index;
for track in &mut self.tracks {
track.matched = false;
}
for index in 0..self.detections.len() {
let detection = self.detections[index];
let tolerance = (2.5 * self.bin_hz).max(0.2 * detection.shift_hz);
let best = self
.tracks
.iter_mut()
.filter(|track| {
!track.matched
&& (track.shift_hz - detection.shift_hz).abs() < 1.0
&& (track.center_hz - detection.center_hz).abs() < tolerance
})
.min_by(|a, b| {
(a.center_hz - detection.center_hz)
.abs()
.total_cmp(&(b.center_hz - detection.center_hz).abs())
});
if let Some(track) = best {
track.center_hz += CENTER_ALPHA * (detection.center_hz - track.center_hz);
track.score += SCORE_ALPHA * (detection.score - track.score);
track.snr_db += SCORE_ALPHA * (detection.snr_db - track.snr_db);
track.hits = track.hits.saturating_add(1);
track.last_seen = now;
track.matched = true;
} else if detection.score >= f64::from(self.config.min_score)
&& self.tracks.len() < self.track_capacity
{
self.tracks.push(Track {
id: None,
center_hz: detection.center_hz,
shift_hz: detection.shift_hz,
score: detection.score,
snr_db: detection.snr_db,
hits: 1,
last_seen: now,
matched: true,
channel: None,
});
}
}
for track in &mut self.tracks {
if !track.matched {
track.score *= 1.0 - SCORE_ALPHA;
track.hits = 0;
}
}
let mut index = 0;
while index < self.tracks.len() {
let duplicate = (0..index).any(|other| {
let (a, b) = (&self.tracks[other], &self.tracks[index]);
(a.shift_hz - b.shift_hz).abs() < 1.0
&& (a.center_hz - b.center_hz).abs() < 0.5 * self.bin_hz.max(0.1 * a.shift_hz)
});
if duplicate && self.tracks[index].id.is_none() {
self.tracks.remove(index);
} else {
index += 1;
}
}
let sample = self.input_index;
let drop_updates = self.drop_updates;
let mut index = 0;
while index < self.tracks.len() {
let track = &self.tracks[index];
let stale = if track.id.is_some() {
now - track.last_seen > drop_updates
} else {
!track.matched
};
if stale {
let track = self.tracks.remove(index);
retire(track, sample, sink);
} else {
index += 1;
}
}
self.promote(sink);
self.retune_channels();
}
fn promote(&mut self, sink: &mut impl FnMut(RttyScanEvent)) {
let min_score = f64::from(self.config.min_score);
loop {
let candidate = self
.tracks
.iter()
.enumerate()
.filter(|(_, track)| {
track.id.is_none() && track.hits >= CONFIRM_UPDATES && track.score >= min_score
})
.max_by(|a, b| {
a.1.score
.total_cmp(&b.1.score)
.then(b.1.center_hz.total_cmp(&a.1.center_hz))
})
.map(|(index, _)| index);
let Some(candidate) = candidate else {
return;
};
let reported = self
.tracks
.iter()
.filter(|track| track.id.is_some())
.count();
if reported >= self.config.max_channels {
let weakest = self
.tracks
.iter()
.enumerate()
.filter(|(_, track)| track.id.is_some())
.min_by(|a, b| a.1.score.total_cmp(&b.1.score))
.map(|(index, track)| (index, track.score));
match weakest {
Some((index, score)) if self.tracks[candidate].score > score + EVICT_MARGIN => {
let track = self.tracks.remove(index);
retire(track, self.input_index, sink);
let candidate = if index < candidate {
candidate - 1
} else {
candidate
};
self.report(candidate);
}
_ => return,
}
} else {
self.report(candidate);
}
}
}
fn report(&mut self, index: usize) {
let id = self.next_id;
self.next_id = self.next_id.wrapping_add(1).max(1);
let profile = RttyProfile {
shift_hz: self.tracks[index].shift_hz,
..self.config.profile
};
let tones = RttyTones::from_center(self.tracks[index].center_hz, profile.shift_hz, false);
let config = RttyDecoderConfig {
profile,
tones,
signal_report_seconds: CHANNEL_REPORT_SECONDS,
..RttyDecoderConfig::default()
};
let preroll = (self.input_index.min(self.preroll as u64)) as usize;
let channel = RttyDecoder::new(self.sample_rate, config).map(|mut decoder| {
decoder.mark_discontinuity(self.input_index - preroll as u64, &mut |_| {});
let mut channel = Channel {
decoder,
tuned_center_hz: tones.center_hz(),
locked: false,
reversed: false,
characters: Vec::with_capacity(64),
};
let (older, newer) = recent(&self.history, self.history_pos, preroll);
channel.push(older);
channel.push(newer);
Box::new(channel)
});
let track = &mut self.tracks[index];
track.id = Some(id);
track.channel = channel.ok();
}
fn retune_channels(&mut self) {
for track in &mut self.tracks {
let center = track.center_hz;
let shift = track.shift_hz;
if let Some(channel) = track
.channel
.as_mut()
.filter(|channel| (center - channel.tuned_center_hz).abs() > RETUNE_HZ)
{
channel.retune(RttyTones::from_center(center, shift, false));
channel.tuned_center_hz = center;
}
}
}
fn emit(&mut self, sink: &mut impl FnMut(RttyScanEvent)) {
let sample = self.input_index;
sink(RttyScanEvent::Channels {
sample,
channels: self.channels(),
});
for track in &mut self.tracks {
let Some(id) = track.id else { continue };
let Some(channel) = track.channel.as_mut() else {
continue;
};
if !channel.characters.is_empty() {
sink(RttyScanEvent::Text {
sample,
channel_id: id,
characters: channel.characters.drain(..).collect(),
});
}
}
}
}
fn recent(history: &[f32], pos: usize, len: usize) -> (&[f32], &[f32]) {
let len = len.min(history.len());
if len <= pos {
(&history[pos - len..pos], &[])
} else {
let wrapped = len - pos;
(&history[history.len() - wrapped..], &history[..pos])
}
}
fn retire(track: Track, sample: u64, sink: &mut impl FnMut(RttyScanEvent)) {
let Some(id) = track.id else {
return;
};
if let Some(mut channel) = track.channel {
channel.finish();
if !channel.characters.is_empty() {
sink(RttyScanEvent::Text {
sample,
channel_id: id,
characters: channel.characters,
});
}
}
sink(RttyScanEvent::Removed {
sample,
channel_id: id,
});
}
#[derive(Clone, Copy, Debug)]
struct PairStats {
mean_a: f64,
mean_b: f64,
var_a: f64,
var_b: f64,
cov: f64,
}
fn pair_stats(rows: &[f32], count: usize, low: f64, high: f64) -> PairStats {
let (index_a, frac_a) = split(low, count);
let (index_b, frac_b) = split(high, count);
let (mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0);
let mut frames = 0.0;
for row in rows.chunks_exact(count) {
let a = f64::from(row[index_a]) * (1.0 - frac_a) + f64::from(row[index_a + 1]) * frac_a;
let b = f64::from(row[index_b]) * (1.0 - frac_b) + f64::from(row[index_b + 1]) * frac_b;
sa += a;
sb += b;
saa += a * a;
sbb += b * b;
sab += a * b;
frames += 1.0;
}
let mean_a = sa / frames;
let mean_b = sb / frames;
PairStats {
mean_a,
mean_b,
var_a: (saa / frames - mean_a * mean_a).max(0.0),
var_b: (sbb / frames - mean_b * mean_b).max(0.0),
cov: sab / frames - mean_a * mean_b,
}
}
fn position(frequency_hz: f64, bin_hz: f64, first_bin: usize) -> f64 {
frequency_hz / bin_hz - first_bin as f64
}
fn split(position: f64, count: usize) -> (usize, f64) {
let clamped = position.clamp(0.0, (count - 1) as f64 - 1e-9);
let index = clamped.floor() as usize;
(index, clamped - index as f64)
}
fn lerp(values: &[f64], position: f64) -> f64 {
let (index, frac) = split(position, values.len());
values[index] * (1.0 - frac) + values[index + 1] * frac
}
fn ramp(value: f64, (low, high): (f64, f64)) -> f64 {
((value - low) / (high - low)).clamp(0.0, 1.0)
}
fn validate_config(config: &RttyScannerConfig, sample_rate: u32) -> Result<()> {
if config.shifts_hz.is_empty() || config.shifts_hz.len() > MAX_SHIFTS {
return Err(Error::InvalidConfiguration(
"RTTY scanner needs between 1 and 8 shifts",
));
}
for &shift in &config.shifts_hz {
RttyProfile {
shift_hz: f64::from(shift),
..config.profile
}
.validate()?;
}
let nyquist = f64::from(sample_rate) / 2.0;
let (min_hz, max_hz) = (f64::from(config.min_hz), f64::from(config.max_hz));
if !min_hz.is_finite() || !max_hz.is_finite() || min_hz < 100.0 || max_hz > 0.9 * nyquist {
return Err(Error::InvalidConfiguration(
"RTTY scanner range must lie between 100 Hz and 90% of Nyquist",
));
}
let widest = config
.shifts_hz
.iter()
.map(|&shift| f64::from(shift))
.fold(0.0, f64::max);
if max_hz - min_hz < widest + 50.0 {
return Err(Error::InvalidConfiguration(
"RTTY scanner range must exceed the widest shift by at least 50 Hz",
));
}
if config.max_channels == 0 || config.max_channels > MAX_CHANNELS {
return Err(Error::InvalidConfiguration(
"RTTY scanner max_channels must be between 1 and 32",
));
}
if !config.min_score.is_finite() || !(0.0..=1.0).contains(&config.min_score) {
return Err(Error::InvalidConfiguration(
"RTTY scanner min_score must be between 0 and 1",
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scanner_types_are_thread_safe() {
static_assertions::assert_impl_all!(RttyChannelScanner: Send, Sync);
static_assertions::assert_impl_all!(RttyScanEvent: Send, Sync);
static_assertions::assert_impl_all!(RttyScannerConfig: Send, Sync, Clone);
}
#[test]
fn ring_buffer_returns_recent_samples_in_order() {
let history = [5.0, 6.0, 7.0, 1.0, 2.0, 3.0, 4.0];
let (older, newer) = recent(&history, 3, 5);
let joined: Vec<f32> = older.iter().chain(newer).copied().collect();
assert_eq!(joined, [3.0, 4.0, 5.0, 6.0, 7.0]);
let (older, newer) = recent(&history, 3, 2);
assert_eq!((older, newer), (&[6.0, 7.0][..], &[][..]));
}
#[test]
fn pair_statistics_detect_alternating_tones() {
let rows: Vec<f32> = (0..8)
.flat_map(|frame| {
let on = if frame % 2 == 0 { 1.0 } else { 0.0 };
[on, 0.0, 1.0 - on, 0.0]
})
.collect();
let stats = pair_stats(&rows, 4, 0.0, 2.0);
assert!((stats.mean_a - 0.5).abs() < 1e-12);
assert!((stats.cov + 0.25).abs() < 1e-12);
assert!((stats.cov / (stats.var_a * stats.var_b).sqrt() + 1.0).abs() < 1e-12);
}
}