datalink 0.2.0

Decode aviation datalink traffic from payloads, SDR, files, and Airframes.io
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
//! HFDL frontend for files, SDR streams, and native diagnostics.
//!
//! The frontend channelizes HF I/Q sources, runs the experimental native HFDL
//! demodulator diagnostics, parses candidate PDUs with `acars::decode::hfdl`,
//! and emits JSON or Redis messages. It shares source parsing with the VDL2 and
//! VHF frontends but uses HFDL-specific channel defaults and frequency handling.
//!
//! ## Known HFDL channels
//!
//! HFDL channels are listed in kHz. The automatic channel selector filters
//! the known channel table to the source bandwidth. The table below groups
//! frequencies by ground station/center. Underlined frequencies were observed
//! in captured Airframes.io data.
//!
//! `†` marks frequencies found only in the older ACARS Online HF ACARS list
//! rather than the current public HFDL system table.
//!
//! | | Center | Frequencies (kHz) |
//! |-|---|---|
//! | 1 | San Francisco, California | 4672†, 5508, 6559, 8559†, <u>8927</u>, <u>10081</u>, <u>11327</u>, <u>13276</u>, <u>17919</u>, <u>21934</u> |
//! | 2 | Molokai, Hawaii | 5514, 6565, <u>8912</u>, <u>8936</u>, <u>10027</u>, 10075†, <u>11312</u>, <u>11348</u>, <u>13276</u>, <u>13312</u>, <u>13324</u>, <u>17919</u>, 17936†, <u>21937</u> |
//! | 3 | Reykjavik, Iceland | 3900, <u>5720</u>, 6712, <u>8977</u>, 11184, <u>15025</u>, 17985 |
//! | 4 | Riverhead, New York | 5523†, 5652, <u>6661</u>, <u>8912</u>, 11315†, <u>11387</u>, 13275†, <u>13276</u>, <u>17919</u>, <u>21931</u>, <u>21934</u>† |
//! | 5 | Auckland, New Zealand | 5583, <u>6535</u>, 8921, 10084, <u>13351</u>, 13352†, <u>17916</u> |
//! | 6 | Hat Yai, Thailand | <u>5655</u>, <u>6535</u>, 8825, 10066, <u>13270</u>, <u>17928</u>, <u>21949</u> |
//! | 7 | Shannon, Ireland | 2998, 3455, 5547, 6532, 8843, <u>8942</u>, <u>10081</u>, 11384 |
//! | 8 | Johannesburg, South Africa | 3016, 4681, 5529, 8834, 11321, 13321, 17922, <u>21949</u> |
//! | 9 | Barrow, Alaska | 2944, 2992, 3007, 3497, 4654, 4687, 5529, 5538, 5544, 6646, <u>8927</u>, <u>8936</u>, <u>10027</u>, <u>10093</u>, 11354, <u>17919</u>, 17934, 21928, <u>21937</u> |
//! | 10 | Muan, South Korea | 2941, 5502, 6619, 8939, <u>10060</u>, <u>13342</u>, <u>17958</u>, <u>21931</u> |
//! | 11 | Albrook, Panama | 5589, <u>6589</u>, 8894, 10063, 13264, 17901 |
//! | 13 | Santa Cruz, Bolivia | 4660, <u>6628</u>, <u>8957</u>, <u>11318</u>, <u>13315</u>, <u>17916</u>, <u>21997</u> |
//! | 14 | Krasnoyarsk, Russia | 5622, 6596, 8886, 10087, 13321, 17912, 21990 |
//! | 15 | Al Muharraq, Bahrain | 2986, 5544, 6646, 8885, 10030, 10045†, <u>11312</u>†, <u>13312</u>, 17967, 21982 |
//! | 16 | Agana, Guam | 5451, 6652, <u>8927</u>, <u>11306</u>, <u>13312</u>, <u>17919</u>, 21928 |
//! | 17 | Canarias, Spain | 6529, <u>8948</u>, <u>11348</u>, <u>13303</u>, <u>17928</u>, <u>21955</u> |

use crate::event::{
    Bearer, DecodedEvent, ProtocolMessage, ReceiverMetadata, SourceClass, SourceMetadata,
};
use crate::source::{Address, Source};
#[cfg(feature = "hackrf")]
use crate::util::hackrf_gain;
#[cfg(feature = "airspy")]
use crate::util::parse_airspy_serial;
use crate::util::{expanduser, infer_capture_params, redis_topic_for_record, RedisPublisher};
use acars::decode::hfdl::{parse_hfdl_pdu, FcsResult};
use acars::demod::hfdl::{diagnose_channel, HfdlDemodConfig};
use clap::{Parser, ValueEnum};
use futures_util::StreamExt;
use rustfft::num_complex::Complex;
use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom};

