orion-sdr 0.0.65

Composable SDR/DSP block library targeting HF-to-EHF: analog and single-carrier digital modes, FT8/FT4, PSK31, OFDM/COFDM, and DVB-T/NB-DVB-T, with Python bindings.
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
// Copyright (c) 2026 G & R Associates LLC
// SPDX-License-Identifier: MIT OR Apache-2.0

// src/modulate/ofdm_frame.rs
//
// The OFDM frame (MAC-layer) modulator: turns a `FramePacket` into a flat
// stream of time-domain IQ, applying the concatenated COFDM coding chain and
// prepending the acquisition preamble + a fixed, MCS-independent header.
//
// On-air layout (transmit order):
//   [ S&C preamble + training symbol ][ header symbols ][ payload symbols ]
//
// The header is coded with a fixed built-in scheme (BPSK + rate-1/2 LDPC, no
// interleaver, no scrambler) so the receiver can always decode it before it
// knows the payload MCS. Its byte layout is `HEADER_FIELD_BYTES` of fields
// followed by the configured `header_crc`. The payload is coded per the MCS
// selected by `metadata.mcs_index` (constellation + inner/outer FEC from the
// MCS table) plus the link-wide interleavers/scrambler/`payload_crc` from
// `OfdmConfig`.
//
// This module owns the shared bit-domain coding chain (`encode_chain`,
// `pack_*`) that the frame demodulator inverts; the demodulator imports these
// so the two are exact mirrors.

use super::ofdm::{ConstellationOrder, OfdmConfig, OfdmMod};
use crate::codec::{crc16, crc32};
use crate::core::Block;
use crate::fec::{
    Bch, CrcKind, FramePacket, InnerFec, InterleaverKind, Ldpc, LdpcCode, OuterFec, PnScrambler,
    ReedSolomon, ScramblerKind, ScramblerPos, SeedMode, conv_encode_punctured_with,
    punctured_coded_len_with,
};
use crate::multicarrier::{CarrierPlan, SymbolWindow};
use crate::sync::{OfdmPreamble, generate_ofdm_preamble};
use num_complex::Complex32 as C32;
use std::sync::{Arc, Mutex};

/// Memoizes the constructed FEC code objects a link reuses frame after frame.
///
/// Constructing a code — especially [`Ldpc::new`], whose sparse parity-check
/// build with its 4-cycle guard costs milliseconds — is a pure function of the
/// code's parameters, so the object is identical every frame. Without this the
/// concatenated-FEC chain rebuilt its `Ldpc`/`Bch`/`ReedSolomon` on *every*
/// frame (encode and decode); the cache builds each once per link and hands out
/// shared references thereafter.
///
/// The key spaces are tiny (a link uses one header LDPC plus the handful of
/// codes in its MCS table), so linear-scan association lists beat a hash map
/// here. A `Mutex` gives lazy population behind the `&self` encode/decode entry
/// points; the cached objects are handed out as `Arc`s so callers hold them
/// without keeping the lock across the (potentially long) encode/decode call.
///
/// `Send + Sync` (via `Arc`/`Mutex`) so it can live inside an `OfdmFrameMod` /
/// `OfdmFrameStreamDemod` exposed to the PyO3 bindings, which require their
/// pyclasses to be thread-safe. Access is a handful of uncontended lookups per
/// frame, so the lock is effectively free. The produced codes are bit-identical
/// to freshly constructed ones — this changes speed, never output.
///
/// A tiny memo map keyed by `K`, holding shared code objects `V`.
type CodeMemo<K, V> = Mutex<Vec<(K, Arc<V>)>>;

#[derive(Debug, Default)]
pub struct CodecCache {
    ldpc: CodeMemo<LdpcCode, Ldpc>,
    /// Shortened-BCH keyed by `(t, msg_bits)`.
    bch: CodeMemo<(usize, usize), Bch>,
    /// Reed–Solomon keyed by `(n, n_parity)`.
    rs: CodeMemo<(usize, usize), ReedSolomon>,
}

impl Clone for CodecCache {
    /// A cloned cache starts empty rather than copying entries — cache contents
    /// are pure derivations of the codes used, rebuilt on demand, and this keeps
    /// `Clone` free of a lock acquisition. (Only `OfdmFrameMod` derives `Clone`;
    /// it is not exercised on a hot path.)
    fn clone(&self) -> Self {
        Self::default()
    }
}

impl CodecCache {
    /// A fresh, empty cache.
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the [`Ldpc`] for `code`, building and caching it on first use.
    pub fn ldpc(&self, code: LdpcCode) -> Arc<Ldpc> {
        let mut table = self.ldpc.lock().unwrap();
        if let Some((_, c)) = table.iter().find(|(k, _)| *k == code) {
            return Arc::clone(c);
        }
        let built = Arc::new(Ldpc::new(code));
        table.push((code, Arc::clone(&built)));
        built
    }

    /// Returns the shortened [`Bch`] correcting `t` errors with a `msg_bits`
    /// message part, building and caching it on first use.
    pub fn bch(&self, t: usize, msg_bits: usize) -> Arc<Bch> {
        let key = (t, msg_bits);
        let mut table = self.bch.lock().unwrap();
        if let Some((_, c)) = table.iter().find(|(k, _)| *k == key) {
            return Arc::clone(c);
        }
        let built = Arc::new(shortened_bch_for(t, msg_bits));
        table.push((key, Arc::clone(&built)));
        built
    }

