rasterwave 0.2.0

High-performance streaming SSTV and radiofax encoder/decoder
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
use crate::fax::{
    FaxDecodeEvent, FaxDecodeEventRef, FaxDecoder, FaxDecoderConfig, FaxIoc, FaxLpm, FaxModulation,
    FaxSpec,
};
use crate::{Error, PaperBoundaryKind, Result};

/// How continuous radiofax paper chooses its active parameters.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FaxPaperMode {
    /// Print with fallback parameters while detecting IOC, LPM and FM/AM.
    Auto {
        /// Parameters used before APT and phasing establish a trusted page.
        fallback: FaxSpec,
    },
    /// Keep one selected specification while observing matching APT/phasing.
    Manual {
        /// Forced parameters.
        spec: FaxSpec,
    },
}

impl Default for FaxPaperMode {
    fn default() -> Self {
        Self::Auto {
            fallback: FaxSpec::standard(FaxIoc::Ioc576, FaxLpm::LPM_120),
        }
    }
}

/// Continuous radiofax paper decoder policy.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FaxPaperConfig {
    /// Automatic fallback or manually locked parameters.
    pub mode: FaxPaperMode,
    /// AM candidate evaluated alongside the fallback FM detector in Auto.
    pub auto_am_modulation: FaxModulation,
    /// Full-scale amplitude used by AM decoding.
    pub am_full_scale: f32,
    /// Stable APT evidence required before IOC selection.
    pub apt_confirm_seconds: f32,
    /// Maximum APT/phasing acquisition time.
    pub acquisition_timeout_seconds: f32,
    /// Expected phasing duration, or `None` for pattern-end detection.
    pub expected_phasing_seconds: Option<f32>,
    /// Stable APT stop evidence required to end a capture.
    pub stop_confirm_seconds: f32,
    /// Signal-loss timeout used by acquisition detectors only.
    pub signal_loss_seconds: f32,
    /// Minimum PCM signal level used by acquisition detectors.
    pub minimum_signal_level: f32,
    /// Minimum target-subcarrier coherence.
    pub minimum_carrier_coherence: f32,
}

impl Default for FaxPaperConfig {
    fn default() -> Self {
        let defaults = FaxDecoderConfig::default();
        Self {
            mode: FaxPaperMode::default(),
            auto_am_modulation: FaxModulation::AmSubcarrier {
                carrier_hz: 1900.0,
                black_level: 0.0,
                white_level: 1.0,
            },
            am_full_scale: defaults.am_full_scale,
            apt_confirm_seconds: defaults.apt_confirm_seconds,
            acquisition_timeout_seconds: defaults.acquisition_timeout_seconds,
            expected_phasing_seconds: defaults.expected_phasing_seconds,
            stop_confirm_seconds: defaults.stop_confirm_seconds,
            signal_loss_seconds: defaults.signal_loss_seconds,
            minimum_signal_level: defaults.minimum_signal_level,
            minimum_carrier_coherence: defaults.minimum_carrier_coherence,
        }
    }
}