/// Known HFDL channels in kHz
const KNOWN_HFDL_CHANNELS_KHZ: &[f64] = &[
    2941.0,  // Muan, South Korea
    2944.0,  // Barrow, Alaska
    2986.0,  // Al Muharraq, Bahrain
    2992.0,  // Barrow, Alaska
    2998.0,  // Shannon, Ireland
    3007.0,  // Barrow, Alaska
    3016.0,  // Johannesburg, South Africa
    3455.0,  // Shannon, Ireland
    3497.0,  // Barrow, Alaska
    3900.0,  // Reykjavik, Iceland
    4654.0,  // Barrow, Alaska
    4660.0,  // Santa Cruz, Bolivia
    4672.0,  // California (ACARS Online older table)
    4681.0,  // Johannesburg, South Africa / Johannesburg (ACARS Online older table)
    4687.0,  // Barrow, Alaska
    5451.0,  // Agana, Guam
    5502.0,  // Muan, South Korea
    5508.0,  // San Francisco, California
    5514.0,  // Molokai, Hawaii
    5523.0,  // New York (ACARS Online older table)
    5529.0,  // Johannesburg, South Africa / Barrow, Alaska
    5538.0,  // Barrow, Alaska
    5544.0,  // Barrow, Alaska / Al Muharraq, Bahrain
    5547.0,  // Shannon, Ireland / Shannon (ACARS Online older table)
    5583.0,  // Auckland, New Zealand / Auckland (ACARS Online older table)
    5589.0,  // Albrook, Panama
    5622.0,  // Krasnoyarsk, Russia
    5652.0,  // Riverhead, New York
    5655.0,  // observed in Airframes.io feed; Hat Yai, Thailand
    5720.0, // observed in Airframes.io feed; Reykjavik, Iceland / Reykjavik (ACARS Online older table)
    6529.0, // Canarias, Spain
    6532.0, // Shannon, Ireland / Shannon (ACARS Online older table)
    6535.0, // observed in Airframes.io feed; Auckland, New Zealand / Hat Yai, Thailand
    6559.0, // San Francisco, California
    6565.0, // Molokai, Hawaii
    6589.0, // observed in Airframes.io feed; Albrook, Panama
    6596.0, // Krasnoyarsk, Russia
    6619.0, // Muan, South Korea
    6628.0, // observed in Airframes.io feed; Santa Cruz, Bolivia
    6646.0, // Barrow, Alaska / Al Muharraq, Bahrain / Barrow (ACARS Online older table)
    6652.0, // Agana, Guam
    6661.0, // observed in Airframes.io feed; Riverhead, New York
    6712.0, // Reykjavik, Iceland / Reykjavik (ACARS Online older table)
    8559.0, // California (ACARS Online older table)
    8825.0, // Hat Yai, Thailand
    8834.0, // Johannesburg, South Africa / Johannesburg (ACARS Online older table)
    8843.0, // Shannon, Ireland / Shannon (ACARS Online older table)
    8885.0, // Al Muharraq, Bahrain / Bahrain (ACARS Online older table)
    8886.0, // Krasnoyarsk, Russia
    8894.0, // Albrook, Panama
    8912.0, // observed in Airframes.io feed; Molokai, Hawaii / Riverhead, New York / Hawaii (ACARS Online older table)
    8921.0, // Auckland, New Zealand
    8927.0, // observed in Airframes.io feed; San Francisco, California / Barrow, Alaska / Agana, Guam / Guam (ACARS Online older table)
    8936.0, // observed in Airframes.io feed; Molokai, Hawaii / Barrow, Alaska / Barrow (ACARS Online older table)
    8939.0, // Muan, South Korea
    8942.0, // observed in Airframes.io feed; Shannon, Ireland / Shannon (ACARS Online older table)
    8948.0, // observed in Airframes.io feed; Canarias, Spain
    8957.0, // observed in Airframes.io feed; Santa Cruz, Bolivia
    8977.0, // observed in Airframes.io feed; Reykjavik, Iceland / Reykjavik (ACARS Online older table)
    10027.0, // observed in Airframes.io feed; Molokai, Hawaii / Barrow, Alaska
    10030.0, // Al Muharraq, Bahrain
    10045.0, // Bahrain (ACARS Online older table)
    10060.0, // observed in Airframes.io feed; Muan, South Korea
    10063.0, // Albrook, Panama
    10066.0, // Hat Yai, Thailand
    10075.0, // Hawaii (ACARS Online older table)
    10081.0, // observed in Airframes.io feed; San Francisco, California / Shannon, Ireland / California (ACARS Online older table)
    10084.0, // Auckland, New Zealand / Auckland (ACARS Online older table)
    10087.0, // Krasnoyarsk, Russia / Krasnoyarsk (ACARS Online older table)
    10093.0, // observed in Airframes.io feed; Barrow, Alaska
    11184.0, // Reykjavik, Iceland / Reykjavik (ACARS Online older table)
    11306.0, // observed in Airframes.io feed; Agana, Guam / Guam (ACARS Online older table)
    11312.0, // observed in Airframes.io feed; Molokai, Hawaii / Bahrain (ACARS Online older table)
    11315.0, // New York (ACARS Online older table)
    11318.0, // observed in Airframes.io feed; Santa Cruz, Bolivia / Bolivia (ACARS Online older table)
    11321.0, // Johannesburg, South Africa
    11327.0, // observed in Airframes.io feed; San Francisco, California / California (ACARS Online older table)
    11348.0, // observed in Airframes.io feed; Molokai, Hawaii / Canarias, Spain / Hawaii (ACARS Online older table)
    11354.0, // Barrow, Alaska
    11384.0, // Shannon, Ireland / Shannon (ACARS Online older table)
    11387.0, // observed in Airframes.io feed; Riverhead, New York
    13264.0, // Albrook, Panama
    13270.0, // observed in Airframes.io feed; Hat Yai, Thailand / Hat Yai (ACARS Online older table)
    13275.0, // New York (ACARS Online older table)
    13276.0, // observed in Airframes.io feed; San Francisco, California / Molokai, Hawaii / Riverhead, New York / California (ACARS Online older table)
    13303.0, // observed in Airframes.io feed; Canarias, Spain
    13312.0, // observed in Airframes.io feed; Molokai, Hawaii / Al Muharraq, Bahrain / Agana, Guam
    13315.0, // observed in Airframes.io feed; Santa Cruz, Bolivia / Bolivia (ACARS Online older table)
    13321.0, // Johannesburg, South Africa / Krasnoyarsk, Russia / Krasnoyarsk (ACARS Online older table)
    13324.0, // observed in Airframes.io feed; Molokai, Hawaii
    13342.0, // observed in Airframes.io feed; Muan, South Korea
    13351.0, // observed in Airframes.io feed; Auckland, New Zealand
    13352.0, // Auckland (ACARS Online older table)
    15025.0, // observed in Airframes.io feed; Reykjavik, Iceland / Reykjavik (ACARS Online older table)
    17901.0, // Albrook, Panama
    17912.0, // Krasnoyarsk, Russia
    17916.0, // observed in Airframes.io feed; Auckland, New Zealand / Santa Cruz, Bolivia
    17919.0, // observed in Airframes.io feed; San Francisco, California / Molokai, Hawaii / Riverhead, New York / Barrow, Alaska / Agana, Guam / New York (ACARS Online older table)
    17922.0, // Johannesburg, South Africa
    17928.0, // observed in Airframes.io feed; Hat Yai, Thailand / Canarias, Spain / Hat Yai (ACARS Online older table)
    17934.0, // Barrow, Alaska
    17936.0, // Hawaii (ACARS Online older table)
    17958.0, // observed in Airframes.io feed; Muan, South Korea
    17967.0, // Al Muharraq, Bahrain / Bahrain (ACARS Online older table)
    17985.0, // Reykjavik, Iceland
    21928.0, // Barrow, Alaska / Agana, Guam
    21931.0, // observed in Airframes.io feed; Riverhead, New York / Muan, South Korea
    21934.0, // observed in Airframes.io feed; San Francisco, California / New York (ACARS Online older table)
    21937.0, // observed in Airframes.io feed; Molokai, Hawaii / Barrow, Alaska
    21949.0, // observed in Airframes.io feed; Hat Yai, Thailand / Johannesburg, South Africa / Johannesburg (ACARS Online older table)
    21955.0, // observed in Airframes.io feed; Canarias, Spain
    21982.0, // Al Muharraq, Bahrain / Bahrain (ACARS Online older table)
    21990.0, // Krasnoyarsk, Russia
    21997.0, // observed in Airframes.io feed; Santa Cruz, Bolivia / Bolivia (ACARS Online older table)
];

