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
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
use std::collections::VecDeque;
use std::f64::consts::TAU;

use super::dsp::{Complex, ComplexFir, Nco, blackman_taps, design_lowpass};
use super::ita2::{self, Decoded, Shift};
use super::profile::{CharacterSet, RttyProfile, RttyTones, validate_sample_rate};
use crate::{Error, Result};

/// Matched-filter cutoff as a fraction of the symbol rate.
const MATCHED_CUTOFF_BAUD: f64 = 0.6;
/// Matched-filter length in symbol periods.
const MATCHED_SPAN_BITS: f64 = 2.0;
/// Minimum baseband rate after decimation, in hertz.
const MIN_BASEBAND_RATE: f64 = 1_500.0;
/// Scale from raw decision energy (relative to the noise floor) to a log-likelihood ratio.
const LLR_SCALE: f64 = 0.35;
/// Averaging time of the decision-directed tone levels, in bits.
const LEVEL_BITS: f64 = 16.0;
/// Averaging time of each tone's "on" level, in bits. Shorter than the noise
/// average so the decision threshold follows selective fading.
const SIGNAL_LEVEL_BITS: f64 = 2.0;
/// Upper bound on concurrently tracked start-bit hypotheses per lane.
const MAX_CANDIDATES: usize = 16;
/// Positions (in bits) that start a new frame hypothesis may not overlap.
const FRAME_OVERLAP_BITS: f64 = 6.5;
/// Largest per-bit log-likelihood ratio, which keeps confidence from saturating.
const MAX_BIT_LLR: f64 = 6.0;
/// Smoothing of the per-polarity framing quality, per accepted character.
const QUALITY_ALPHA: f64 = 0.35;
/// Below this stream evidence (chain times mean confidence) the squelch
/// requires a strong character.
const QUALITY_GATE: f64 = 0.12;
/// Confidence that lets a character through a low-quality stream.
const STRONG_CHARACTER: f64 = 0.7;
/// Strong-character squelch period after a cold start, a discontinuity or silence, in bits.
const WARMUP_BITS: f64 = 24.0;
/// Baseband power below which the input counts as digital silence.
const SILENCE_POWER: f64 = 1e-14;
/// Signal estimate: per-frame decay of the accumulated bit-centre powers.
const SNR_DECAY: f64 = 0.85;
/// Signal estimate: part of each bit around its centre that is measured.
const SNR_WINDOW: (f64, f64) = (0.3, 0.7);
/// Signal estimate: length of the per-sample power history, in bits.
const SNR_HISTORY_BITS: f64 = 32.0;
/// Reported SNR when nothing has been measured or the estimate is below it.
const SNR_FLOOR_DB: f64 = -30.0;
/// Reported SNR ceiling.
const SNR_CEILING_DB: f64 = 60.0;
/// Bandwidth to which [`RttySignal::snr_db`] is referred, in hertz.
const SNR_REFERENCE_HZ: f64 = 3_000.0;
/// Smoothed character confidence above which the stream counts as locked.
const LOCK_SCORE: f64 = 0.35;
/// Interval of lock decay and AFC updates, in seconds.
const TICK_SECONDS: f64 = 0.1;
/// Noise blanker: impulses above this multiple of the running RMS are removed.
const BLANKER_THRESHOLD: f64 = 6.0;
/// Noise blanker: averaging time of the running power estimate, in seconds.
const BLANKER_AVERAGE_SECONDS: f64 = 0.2;
/// Noise blanker: samples removed after each detected impulse, in seconds.
const BLANKER_HOLD_SECONDS: f64 = 0.000_5;
/// Noise blanker: longer excursions are treated as level changes, in seconds.
const BLANKER_MAX_IMPULSE_SECONDS: f64 = 0.003;
/// Noise blanker: below this mean power (about -90 dBFS) nothing is blanked.
const BLANKER_POWER_FLOOR: f64 = 1e-9;
/// How strongly a chaining stream disfavours hypotheses that break the chain.
const CHAIN_PRIOR: f64 = 0.8;
/// Quality advantage required before another lane or polarity takes over.
const STREAM_HYSTERESIS: f64 = 0.1;

/// Demodulator decision rule.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RttyLane {
    /// Optimal automatic threshold correction using both tones.
    Atc,
    /// Ratio-squared (Kahn) combining of both tones.
    Kahn,
    /// Mark tone only, for selective fading of the space tone.
    MarkOnly,
    /// Space tone only, for selective fading of the mark tone.
    SpaceOnly,
}

/// Enabled demodulator decision rules. Each lane and polarity forms its own
/// character stream; the decoder emits the stream that currently frames the
/// signal best.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct RttyLaneSet {
    /// Enable [`RttyLane::Atc`].
    pub atc: bool,
    /// Enable [`RttyLane::Kahn`].
    pub kahn: bool,
    /// Enable [`RttyLane::MarkOnly`].
    pub mark_only: bool,
    /// Enable [`RttyLane::SpaceOnly`].
    pub space_only: bool,
}

impl Default for RttyLaneSet {
    /// Optimal ATC and Kahn: the stream selector follows Kahn on stationary
    /// and flat-fading channels and ATC when the tones are unbalanced.
    fn default() -> Self {
        Self::ATC_KAHN
    }
}

impl RttyLaneSet {
    /// Optimal ATC and Kahn ratio-squared.
    pub const ATC_KAHN: Self = Self {
        atc: true,
        kahn: true,
        mark_only: false,
        space_only: false,
    };
    /// Optimal ATC only.
    pub const ATC: Self = Self {
        atc: true,
        kahn: false,
        mark_only: false,
        space_only: false,
    };
    /// Every decision rule. The single-tone lanes rarely win on real channels;
    /// prefer the default unless measurements show otherwise.
    pub const ALL: Self = Self {
        atc: true,
        kahn: true,
        mark_only: true,
        space_only: true,
    };

    fn lanes(self) -> Vec<RttyLane> {
        let mut lanes = Vec::with_capacity(4);
        if self.atc {
            lanes.push(RttyLane::Atc);
        }
        if self.kahn {
            lanes.push(RttyLane::Kahn);
        }
        if self.mark_only {
            lanes.push(RttyLane::MarkOnly);
        }
        if self.space_only {
            lanes.push(RttyLane::SpaceOnly);
        }
        lanes
    }
}