/// Borrowed event emitted by [`FaxPaperDecoder`].
#[derive(Debug)]
#[non_exhaustive]
pub enum FaxPaperEventRef<'a> {
    /// An indefinitely growing fax paper raster began.
    PaperStarted {
        /// Decoder-local paper identifier.
        paper_id: u64,
        /// Initial fallback or manually selected parameters.
        spec: FaxSpec,
    },
    /// A meaningful divider in the fax paper.
    Boundary {
        /// Decoder-local paper identifier.
        paper_id: u64,
        /// Monotonic boundary identifier.
        boundary_id: u64,
        /// First row after the divider.
        line_index: u64,
        /// Parameters active after the divider.
        spec: FaxSpec,
        /// Divider classification.
        kind: PaperBoundaryKind,
        /// Whether the divider anchors an automatic capture.
        trusted: bool,
    },
    /// APT identified an IOC candidate.
    AptDetected {
        /// Candidate IOC.
        ioc: FaxIoc,
    },
    /// One continuous-paper grayscale row is ready.
    LineReady {
        /// Decoder-local paper identifier.
        paper_id: u64,
        /// Current segment boundary.
        boundary_id: u64,
        /// Monotonic paper row.
        line_index: u64,
        /// Row within the current segment.
        segment_line_index: u32,
        /// Active fax parameters.
        spec: FaxSpec,
        /// Grayscale pixels, valid until the callback returns.
        pixels: &'a [u8],
    },
    /// A trusted APT-delimited fax capture completed.
    TransmissionCompleted {
        /// Decoder-local paper identifier.
        paper_id: u64,
        /// Boundary that opened the capture.
        boundary_id: u64,
        /// First captured row.
        start_line: u64,
        /// Exclusive captured end.
        end_line: u64,
        /// Active parameters.
        spec: FaxSpec,
        /// Number of completed rows.
        lines: u32,
    },
    /// A valid fax header was rejected by a manual lock.
    ProtocolObserved {
        /// Observed parameters.
        spec: FaxSpec,
        /// Whether APT and phasing fully established the parameters.
        trusted: bool,
    },
    /// APT or phasing acquisition was rejected.
    SignalRejected {
        /// Stable reason.
        reason: &'static str,
    },
}

/// Owned form of [`FaxPaperEventRef`].
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum FaxPaperEvent {
    /// A fax paper raster began.
    PaperStarted {
        /// Decoder-local paper identifier.
        paper_id: u64,
        /// Initial parameters.
        spec: FaxSpec,
    },
    /// A fax paper divider.
    Boundary {
        /// Decoder-local paper identifier.
        paper_id: u64,
        /// Boundary identifier.
        boundary_id: u64,
        /// First row after the divider.
        line_index: u64,
        /// Active parameters.
        spec: FaxSpec,
        /// Divider classification.
        kind: PaperBoundaryKind,
        /// Whether the divider anchors an automatic capture.
        trusted: bool,
    },
    /// APT identified an IOC candidate.
    AptDetected {
        /// Candidate IOC.
        ioc: FaxIoc,
    },
    /// One owned fax paper row.
    LineReady {
        /// Decoder-local paper identifier.
        paper_id: u64,
        /// Current segment boundary.
        boundary_id: u64,
        /// Monotonic paper row.
        line_index: u64,
        /// Row within the current segment.
        segment_line_index: u32,
        /// Active parameters.
        spec: FaxSpec,
        /// Owned grayscale pixels.
        pixels: Vec<u8>,
    },
    /// A trusted fax transmission completed.
    TransmissionCompleted {
        /// Decoder-local paper identifier.
        paper_id: u64,
        /// Boundary that opened the capture.
        boundary_id: u64,
        /// First captured row.
        start_line: u64,
        /// Exclusive captured end.
        end_line: u64,
        /// Active parameters.
        spec: FaxSpec,
        /// Number of completed rows.
        lines: u32,
    },
    /// A fax protocol was observed but rejected.
    ProtocolObserved {
        /// Observed parameters.
        spec: FaxSpec,
        /// Whether the observation was trusted.
        trusted: bool,
    },
    /// Acquisition was rejected.
    SignalRejected {
        /// Stable reason.
        reason: &'static str,
    },
}