/// Supported raw I/Q sample formats for HFDL file and stream input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub(crate) enum SampleFormat {
    /// Unsigned interleaved 8-bit complex samples.
    U8,
    /// Signed interleaved 16-bit complex samples.
    Cs16,
    /// Interleaved 32-bit floating-point complex samples.
    Cf32,
    /// 16-bit stereo WAV I/Q file (auto-selected for .wav sources when --format is omitted).
    Wav16,
}

impl SampleFormat {
    fn bytes_per_complex(self) -> usize {
        match self {
            Self::U8 => 2,
            Self::Cs16 => 4,
            Self::Cf32 => 8,
            Self::Wav16 => 4,
        }
    }
}

/// Command-line options for the standalone `datalink hfdl` frontend.
#[derive(Debug, Parser)]
#[command(about = "HF Data Link frontend for WAV and I/Q captures")]
pub(crate) struct Options {
    /// WAV, I/Q, or SDR source, e.g. file://capture.wav, rtlsdr://0, hackrf://0, or ~/capture.raw.
    source: Option<Source>,

    /// I/Q sample format
    #[arg(long, value_enum, default_value_t = SampleFormat::Cf32)]
    format: SampleFormat,

    /// Recording center frequency in Hz
    #[arg(long, default_value_t = 10_000_000)]
    center_freq: u32,