    /// Returns the [`ReedSolomon`] code `(n, n_parity)`, building and caching it
    /// on first use.
    pub fn rs(&self, n: usize, n_parity: usize) -> Arc<ReedSolomon> {
        let key = (n, n_parity);
        let mut table = self.rs.lock().unwrap();
        if let Some((_, c)) = table.iter().find(|(k, _)| *k == key) {
            return Arc::clone(c);
        }
        let built = Arc::new(ReedSolomon::new(n, n_parity).expect("valid RS config"));
        table.push((key, Arc::clone(&built)));
        built
    }
}

/// Number of header field bytes before the header CRC: `mcs_index` (1) +
/// `payload_len` (4, big-endian) + `sequence_num` (4) + `flags` (1) +
/// `scrambler_seed` (4) = 14 bytes.
pub const HEADER_FIELD_BYTES: usize = 14;

/// The fixed constellation used for header symbols (most robust).
pub const HEADER_CONSTELLATION: ConstellationOrder = ConstellationOrder::Bpsk;

/// The fixed inner code protecting the header — a rate-1/2 LDPC, independent of
/// the payload MCS.
pub const HEADER_LDPC: LdpcCode = LdpcCode::N512R12;

/// A modulation-and-coding scheme: the payload's constellation plus its inner
/// and outer FEC. Selected per-frame by `FrameMetadata::mcs_index` via an
/// [`McsTable`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Mcs {
    pub constellation: ConstellationOrder,
    pub inner_fec: InnerFec,
    pub outer_fec: OuterFec,
}

impl Mcs {
    pub const fn new(
        constellation: ConstellationOrder,
        inner_fec: InnerFec,
        outer_fec: OuterFec,
    ) -> Self {
        Self {
            constellation,
            inner_fec,
            outer_fec,
        }
    }
}

/// Maps an 8-bit `mcs_index` to an [`Mcs`]. The sender and receiver must share
/// the same table.
#[derive(Debug, Clone)]
pub struct McsTable {
    entries: Vec<Mcs>,
}

impl McsTable {
    pub fn new(entries: Vec<Mcs>) -> Self {
        assert!(
            !entries.is_empty(),
            "MCS table must have at least one entry"
        );
        Self { entries }
    }

    /// A small default ladder: increasing constellation order, all with a
    /// rate-1/2 LDPC inner code and a BCH(t=8) outer code — the concatenated
    /// COFDM baseline.
    pub fn default_ladder() -> Self {
        let inner = InnerFec::Ldpc(LdpcCode::N512R12);
        let outer = OuterFec::Bch { t: 8 };
        Self::new(vec![
            Mcs::new(ConstellationOrder::Bpsk, inner, outer),
            Mcs::new(ConstellationOrder::Qpsk, inner, outer),
            Mcs::new(ConstellationOrder::Qam16, inner, outer),
            Mcs::new(ConstellationOrder::Qam64, inner, outer),
        ])
    }