impl FaxPaperEventRef<'_> {
    /// Copy a borrowed event into an owned value.
    pub fn to_owned(&self) -> FaxPaperEvent {
        match self {
            Self::PaperStarted { paper_id, spec } => FaxPaperEvent::PaperStarted {
                paper_id: *paper_id,
                spec: *spec,
            },
            Self::Boundary {
                paper_id,
                boundary_id,
                line_index,
                spec,
                kind,
                trusted,
            } => FaxPaperEvent::Boundary {
                paper_id: *paper_id,
                boundary_id: *boundary_id,
                line_index: *line_index,
                spec: *spec,
                kind: *kind,
                trusted: *trusted,
            },
            Self::AptDetected { ioc } => FaxPaperEvent::AptDetected { ioc: *ioc },
            Self::LineReady {
                paper_id,
                boundary_id,
                line_index,
                segment_line_index,
                spec,
                pixels,
            } => FaxPaperEvent::LineReady {
                paper_id: *paper_id,
                boundary_id: *boundary_id,
                line_index: *line_index,
                segment_line_index: *segment_line_index,
                spec: *spec,
                pixels: pixels.to_vec(),
            },
            Self::TransmissionCompleted {
                paper_id,
                boundary_id,
                start_line,
                end_line,
                spec,
                lines,
            } => FaxPaperEvent::TransmissionCompleted {
                paper_id: *paper_id,
                boundary_id: *boundary_id,
                start_line: *start_line,
                end_line: *end_line,
                spec: *spec,
                lines: *lines,
            },
            Self::ProtocolObserved { spec, trusted } => FaxPaperEvent::ProtocolObserved {
                spec: *spec,
                trusted: *trusted,
            },
            Self::SignalRejected { reason } => FaxPaperEvent::SignalRejected { reason },
        }
    }
}

/// Synchronous consumer for borrowed continuous fax events.
pub trait FaxPaperSink {
    /// Handle one event before borrowed pixels are reused.
    fn on_event(&mut self, event: FaxPaperEventRef<'_>);
}

impl<F> FaxPaperSink for F
where
    F: for<'a> FnMut(FaxPaperEventRef<'a>),
{
    fn on_event(&mut self, event: FaxPaperEventRef<'_>) {
        self(event);
    }
}

#[derive(Debug)]
struct Detector {
    decoder: FaxDecoder,
}

#[derive(Debug)]
struct Capture {
    detector: usize,
    page_id: u64,
    boundary_id: u64,
    start_line: u64,
    spec: FaxSpec,
}

/// Continuous radiofax raster with parallel APT/phasing acquisition.
#[derive(Debug)]
pub struct FaxPaperDecoder {
    input_sample_rate: u32,
    config: FaxPaperConfig,
    detectors: Vec<Detector>,
    raster: FaxDecoder,
    paper_id: u64,
    next_boundary_id: u64,
    active_boundary_id: u64,
    paper_line: u64,
    current_spec: FaxSpec,
    raster_page_id: Option<u64>,
    raster_segment_start: u64,
    capture: Option<Capture>,
    started: bool,
    finished: bool,
}

impl FaxPaperDecoder {
    /// Construct a continuous radiofax paper decoder.
    pub fn new(input_sample_rate: u32, config: FaxPaperConfig) -> Result<Self> {
        let initial_spec = match config.mode {
            FaxPaperMode::Auto { fallback } => fallback,
            FaxPaperMode::Manual { spec } => spec,
        };
        let raster = immediate_decoder(input_sample_rate, initial_spec, config.am_full_scale)?;
        let detectors = build_detectors(input_sample_rate, config)?;
        Ok(Self {
            input_sample_rate,
            config,
            detectors,
            raster,
            paper_id: 1,
            next_boundary_id: 2,
            active_boundary_id: 1,
            paper_line: 0,
            current_spec: initial_spec,
            raster_page_id: None,
            raster_segment_start: 0,
            capture: None,
            started: false,
            finished: false,
        })
    }