    /// Recording sample rate in samples/s
    #[arg(long, default_value_t = 8_000_000)]
    sample_rate: u32,

    /// HFDL channel frequencies, in Hz or kHz. Defaults to known channels within the recording bandwidth.
    #[arg(long, num_args = 1..)]
    channel: Option<Vec<f64>>,

    /// Start offset in seconds for file decoding
    #[arg(long, default_value_t = 0.0)]
    start_second: f64,

    /// Maximum seconds to decode from the file
    #[arg(long, default_value_t = 20.0)]
    max_seconds: f64,

    /// Print demod/decode counters to stderr at end
    #[arg(long)]
    stats: bool,

    /// Publish decoded PDUs to application-specific Redis pub/sub topics
    #[arg(long, value_name = "REDIS URL")]
    redis_url: Option<String>,

    /// Retry interval (seconds) when publishing to Redis fails; 0 disables retry
    #[arg(long)]
    redis_retry_interval: Option<u64>,
}

/// Run the standalone HFDL frontend.
pub(crate) async fn run(options: Options) -> anyhow::Result<()> {
    decode_mode(&options).await
}

/// Decode HFDL PDUs from a file source and collect common decoded events for merged mode.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn decode_file_values(
    source: &str,
    format: Option<&str>,
    center_freq: Option<u32>,
    sample_rate: Option<u32>,
    channels: Option<&[u32]>,
    start_second: f64,
    max_seconds: f64,
    source_meta: &SourceMetadata,
    receiver_bearer: Bearer,
) -> anyhow::Result<Vec<DecodedEvent>> {
    let options = Options {
        source: Some(source.parse()?),
        format: format
            .and_then(parse_sample_format)
            .unwrap_or(SampleFormat::Cf32),
        center_freq: center_freq.unwrap_or(10_000_000),
        sample_rate: sample_rate.unwrap_or(8_000_000),
        channel: channels.map(|v| v.iter().map(|&hz| hz as f64).collect()),
        start_second,
        max_seconds,
        stats: false,
        redis_url: None,
        redis_retry_interval: None,
    };

    let mut out = Vec::new();
    for parsed in collect_decoded_pdus(&options, source_meta, receiver_bearer).await? {
        out.push(parsed);
    }
    Ok(out)
}

fn parse_sample_format(value: &str) -> Option<SampleFormat> {
    match value.to_ascii_lowercase().as_str() {
        "u8" | "cu8" => Some(SampleFormat::U8),
        "cs16" => Some(SampleFormat::Cs16),
        "cf32" => Some(SampleFormat::Cf32),
        "wav16" | "wav" => Some(SampleFormat::Wav16),
        _ => None,
    }
}

async fn decode_mode(options: &Options) -> anyhow::Result<()> {
    let mut redis = if let Some(url) = options.redis_url.as_deref() {
        Some(
            RedisPublisher::connect_with_prefix(
                url,
                options.redis_retry_interval.unwrap_or(5),
                "datalink hfdl",
            )
            .await?,
        )
    } else {
        None
    };

    let source_meta = SourceMetadata {
        id: "hfdl_cli".into(),
        name: options
            .source
            .as_ref()
            .map(|s| s.label())
            .unwrap_or_else(|| "hfdl".into()),
        class: SourceClass::Iq,
        format: None,
    };

    for parsed in collect_decoded_pdus(options, &source_meta, Bearer::Hfdl).await? {
        let line = serde_json::to_string(&parsed)?;
        println!("{line}");
        if let Some(redis) = redis.as_mut() {
            redis
                .publish(redis_topic_for_record(&parsed.message), &line)
                .await;
        }
    }
    Ok(())
}