/// RTTY demodulator options.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RttyDecoderConfig {
    /// Expected signalling profile. Stop-bit length is not enforced: 1, 1.5
    /// and 2 stop bits are all accepted.
    pub profile: RttyProfile,
    /// Expected audio tones.
    pub tones: RttyTones,
    /// Figures-case variant.
    pub character_set: CharacterSet,
    /// Return to letters case after a received space (unshift on space).
    pub usos: bool,
    /// Track small frequency errors automatically.
    pub afc: bool,
    /// Largest correction AFC may apply, in hertz.
    pub afc_range_hz: f64,
    /// Minimum character confidence, in `0.0..=1.0`, below which characters are
    /// suppressed. Zero disables the squelch. Shift codes use half this threshold.
    pub squelch: f32,
    /// Enabled decision rules.
    pub lanes: RttyLaneSet,
    /// Also decode with mark and space exchanged and keep the more confident result.
    pub auto_reverse: bool,
    /// Interval between [`RttyDecodeEvent::Signal`] reports in seconds.
    pub signal_report_seconds: f64,
    /// Remove short impulses (static crashes) before filtering.
    pub noise_blanker: bool,
}

impl Default for RttyDecoderConfig {
    fn default() -> Self {
        Self {
            profile: RttyProfile::default(),
            tones: RttyTones::default(),
            character_set: CharacterSet::default(),
            usos: true,
            afc: true,
            afc_range_hz: 50.0,
            squelch: 0.25,
            lanes: RttyLaneSet::default(),
            auto_reverse: true,
            signal_report_seconds: 0.1,
            noise_blanker: true,
        }
    }
}

/// A received character.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct RttyCharacter {
    /// Decoded character. Line breaks are reported as `\r` and `\n`.
    pub ch: char,
    /// Raw five-bit code.
    pub code: u8,
    /// Character confidence in `0.0..=1.0`: zero is indistinguishable from
    /// noise, one means every bit of the frame was decided with certainty.
    /// It is the frame's all-bits-correct probability on a log scale.
    pub confidence: f32,
    /// Input sample where the start bit began, on the caller's input timeline.
    pub start_sample: u64,
    /// Decision rule that produced the character.
    pub lane: RttyLane,
    /// True when the character was decoded with mark and space exchanged.
    pub reversed: bool,
}

/// Periodic demodulator state for tuning indicators.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct RttySignal {
    /// Input sample at which the report was produced.
    pub sample: u64,
    /// True while recent characters are decoded with good confidence.
    /// AFC only adapts while locked.
    pub locked: bool,
    /// Estimated signal-to-noise ratio referred to a 3 kHz noise bandwidth,
    /// in decibels: average signal power over noise power in 3 kHz, the usual
    /// convention for HF digital modes.
    ///
    /// Measured in the power domain at the bit centres of recently decoded
    /// characters (squelched ones included): the keyed filter gives signal
    /// plus noise, the other filter noise alone, both tones contribute in
    /// proportion to how long they are keyed, and the noise is scaled from
    /// the matched filters' equivalent noise bandwidth to 3 kHz. Only bits
    /// whose neighbours carry the same tone are used, so inter-symbol leakage
    /// does not limit the estimate; a run of `RYRY` alone does not update it.
    ///
    /// With white noise it tracks the true value within about 1 dB from
    /// −12 to +40 dB, smoothed over roughly the last seven characters.
    /// Below −12 dB it flattens out between −13 and −16 dB, which is also
    /// what noise alone reads, because characters framed from noise still
    /// look like a weak signal. It holds its value while nothing is decoded
    /// (digital silence, a steady carrier) and is `-30.0` until the first
    /// measurement.
    pub snr_db: f32,
    /// Mark filter level: the smoothed amplitude while mark is keyed over
    /// the smoothed amplitude while space is keyed (the mark filter's noise
    /// floor), as `20·log10((on − off) / off)` in the matched-filter
    /// bandwidth; `-30.0` at or below the floor and `0.0` before any level is
    /// known.
    ///
    /// A fast relative indicator for tuning and tone balance (selective
    /// fading shows as a difference between `mark_db` and `space_db`), not a
    /// calibrated SNR: leakage between adjacent bits caps it near 15–16 dB,
    /// so it is compressed above about 10 dB [`RttySignal::snr_db`].
    pub mark_db: f32,
    /// Space filter level, defined like [`RttySignal::mark_db`].
    pub space_db: f32,
    /// Correction currently applied by AFC, in hertz.
    pub frequency_offset_hz: f32,
    /// True when recent characters were decoded reversed.
    pub reversed: bool,
}

/// Decoder output.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum RttyDecodeEvent {
    /// A character passed the squelch.
    Character(RttyCharacter),
    /// Periodic demodulator report.
    Signal(RttySignal),
}

/// Receives decoder events.
pub trait RttySink {
    /// Handles one event.
    fn on_event(&mut self, event: RttyDecodeEvent);
}

impl<F: FnMut(RttyDecodeEvent)> RttySink for F {
    fn on_event(&mut self, event: RttyDecodeEvent) {
        self(event);
    }
}

impl RttySink for Vec<RttyDecodeEvent> {
    fn on_event(&mut self, event: RttyDecodeEvent) {
        self.push(event);
    }
}

#[derive(Clone, Copy, Debug)]
struct FrameResult {
    t0: f64,
    code: u8,
    confidence: f64,
    lane: RttyLane,
    reversed: bool,
}

#[derive(Clone, Copy, Debug)]
struct Candidate {
    t0: f64,
    sums: [f64; 7],
    counts: [u32; 7],
}

#[derive(Debug)]
struct Framer {
    lane: RttyLane,
    reversed: bool,
    frame_bits: f64,
    previous: f64,
    recent: VecDeque<f64>,
    recent_len: usize,
    candidates: Vec<Candidate>,
    last_valid_start: f64,
}

impl Framer {
    fn new(lane: RttyLane, reversed: bool, samples_per_bit: f64, frame_bits: f64) -> Self {
        let recent_len = (samples_per_bit / 2.0).round().max(1.0) as usize;
        Self {
            lane,
            reversed,
            frame_bits,
            previous: 0.0,
            recent: VecDeque::with_capacity(recent_len + 1),
            recent_len,
            candidates: Vec::with_capacity(MAX_CANDIDATES),
            last_valid_start: f64::NEG_INFINITY,
        }
    }

    fn reset(&mut self) {
        self.previous = 0.0;
        self.recent.clear();
        self.candidates.clear();
        self.last_valid_start = f64::NEG_INFINITY;
    }