    pub fn get(&self, mcs_index: u8) -> Option<Mcs> {
        self.entries.get(mcs_index as usize).copied()
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

// ── Shared bit/byte helpers ────────────────────────────────────────────────

/// Unpacks bytes into a bit vector, MSB-first per byte.
pub fn bytes_to_bits(bytes: &[u8]) -> Vec<u8> {
    let mut bits = Vec::with_capacity(bytes.len() * 8);
    for &b in bytes {
        for i in (0..8).rev() {
            bits.push((b >> i) & 1);
        }
    }
    bits
}

/// Packs a bit slice (MSB-first per byte) back into bytes. The bit count must
/// be a multiple of 8.
pub fn bits_to_bytes(bits: &[u8]) -> Vec<u8> {
    assert_eq!(
        bits.len() % 8,
        0,
        "bit count must be a whole number of bytes"
    );
    let mut bytes = Vec::with_capacity(bits.len() / 8);
    for chunk in bits.chunks(8) {
        let mut b = 0u8;
        for &bit in chunk {
            b = (b << 1) | (bit & 1);
        }
        bytes.push(b);
    }
    bytes
}

/// Appends the selected CRC (over `data`) to `data`, big-endian.
pub fn append_crc(crc: CrcKind, data: &[u8]) -> Vec<u8> {
    let mut out = data.to_vec();
    match crc {
        CrcKind::None => {}
        CrcKind::Crc16 => out.extend_from_slice(&crc16(data).to_be_bytes()),
        CrcKind::Crc32 => out.extend_from_slice(&crc32(data).to_be_bytes()),
    }
    out
}

/// Splits `data` into (payload, crc-ok). Returns `None` if `data` is too short
/// to hold the CRC field. With [`CrcKind::None`] the check is vacuously true.
pub fn check_and_strip_crc(crc: CrcKind, data: &[u8]) -> Option<(Vec<u8>, bool)> {
    let clen = crc.len_bytes();
    if data.len() < clen {
        return None;
    }
    let (payload, tail) = data.split_at(data.len() - clen);
    let ok = match crc {
        CrcKind::None => true,
        CrcKind::Crc16 => crc16(payload).to_be_bytes()[..] == *tail,
        CrcKind::Crc32 => crc32(payload).to_be_bytes()[..] == *tail,
    };
    Some((payload.to_vec(), ok))
}

/// Builds a [`PnScrambler`] from a [`ScramblerKind`] and an explicit seed value
/// (for `PerFrameRandom`, the caller supplies the drawn seed). Returns `None`
/// for [`ScramblerKind::None`].
pub fn build_scrambler(kind: ScramblerKind, per_frame_seed: u32) -> Option<PnScrambler> {
    match kind {
        // `None` and DVB-T energy dispersal produce no generic `PnScrambler`:
        // DVB-T's whitener is a distinct byte-domain routine applied separately
        // (see `scramble_bytes`), not a parameterized additive LFSR.
        ScramblerKind::None | ScramblerKind::DvbTEnergyDispersal => None,
        ScramblerKind::Additive { poly, width, seed } => {
            let raw = match seed {
                SeedMode::Fixed(v) => v,
                SeedMode::PerFrameRandom => per_frame_seed,
            };
            // Reduce the seed into the register width, and avoid the all-zero
            // fixed point (an all-zero additive LFSR never advances). The
            // receiver derives the same value from the header field, so this
            // reduction must be deterministic.
            let mask = if width >= 32 {
                u32::MAX
            } else {
                (1u32 << width) - 1
            };
            let s = {
                let m = raw & mask;
                if m == 0 { 1 } else { m }
            };
            Some(PnScrambler::new(poly, width as u32, s))
        }
    }
}

/// Applies the byte-domain whitener for `kind` to `bytes` in place (self-inverse,
/// so the same call scrambles and descrambles). Handles both the generic
/// `Additive` LFSR and DVB-T energy dispersal; a no-op for `None`. The
/// after-inner-FEC bit-domain scramble position uses the `PnScrambler` directly
/// (DVB-T energy dispersal is byte-domain / before-FEC only).
pub fn scramble_bytes(kind: ScramblerKind, per_frame_seed: u32, bytes: &mut [u8]) {
    match kind {
        ScramblerKind::None => {}
        ScramblerKind::DvbTEnergyDispersal => {
            crate::waveform::dvb_t::DvbTEnergyDispersal::new().feed_in_place(bytes);
        }
        ScramblerKind::Additive { .. } => {
            if let Some(s) = build_scrambler(kind, per_frame_seed) {
                s.scramble(bytes);
            }
        }
    }
}

// ── Block-size bookkeeping (shared TX/RX) ──────────────────────────────────

/// Deterministic size accounting for one logical block's coding chain, so the
/// transmitter and receiver agree on every intermediate length (needed to trim
/// interleaver/fragmentation zero-padding on receive) and on how many OFDM
/// symbols the coded bits occupy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlockPlan {
    /// Raw payload/field byte count (before CRC).
    pub info_bytes: usize,
    /// Bytes after appending the CRC.
    pub framed_bytes: usize,
    /// Bits after the outer code (before outer interleave).
    pub outer_coded_bits: usize,
    /// Bits after outer interleave.
    pub outer_il_bits: usize,
    /// Bits after the inner code (before inner interleave).
    pub inner_coded_bits: usize,
    /// Final coded-bit count (after inner interleave) = symbols · bits/symbol.
    pub coded_bits: usize,
}

/// Rounds `n` up to a whole number of `block`-sized units (identity if
/// `block == 0`).
fn round_up(n: usize, block: usize) -> usize {
    if block == 0 {
        n
    } else {
        n.div_ceil(block) * block
    }
}

/// Bit count after the frame-mode streaming Forney interleaver: pack `n_bits`
/// to whole bytes, round the byte count up to a multiple of `branches` (the
/// feed alignment), add the round-trip delay `branches·(branches−1)·depth`
/// (the flush drain), then back to bits. Mirrors the length growth in
/// [`interleave_bits`]'s `Convolutional` arm so the deinterleaver sees the exact
/// length and can trim the delay offset.
fn conv_il_bits(n_bits: usize, branches: usize, depth: usize) -> usize {
    let bytes =
        round_up(n_bits.div_ceil(8), branches) + crate::fec::conv_roundtrip_delay(branches, depth);
    bytes * 8
}

/// Computes the [`BlockPlan`] for `info_bytes` under the given coding chain,
/// reusing constructed code objects from `cache` (their dimensions are all this
/// needs, but sharing the cache avoids rebuilding them here and in the
/// encode/decode passes).
pub fn block_plan(
    info_bytes: usize,
    crc: CrcKind,
    outer: OuterFec,
    inner: InnerFec,
    outer_il: InterleaverKind,
    inner_il: InterleaverKind,
    cache: &CodecCache,
) -> BlockPlan {
    let framed_bytes = info_bytes + crc.len_bytes();
    let framed_bits = framed_bytes * 8;

    let outer_coded_bits = match outer {
        OuterFec::None => framed_bits,
        OuterFec::Bch { t } => {
            let code = cache.bch(t, BCH_INFO_BITS);
            let n_blocks = framed_bits.div_ceil(BCH_INFO_BITS);
            n_blocks * code.n()
        }
        OuterFec::ReedSolomon { n, n_parity } => {
            // Byte-domain: whole k-byte info blocks → n-byte codewords.
            let rs = cache.rs(n, n_parity);
            let n_blocks = framed_bytes.div_ceil(rs.k());
            n_blocks * rs.n() * 8
        }
    };

    let outer_il_bits = match outer_il {
        InterleaverKind::None => outer_coded_bits,
        InterleaverKind::Block { rows, cols } => round_up(outer_coded_bits, rows * cols),
        InterleaverKind::Convolutional { branches, depth } => {
            conv_il_bits(outer_coded_bits, branches, depth)
        }
    };

    let inner_coded_bits = match inner {
        InnerFec::None => outer_il_bits,
        InnerFec::Ldpc(code) => {
            // LDPC dimensions come straight off the code point (no construction
            // needed), but touch the cache so the object is warm for encode.
            let ldpc = cache.ldpc(code);
            let n_blocks = outer_il_bits.div_ceil(ldpc.k());
            n_blocks * ldpc.n()
        }
        InnerFec::Convolutional { rate, code } => {
            punctured_coded_len_with(code, outer_il_bits, rate)
        }
    };

    let coded_bits = match inner_il {
        InterleaverKind::None => inner_coded_bits,
        InterleaverKind::Block { rows, cols } => round_up(inner_coded_bits, rows * cols),
        InterleaverKind::Convolutional { branches, depth } => {
            conv_il_bits(inner_coded_bits, branches, depth)
        }
    };

    BlockPlan {
        info_bytes,
        framed_bytes,
        outer_coded_bits,
        outer_il_bits,
        inner_coded_bits,
        coded_bits,
    }
}

/// Number of OFDM symbols a logical block occupies for a given constellation
/// over the base plan.
pub fn symbols_for_coded_bits(
    base: &OfdmConfig,
    constellation: ConstellationOrder,
    bits: usize,
) -> usize {
    let bps = base.carrier_plan.data_carriers().len() * constellation.bits_per_symbol();
    bits.div_ceil(bps)
}

// ── Coding chain (encode side) ─────────────────────────────────────────────

/// Applies a block interleaver to `bits` in place-by-value: writes bit `i` of
/// each padded block row-major and reads column-major. Returns the interleaved
/// bits plus the block size used, so the deinterleaver can trim padding.
pub fn interleave_bits(il: InterleaverKind, bits: &[u8]) -> Vec<u8> {
    match il {
        InterleaverKind::None => bits.to_vec(),
        InterleaverKind::Block { rows, cols } => {
            let block = rows * cols;
            let bi = crate::fec::BlockInterleaver::new(rows, cols);
            let mut out = Vec::with_capacity(bits.len().div_ceil(block) * block);
            // Reused across chunks: the interleaver and both scratch buffers are
            // built once instead of per chunk.
            let mut padded = vec![0u8; block];
            let mut permuted = vec![0u8; block];
            for chunk in bits.chunks(block) {
                padded[..chunk.len()].copy_from_slice(chunk);
                padded[chunk.len()..].fill(0);
                bi.interleave(&padded, &mut permuted);
                out.extend_from_slice(&permuted);
            }
            out
        }
        InterleaverKind::Convolutional { branches, depth } => {
            // Byte-domain streaming Forney interleaver, driven in FRAME mode:
            // reset, feed the (byte-packed, `branches`-aligned) payload, then
            // flush the delay lines. The output grows by the round-trip delay
            // `branches·(branches−1)·depth`, which `block_plan`'s `conv_il_bits`
            // mirrors so the deinterleaver knows the length and trims it.
            let mut ci = crate::fec::ConvInterleaver::new(branches, depth);
            let bytes = pack_bits_padded(bits);
            let n = round_up(bytes.len(), branches);
            let mut padded = bytes;
            padded.resize(n, 0);
            let mut out_bytes = ci.feed(&padded);
            out_bytes.extend_from_slice(&ci.flush());
            bytes_to_bits(&out_bytes)
        }
    }
}

/// Fixed information-bit block size for the outer BCH code (per shortened
/// codeword). Chosen so one codeword fits comfortably within GF(2^8)'s length
/// bound (n = k + parity ≤ 255) for the t values used here.
pub const BCH_INFO_BITS: usize = 120;

/// Encodes `message_bytes` through the outer code (byte domain), returning the
/// coded bits (MSB-first). The message bit stream is fragmented into
/// [`BCH_INFO_BITS`]-bit blocks, each encoded into one shortened BCH codeword;
/// the final block is zero-padded. `None` outer code passes the bytes through
/// as bits.
pub fn outer_encode(outer: OuterFec, message_bytes: &[u8], cache: &CodecCache) -> Vec<u8> {
    match outer {
        OuterFec::None => bytes_to_bits(message_bytes),
        OuterFec::Bch { t } => {
            let msg_bits = bytes_to_bits(message_bytes);
            let code = cache.bch(t, BCH_INFO_BITS);
            let mut out = Vec::new();
            for chunk in msg_bits.chunks(BCH_INFO_BITS) {
                let mut block = chunk.to_vec();
                block.resize(BCH_INFO_BITS, 0);
                out.extend_from_slice(&code.encode(&block));
            }
            out
        }
        OuterFec::ReedSolomon { n, n_parity } => {
            // RS is a byte-domain code: fragment into k-byte blocks, encode each
            // into an n-byte codeword (final block zero-padded), then emit bits.
            let rs = cache.rs(n, n_parity);
            let k = rs.k();
            let mut out_bytes = Vec::new();
            for chunk in message_bytes.chunks(k) {
                let mut block = chunk.to_vec();
                block.resize(k, 0);
                out_bytes.extend_from_slice(&rs.encode(&block));
            }
            bytes_to_bits(&out_bytes)
        }
    }
}

/// Encodes `info_bits` through the inner code, returning coded bits. The info
/// bit stream is fragmented into K-bit blocks, each encoded into one N-bit
/// codeword (final block zero-padded). `None` passes through.
pub fn inner_encode(inner: InnerFec, info_bits: &[u8], cache: &CodecCache) -> Vec<u8> {
    match inner {
        InnerFec::None => info_bits.to_vec(),
        InnerFec::Ldpc(code) => {
            let ldpc = cache.ldpc(code);
            let k = ldpc.k();
            let mut out = Vec::new();
            for chunk in info_bits.chunks(k) {
                let mut msg = chunk.to_vec();
                msg.resize(k, 0);
                out.extend_from_slice(&ldpc.encode(&msg));
            }
            out
        }
        // The convolutional code terminates once per block (whole info stream +
        // tail bits), not per fixed-size fragment.
        InnerFec::Convolutional { rate, code } => conv_encode_punctured_with(code, info_bits, rate),
    }
}

/// Constructs a BCH code correcting `t` errors, shortened so its message part
/// holds exactly `msg_bits` information bits.
pub fn shortened_bch_for(t: usize, msg_bits: usize) -> Bch {
    // Parity length is fixed by t; choose n = msg_bits + parity_bits.
    let full = Bch::new(t).expect("valid BCH t");
    let parity = full.parity_bits();
    Bch::shortened(msg_bits + parity, t).expect("valid shortened BCH")
}

/// The intermediate bit-streams the encode chain passes through, kept so a
/// receiver can measure error rates against them.
///
/// Re-encoding a successfully decoded frame reconstructs exactly what the
/// transmitter sent; comparing that against what actually arrived at each
/// stage is what turns a pass/fail flag into a bit error *rate*.
pub struct EncodedStages {
    /// The outer decoder's expected output — what should have arrived at the
    /// inner decoder's *output*, before outer deinterleaving.
    pub outer_il_bits: Vec<u8>,
    /// The fully coded bits as transmitted — what should have arrived at the
    /// inner decoder's *input*.
    pub coded: Vec<u8>,
}

/// [`encode_chain`], keeping the per-stage intermediates instead of only the
/// final coded bits — see [`EncodedStages`].
#[allow(clippy::too_many_arguments)]
pub fn encode_chain_stages(
    bytes: &[u8],
    crc: CrcKind,
    outer: OuterFec,
    inner: InnerFec,
    outer_il: InterleaverKind,
    inner_il: InterleaverKind,
    scrambler: ScramblerKind,
    scrambler_pos: ScramblerPos,
    per_frame_seed: u32,
    cache: &CodecCache,
) -> EncodedStages {
    // 1. CRC over the raw bytes.
    let mut framed = append_crc(crc, bytes);

    // 2. Optional scramble before the outer code (byte domain — handles both the
    //    generic additive LFSR and DVB-T energy dispersal).
    let sc = build_scrambler(scrambler, per_frame_seed);
    if scrambler_pos == ScramblerPos::BeforeOuterFec {
        scramble_bytes(scrambler, per_frame_seed, &mut framed);
    }

    // 3. Outer FEC (byte → coded bits), then outer interleave (byte-domain,
    //    but we operate on bits here for a single generic interleaver).
    let outer_bits = outer_encode(outer, &framed, cache);
    let outer_il_bits = interleave_bits(outer_il, &outer_bits);

    // 4. Inner FEC (bits → coded bits), then inner interleave.
    let inner_bits = inner_encode(inner, &outer_il_bits, cache);
    let mut coded = interleave_bits(inner_il, &inner_bits);

    // 5. Optional scramble after the inner code (bit domain).
    if scrambler_pos == ScramblerPos::AfterInnerFec
        && let Some(ref s) = sc
    {
        // Scramble whole bytes; pad to a byte boundary, scramble, trim.
        scramble_bits(s, &mut coded);
    }

    EncodedStages {
        outer_il_bits,
        coded,
    }
}

/// Runs the full encode chain for one logical block (header or payload):
/// `bytes → CRC → [scramble if before] → outer → outer-interleave → inner →
/// inner-interleave → [scramble if after]`, returning coded bits ready to map.
#[allow(clippy::too_many_arguments)]
pub fn encode_chain(
    bytes: &[u8],
    crc: CrcKind,
    outer: OuterFec,
    inner: InnerFec,
    outer_il: InterleaverKind,
    inner_il: InterleaverKind,
    scrambler: ScramblerKind,
    scrambler_pos: ScramblerPos,
    per_frame_seed: u32,
    cache: &CodecCache,
) -> Vec<u8> {
    encode_chain_stages(
        bytes,
        crc,
        outer,
        inner,
        outer_il,
        inner_il,
        scrambler,
        scrambler_pos,
        per_frame_seed,
        cache,
    )
    .coded
}

/// Scrambles a bit vector by packing to bytes (zero-padded), XORing the PN
/// sequence, and unpacking — used for the after-inner-FEC bit-domain position.
pub fn scramble_bits(s: &PnScrambler, bits: &mut [u8]) {
    let mut bytes = pack_bits_padded(bits);
    s.scramble(&mut bytes);
    let unpacked = bytes_to_bits(&bytes);
    bits.copy_from_slice(&unpacked[..bits.len()]);
}

/// Packs bits to bytes, zero-padding the final partial byte.
fn pack_bits_padded(bits: &[u8]) -> Vec<u8> {
    let mut padded = bits.to_vec();
    let rem = padded.len() % 8;
    if rem != 0 {
        padded.resize(padded.len() + (8 - rem), 0);
    }
    bits_to_bytes(&padded)
}

/// Serializes the 14 header field bytes (before CRC), big-endian.
pub fn pack_header_fields(
    mcs_index: u8,
    payload_len: u32,
    sequence_num: u32,
    flags: u8,
    scrambler_seed: u32,
) -> [u8; HEADER_FIELD_BYTES] {
    let mut out = [0u8; HEADER_FIELD_BYTES];
    out[0] = mcs_index;
    out[1..5].copy_from_slice(&payload_len.to_be_bytes());
    out[5..9].copy_from_slice(&sequence_num.to_be_bytes());
    out[9] = flags;
    out[10..14].copy_from_slice(&scrambler_seed.to_be_bytes());
    out
}

/// Maps coded bits to IQ symbols by running `OfdmMod::modulate` with the given
/// constellation over the shared carrier plan. Zero-pads the final partial
/// OFDM symbol (as `OfdmMod::modulate` does).
fn map_bits_to_iq(base: &OfdmConfig, constellation: ConstellationOrder, bits: &[u8]) -> Vec<C32> {
    let cfg = symbol_config(base, constellation);
    let mut modstage = OfdmMod::new(&cfg);
    modstage.modulate(bits)
}

/// Scattered-pilot variant of [`map_bits_to_iq`] for DVB-T: maps `bits` through
/// the four-phase grid rotation (`mapper`), so each OFDM symbol reserves the
/// phase-appropriate continual/scattered/TPS pilot bins (EN 300 744 §4.5). The
/// `mapper`'s symbol-phase counter carries across calls, so a whole frame's
/// header-then-payload symbols form one continuous rotation (`l = 0` at the
/// first symbol after [`ScatteredPilotMapper::reset`]).
///
/// Mirrors `OfdmMod`'s per-symbol pipeline (map → grid → IFFT → CP → gain) but
/// swaps the static [`GridMap`] for the rotating grid. Baseband only
/// (`rf_hz == 0.0`, which every DVB-T config uses); zero-pads a final partial
/// symbol like `OfdmMod::modulate`.
///
/// Payload symbols on a DVB-T constellation (QPSK/16-QAM/64-QAM) are mapped with
/// the DVB-T-exact Figure-9a mapping (`dvb_t_map_symbol`); a BPSK block (the
/// `OrionSdr` header, not a DVB-T order) falls back to the generic mapper.
fn map_bits_to_iq_scattered(
    base: &OfdmConfig,
    constellation: ConstellationOrder,
    bits: &[u8],
    mapper: &mut crate::waveform::dvb_t::ScatteredPilotMapper,
) -> Vec<C32> {
    use crate::waveform::dvb_t::{dvb_t_map_symbol, is_dvb_t_constellation};

    let n_data = mapper.num_data_carriers();
    let n_fft = mapper.n_fft();
    let cp_len = base.carrier_plan.cp_len();
    let vbits = constellation.bits_per_symbol();
    let bps = n_data * vbits;
    if bps == 0 {
        return Vec::new();
    }
    let n_symbols = bits.len().div_ceil(bps);
    let mut padded = bits.to_vec();
    padded.resize(n_symbols * bps, 0);

    let dvb_t_map = is_dvb_t_constellation(constellation);
    let mut sym_mapper = crate::modulate::ofdm::ideal_symbol_mapper(constellation);
    let mut ifft = crate::multicarrier::IfftBlock::new(n_fft);
    let mut cp_insert = crate::multicarrier::CyclicPrefixInsert::new(n_fft, cp_len);
    let mut symbols = vec![C32::default(); n_data];
    let mut freq = vec![C32::default(); n_fft];
    let mut time = vec![C32::default(); n_fft];
    let sps = n_fft + cp_len;
    let mut out = vec![C32::default(); n_symbols * sps];

    let g = base.gain;
    for s in 0..n_symbols {
        let bit_off = s * bps;
        let sym_bits = &padded[bit_off..bit_off + bps];
        if dvb_t_map {
            // DVB-T Figure-9a constellation, carrier by carrier.
            for (c, chunk) in sym_bits.chunks(vbits).enumerate() {
                symbols[c] = dvb_t_map_symbol(chunk).expect("DVB-T order");
            }
        } else {
            sym_mapper.process(sym_bits, &mut symbols);
        }
        mapper.map_symbol(&symbols, &mut freq);
        ifft.process(&freq, &mut time);
        let cp_out = &mut out[s * sps..(s + 1) * sps];
        cp_insert.process(&time, cp_out);
        if g != 1.0 {
            for v in cp_out.iter_mut() {
                *v = C32::new(g * v.re, g * v.im);
            }
        }
    }
    out
}

/// Builds a bare per-symbol `OfdmConfig` (no frame fields) for a given
/// constellation, sharing the base plan/fs/rf/gain. Used to drive `OfdmMod`
/// for the header (BPSK) and payload (MCS) symbol streams.
pub fn symbol_config(base: &OfdmConfig, constellation: ConstellationOrder) -> OfdmConfig {
    // The bare symbol config drops the frame-layer FEC/interleaver settings (a
    // single symbol carries no coded block), but must carry the RX window
    // back-off: it is per-symbol demod geometry, and a reconstructed config that
    // reset it to 0 would silently demodulate at the wrong window position.
    OfdmConfig::new(
        base.carrier_plan.clone(),
        base.fs,
        base.rf_hz,
        base.gain,
        constellation,
    )
    .with_rx_window_backoff(base.rx_window_backoff)
}

/// The OFDM frame modulator.
#[derive(Debug, Clone)]
pub struct OfdmFrameMod {
    cfg: OfdmConfig,
    mcs_table: McsTable,
    preamble: OfdmPreamble,
    /// FEC code cache, so a stream of frames builds each code once (see
    /// [`CodecCache`]). Held behind `Arc` so it can be shared with a paired
    /// demodulator (TX and RX then reuse the same built codes).
    cache: Arc<CodecCache>,
}

/// Panics if `cfg` carries a nonzero `rf_hz`.
///
/// `rf_hz` is honoured by [`OfdmMod`](crate::modulate::OfdmMod), which rotates
/// each symbol as it is produced. The **frame** layer cannot honour it, in
/// three independent ways:
///
/// - [`TxLowpass`](crate::multicarrier::TxLowpass) is a low-pass centred on DC.
///   Run over an already-upconverted stream it deletes the signal, so a
///   spectral mask and a nonzero `rf_hz` cannot coexist.
/// - `generate_ofdm_preamble` does not apply it, leaving the preamble at
///   baseband while header and payload sit at the IF.
/// - `map_bits_to_iq` builds a fresh `OfdmMod` per block, so each starts its
///   rotator at phase 0 — a phase step at every header/payload and frame seam.
///
/// The receiver never applies it either: `rf_hz` appears nowhere in
/// `demodulate`, so a frame modulated at an IF could not be decoded even if
/// the transmit side were correct.
///
/// Modulate at `rf_hz = 0.0` and upconvert the whole burst yourself with one
/// continuous [`Rotator`](crate::dsp::Rotator). That is the right ordering
/// whenever a baseband shaping stage exists — shape first, upconvert once —
/// and it keeps the rotator continuous across every seam.
pub(crate) fn assert_baseband(cfg: &OfdmConfig) {
    assert!(
        cfg.rf_hz == 0.0,
        "OFDM frame assembly is baseband-only: got rf_hz = {} Hz. Modulate at \
         rf_hz = 0.0 and upconvert the whole burst with one continuous Rotator.",
        cfg.rf_hz
    );
}

impl OfdmFrameMod {
    /// Creates a frame modulator over `cfg`, an `mcs_table`, and the
    /// acquisition `preamble` (which should carry a training symbol sized to
    /// the plan for the receiver's channel estimation). The modulator owns a
    /// fresh, private [`CodecCache`]; use [`with_cache`](Self::with_cache) to
    /// share one with a demodulator.
    pub fn new(cfg: OfdmConfig, mcs_table: McsTable, preamble: OfdmPreamble) -> Self {
        Self::with_cache(cfg, mcs_table, preamble, Arc::new(CodecCache::new()))
    }