/// Run HFDL diagnostics over the configured source and collect CRC-valid parsed PDUs.
async fn collect_decoded_pdus(
    options: &Options,
    source_meta: &SourceMetadata,
    receiver_bearer: Bearer,
) -> anyhow::Result<Vec<DecodedEvent>> {
    let source = options
        .source
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("missing source; pass an explicit I/Q or SDR source"))?;
    let (samples, sample_rate, center_freq, channels) = samples_for_source(source, options).await?;
    anyhow::ensure!(
        !channels.is_empty(),
        "no HFDL channels selected; pass --channel or use a wider/centered recording"
    );
    let mut pdu_ok = 0u64;
    let mut candidate_count = 0u64;
    let mut frame_sync_count = 0u64;
    let mut out = Vec::new();
    for &channel_khz in &channels {
        let diagnostics = diagnose_channel(
            &samples,
            &HfdlDemodConfig {
                input_sample_rate: sample_rate,
                center_freq_hz: center_freq as f64,
                channel_khz,
                use_symbol_sync: true,
            },
        )?;
        frame_sync_count += diagnostics.frame_hits.len() as u64;
        candidate_count += diagnostics.pdu_candidates.len() as u64;
        for candidate in &diagnostics.pdu_candidates {
            let Ok(parsed) = parse_hfdl_pdu(&candidate.bytes) else {
                continue;
            };
            if parsed.fcs == FcsResult::Pass {
                continue;
            }
            pdu_ok += 1;
            let pmsg = ProtocolMessage::Hfdl(Box::new(parsed));

            let event = DecodedEvent {
                event: "message".to_string(),
                timestamp: None,
                bearer: receiver_bearer,
                source: source_meta.clone(),
                receiver: Some(ReceiverMetadata {
                    bearer: receiver_bearer,
                    channel_hz: Some((channel_khz * 1000.0).round() as u32),
                }),
                aircraft: crate::merged::aircraft_summary(&pmsg),
                kinematics: pmsg.kinematics(),
                raw_frame_hex: Some(hex::encode_upper(&candidate.bytes)),
                message: pmsg,
            };
            out.push(event);
        }
    }
    if options.stats {
        eprintln!(
            "datalink hfdl stats: channels={} frame_sync={} candidates={} pdu_ok={}",
            channels.len(),
            frame_sync_count,
            candidate_count,
            pdu_ok
        );
    }
    Ok(out)
}

async fn samples_for_source(
    source: &Source,
    options: &Options,
) -> anyhow::Result<(Vec<Complex<f32>>, u32, u32, Vec<f64>)> {
    let mut effective_source = source.clone();
    if effective_source.center_freq.is_none() {
        effective_source.center_freq = Some(options.center_freq);
    }
    if effective_source.sample_rate.is_none() {
        effective_source.sample_rate = Some(options.sample_rate);
    }
    let sample_rate = effective_source.sample_rate.unwrap_or(options.sample_rate);
    let center_freq = effective_source.center_freq.unwrap_or(options.center_freq);
    let configured_channels = options.channel.clone().or_else(|| {
        effective_source
            .channels
            .clone()
            .map(|channels| channels.into_iter().map(|hz| hz as f64).collect())
    });
    let channels = channels_khz_for(configured_channels.as_deref(), sample_rate, center_freq);

    let samples = match &effective_source.address {
        Address::File { file } => {
            let path = expanduser(file.strip_prefix("file://").unwrap_or(file));
            let path = path.to_string_lossy();
            let inferred = infer_capture_params(&path);
            let requested_format = effective_source
                .format
                .as_deref()
                .and_then(parse_sample_format)
                .unwrap_or(options.format);
            let format = effective_format(&path, requested_format);
            let sample_rate = effective_sample_rate(
                &path,
                format,
                inferred
                    .and_then(|params| params.sample_rate)
                    .unwrap_or(sample_rate),
            )?;
            let center_freq = inferred
                .map(|params| params.center_freq)
                .unwrap_or_else(|| effective_center_freq(&path, format, center_freq));
            let channels =
                channels_khz_for(configured_channels.as_deref(), sample_rate, center_freq);
            let samples = read_complex_window(
                &path,
                format,
                sample_rate,
                options.start_second,
                options.max_seconds,
            )?;
            return Ok((samples, sample_rate, center_freq, channels));
        }
        _ => read_sdr_window(&effective_source, options.start_second, options.max_seconds).await?,
    };

    Ok((samples, sample_rate, center_freq, channels))
}

async fn read_sdr_window(
    source: &Source,
    start_second: f64,
    max_seconds: f64,
) -> anyhow::Result<Vec<Complex<f32>>> {
    let sample_rate = source.sample_rate.unwrap_or(8_000_000);
    let skip = (start_second.max(0.0) * sample_rate as f64).round() as usize;
    let keep = (max_seconds.max(0.0) * sample_rate as f64).ceil() as usize;
    let mut stream = open_source(source).await?;
    let mut seen = 0usize;
    let mut out = Vec::with_capacity(keep);
    while out.len() < keep {
        let Some(chunk_result) = stream.next().await else {
            break;
        };
        let chunk = chunk_result?;
        for sample in chunk {
            if seen >= skip && out.len() < keep {
                out.push(Complex::new(sample.re, sample.im));
            }
            seen = seen.saturating_add(1);
            if out.len() >= keep {
                break;
            }
        }
    }
    Ok(out)
}