    fn push(&mut self, index: f64, llr: f64, bit: f64, out: &mut Vec<FrameResult>) {
        let llr = if self.reversed { -llr } else { llr };

        // The mark run before a start bit is summed afresh (a running sum would
        // keep the rounding error of an extreme value long after it left the
        // window), but only at a mark-to-space crossing, where it is needed.
        if self.previous >= 0.0
            && llr < 0.0
            && self.candidates.len() < MAX_CANDIDATES
            && self.recent.len() == self.recent_len
            && self.recent.iter().sum::<f64>() > 0.0
        {
            let fraction = self.previous / (self.previous - llr);
            let t0 = index - 1.0 + fraction;
            if t0 >= self.last_valid_start + FRAME_OVERLAP_BITS * bit {
                self.candidates.push(Candidate {
                    t0,
                    sums: [0.0; 7],
                    counts: [0; 7],
                });
            }
        }
        self.previous = llr;
        self.recent.push_back(llr);
        if self.recent.len() > self.recent_len {
            self.recent.pop_front();
        }

        let mut position = 0;
        while position < self.candidates.len() {
            let candidate = &mut self.candidates[position];
            let offset = (index - candidate.t0) / bit;
            if offset >= 6.75 {
                let finished = self.candidates.swap_remove(position);
                if let Some(result) = self.finish(finished) {
                    out.push(result);
                    // Flywheel: a valid frame predicts the next start bit, which keeps
                    // timing when noise blurs the next mark-to-space edge.
                    let predicted = result.t0 + self.frame_bits * bit;
                    let duplicate = self
                        .candidates
                        .iter()
                        .any(|other| (other.t0 - predicted).abs() < 0.1 * bit);
                    if !duplicate && self.candidates.len() < MAX_CANDIDATES {
                        self.candidates.push(Candidate {
                            t0: predicted,
                            sums: [0.0; 7],
                            counts: [0; 7],
                        });
                    }
                }
                continue;
            }
            if offset >= 0.0 {
                let slot = offset.floor();
                let fraction = offset - slot;
                if (0.25..=0.75).contains(&fraction) {
                    let slot = slot as usize;
                    candidate.sums[slot] += llr;
                    candidate.counts[slot] += 1;
                }
            }
            position += 1;
        }
    }

    /// Validates one hypothesis. Overlapping hypotheses from every lane are
    /// resolved by confidence in [`RttyDecoder::flush`].
    fn finish(&self, candidate: Candidate) -> Option<FrameResult> {
        let mut averages = [0.0; 7];
        for ((average, sum), count) in averages
            .iter_mut()
            .zip(candidate.sums)
            .zip(candidate.counts)
        {
            if count == 0 {
                return None;
            }
            *average = sum / f64::from(count);
        }
        if averages[0] >= 0.0 || averages[6] <= 0.0 {
            return None;
        }
        let clip = |value: f64| value.clamp(-MAX_BIT_LLR, MAX_BIT_LLR);
        let mut confidence = sigmoid(-clip(averages[0])) * sigmoid(clip(averages[6]));
        let mut code = 0u8;
        for bit in 0..5 {
            let value = averages[bit + 1];
            confidence *= sigmoid(clip(value).abs());
            if value > 0.0 {
                code |= 1 << bit;
            }
        }
        Some(FrameResult {
            t0: candidate.t0,
            code,
            confidence,
            lane: self.lane,
            reversed: self.reversed,
        })
    }

    fn mark_accepted(&mut self, t0: f64, bit: f64) {
        self.last_valid_start = self.last_valid_start.max(t0);
        self.candidates
            .retain(|candidate| candidate.t0 >= t0 + FRAME_OVERLAP_BITS * bit);
    }
}

#[inline]
fn sigmoid(x: f64) -> f64 {
    1.0 / (1.0 + (-x).exp())
}

/// Resolves overlapping frame hypotheses of one polarity and tracks evidence
/// that this polarity frames the signal correctly.
#[derive(Debug)]
struct Combiner {
    pending: Vec<FrameResult>,
    last_t0: f64,
    /// Smoothed fraction of back-to-back characters that start exactly one
    /// frame after the previous one. Gaps (idle mark) leave it unchanged.
    chain: f64,
    /// Smoothed confidence of accepted characters.
    score: f64,
    /// Most recent resolved character, kept so it can still be emitted when
    /// this stream becomes active because of that very character.
    last_winner: Option<FrameResult>,
}

impl Combiner {
    fn new() -> Self {
        Self {
            pending: Vec::new(),
            last_t0: f64::NEG_INFINITY,
            chain: 0.0,
            score: 0.0,
            last_winner: None,
        }
    }

    fn clear(&mut self) {
        self.pending.clear();
        self.last_t0 = f64::NEG_INFINITY;
        self.last_winner = None;
    }

    /// Start of the oldest unresolved hypothesis whose competitors are all final at `now`.
    fn ready_at(&self, now: f64, bit: f64) -> Option<f64> {
        let earliest = self
            .pending
            .iter()
            .map(|result| result.t0)
            .min_by(f64::total_cmp)?;
        (!now.is_finite() || now >= earliest + (FRAME_OVERLAP_BITS + 7.25) * bit)
            .then_some(earliest)
    }

    /// Resolves the oldest group of overlapping hypotheses.
    fn next(&mut self, now: f64, bit: f64) -> Option<FrameResult> {
        let earliest = self.ready_at(now, bit)?;
        let window_end = earliest + FRAME_OVERLAP_BITS * bit;
        // While characters arrive back to back, a hypothesis that continues the
        // chain is far more likely than one starting inside a character.
        let penalty = 1.0 - CHAIN_PRIOR * self.chain;
        let weight = |result: &FrameResult| {
            let distance = (result.t0 - self.last_t0) / bit;
            if (6.8..=8.3).contains(&distance) {
                result.confidence
            } else {
                result.confidence * penalty
            }
        };
        let mut winner: Option<(FrameResult, f64)> = None;
        for result in &self.pending {
            if result.t0 >= window_end {
                continue;
            }
            let weighted = weight(result);
            if winner.is_none_or(|(_, best)| weighted > best) {
                winner = Some((*result, weighted));
            }
        }
        let (winner, _) = winner?;
        let keep_from = window_end.max(winner.t0 + FRAME_OVERLAP_BITS * bit);
        self.pending.retain(|result| result.t0 >= keep_from);

        let distance = (winner.t0 - self.last_t0) / bit;
        if distance < 6.8 {
            self.chain += QUALITY_ALPHA * (0.0 - self.chain);
        } else if distance <= 8.3 {
            self.chain += QUALITY_ALPHA * (1.0 - self.chain);
        }
        self.score += QUALITY_ALPHA * (confidence_score(winner.confidence) - self.score);
        self.last_t0 = winner.t0;
        self.last_winner = Some(winner);
        Some(winner)
    }
}