    /// Push arbitrary-sized mono PCM and emit fax rows before returning.
    pub fn push_f32(&mut self, input: &[f32], sink: &mut impl FaxPaperSink) -> Result<usize> {
        if self.finished {
            return Err(Error::DecoderFinished);
        }
        if input.iter().any(|sample| !sample.is_finite()) {
            return Err(Error::NonFiniteSample);
        }
        if input.is_empty() {
            return Ok(0);
        }
        let mut emitted = 0;
        if !self.started {
            self.started = true;
            sink.on_event(FaxPaperEventRef::PaperStarted {
                paper_id: self.paper_id,
                spec: self.current_spec,
            });
            sink.on_event(FaxPaperEventRef::Boundary {
                paper_id: self.paper_id,
                boundary_id: self.active_boundary_id,
                line_index: 0,
                spec: self.current_spec,
                kind: PaperBoundaryKind::Initial,
                trusted: false,
            });
            emitted += 2;
        }
        for chunk in input.chunks(64) {
            let capture_was_active = self.capture.is_some();
            let mut claimed = capture_was_active;
            for detector_index in 0..self.detectors.len() {
                let mut events = Vec::new();
                self.detectors[detector_index]
                    .decoder
                    .process_into(chunk, &mut events)?;
                for event in events {
                    emitted +=
                        self.handle_detector_event(detector_index, event, &mut claimed, sink)?;
                }
            }
            if !claimed && self.capture.is_none() {
                let mut events = Vec::new();
                self.raster.process_into(chunk, &mut events)?;
                for event in events {
                    emitted += self.handle_raster_event(event, sink);
                }
            }
        }
        Ok(emitted)
    }

    /// Collect owned events for one PCM chunk.
    pub fn process_into(
        &mut self,
        input: &[f32],
        output: &mut Vec<FaxPaperEvent>,
    ) -> Result<usize> {
        let mut sink = |event: FaxPaperEventRef<'_>| output.push(event.to_owned());
        self.push_f32(input, &mut sink)
    }