    /// Like [`new`](Self::new), but reuses the caller-provided `cache` — share
    /// one `Arc<CodecCache>` across a modulator/demodulator pair (or several
    /// links on the same MCS) so each FEC code is constructed only once.
    pub fn with_cache(
        cfg: OfdmConfig,
        mcs_table: McsTable,
        preamble: OfdmPreamble,
        cache: Arc<CodecCache>,
    ) -> Self {
        assert_baseband(&cfg);
        Self {
            cfg,
            mcs_table,
            preamble,
            cache,
        }
    }

    pub fn config(&self) -> &OfdmConfig {
        &self.cfg
    }

    /// The training-symbol-carrying preamble prepended to every frame.
    pub fn preamble(&self) -> &OfdmPreamble {
        &self.preamble
    }

    /// Modulates a whole `FramePacket` into a flat IQ stream:
    /// `[preamble+training][header][payload]`.
    ///
    /// `per_frame_seed` supplies the scrambler seed for a `PerFrameRandom`
    /// configuration (ignored otherwise); it is recorded in the header so the
    /// receiver can rebuild the descrambler.
    pub fn modulate_frame(&self, frame: &FramePacket, per_frame_seed: u32) -> Vec<C32> {
        let mut out = Vec::new();

        // For a DVB-T scattered-pilot link, one grid-rotation orchestrator spans
        // the whole frame's OFDM symbols (header then payload), so `l = 0` is the
        // first header symbol and the phase carries through — matching the RX
        // extractor's per-frame reset. `None` for every other link.
        let mut scattered = self.cfg.dvb_t_scattered.then(|| {
            let guard = crate::waveform::dvb_t::GuardInterval::from_cp_len_2k(
                self.cfg.carrier_plan.cp_len(),
            )
            .expect("DVB-T scattered link requires a 2K guard interval");
            crate::waveform::dvb_t::ScatteredPilotMapper::new(guard)
        });

        // Maps coded bits either through the rotating scattered grid (DVB-T) or
        // the static plan.
        let mut map = |constellation, bits: &[u8]| match scattered.as_mut() {
            Some(m) => map_bits_to_iq_scattered(&self.cfg, constellation, bits, m),
            None => map_bits_to_iq(&self.cfg, constellation, bits),
        };

        // 1. Preamble + training symbol.
        out.extend_from_slice(&generate_ofdm_preamble(&self.preamble, &self.cfg));

        // 2. Header (only OrionSdr prepends a dedicated header block; NoHeader
        //    and DvbTps carry no separate header — DvbTps signals in-band on the
        //    TPS carriers, handled by the dedicated DVB-T frame assembler).
        if self.cfg.header_format.has_header_block() {
            let fields = pack_header_fields(
                frame.metadata.mcs_index,
                frame.payload.len() as u32,
                frame.metadata.sequence_num,
                frame.metadata.flags,
                per_frame_seed,
            );
            let header_bits = encode_chain(
                &fields,
                self.cfg.header_crc,
                OuterFec::None,
                InnerFec::Ldpc(HEADER_LDPC),
                InterleaverKind::None,
                InterleaverKind::None,
                ScramblerKind::None,
                ScramblerPos::BeforeOuterFec,
                0,
                &self.cache,
            );
            out.extend_from_slice(&map(HEADER_CONSTELLATION, &header_bits));
        }

        // 3. Payload, coded per the selected MCS.
        let mcs = self
            .mcs_table
            .get(frame.metadata.mcs_index)
            .expect("mcs_index must be in the MCS table");
        let payload_bits = encode_chain(
            &frame.payload,
            self.cfg.payload_crc,
            mcs.outer_fec,
            mcs.inner_fec,
            self.cfg.outer_interleaver,
            self.cfg.inner_interleaver,
            self.cfg.scrambler,
            self.cfg.scrambler_pos,
            per_frame_seed,
            &self.cache,
        );
        out.extend_from_slice(&map(mcs.constellation, &payload_bits));

        // 4. Optional TX symbol windowing (raised-cosine edge taper). Applied as
        //    a post-pass over the assembled stream: every CP-bearing symbol from
        //    the training symbol onward is windowed, but the raw S&C preamble
        //    repeats (no CP, correlated raw by `ofdm_sync`) are skipped — see
        //    the RX-transparency and preamble constraints in the windowing design.
        self.apply_symbol_windowing(&mut out);

        // 5. Optional TX baseband low-pass (spectral mask). Applied last, over
        //    the whole assembled stream — spanning symbol boundaries, which is
        //    what makes it a spectral filter rather than a per-symbol taper.
        //    Unlike the taper this DOES include the S&C preamble: a real
        //    transmitter band-limits everything it emits, and filtering only
        //    part of the burst would put an unfiltered spectral step back in.
        //    Periodicity — the property `ofdm_sync` correlates on — survives a
        //    filter whose reach is short relative to `repeat_len`, since the
        //    same taps see the same repeated samples; see `TxLowpass`.
        if let Some(lowpass) = self.cfg.tx_lowpass {
            lowpass.apply(&mut out);
        }

        out
    }