/// Combined evidence that a stream frames a real signal.
fn stream_quality(combiner: &Combiner) -> f64 {
    0.5 * combiner.chain + 0.5 * combiner.score
}

/// Maps the all-bits-correct probability of a frame to `0.0..=1.0` on a log
/// scale: seven coin flips (2^-7) map to zero, certainty maps to one.
fn confidence_score(probability: f64) -> f64 {
    (1.0 + probability.max(1e-12).log2() / 7.0).clamp(0.0, 1.0)
}

/// Running level estimate: the plain mean of the first `tau` inputs, then an
/// exponential average with time constant `tau` (in samples).
///
/// Starting as a cumulative mean gives the least noisy estimate while few
/// samples are known, so a cold start neither trusts a handful of samples nor
/// settles on whatever value happened to come last.
#[derive(Clone, Copy, Debug, Default)]
struct Level {
    value: f64,
    count: f64,
}

impl Level {
    #[inline]
    fn update(&mut self, input: f64, tau: f64) {
        self.count += 1.0;
        self.value += (input - self.value) / self.count.min(tau.max(1.0));
    }
}

#[derive(Debug)]
struct ToneTrack {
    nco: Nco,
    filter: ComplexFir,
    previous: Complex,
    envelope: Level,
    noise: Level,
}

impl ToneTrack {
    fn new(offset_hz: f64, baseband_rate: f64, taps: Vec<f64>) -> Self {
        Self {
            nco: Nco::new(offset_hz, baseband_rate),
            filter: ComplexFir::new(taps),
            previous: Complex::ZERO,
            envelope: Level::default(),
            noise: Level::default(),
        }
    }
}

/// Streaming RTTY demodulator and ITA2 decoder.
#[derive(Debug)]
pub struct RttyDecoder {
    config: RttyDecoderConfig,
    sample_rate: u32,
    decimation: usize,
    baseband_rate: f64,
    samples_per_bit: f64,
    blanker: NoiseBlanker,
    decimator: ComplexFir,
    center_nco: Nco,
    mark: ToneTrack,
    space: ToneTrack,
    framers: Vec<Framer>,
    results: Vec<FrameResult>,
    /// One combiner per framer: every lane and polarity forms its own stream.
    combiners: Vec<Combiner>,
    /// Stream whose characters are emitted.
    active_stream: usize,
    /// Start of the last emitted character, used to avoid duplicates when the
    /// active stream changes.
    last_emitted_t0: f64,
    shift: Shift,
    input_index: u64,
    /// Input sample that corresponds to baseband sample zero.
    base_input_offset: u64,
    phase: usize,
    baseband_index: u64,
    afc_offset_hz: f64,
    afc_error: f64,
    afc_weight: f64,
    /// Smoothed confidence of the active stream, used for lock and AFC.
    lock_score: f64,
    last_character_index: f64,
    next_tick: u64,
    tick_interval: u64,
    next_report: u64,
    report_interval: u64,
    matched_delay: f64,
    decimator_delay: f64,
    levels: [f64; 4],
    warmup: u64,
    warmup_length: u64,
    /// Consecutive non-silent baseband samples; levels are learned only once
    /// the matched filters have filled after silence.
    active_run: u64,
    /// Matched-filter length in baseband samples.
    matched_len: u64,
    /// Recent `(baseband index, |mark|², |space|²)` matched-filter powers.
    power_history: Vec<(u64, f64, f64)>,
    /// Decaying sums of keyed-filter power, other-filter power and sample
    /// count over measured bit centres.
    snr_sums: [f64; 3],
    /// Equivalent noise bandwidth of the matched filters, in hertz.
    noise_bandwidth_hz: f64,
    finished: bool,
}

impl RttyDecoder {
    /// Creates a decoder for mono PCM at `sample_rate`.
    pub fn new(sample_rate: u32, config: RttyDecoderConfig) -> Result<Self> {
        validate_sample_rate(sample_rate)?;
        validate_config(&config, sample_rate)?;
        let rate = f64::from(sample_rate);
        let half_band = config.tones.shift_hz() / 2.0 + 2.0 * config.profile.baud + 30.0;
        let target = (3.0 * half_band).max(MIN_BASEBAND_RATE);
        let decimation = ((rate / target).floor() as usize).max(1);
        let baseband_rate = rate / decimation as f64;
        let transition = (baseband_rate - 2.0 * half_band).max(100.0);
        let decimator_taps = if decimation == 1 {
            vec![1.0]
        } else {
            design_lowpass(half_band, rate, blackman_taps(transition, rate, 2_047))
        };
        let samples_per_bit = baseband_rate / config.profile.baud;
        let matched_taps = design_lowpass(
            MATCHED_CUTOFF_BAUD * config.profile.baud,
            baseband_rate,
            (MATCHED_SPAN_BITS * samples_per_bit).round() as usize,
        );
        let matched_delay = (matched_taps.len() - 1) as f64 / 2.0;
        let matched_len = matched_taps.len() as u64;
        let noise_bandwidth_hz = equivalent_noise_bandwidth(&matched_taps, baseband_rate);
        let history_len = (SNR_HISTORY_BITS * samples_per_bit).ceil() as usize;
        let decimator_delay = (decimator_taps.len() - 1) as f64 / 2.0;
        let center = config.tones.center_hz();
        let mark = ToneTrack::new(
            config.tones.mark_hz - center,
            baseband_rate,
            matched_taps.clone(),
        );
        let space = ToneTrack::new(config.tones.space_hz - center, baseband_rate, matched_taps);
        let framers = build_framers(&config, samples_per_bit);
        let framers_len = framers.len();
        let report_interval =
            ((config.signal_report_seconds * baseband_rate).round() as u64).max(1);
        let tick_interval = ((TICK_SECONDS * baseband_rate).round() as u64).max(1);
        let warmup_length = (WARMUP_BITS * samples_per_bit).ceil() as u64;
        Ok(Self {
            config,
            sample_rate,
            decimation,
            baseband_rate,
            samples_per_bit,
            blanker: NoiseBlanker::new(rate),
            decimator: ComplexFir::new(decimator_taps),
            center_nco: Nco::new(center, rate),
            mark,
            space,
            framers,
            results: Vec::new(),
            combiners: (0..framers_len).map(|_| Combiner::new()).collect(),
            active_stream: 0,
            last_emitted_t0: f64::NEG_INFINITY,
            shift: Shift::Letters,
            input_index: 0,
            base_input_offset: 0,
            phase: 0,
            baseband_index: 0,
            afc_offset_hz: 0.0,
            afc_error: 0.0,
            afc_weight: 0.0,
            lock_score: 0.0,
            last_character_index: f64::NEG_INFINITY,
            next_tick: tick_interval,
            tick_interval,
            next_report: report_interval,
            report_interval,
            matched_delay,
            decimator_delay,
            levels: [0.0; 4],
            warmup: warmup_length,
            warmup_length,
            active_run: 0,
            matched_len,
            power_history: vec![(u64::MAX, 0.0, 0.0); history_len.max(1)],
            snr_sums: [0.0; 3],
            noise_bandwidth_hz,
            finished: false,
        })
    }

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

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