async fn open_source(src: &Source) -> anyhow::Result<desperado::IqAsyncSource> {
    use desperado::{DeviceConfig, IqAsyncSource};

    let center_freq = src.center_freq.unwrap_or(10_000_000);
    let sample_rate = src.sample_rate.unwrap_or(8_000_000);
    match &src.address {
        Address::File { file } if file == "-" => Ok(IqAsyncSource::from_stdin(
            center_freq,
            sample_rate,
            65_536,
            src.iq_format(),
        )),
        Address::File { file } => {
            Ok(
                IqAsyncSource::from_file(file, center_freq, sample_rate, 65_536, src.iq_format())
                    .await?,
            )
        }
        #[cfg(feature = "rtlsdr")]
        Address::Rtlsdr { device, serial } => {
            let selector = if let Some(serial) = serial {
                desperado::rtlsdr::DeviceSelector::Filter {
                    manufacturer: None,
                    product: None,
                    serial: Some(serial.clone()),
                }
            } else {
                desperado::rtlsdr::DeviceSelector::Index(device.unwrap_or(0))
            };
            let cfg = desperado::rtlsdr::RtlSdrConfig {
                device: selector,
                center_freq,
                sample_rate,
                gain: src.gain_or(desperado::Gain::Manual(49.6)),
                bias_tee: src.bias_tee.unwrap_or(false),
                freq_correction_ppm: 0,
            };
            Ok(IqAsyncSource::from_device_config(&DeviceConfig::RtlSdr(cfg)).await?)
        }
        #[cfg(feature = "airspy")]
        Address::Airspy { device, serial } => {
            let selector = if let Some(serial) = serial {
                desperado::airspy::DeviceSelector::Serial(parse_airspy_serial(serial)?)
            } else {
                desperado::airspy::DeviceSelector::Index(device.unwrap_or(0))
            };
            let cfg = desperado::airspy::AirspyConfig {
                device: selector,
                center_freq,
                sample_rate,
                gain: src.gain_or(desperado::Gain::Manual(50.0)),
                bias_tee: src.bias_tee.unwrap_or(false),
                packing: false,
                lna_gain: src.lna_gain.map(|v| v as u8),
                mixer_gain: src.mixer_gain.map(|v| v as u8),
                vga_gain: src.vga_gain.map(|v| v as u8),
                gain_mode: desperado::airspy::AirspyGainMode::Sensitivity,
            };
            Ok(IqAsyncSource::from_device_config(&DeviceConfig::Airspy(cfg)).await?)
        }
        #[cfg(feature = "hackrf")]
        Address::Hackrf { device } => {
            let cfg = desperado::hackrf::HackRfConfig {
                device_index: device.unwrap_or(0),
                center_freq: center_freq as u64,
                sample_rate,
                gain: hackrf_gain(src),
                amp_enable: src.hackrf_amp_enable(),
                bias_tee: src.bias_tee.unwrap_or(false),
            };
            Ok(IqAsyncSource::from_device_config(&DeviceConfig::HackRf(cfg)).await?)
        }
        #[cfg(feature = "soapy")]
        Address::Soapy { soapy } => {
            let cfg = desperado::soapy::SoapyConfig {
                args: soapy.clone(),
                center_freq: center_freq as f64,
                sample_rate: sample_rate as f64,
                channel: 0,
                gain: src.gain_or(desperado::Gain::Manual(49.6)),
                bias_tee: src.bias_tee.unwrap_or(false),
            };
            Ok(IqAsyncSource::from_device_config(&DeviceConfig::Soapy(cfg)).await?)
        }
        #[allow(unreachable_patterns)]
        _ => Err(anyhow::anyhow!("source type is not enabled in this build")),
    }
}

fn read_complex_window(
    path: &str,
    format: SampleFormat,
    sample_rate: u32,
    start_second: f64,
    max_seconds: f64,
) -> anyhow::Result<Vec<Complex<f32>>> {
    if format == SampleFormat::Wav16 {
        return read_wav_complex_window(path, start_second, max_seconds);
    }
    let mut reader = BufReader::new(File::open(path)?);
    seek_to_second(&mut reader, format, sample_rate, start_second)?;
    let count = (sample_rate as f64 * max_seconds).ceil() as usize;
    let mut raw = vec![0u8; count * format.bytes_per_complex()];
    let mut filled = 0usize;
    while filled < raw.len() {
        let n = reader.read(&mut raw[filled..])?;
        if n == 0 {
            break;
        }
        filled += n;
    }
    raw.truncate(filled - (filled % format.bytes_per_complex()));
    let mut out = vec![Complex::new(0.0f32, 0.0f32); raw.len() / format.bytes_per_complex()];
    decode_complex_bytes(format, &raw, &mut out);
    Ok(out)
}