    /// In-place raised-cosine edge taper over the CP-bearing symbols of an
    /// assembled frame. No-op when the carrier plan's `window_roll_off` is 0.
    ///
    /// The raw S&C preamble repeats (`num_repeats * repeat_len` leading samples)
    /// carry no cyclic prefix and are correlated sample-for-sample by the
    /// receiver's timing/CFO stage, so they must not be tapered. Everything from
    /// the training symbol onward (training, header, payload) is a contiguous run
    /// of `samples_per_ofdm_symbol()`-sized CP'd symbols and is windowed.
    fn apply_symbol_windowing(&self, out: &mut [C32]) {
        let roll_off = self.cfg.carrier_plan.window_roll_off();
        if roll_off == 0 {
            return;
        }
        let sps = self.cfg.samples_per_ofdm_symbol();
        // Start of the first windowable (CP-bearing) symbol: past the raw S&C
        // repeats. The training symbol (if any) is the first such symbol; without
        // one, the first header/payload symbol sits here instead.
        let start = self.preamble.num_repeats * self.preamble.repeat_len;
        let mut win = SymbolWindow::new(sps, roll_off);
        let mut off = start;
        while off + sps <= out.len() {
            // Window in place: read the symbol, write it back tapered.
            let symbol: Vec<C32> = out[off..off + sps].to_vec();
            win.process(&symbol, &mut out[off..off + sps]);
            off += sps;
        }
    }
}

/// Convenience: the carrier plan cloned from a config (used by the demodulator).
pub fn plan_of(cfg: &OfdmConfig) -> CarrierPlan {
    cfg.carrier_plan.clone()
}