    /// Number of input samples consumed, including samples declared lost by
    /// [`RttyDecoder::mark_discontinuity`].
    #[must_use]
    pub fn samples_consumed(&self) -> u64 {
        self.input_index
    }

    /// Current shift state of the received stream.
    #[must_use]
    pub fn shift(&self) -> Shift {
        self.shift
    }

    /// Frequency correction currently applied by AFC, in hertz.
    #[must_use]
    pub fn frequency_offset_hz(&self) -> f64 {
        self.afc_offset_hz
    }

    /// Changes the squelch threshold.
    pub fn set_squelch(&mut self, squelch: f32) -> Result<()> {
        if !squelch.is_finite() || !(0.0..=1.0).contains(&squelch) {
            return Err(Error::InvalidConfiguration(
                "RTTY squelch must be between 0 and 1",
            ));
        }
        self.config.squelch = squelch;
        Ok(())
    }

    /// Enables or disables AFC. Disabling returns the correction to zero.
    pub fn set_afc(&mut self, enabled: bool) {
        self.config.afc = enabled;
        if !enabled {
            self.afc_offset_hz = 0.0;
            self.apply_center();
        }
    }

    /// Enables or disables unshift-on-space reception.
    pub fn set_usos(&mut self, enabled: bool) {
        self.config.usos = enabled;
    }

    /// Selects the figures-case variant.
    pub fn set_character_set(&mut self, character_set: CharacterSet) {
        self.config.character_set = character_set;
    }

    /// Changes the decision lanes and reverse detection.
    ///
    /// Unchanged settings are a no-op. Streams that remain enabled keep their
    /// state; characters already demodulated are emitted first.
    pub fn set_lanes(
        &mut self,
        lanes: RttyLaneSet,
        auto_reverse: bool,
        sink: &mut impl RttySink,
    ) -> Result<()> {
        if lanes == self.config.lanes && auto_reverse == self.config.auto_reverse {
            return Ok(());
        }
        let config = RttyDecoderConfig {
            lanes,
            auto_reverse,
            ..self.config
        };
        validate_config(&config, self.sample_rate)?;
        self.flush(f64::INFINITY, sink);
        let active_key = {
            let framer = &self.framers[self.active_stream];
            (framer.lane, framer.reversed)
        };
        let mut old: Vec<(Framer, Combiner)> = self
            .framers
            .drain(..)
            .zip(self.combiners.drain(..))
            .collect();
        self.config = config;
        for fresh in build_framers(&self.config, self.samples_per_bit) {
            let kept = old
                .iter()
                .position(|(framer, _)| {
                    framer.lane == fresh.lane && framer.reversed == fresh.reversed
                })
                .map(|index| old.swap_remove(index));
            let (framer, combiner) = kept.unwrap_or_else(|| (fresh, Combiner::new()));
            self.framers.push(framer);
            self.combiners.push(combiner);
        }
        self.active_stream = self
            .framers
            .iter()
            .position(|framer| (framer.lane, framer.reversed) == active_key)
            .unwrap_or(0);
        Ok(())
    }

    /// Moves the decoder to new tones.
    ///
    /// A change of centre frequency only is applied in place. A different
    /// shift updates the profile, emits characters already demodulated and
    /// rebuilds the filters, which drops partial characters and re-learns
    /// signal levels.
    pub fn retune(&mut self, tones: RttyTones, sink: &mut impl RttySink) -> Result<()> {
        tones.validate(self.sample_rate)?;
        if (tones.shift_hz() - self.config.tones.shift_hz()).abs() > 0.5 {
            let config = RttyDecoderConfig {
                tones,
                profile: RttyProfile {
                    shift_hz: tones.shift_hz(),
                    ..self.config.profile
                },
                ..self.config
            };
            validate_config(&config, self.sample_rate)?;
            self.flush(f64::INFINITY, sink);
            let mut fresh = Self::new(self.sample_rate, config)?;
            fresh.input_index = self.input_index;
            fresh.base_input_offset = self.input_index;
            fresh.shift = self.shift;
            fresh.finished = self.finished;
            *self = fresh;
            return Ok(());
        }
        self.config.tones = tones;
        self.afc_offset_hz = 0.0;
        let center = tones.center_hz();
        self.apply_center();
        self.mark
            .nco
            .set_frequency(tones.mark_hz - center, self.baseband_rate);
        self.space
            .nco
            .set_frequency(tones.space_hz - center, self.baseband_rate);
        Ok(())
    }

    /// Feeds `f32` PCM in `-1.0..=1.0`.
    pub fn push_f32(&mut self, samples: &[f32], sink: &mut impl RttySink) -> Result<()> {
        if self.finished {
            return Err(Error::DecoderFinished);
        }
        if samples.iter().any(|sample| !sample.is_finite()) {
            return Err(Error::NonFiniteSample);
        }
        for &sample in samples {
            self.process_sample(f64::from(sample), sink);
        }
        Ok(())
    }

    /// Feeds signed 16-bit PCM.
    pub fn push_i16(&mut self, samples: &[i16], sink: &mut impl RttySink) -> Result<()> {
        if self.finished {
            return Err(Error::DecoderFinished);
        }
        for &sample in samples {
            self.process_sample(f64::from(sample) / 32_768.0, sink);
        }
        Ok(())
    }