fn read_wav_complex_window(
    path: &str,
    start_second: f64,
    max_seconds: f64,
) -> anyhow::Result<Vec<Complex<f32>>> {
    let mut reader = hound::WavReader::open(path)?;
    let spec = reader.spec();
    anyhow::ensure!(
        spec.channels == 2,
        "HFDL WAV input expects stereo I/Q, got {} channels",
        spec.channels
    );
    anyhow::ensure!(
        spec.sample_format == hound::SampleFormat::Int && spec.bits_per_sample == 16,
        "HFDL WAV input currently supports 16-bit PCM stereo only"
    );
    let start_frames = (start_second * spec.sample_rate as f64).round() as usize;
    let max_frames = (max_seconds * spec.sample_rate as f64).ceil() as usize;
    let mut samples = reader.samples::<i16>();
    for _ in 0..start_frames.saturating_mul(2) {
        if samples.next().is_none() {
            return Ok(Vec::new());
        }
    }
    let mut out = Vec::with_capacity(max_frames);
    for _ in 0..max_frames {
        let Some(i) = samples.next() else { break };
        let Some(q) = samples.next() else { break };
        out.push(Complex::new(i? as f32 / 32768.0, q? as f32 / 32768.0));
    }
    Ok(out)
}

fn seek_to_second<R: Seek>(
    reader: &mut R,
    format: SampleFormat,
    sample_rate: u32,
    start_second: f64,
) -> anyhow::Result<()> {
    if start_second <= 0.0 {
        return Ok(());
    }
    let byte_offset =
        (start_second * sample_rate as f64).round() as u64 * format.bytes_per_complex() as u64;
    reader.seek(SeekFrom::Start(byte_offset))?;
    Ok(())
}

fn decode_complex_bytes(format: SampleFormat, raw: &[u8], out: &mut [Complex<f32>]) {
    match format {
        SampleFormat::U8 => {
            for (idx, chunk) in raw.chunks_exact(2).enumerate() {
                out[idx].re = (chunk[0] as f32 - 127.5) / 128.0;
                out[idx].im = (chunk[1] as f32 - 127.5) / 128.0;
            }
        }
        SampleFormat::Cs16 => {
            for (idx, chunk) in raw.chunks_exact(4).enumerate() {
                let i = i16::from_le_bytes([chunk[0], chunk[1]]) as f32 / 32768.0;
                let q = i16::from_le_bytes([chunk[2], chunk[3]]) as f32 / 32768.0;
                out[idx].re = i;
                out[idx].im = q;
            }
        }
        SampleFormat::Wav16 => unreachable!("WAV samples are decoded by read_wav_complex_window"),
        SampleFormat::Cf32 => {
            for (idx, chunk) in raw.chunks_exact(8).enumerate() {
                out[idx].re = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
                out[idx].im = f32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
            }
        }
    }
}

/// Resolve requested channels or derive default HFDL channels within the source bandwidth.
fn channels_khz_for(
    configured_channels: Option<&[f64]>,
    sample_rate: u32,
    center_freq: u32,
) -> Vec<f64> {
    if let Some(channels) = configured_channels {
        channels.iter().copied().map(to_khz).collect()
    } else {
        auto_channels_khz(sample_rate, center_freq).collect()
    }
}

fn auto_channels_khz(sample_rate: u32, center_freq: u32) -> impl Iterator<Item = f64> {
    let center_khz = center_freq as f64 / 1000.0;
    let usable_half_bw_khz = sample_rate as f64 * 0.40 / 1000.0;
    let lo = center_khz - usable_half_bw_khz;
    let hi = center_khz + usable_half_bw_khz;
    KNOWN_HFDL_CHANNELS_KHZ
        .iter()
        .copied()
        .filter(move |freq| *freq >= lo && *freq <= hi)
}

fn to_khz(freq: f64) -> f64 {
    if freq > 100_000.0 {
        freq / 1000.0
    } else {
        freq
    }
}

fn effective_format(path: &str, requested: SampleFormat) -> SampleFormat {
    if requested == SampleFormat::Cf32 && path.to_ascii_lowercase().ends_with(".wav") {
        SampleFormat::Wav16
    } else {
        requested
    }
}

fn effective_center_freq(path: &str, format: SampleFormat, requested: u32) -> u32 {
    if format == SampleFormat::Wav16 && requested == 10_000_000 {
        if let Some(params) = infer_capture_params(path) {
            return params.center_freq;
        }
    }
    requested
}

