rasterwave 0.6.0

High-performance streaming SSTV, radiofax and RTTY encoders/decoders
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
//! Wideband RTTY channel scanner ("signal browser").
//!
//! The scanner looks at a whole audio passband at once, finds tone pairs that
//! behave like frequency-shift keying and runs one [`RttyDecoder`] per tracked
//! signal so a caller can show a short decoded preview next to each.

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

/// Preferred analysis bin spacing in hertz; the FFT length is the nearest power of two.
const TARGET_BIN_HZ: f64 = 12.5;
/// Length of the statistics window, in seconds.
const WINDOW_SECONDS: f64 = 1.5;
/// Interval between analysis updates and [`RttyScanEvent::Channels`] reports, in seconds.
const UPDATE_SECONDS: f64 = 0.5;
/// Audio history replayed into the decoder of a newly reported channel, in seconds.
const PREROLL_SECONDS: f64 = 2.0;
/// Consecutive updates a candidate must be seen before it is reported.
const CONFIRM_UPDATES: u32 = 2;
/// A reported channel is removed after this long without a matching detection, in seconds.
const DROP_SECONDS: f64 = 3.0;
/// Detections down to this fraction of `min_score` keep an existing track alive.
const KEEP_FRACTION: f64 = 0.6;
/// Smoothing of the tracked centre frequency per update.
const CENTER_ALPHA: f64 = 0.35;
/// Smoothing of the tracked score and SNR per update.
const SCORE_ALPHA: f64 = 0.5;
/// A confirmed candidate replaces the weakest reported channel only with this score advantage.
const EVICT_MARGIN: f64 = 0.25;
/// A channel decoder is re-centred when the tracked centre moves further than this, in hertz.
const RETUNE_HZ: f64 = 15.0;
/// Local noise floor: percentile of the mean band power around each bin.
const NOISE_PERCENTILE: f64 = 0.2;
/// Local noise floor: half-width of the neighbourhood, in hertz.
const NOISE_SPAN_HZ: f64 = 400.0;
/// Mark/space correlation ramp: `-rho` below the first value scores zero, above the second one.
const RHO_RAMP: (f64, f64) = (0.35, 0.75);
/// Weaker tone above its local noise floor (band power ratio) ramp.
const PRESENCE_RAMP: (f64, f64) = (0.3, 1.2);
/// Keying index (anti-covariance relative to the tone powers) ramp.
const KEYING_RAMP: (f64, f64) = (0.04, 0.15);
/// Most shifts that may be scanned at once.
const MAX_SHIFTS: usize = 8;
/// Most channels that may be decoded at once.
const MAX_CHANNELS: usize = 32;
/// Report interval of the per-channel decoders, in seconds.
const CHANNEL_REPORT_SECONDS: f64 = 0.25;

/// Scanner options.
#[derive(Clone, Debug, PartialEq)]
pub struct RttyScannerConfig {
    /// Tone shifts to search for, in hertz.
    pub shifts_hz: Vec<f32>,
    /// Lowest audio frequency either tone of a channel may occupy, in hertz.
    pub min_hz: f32,
    /// Highest audio frequency either tone of a channel may occupy, in hertz.
    pub max_hz: f32,
    /// Most channels reported and decoded at once.
    pub max_channels: usize,
    /// Detection score in `0.0..=1.0` a candidate needs before it is reported.
    pub min_score: f32,
    /// Baud and stop bits of the per-channel decoders. The shift is taken
    /// from the detected channel, so `profile.shift_hz` is not used.
    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,
        }
    }
}

/// One tracked RTTY signal.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct RttyScanChannel {
    /// Stable identifier, never reused by the same scanner (also not after [`RttyChannelScanner::reset`]).
    pub id: u32,
    /// Smoothed centre between the two tones, in hertz.
    pub center_hz: f32,
    /// Tone shift, in hertz (one of the configured shifts).
    pub shift_hz: f32,
    /// Smoothed detection score in `0.0..=1.0`.
    pub score: f32,
    /// Signal-to-noise ratio referred to a 3 kHz bandwidth, estimated from
    /// the spectrum for ranking channels: it reads 1 to 2 dB low up to about
    /// 20 dB and flattens near 25 dB above that. The
    /// channel decoder's [`RttySignal::snr_db`](super::RttySignal::snr_db) is
    /// the calibrated value.
    pub snr_db: f32,
    /// True when the channel decoder found mark on the upper audio tone while
    /// locked. When false mark is the lower tone (the lower-sideband AFSK
    /// convention) or the decoder has not locked yet.
    pub reversed: bool,
    /// True while the channel decoder frames characters with good confidence.
    pub locked: bool,
}

impl RttyScanChannel {
    /// Audio tones of this channel with mark and space assigned as the decoder found them.
    #[must_use]
    pub fn tones(&self) -> RttyTones {
        RttyTones::from_center(
            f64::from(self.center_hz),
            f64::from(self.shift_hz),
            self.reversed,
        )
    }
}