    /// Feeds PCM and appends the resulting events to `events`.
    pub fn process_into(
        &mut self,
        samples: &[f32],
        events: &mut Vec<RttyDecodeEvent>,
    ) -> Result<()> {
        self.push_f32(samples, events)
    }

    /// Ends the input: drains the filter delay, emits every pending character
    /// and rejects further input until [`RttyDecoder::reset`].
    pub fn finish(&mut self, sink: &mut impl RttySink) {
        if self.finished {
            return;
        }
        let tail = self.decimator_delay
            + (self.matched_delay + 8.0 * self.samples_per_bit) * self.decimation as f64;
        for _ in 0..tail.ceil() as usize {
            self.process_sample(0.0, sink);
        }
        self.flush(f64::INFINITY, sink);
        self.finished = true;
    }

    /// Declares that `dropped_samples` input samples were lost.
    ///
    /// Characters already demodulated are emitted first; partial characters
    /// and filter history are discarded. AFC, lock and shift state are kept,
    /// and sample positions stay aligned with the original input timeline.
    pub fn mark_discontinuity(&mut self, dropped_samples: u64, sink: &mut impl RttySink) {
        self.flush(f64::INFINITY, sink);
        self.input_index += dropped_samples;
        self.base_input_offset = self.input_index;
        self.baseband_index = 0;
        self.phase = 0;
        self.decimator.reset();
        self.mark.filter.reset();
        self.space.filter.reset();
        self.mark.previous = Complex::ZERO;
        self.space.previous = Complex::ZERO;
        for framer in &mut self.framers {
            framer.reset();
        }
        for combiner in &mut self.combiners {
            combiner.clear();
        }
        self.warmup = self.warmup_length;
        self.active_run = 0;
        self.last_character_index = f64::NEG_INFINITY;
        self.last_emitted_t0 = f64::NEG_INFINITY;
        self.next_tick = self.tick_interval;
        self.next_report = self.report_interval;
    }

    /// Returns to the freshly constructed state with the current configuration.
    pub fn reset(&mut self) {
        if let Ok(fresh) = Self::new(self.sample_rate, self.config) {
            *self = fresh;
        }
    }

    fn apply_center(&mut self) {
        self.center_nco.set_frequency(
            self.config.tones.center_hz() + self.afc_offset_hz,
            f64::from(self.sample_rate),
        );
    }

    fn process_sample(&mut self, sample: f64, sink: &mut impl RttySink) {
        let sample = if self.config.noise_blanker {
            self.blanker.process(sample)
        } else {
            sample
        };
        let mixed = self.center_nco.next().scale(sample);
        self.input_index += 1;
        self.decimator.push(mixed);
        self.phase += 1;
        if self.phase < self.decimation {
            return;
        }
        self.phase = 0;
        let baseband = self.decimator.output();
        self.process_baseband(baseband, sink);
    }

    fn process_baseband(&mut self, baseband: Complex, sink: &mut impl RttySink) {
        let bit = self.samples_per_bit;
        let mark_out = self.mark.filter.filter(baseband * self.mark.nco.next());
        let space_out = self.space.filter.filter(baseband * self.space.nco.next());
        let m = mark_out.norm();
        let s = space_out.norm();

        let slot = (self.baseband_index % self.power_history.len() as u64) as usize;
        self.power_history[slot] = (self.baseband_index, m * m, s * s);

        // Decision-directed tone levels: each tone's "on" level is averaged
        // while it dominates and its "off" (noise) level while the other does.
        // They start as plain means of the samples seen so far, and the
        // output demands strong characters for a while after construction, a
        // discontinuity or silence. Digital silence carries no noise floor:
        // the levels are frozen while it lasts and until the matched filters
        // have refilled, otherwise they would decay toward zero and make the
        // first noise after the silence look like a confident signal.
        let power = baseband.norm_sqr();
        if power < SILENCE_POWER {
            self.warmup = self.warmup_length;
            self.active_run = 0;
        } else {
            self.warmup = self.warmup.saturating_sub(1);
            self.active_run = self.active_run.saturating_add(1);
        }
        if self.active_run > self.matched_len {
            let signal_tau = SIGNAL_LEVEL_BITS * bit;
            let noise_tau = LEVEL_BITS * bit;
            if m > s {
                self.mark.envelope.update(m, signal_tau);
                self.space.noise.update(s, noise_tau);
            } else {
                self.space.envelope.update(s, signal_tau);
                self.mark.noise.update(m, noise_tau);
            }
        }
        let me = self.mark.envelope.value;
        let se = self.space.envelope.value;
        let mn = self.mark.noise.value;
        let sn = self.space.noise.value;
        self.levels = [me, se, mn, sn];

        if self.config.afc && self.locked() {
            let (current, previous, weight) = if m > s {
                (mark_out, self.mark.previous, m * m)
            } else {
                (space_out, self.space.previous, s * s)
            };
            self.afc_error += (current * previous.conj()).arg() * weight;
            self.afc_weight += weight;
        }
        self.mark.previous = mark_out;
        self.space.previous = space_out;

        // Decisions are scaled by the lower noise floor that rests on at
        // least a bit of samples: a floor learned from a few readings could
        // be arbitrarily small and scale them without bound.
        let noise = [self.mark.noise, self.space.noise]
            .iter()
            .filter(|level| level.count >= bit)
            .map(|level| level.value)
            .reduce(f64::min);
        let norm = noise.map_or(0.0, |noise| 1.0 / (noise * noise).max(1e-18));
        let mark_amp = (me - mn).max(0.0);
        let space_amp = (se - sn).max(0.0);
        let mc = (m.clamp(mn.min(me), me.max(mn)) - mn).max(0.0);
        let sc = (s.clamp(sn.min(se), se.max(sn)) - sn).max(0.0);

        let index = self.baseband_index as f64;
        for (stream, framer) in self.framers.iter_mut().enumerate() {
            let raw = match framer.lane {
                RttyLane::Atc => {
                    mc * mark_amp
                        - sc * space_amp
                        - 0.5 * (mark_amp * mark_amp - space_amp * space_amp)
                }
                // Scaled so a clean bit gives the same magnitude in every lane,
                // which keeps stream qualities comparable.
                RttyLane::Kahn => mc * mc - sc * sc,
                RttyLane::MarkOnly => 2.0 * mc * mark_amp - mark_amp * mark_amp,
                RttyLane::SpaceOnly => space_amp * space_amp - 2.0 * sc * space_amp,
            };
            framer.push(index, LLR_SCALE * raw * norm, bit, &mut self.results);
            self.combiners[stream].pending.append(&mut self.results);
        }
        self.flush(index, sink);
        self.baseband_index += 1;

        if self.baseband_index >= self.next_tick {
            self.next_tick += self.tick_interval;
            self.tick(index);
        }
        if self.baseband_index >= self.next_report {
            self.next_report += self.report_interval;
            self.report(sink);
        }
    }