    /// Finalize input without completing an untrusted or partial capture.
    pub fn finish(&mut self, sink: &mut impl FaxPaperSink) -> Result<usize> {
        if self.finished {
            return Err(Error::DecoderFinished);
        }
        let mut emitted = 0;
        for detector_index in 0..self.detectors.len() {
            let mut events = Vec::new();
            self.detectors[detector_index]
                .decoder
                .finish(&mut |event: FaxDecodeEventRef<'_>| events.push(event.to_owned()))?;
            let mut claimed = self.capture.is_some();
            for event in events {
                emitted += self.handle_detector_event(detector_index, event, &mut claimed, sink)?;
            }
        }
        let mut ignored = Vec::new();
        let _ = self
            .raster
            .finish(&mut |event: FaxDecodeEventRef<'_>| ignored.push(event.to_owned()));
        self.finished = true;
        Ok(emitted)
    }

    /// End receiver continuity without completing or persisting a page.
    pub fn mark_signal_lost(&mut self, sink: &mut impl FaxPaperSink) -> Result<usize> {
        if self.finished {
            return Err(Error::DecoderFinished);
        }
        self.rebuild(PaperBoundaryKind::Discontinuity, sink)?;
        Ok(1)
    }

    /// Reset acquisition and continue the same paper with an explicit divider.
    pub fn reset(&mut self, sink: &mut impl FaxPaperSink) -> Result<usize> {
        self.finished = false;
        self.rebuild(PaperBoundaryKind::Reset, sink)?;
        Ok(1)
    }

    /// Monotonic row after the latest emitted paper row.
    pub const fn next_line_index(&self) -> u64 {
        self.paper_line
    }

    fn handle_detector_event(
        &mut self,
        detector_index: usize,
        event: FaxDecodeEvent,
        claimed: &mut bool,
        sink: &mut impl FaxPaperSink,
    ) -> Result<usize> {
        match event {
            FaxDecodeEvent::AptDetected { ioc } => {
                sink.on_event(FaxPaperEventRef::AptDetected { ioc });
                Ok(1)
            }
            FaxDecodeEvent::PageStarted { page_id, spec } => {
                if self.capture.is_some() {
                    return Ok(0);
                }
                let accepted = match self.config.mode {
                    FaxPaperMode::Auto { .. } => true,
                    FaxPaperMode::Manual { spec: locked } => same_decode_spec(locked, spec),
                };
                if !accepted {
                    sink.on_event(FaxPaperEventRef::ProtocolObserved {
                        spec,
                        trusted: true,
                    });
                    return Ok(1);
                }
                *claimed = true;
                let boundary_id = self.next_boundary_id;
                self.next_boundary_id += 1;
                self.active_boundary_id = boundary_id;
                self.current_spec = spec;
                self.capture = Some(Capture {
                    detector: detector_index,
                    page_id,
                    boundary_id,
                    start_line: self.paper_line,
                    spec,
                });
                sink.on_event(FaxPaperEventRef::Boundary {
                    paper_id: self.paper_id,
                    boundary_id,
                    line_index: self.paper_line,
                    spec,
                    kind: PaperBoundaryKind::AptPhasing,
                    trusted: true,
                });
                Ok(1)
            }
            FaxDecodeEvent::LineReady {
                page_id,
                line_index,
                pixels,
            } => {
                let Some(capture) = self.capture.as_ref().filter(|capture| {
                    capture.detector == detector_index && capture.page_id == page_id
                }) else {
                    return Ok(0);
                };
                *claimed = true;
                let paper_line = capture.start_line + u64::from(line_index);
                self.paper_line = self.paper_line.max(paper_line + 1);
                sink.on_event(FaxPaperEventRef::LineReady {
                    paper_id: self.paper_id,
                    boundary_id: capture.boundary_id,
                    line_index: paper_line,
                    segment_line_index: line_index,
                    spec: capture.spec,
                    pixels: &pixels,
                });
                Ok(1)
            }
            FaxDecodeEvent::PageCompleted {
                page_id,
                lines,
                partial,
            } => {
                let Some(capture) = self.capture.take().filter(|capture| {
                    capture.detector == detector_index && capture.page_id == page_id
                }) else {
                    return Ok(0);
                };
                *claimed = true;
                if partial {
                    self.raster = immediate_decoder(
                        self.input_sample_rate,
                        self.current_spec,
                        self.config.am_full_scale,
                    )?;
                    self.raster_page_id = None;
                    self.raster_segment_start = self.paper_line;
                    self.emit_boundary(PaperBoundaryKind::Discontinuity, sink);
                    return Ok(1);
                }
                let end_line = capture.start_line + u64::from(lines);
                self.paper_line = self.paper_line.max(end_line);
                sink.on_event(FaxPaperEventRef::TransmissionCompleted {
                    paper_id: self.paper_id,
                    boundary_id: capture.boundary_id,
                    start_line: capture.start_line,
                    end_line,
                    spec: capture.spec,
                    lines,
                });
                self.raster = immediate_decoder(
                    self.input_sample_rate,
                    capture.spec,
                    self.config.am_full_scale,
                )?;
                self.raster_page_id = None;
                self.raster_segment_start = end_line;
                self.emit_boundary(PaperBoundaryKind::ProtocolEnd, sink);
                Ok(2)
            }
            FaxDecodeEvent::SignalRejected { reason } => {
                sink.on_event(FaxPaperEventRef::SignalRejected { reason });
                Ok(1)
            }
            FaxDecodeEvent::PhasingLocked { .. } => Ok(0),
        }
    }

    fn handle_raster_event(
        &mut self,
        event: FaxDecodeEvent,
        sink: &mut impl FaxPaperSink,
    ) -> usize {
        match event {
            FaxDecodeEvent::PageStarted { page_id, spec } => {
                self.raster_page_id = Some(page_id);
                self.raster_segment_start = self.paper_line;
                self.current_spec = spec;
                0
            }
            FaxDecodeEvent::LineReady {
                page_id,
                line_index,
                pixels,
            } if self.raster_page_id == Some(page_id) => {
                let paper_line = self.raster_segment_start + u64::from(line_index);
                self.paper_line = self.paper_line.max(paper_line + 1);
                sink.on_event(FaxPaperEventRef::LineReady {
                    paper_id: self.paper_id,
                    boundary_id: self.active_boundary_id,
                    line_index: paper_line,
                    segment_line_index: line_index,
                    spec: self.current_spec,
                    pixels: &pixels,
                });
                1
            }
            _ => 0,
        }
    }

    fn rebuild(&mut self, kind: PaperBoundaryKind, sink: &mut impl FaxPaperSink) -> Result<()> {
        self.capture = None;
        self.raster = immediate_decoder(
            self.input_sample_rate,
            self.current_spec,
            self.config.am_full_scale,
        )?;
        self.detectors = build_detectors(self.input_sample_rate, self.config)?;
        self.raster_page_id = None;
        self.raster_segment_start = self.paper_line;
        self.emit_boundary(kind, sink);
        Ok(())
    }

    fn emit_boundary(&mut self, kind: PaperBoundaryKind, sink: &mut impl FaxPaperSink) {
        let boundary_id = self.next_boundary_id;
        self.next_boundary_id += 1;
        self.active_boundary_id = boundary_id;
        sink.on_event(FaxPaperEventRef::Boundary {
            paper_id: self.paper_id,
            boundary_id,
            line_index: self.paper_line,
            spec: self.current_spec,
            kind,
            trusted: false,
        });
    }
}

fn immediate_decoder(
    input_sample_rate: u32,
    spec: FaxSpec,
    am_full_scale: f32,
) -> Result<FaxDecoder> {
    FaxDecoder::new(
        input_sample_rate,
        FaxDecoderConfig {
            immediate_decode: true,
            ioc: Some(spec.ioc),
            lpm: Some(spec.lpm),
            modulation: spec.modulation,
            max_lines: None,
            am_full_scale,
            minimum_signal_level: 0.0,
            minimum_carrier_coherence: 0.0,
            ..FaxDecoderConfig::default()
        },
    )
}

fn build_detectors(input_sample_rate: u32, config: FaxPaperConfig) -> Result<Vec<Detector>> {
    let mut detectors = Vec::with_capacity(2);
    match config.mode {
        FaxPaperMode::Manual { spec } => detectors.push(Detector {
            decoder: acquisition_decoder(input_sample_rate, config, spec.modulation, None)?,
        }),
        FaxPaperMode::Auto { fallback } => {
            detectors.push(Detector {
                decoder: acquisition_decoder(input_sample_rate, config, fallback.modulation, None)?,
            });
            if modulation_kind(fallback.modulation) != modulation_kind(config.auto_am_modulation) {
                detectors.push(Detector {
                    decoder: acquisition_decoder(
                        input_sample_rate,
                        config,
                        config.auto_am_modulation,
                        None,
                    )?,
                });
            }
        }
    }
    Ok(detectors)
}

fn acquisition_decoder(
    input_sample_rate: u32,
    paper: FaxPaperConfig,
    modulation: FaxModulation,
    locked: Option<FaxSpec>,
) -> Result<FaxDecoder> {
    FaxDecoder::new(
        input_sample_rate,
        FaxDecoderConfig {
            immediate_decode: false,
            ioc: locked.map(|spec| spec.ioc),
            lpm: locked.map(|spec| spec.lpm),
            modulation,
            max_lines: None,
            am_full_scale: paper.am_full_scale,
            expected_phasing_seconds: locked
                .map(|spec| spec.phasing_seconds)
                .or(paper.expected_phasing_seconds),
            apt_confirm_seconds: paper.apt_confirm_seconds,
            acquisition_timeout_seconds: paper.acquisition_timeout_seconds,
            stop_confirm_seconds: paper.stop_confirm_seconds,
            signal_loss_seconds: paper.signal_loss_seconds,
            minimum_signal_level: paper.minimum_signal_level,
            minimum_carrier_coherence: paper.minimum_carrier_coherence,
        },
    )
}

fn modulation_kind(modulation: FaxModulation) -> u8 {
    match modulation {
        FaxModulation::FmSubcarrier { .. } => 0,
        FaxModulation::AmSubcarrier { .. } => 1,
    }
}

fn same_decode_spec(left: FaxSpec, right: FaxSpec) -> bool {
    left.ioc == right.ioc
        && left.lpm == right.lpm
        && modulation_kind(left.modulation) == modulation_kind(right.modulation)
}