/// Scanner output.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum RttyScanEvent {
    /// Current channel list, emitted on a fixed cadence (also when empty).
    Channels {
        /// Input sample at which the list was produced.
        sample: u64,
        /// Reported channels ordered by centre frequency.
        channels: Vec<RttyScanChannel>,
    },
    /// Characters decoded on one channel since its previous text event.
    Text {
        /// Input sample at which the characters were reported.
        sample: u64,
        /// Channel identifier.
        channel_id: u32,
        /// Decoded characters; `start_sample` is on the scanner's input timeline.
        characters: Vec<RttyCharacter>,
    },
    /// A channel was dropped; its identifier will not appear again.
    Removed {
        /// Input sample at which the channel was dropped.
        sample: u64,
        /// Channel identifier.
        channel_id: u32,
    },
}

/// Candidate found by one analysis update.
#[derive(Clone, Copy, Debug)]
struct Detection {
    center_hz: f64,
    shift_hz: f64,
    score: f64,
    snr_db: f64,
}

/// Search grid and per-candidate results for one shift.
#[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;
        // Input is validated by the scanner, so pushing cannot fail.
        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;
        // Same shift: applied in place and cannot fail for validated tones.
        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;
                // Polarity is only meaningful while characters frame well;
                // keep the last locked value through fades and noise.
                if signal.locked {
                    *reversed = signal.reversed;
                }
            }
        }
    }
}

#[derive(Debug)]
struct Track {
    /// Assigned when the track is reported.
    id: Option<u32>,
    center_hz: f64,
    shift_hz: f64,
    score: f64,
    snr_db: f64,
    /// Consecutive updates with a matching detection.
    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,
        }
    }
}

/// Streaming wideband RTTY detector with per-channel preview decoders.
///
/// Every hop the scanner computes a Hann-windowed power spectrum (bins of
/// roughly 10 to 16 Hz) and keeps the last 1.5 s of three-bin band powers.
/// Every 500 ms it evaluates each candidate centre (half-bin grid) for every
/// configured shift: both tones must stand above the local noise floor, their
/// powers must be strongly anti-correlated over time (energy moves between
/// mark and space, unlike two carriers or the harmonics of a voice) and a
/// substantial share of their power must swing between them. Detections are
/// tracked with hysteresis; each reported channel gets its own
/// [`RttyDecoder`] (default lanes, auto-reverse) that is primed with the last
/// two seconds of audio.
///
/// Output depends only on the input samples, never on how they are chunked.
#[derive(Debug)]
pub struct RttyChannelScanner {
    config: RttyScannerConfig,
    sample_rate: u32,
    fft: Fft,
    window: Vec<f64>,
    spectrum: Vec<Complex>,
    hop: usize,
    until_hop: usize,
    /// Ring buffer of recent input (analysis frame and decoder pre-roll).
    history: Vec<f32>,
    history_pos: usize,
    history_len: usize,
    preroll: usize,
    input_index: u64,
    bin_hz: f64,
    /// FFT bin of band index zero.
    first_bin: usize,
    band_count: usize,
    /// `window_frames` rows of `band_count` three-bin band powers.
    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 {
    /// Creates a scanner for mono PCM at `sample_rate`.
    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,
        })
    }

    /// Current configuration.
    #[must_use]
    pub fn config(&self) -> &RttyScannerConfig {
        &self.config
    }

    /// Input sample rate.
    #[must_use]
    pub fn sample_rate(&self) -> u32 {
        self.sample_rate
    }

    /// Number of input samples consumed.
    #[must_use]
    pub fn samples_consumed(&self) -> u64 {
        self.input_index
    }

    /// Analysis bin spacing in hertz.
    #[must_use]
    pub fn bin_hz(&self) -> f64 {
        self.bin_hz
    }

    /// Currently reported channels ordered by centre frequency.
    #[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
    }

    /// Feeds `f32` PCM in `-1.0..=1.0`.
    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(())
    }

    /// Feeds signed 16-bit PCM.
    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(())
    }

    /// Ends the input: flushes every channel decoder, emits the remaining
    /// text and a final channel list, and rejects further input until
    /// [`RttyChannelScanner::reset`].
    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;
    }

    /// Returns to the freshly constructed state with the current
    /// configuration. Channel identifiers keep counting up.
    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);
    }

    /// Evaluates every candidate centre of every shift over the last `frames` frames.
    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;
                // Regularised so that numerically constant carriers give no correlation.
                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
                };
                // Local maximum of the anti-covariance; ties resolve to the left.
                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],
                });
            }
        }

        // Strongest first, then non-maximum suppression across shifts.
        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;
            }
        }

        // Merge tracks that converged onto the same signal: the reported (or
        // older) one survives.
        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;
            }
        }

        // Drop stale tracks. Unreported candidates must be seen on every update.
        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();
    }

    /// Reports confirmed candidates while slots are free, replacing a clearly weaker channel otherwise.
    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);
        // Validated tones always build; a failure leaves the channel without preview.
        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(),
                });
            }
        }
    }
}

/// The most recent `len` samples of a ring buffer whose next write position is `pos`, in order.
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])
    }
}

/// Emits the final text of a dropped track and its removal.
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,
}

/// Time statistics of the band power at two fractional band positions.
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,
    }
}

/// Fractional band index of a frequency.
fn position(frequency_hz: f64, bin_hz: f64, first_bin: usize) -> f64 {
    frequency_hz / bin_hz - first_bin as f64
}

/// Integer part (clamped so that `index + 1` is valid) and fraction of a band position.
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];
        // Next write position 3: the oldest sample is 1.0, the newest 7.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() {
        // Two bands whose powers swap every frame are perfectly anti-correlated.
        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);
    }
}