    fn locked(&self) -> bool {
        self.lock_score > LOCK_SCORE
    }

    fn flush(&mut self, now: f64, sink: &mut impl RttySink) {
        let bit = self.samples_per_bit;
        // Resolve streams in global start-time order so the active stream can
        // change between characters without reordering or skipping output.
        loop {
            let Some((stream, _)) = self
                .combiners
                .iter()
                .enumerate()
                .filter_map(|(stream, combiner)| combiner.ready_at(now, bit).map(|t0| (stream, t0)))
                .min_by(|a, b| a.1.total_cmp(&b.1))
            else {
                return;
            };
            let Some(winner) = self.combiners[stream].next(now, bit) else {
                return;
            };
            self.framers[stream].mark_accepted(winner.t0, bit);
            let previous = self.active_stream;
            self.select_stream();
            if self.active_stream != previous && self.active_stream != stream {
                // The newly active stream may have resolved this character
                // while it was inactive; emit it rather than lose it.
                if let Some(replay) = self.combiners[self.active_stream].last_winner {
                    self.emit_if_new(self.active_stream, replay, sink);
                }
            }
            if stream == self.active_stream {
                self.emit_if_new(stream, winner, sink);
            }
        }
    }

    fn emit_if_new(&mut self, stream: usize, frame: FrameResult, sink: &mut impl RttySink) {
        if frame.t0 < self.last_emitted_t0 + FRAME_OVERLAP_BITS * self.samples_per_bit {
            return;
        }
        self.last_emitted_t0 = frame.t0;
        let combiner = &self.combiners[stream];
        let evidence = combiner.chain * combiner.score;
        self.accept(frame, evidence, sink);
    }

    /// Follows the decision rule and polarity that currently frame the signal
    /// best, in the spirit of running several complete decoders side by side.
    fn select_stream(&mut self) {
        let quality = stream_quality;
        let current = quality(&self.combiners[self.active_stream]);
        let mut best = (self.active_stream, current);
        for (stream, combiner) in self.combiners.iter().enumerate() {
            let candidate = quality(combiner);
            if candidate > best.1 {
                best = (stream, candidate);
            }
        }
        if best.0 != self.active_stream && best.1 > current + STREAM_HYSTERESIS {
            self.active_stream = best.0;
        }
    }

    fn accept(&mut self, frame: FrameResult, quality: f64, sink: &mut impl RttySink) {
        self.last_character_index = frame.t0;
        self.measure_frame(&frame);
        let confidence = confidence_score(frame.confidence);
        self.lock_score += QUALITY_ALPHA * (confidence - self.lock_score);
        let mut squelch = f64::from(self.config.squelch);
        if squelch > 0.0 && (quality < QUALITY_GATE || self.warmup > 0) {
            // A stream that neither chains nor decodes confidently is noise,
            // and level estimates are not trustworthy while warming up: only
            // characters that are convincing on their own pass.
            squelch = squelch.max(STRONG_CHARACTER);
        }
        match ita2::decode(frame.code, self.shift, self.config.character_set) {
            // Shift codes use a lower threshold: losing a FIGS corrupts every
            // following figure, while a spurious one is undone by USOS or LTRS.
            Decoded::ShiftTo(shift) if confidence >= squelch * 0.5 => self.shift = shift,
            Decoded::ShiftTo(_) | Decoded::Nothing => {}
            Decoded::Char(ch) if confidence >= squelch => {
                if ch == ' ' && self.config.usos {
                    self.shift = Shift::Letters;
                }
                let decimation = self.decimation as f64;
                let start =
                    (frame.t0 - self.matched_delay + 1.0) * decimation - 1.0 - self.decimator_delay;
                sink.on_event(RttyDecodeEvent::Character(RttyCharacter {
                    ch,
                    code: frame.code,
                    confidence: confidence as f32,
                    start_sample: self.base_input_offset + start.max(0.0).round() as u64,
                    lane: frame.lane,
                    reversed: frame.reversed,
                }));
            }
            Decoded::Char(_) => {}
        }
    }

    /// Accumulates keyed-filter and other-filter power at the centres of the
    /// frame's data bits whose neighbours carry the same tone.
    fn measure_frame(&mut self, frame: &FrameResult) {
        let bit = self.samples_per_bit;
        let mut bits = [true; 7];
        bits[0] = false;
        for (index, value) in bits[1..6].iter_mut().enumerate() {
            *value = (frame.code >> index) & 1 == 1;
        }
        let mut sums = [0.0; 3];
        for k in 1..6 {
            if bits[k - 1] != bits[k] || bits[k + 1] != bits[k] {
                continue;
            }
            let mark_keyed = bits[k] != frame.reversed;
            let first = (frame.t0 + (k as f64 + SNR_WINDOW.0) * bit).ceil();
            let last = (frame.t0 + (k as f64 + SNR_WINDOW.1) * bit).floor();
            if first < 0.0 || last < first {
                continue;
            }
            for index in first as u64..=last as u64 {
                let slot = (index % self.power_history.len() as u64) as usize;
                let (stored, mark, space) = self.power_history[slot];
                if stored != index {
                    continue;
                }
                let (keyed, other) = if mark_keyed {
                    (mark, space)
                } else {
                    (space, mark)
                };
                sums[0] += keyed;
                sums[1] += other;
                sums[2] += 1.0;
            }
        }
        if sums[2] > 0.0 {
            for (total, value) in self.snr_sums.iter_mut().zip(sums) {
                *total = *total * SNR_DECAY + value;
            }
        }
    }