fn effective_sample_rate(path: &str, format: SampleFormat, requested: u32) -> anyhow::Result<u32> {
    if format == SampleFormat::Wav16 {
        let reader = hound::WavReader::open(path)?;
        Ok(reader.spec().sample_rate)
    } else {
        Ok(requested)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use acars::decode::hfdl::Mpdu;

    fn hfdl_fcs(data: &[u8]) -> u16 {
        crc16_ccitt_reflected(data, 0xffff) ^ 0xffff
    }

    fn crc16_ccitt_reflected(data: &[u8], init: u16) -> u16 {
        let mut crc = init;
        for &byte in data {
            crc ^= byte as u16;
            for _ in 0..8 {
                if crc & 1 != 0 {
                    crc = (crc >> 1) ^ 0x8408;
                } else {
                    crc >>= 1;
                }
            }
        }
        crc
    }

    #[test]
    fn crc_check_accepts_constructed_spdu() {
        let mut pdu = vec![0u8; 66];
        pdu[0] = 0x00;
        pdu[1] = 12;
        let fcs = crc16_ccitt_reflected(&pdu[..64], 0xffff) ^ 0xffff;
        pdu[64..66].copy_from_slice(&fcs.to_le_bytes());
        let parsed = parse_hfdl_pdu(&pdu).unwrap();
        assert!(matches!(parsed.pdu, acars::decode::hfdl::HfdlPdu::Spdu(_)));
        assert!(parsed.fcs == FcsResult::Pass);
    }

    #[test]
    fn parse_downlink_mpdu_extracts_hfnpdu_payload() {
        let hfnpdu = [0xff, 0xd2, 0x34, 0x12];
        let mut lpdu = vec![0x0d];
        lpdu.extend_from_slice(&hfnpdu);
        let lpdu_fcs = hfdl_fcs(&lpdu);
        lpdu.extend_from_slice(&lpdu_fcs.to_le_bytes());

        let lpdu_len = lpdu.len();
        let mut pdu = vec![0x07, 0x8c, 0x2a, 0, 0, 0, (lpdu_len - 1) as u8];
        let hdr_fcs = hfdl_fcs(&pdu);
        pdu.extend_from_slice(&hdr_fcs.to_le_bytes());
        pdu.extend_from_slice(&lpdu);

        let parsed = parse_hfdl_pdu(&pdu).unwrap();
        let acars::decode::hfdl::HfdlPdu::Mpdu(Mpdu::Downlink(dl)) = parsed.pdu else {
            panic!()
        };
        assert!(parsed.fcs == FcsResult::Pass);
        assert!(dl.lpdus[0].fcs == FcsResult::Pass);
        if let acars::decode::hfdl::LpduData::Hfnpdu { hfnpdu, .. } = &dl.lpdus[0].data {
            if let acars::decode::hfdl::Hfnpdu::SystemTableRequest { request_data, .. } =
                &hfnpdu.data
            {
                assert_eq!(*request_data, 0x1234);
            } else {
                panic!("expected SystemTableRequest");
            }
        } else {
            panic!("expected Hfnpdu LPDU type");
        }
    }

    #[test]
    fn parse_uplink_mpdu_uses_high_nibble_lpdu_count() {
        let mut lpdu = vec![0x1d, 0xff, 0xff, 0x01, 0x02, 0x03];
        let lpdu_fcs = hfdl_fcs(&lpdu);
        lpdu.extend_from_slice(&lpdu_fcs.to_le_bytes());

        let mut pdu = vec![0x01, 0x8c, 0x2a, 0x10, (lpdu.len() - 1) as u8];
        let hdr_fcs = hfdl_fcs(&pdu);
        pdu.extend_from_slice(&hdr_fcs.to_le_bytes());
        pdu.extend_from_slice(&lpdu);

        let parsed = parse_hfdl_pdu(&pdu).unwrap();
        assert!(parsed.fcs == FcsResult::Pass);
        let acars::decode::hfdl::HfdlPdu::Mpdu(Mpdu::Uplink(ul)) = parsed.pdu else {
            panic!()
        };
        assert_eq!(ul.aircraft[0].lpdu_count, 1);
        if let acars::decode::hfdl::LpduData::Hfnpdu { hfnpdu, .. } = &ul.aircraft[0].lpdus[0].data
        {
            if let acars::decode::hfdl::Hfnpdu::Unknown { raw_hex, .. } = &hfnpdu.data {
                assert_eq!(hfnpdu.kind_code, "0xFF");
                assert_eq!(raw_hex, "010203");
            } else {
                panic!("expected Hfnpdu::Unknown (due to invalid acars frame)");
            }
        } else {
            panic!("expected Hfnpdu LPDU type");
        }
    }

    #[test]
    fn auto_channels_cover_10mhz_capture() {
        let options = Options {
            source: Some("dummy".parse().unwrap()),
            format: SampleFormat::Cf32,
            center_freq: 10_000_000,
            sample_rate: 8_000_000,
            channel: None,
            start_second: 0.0,
            max_seconds: 1.0,
            stats: false,
            redis_url: None,
            redis_retry_interval: None,
        };
        let channels = channels_khz_for(
            options.channel.as_deref(),
            options.sample_rate,
            options.center_freq,
        );
        assert!(channels.contains(&10081.0));
        assert!(channels.contains(&11387.0));
        assert!(!channels.contains(&6529.0));
    }

    #[test]
    fn gqrx_inferred_params_cover_hfdl_channels() {
        let params = infer_capture_params("gqrx_20260518_114025_10000000_8000000_fc.raw").unwrap();
        let channels = channels_khz_for(None, params.sample_rate.unwrap(), params.center_freq);
        assert_eq!(params.format, Some("cf32"));
        assert!(channels.contains(&10081.0));
        assert!(channels.contains(&11387.0));
        assert!(!channels.contains(&6529.0));
    }
}