    /// Signal-to-noise ratio in 3 kHz from the bit-centre powers.
    fn snr_db(&self) -> f64 {
        let [keyed, other, count] = self.snr_sums;
        if count <= 0.0 || other <= 0.0 {
            return SNR_FLOOR_DB;
        }
        let noise = other / count;
        let signal = keyed / count - noise;
        if signal <= 0.0 {
            return SNR_FLOOR_DB;
        }
        let ratio = signal / noise * self.noise_bandwidth_hz / SNR_REFERENCE_HZ;
        (10.0 * ratio.log10()).clamp(SNR_FLOOR_DB, SNR_CEILING_DB)
    }

    /// Fixed-rate housekeeping, independent of the report interval.
    fn tick(&mut self, index: f64) {
        let frame_bits = 6.0 + self.config.profile.stop_bits.bits();
        if index - self.last_character_index > 3.0 * frame_bits * self.samples_per_bit {
            self.lock_score *= 0.85;
        }
        if self.config.afc && self.locked() && self.afc_weight > 0.0 {
            let error_hz = self.afc_error / self.afc_weight * self.baseband_rate / TAU;
            let range = self.config.afc_range_hz;
            self.afc_offset_hz = (self.afc_offset_hz + 0.5 * error_hz).clamp(-range, range);
            self.apply_center();
        } else if !self.locked() && self.afc_offset_hz != 0.0 {
            // Without a signal, drift back to the nominal tones.
            self.afc_offset_hz *= 0.9;
            if self.afc_offset_hz.abs() < 0.05 {
                self.afc_offset_hz = 0.0;
            }
            self.apply_center();
        }
        self.afc_error = 0.0;
        self.afc_weight = 0.0;
    }

    fn report(&mut self, sink: &mut impl RttySink) {
        let [me, se, mn, sn] = self.levels;
        let ratio_db = |envelope: f64, noise: f64| {
            if noise <= 1e-12 {
                0.0
            } else {
                (20.0 * ((envelope - noise).max(1e-12) / noise).log10()).max(-30.0)
            }
        };
        let mark_db = ratio_db(me, mn);
        let space_db = ratio_db(se, sn);
        let snr_db = self.snr_db();
        sink.on_event(RttyDecodeEvent::Signal(RttySignal {
            sample: self.input_index,
            locked: self.locked(),
            snr_db: snr_db as f32,
            mark_db: mark_db as f32,
            space_db: space_db as f32,
            frequency_offset_hz: self.afc_offset_hz as f32,
            reversed: self.framers[self.active_stream].reversed,
        }));
    }
}

/// Removes impulsive noise (static crashes, ignition) before filtering.
///
/// Samples whose magnitude exceeds a multiple of the running RMS are replaced
/// by zero, together with a short guard around them, so isolated impulses
/// cannot ring through the narrow matched filters. An excursion that lasts
/// longer than a few milliseconds is a level change (a signal starting, AGC),
/// not an impulse: it passes and re-seeds the power estimate.
#[derive(Debug)]
struct NoiseBlanker {
    power: f64,
    alpha: f64,
    hold: usize,
    hold_samples: usize,
    episode: usize,
    episode_energy: f64,
    max_impulse_samples: usize,
}

impl NoiseBlanker {
    fn new(sample_rate: f64) -> Self {
        Self {
            power: 0.0,
            alpha: 1.0 / (BLANKER_AVERAGE_SECONDS * sample_rate).max(1.0),
            hold: 0,
            hold_samples: (BLANKER_HOLD_SECONDS * sample_rate).ceil() as usize,
            episode: 0,
            episode_energy: 0.0,
            max_impulse_samples: (BLANKER_MAX_IMPULSE_SECONDS * sample_rate).ceil() as usize,
        }
    }

    #[inline]
    fn process(&mut self, sample: f64) -> f64 {
        let energy = sample * sample;
        if self.power > BLANKER_POWER_FLOOR
            && energy > BLANKER_THRESHOLD * BLANKER_THRESHOLD * self.power
        {
            if self.hold == 0 {
                self.episode = 0;
                self.episode_energy = 0.0;
            }
            self.hold = self.hold_samples;
        }
        if self.hold > 0 {
            self.hold -= 1;
            self.episode += 1;
            self.episode_energy += energy;
            if self.episode <= self.max_impulse_samples {
                return 0.0;
            }
            self.power = self.episode_energy / self.episode as f64;
            self.hold = 0;
        }
        self.power += (energy - self.power) * self.alpha;
        sample
    }
}

/// Equivalent noise bandwidth of an FIR filter in hertz: the width of an
/// ideal filter with the same DC gain that passes the same white-noise power.
/// For the complex baseband filters used here it spans negative and positive
/// frequencies, which matches a real passband of the same width.
fn equivalent_noise_bandwidth(taps: &[f64], sample_rate: f64) -> f64 {
    let sum: f64 = taps.iter().sum();
    let energy: f64 = taps.iter().map(|tap| tap * tap).sum();
    sample_rate * energy / (sum * sum).max(f64::MIN_POSITIVE)
}

fn build_framers(config: &RttyDecoderConfig, samples_per_bit: f64) -> Vec<Framer> {
    let mut framers = Vec::new();
    let frame_bits = 6.0 + config.profile.stop_bits.bits();
    for lane in config.lanes.lanes() {
        framers.push(Framer::new(lane, false, samples_per_bit, frame_bits));
        if config.auto_reverse {
            framers.push(Framer::new(lane, true, samples_per_bit, frame_bits));
        }
    }
    framers
}

fn validate_config(config: &RttyDecoderConfig, sample_rate: u32) -> Result<()> {
    config.profile.validate()?;
    config.tones.validate(sample_rate)?;
    config.profile.check_tones(&config.tones)?;
    if config.lanes.lanes().is_empty() {
        return Err(Error::InvalidConfiguration(
            "at least one RTTY decision lane must be enabled",
        ));
    }
    if !config.squelch.is_finite() || !(0.0..=1.0).contains(&config.squelch) {
        return Err(Error::InvalidConfiguration(
            "RTTY squelch must be between 0 and 1",
        ));
    }
    if !config.afc_range_hz.is_finite() || !(0.0..=500.0).contains(&config.afc_range_hz) {
        return Err(Error::InvalidConfiguration(
            "RTTY AFC range must be between 0 and 500 Hz",
        ));
    }
    if !config.signal_report_seconds.is_finite()
        || !(0.01..=10.0).contains(&config.signal_report_seconds)
    {
        return Err(Error::InvalidConfiguration(
            "RTTY signal report interval must be between 0.01 and 10 seconds",
        ));
    }
    Ok(())
}