orion-sdr 0.0.74

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
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
"""
Type stubs for the orion-sdr native extension module.

All classes live in the flat ``orion_sdr`` namespace.  IQ arrays use
``numpy.complex64``; audio arrays use ``numpy.float32``; bit arrays use
``numpy.uint8`` (one bit per byte, value 0 or 1).  Every ``process()``
call returns a new 1-D array; arrays must be 1-D and C-contiguous, or a
``ValueError`` is raised.
"""

import numpy as np
from numpy.typing import NDArray

# ---------------------------------------------------------------------------
# Demodulators  (IQ complex64 → audio float32)
# ---------------------------------------------------------------------------

class CwEnvelopeDemod:
    """One-pole envelope detector for CW signals.

    Tracks the instantaneous magnitude of the IQ input with a low-pass
    time constant derived from *env_bw_hz*.  *tone_hz* is accepted for
    API symmetry but is not used internally (pre-tune the signal before
    passing it in).
    """

    def __init__(self, sample_rate: float, tone_hz: float, env_bw_hz: float) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def process(self, iq: NDArray[np.complex64]) -> NDArray[np.float32]: ...

class AmEnvelopeDemod:
    """AM envelope demodulator with 4th-order IIR low-pass and DC blocker.

    Two envelope methods are available:

    * ``abs_approx=False`` (default) — ``sqrt(I² + Q²)`` after the LP filter
      (*PowerSqrt*); highest fidelity.
    * ``abs_approx=True`` — ``k1·|I| + k2·|Q|`` approximation (*AbsApprox*,
      k1=0.9482, k2=0.3920); slightly faster with a small amplitude error.
    """

    def __init__(
        self,
        fs: float,
        audio_bw_hz: float,
        abs_approx: bool = False,
    ) -> None: ...
    def process(self, iq: NDArray[np.complex64]) -> NDArray[np.float32]: ...

class SsbProductDemod:
    """SSB product detector with BFO rotator and 4th-order IIR audio filter.

    Set *bfo_hz* to 0 for a signal already tuned to baseband, or to a small
    offset to shift the recovered audio pitch.
    """

    def __init__(self, fs: float, bfo_hz: float, audio_bw_hz: float) -> None: ...
    def process(self, iq: NDArray[np.complex64]) -> NDArray[np.float32]: ...

class FmQuadratureDemod:
    """FM quadrature (phase-difference) discriminator.

    Output is scaled so that ±*dev_hz* of instantaneous frequency deviation
    maps to roughly ±1.0.  A 4th-order IIR low-pass at *audio_bw_hz* follows
    the discriminator.
    """

    def __init__(self, fs: float, dev_hz: float, audio_bw_hz: float) -> None: ...
    def process(self, iq: NDArray[np.complex64]) -> NDArray[np.float32]: ...

class PmQuadratureDemod:
    """PM quadrature demodulator (instantaneous phase difference).

    *k* scales the recovered phase difference to the output audio level.
    A 4th-order IIR low-pass at *audio_bw_hz* follows the discriminator.
    """

    def __init__(self, fs: float, k: float, audio_bw_hz: float) -> None: ...
    def process(self, iq: NDArray[np.complex64]) -> NDArray[np.float32]: ...

# ---------------------------------------------------------------------------
# Digital demodulators  (IQ complex64 → bits uint8)
# ---------------------------------------------------------------------------

class BpskDemod:
    """BPSK demodulator: hard-decision slicer.

    Input: complex64 IQ array, carrier-removed baseband, 1 sample per symbol.
    Output: uint8 bit array — one bit (0 or 1) per input symbol.
    Decision rule: Re(z) ≥ 0 → 0, Re(z) < 0 → 1.

    *gain* scales the soft metric before slicing (use 1.0 for normalized input).
    """

    def __init__(self, gain: float = 1.0) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def process(self, iq: NDArray[np.complex64]) -> NDArray[np.uint8]: ...

class QpskDemod:
    """QPSK demodulator: hard-decision slicer.

    Input: complex64 IQ array, carrier-removed baseband, 1 sample per symbol.
    Output: uint8 bit array — two bits per input symbol, interleaved as
    ``[b0_I, b0_Q, b1_I, b1_Q, …]``.  Matches the Gray coding of ``QpskMod``.

    *gain* scales the soft metric before slicing (use 1.0 for normalized input).
    """

    def __init__(self, gain: float = 1.0) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def process(self, iq: NDArray[np.complex64]) -> NDArray[np.uint8]: ...

class QamDemod:
    """QAM demodulator: hard-decision slicer for square QAM constellations.

    *order* must be 16, 64, or 256 (raises ``ValueError`` otherwise).
    Input: complex64 IQ array, carrier-removed baseband, 1 sample per symbol.
    Output: uint8 bit array — ``log2(order)`` bits per input symbol, laid out
    as ``log2(order)/2`` I-axis bits then ``log2(order)/2`` Q-axis bits
    (MSB-first within each axis Gray index).  Matches ``QamMod`` bit layout.

    *gain* scales the soft metric before slicing (use 1.0 for normalized input).
    """

    def __init__(self, order: int, gain: float = 1.0) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def process(self, iq: NDArray[np.complex64]) -> NDArray[np.uint8]: ...

# ---------------------------------------------------------------------------
# Modulators  (audio float32 → IQ complex64)
# ---------------------------------------------------------------------------

class AmDsbMod:
    """AM double-sideband modulator with optional carrier and RF upconversion.

    * *carrier_level* — 1.0 produces full carrier (A3E); 0.0 gives DSB-SC.
    * *modulation_index* — values ≤ 1.0 are recommended to avoid
      over-modulation.
    * *rf_hz* — set to 0.0 for baseband IQ output.
    """

    def __init__(
        self,
        fs: float,
        rf_hz: float,
        carrier_level: float,
        modulation_index: float,
    ) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def set_clamp(self, on: bool) -> None:
        """Clamp the modulated envelope to ±1 to prevent over-modulation."""
        ...
    def process(self, audio: NDArray[np.float32]) -> NDArray[np.complex64]: ...

class CwKeyedMod:
    """CW keyed carrier modulator with shaped rise/fall envelope.

    The input array is a **keying envelope** in the range 0..1 (not raw
    audio): 1.0 = key down, 0.0 = key up.  Rise and fall times are
    smoothed by one-pole filters with time constants *rise_ms* / *fall_ms*
    to suppress key clicks.
    """

    def __init__(
        self,
        sample_rate: float,
        tone_hz: float,
        rise_ms: float,
        fall_ms: float,
    ) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def process(self, audio: NDArray[np.float32]) -> NDArray[np.complex64]: ...

class FmPhaseAccumMod:
    """FM modulator using a phasor-recurrence phase accumulator.

    Each sample multiplies a running phasor by ``exp(j·2π·kf·x/fs)``
    where ``kf = deviation_hz``.  The phasor is renormalized every 1024
    samples to prevent amplitude drift.  Set *rf_hz* to 0.0 for baseband
    output.
    """

    def __init__(
        self,
        sample_rate: float,
        deviation_hz: float,
        rf_hz: float,
    ) -> None: ...
    def set_deviation(self, hz: float) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def process(self, audio: NDArray[np.float32]) -> NDArray[np.complex64]: ...

class PmDirectPhaseMod:
    """PM modulator: instantaneous phase φ = kp · x[n].

    *kp_rad_per_unit* maps ±1.0 audio to ±kp radians of carrier phase.
    Set *rf_hz* to 0.0 for baseband output.
    """

    def __init__(
        self,
        sample_rate: float,
        kp_rad_per_unit: float,
        rf_hz: float,
    ) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def set_sensitivity(self, kp: float) -> None:
        """Update the phase sensitivity (rad per unit input amplitude)."""
        ...
    def process(self, audio: NDArray[np.float32]) -> NDArray[np.complex64]: ...

class SsbPhasingMod:
    """SSB phasing modulator (Weaver-style IIR variant).

    Audio is up-converted to *audio_if_hz* via a complex rotator, split
    into I and Q paths through matched 4th-order IIR low-pass filters,
    then combined to select the desired sideband.  Set *usb=True* for
    upper sideband, *usb=False* for lower sideband.  Set *rf_hz* to 0.0
    for baseband IQ output.
    """

    def __init__(
        self,
        fs: float,
        audio_bw_hz: float,
        audio_if_hz: float,
        rf_hz: float,
        usb: bool,
    ) -> None: ...
    def process(self, audio: NDArray[np.float32]) -> NDArray[np.complex64]: ...

# ---------------------------------------------------------------------------
# Digital modulators  (bits uint8 → IQ complex64)
# ---------------------------------------------------------------------------

class BpskMod:
    """BPSK modulator: Gray-coded constellation mapper + waveform stage.

    Input: uint8 bit array (LSB of each byte used), one bit per symbol.
    Output: complex64 IQ array of the same length.
    Constellation: bit 0 → (+1, 0), bit 1 → (−1, 0).

    Set *rf_hz* to 0.0 for baseband output; non-zero upconverts via an
    internal ``Rotator`` (phasor recurrence, no per-sample trig).
    """

    def __init__(self, fs: float, rf_hz: float, gain: float = 1.0) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def process(self, bits: NDArray[np.uint8]) -> NDArray[np.complex64]: ...

class QpskMod:
    """QPSK modulator: Gray-coded constellation mapper + waveform stage.

    Input: uint8 bit array (LSB of each byte); consumed in pairs ``[b0, b1]``.
    Output: complex64 IQ array of length ``len(bits) // 2``.
    Constellation is normalized to unit energy (each axis ±1/√2).

    Set *rf_hz* to 0.0 for baseband output.
    """

    def __init__(self, fs: float, rf_hz: float, gain: float = 1.0) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def process(self, bits: NDArray[np.uint8]) -> NDArray[np.complex64]: ...

class QamMod:
    """Square QAM modulator: Gray-coded constellation mapper + waveform stage.

    *order* must be 16, 64, or 256 (raises ``ValueError`` otherwise).
    Input: uint8 bit array (LSB of each byte); consumed ``log2(order)`` bytes
    per symbol.  Output: complex64 IQ array of length
    ``len(bits) // log2(order)``.

    Constellation is Gray-coded on each axis independently and normalized to
    unit average symbol energy.  Set *rf_hz* to 0.0 for baseband output.
    """

    def __init__(self, order: int, fs: float, rf_hz: float, gain: float = 1.0) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def process(self, bits: NDArray[np.uint8]) -> NDArray[np.complex64]: ...

# ---------------------------------------------------------------------------
# FT8/FT4 waveform classes
# ---------------------------------------------------------------------------

class Ft8Mod:
    """FT8 frame modulator: 8-FSK CPFSK, 79 symbols, 151 680 samples at 12 kHz.

    Input: uint8 array of 58 tone indices (0–7).
    Output: complex64 IQ array of shape (151680,).
    """

    def __init__(self, fs: float, base_hz: float, rf_hz: float, gain: float = 1.0) -> None: ...
    def modulate(self, tones: NDArray[np.uint8]) -> NDArray[np.complex64]: ...

class Ft8Demod:
    """FT8 frame demodulator: Goertzel/dot-product tone detector.

    Input: complex64 IQ array of at least 151 680 samples.
    Output: uint8 array of 58 tone indices.
    Raises ``ValueError`` if input is too short or demodulation fails.
    """

    def __init__(self, fs: float, base_hz: float) -> None: ...
    def demodulate(self, iq: NDArray[np.complex64]) -> NDArray[np.uint8]: ...

class Ft8Codec:
    """FT8 channel codec: CRC-14 + LDPC(174,91) + Gray code.

    All methods are static; no per-instance state.
    """

    def __init__(self) -> None: ...
    @staticmethod
    def encode(payload: bytes) -> NDArray[np.uint8]:
        """Encode a 10-byte payload → uint8[58] Gray-coded tone indices."""
        ...
    @staticmethod
    def decode_hard(tones: NDArray[np.uint8]) -> bytes | None:
        """Hard-decision decode 58 tone indices → bytes[10], or None on failure."""
        ...
    @staticmethod
    def decode_soft(llr: NDArray[np.float32]) -> bytes | None:
        """Soft-decision decode float32[174] LLRs → bytes[10], or None on failure."""
        ...

class Ft4Mod:
    """FT4 frame modulator: 4-FSK CPFSK, 105 symbols, 60 480 samples at 12 kHz.

    Input: uint8 array of 87 tone indices (0–3).
    Output: complex64 IQ array of shape (60480,).
    """

    def __init__(self, fs: float, base_hz: float, rf_hz: float, gain: float = 1.0) -> None: ...
    def modulate(self, tones: NDArray[np.uint8]) -> NDArray[np.complex64]: ...

class Ft4Demod:
    """FT4 frame demodulator: Goertzel/dot-product tone detector.

    Input: complex64 IQ array of at least 60 480 samples.
    Output: uint8 array of 87 tone indices.
    Raises ``ValueError`` if input is too short or demodulation fails.
    """

    def __init__(self, fs: float, base_hz: float) -> None: ...
    def demodulate(self, iq: NDArray[np.complex64]) -> NDArray[np.uint8]: ...

class Ft4Codec:
    """FT4 channel codec: XOR scramble + CRC-14 + LDPC(174,91) + Gray code.

    All methods are static; no per-instance state.
    """

    def __init__(self) -> None: ...
    @staticmethod
    def encode(payload: bytes) -> NDArray[np.uint8]:
        """Encode a 10-byte payload → uint8[87] Gray-coded tone indices."""
        ...
    @staticmethod
    def decode_hard(tones: NDArray[np.uint8]) -> bytes | None:
        """Hard-decision decode 87 tone indices → bytes[10], or None on failure."""
        ...
    @staticmethod
    def decode_soft(llr: NDArray[np.float32]) -> bytes | None:
        """Soft-decision decode float32[174] LLRs → bytes[10], or None on failure."""
        ...

# ---------------------------------------------------------------------------
# FT8/FT4 sync functions
# ---------------------------------------------------------------------------

def ft8_sync(
    iq: NDArray[np.complex64],
    fs: float,
    base_hz: float,
    max_hz: float,
    t_min: int,
    t_max: int,
    max_cand: int,
) -> list[dict]:
    """Synchronise an FT8 IQ buffer and return up to *max_cand* frame candidates.

    Each candidate is a dict::

        {
            "time_sym": int,           # symbol offset of frame start
            "freq_bin": int,           # frequency bin of tone-0
            "score":    float,         # Costas match score
            "llr":      float32[174],  # soft LLRs for Ft8Codec.decode_soft
        }

    Pass each result's ``"llr"`` to ``Ft8Codec.decode_soft`` to recover the
    77-bit payload.
    """
    ...

def ft4_sync(
    iq: NDArray[np.complex64],
    fs: float,
    base_hz: float,
    max_hz: float,
    t_min: int,
    t_max: int,
    max_cand: int,
) -> list[dict]:
    """Synchronise an FT4 IQ buffer and return up to *max_cand* frame candidates.

    Same return shape as ``ft8_sync``.
    """
    ...

# ---------------------------------------------------------------------------
# FT8/FT4 message packing functions
# ---------------------------------------------------------------------------

def ft8_pack_standard(call_to: str, call_de: str, extra: str) -> bytes:
    """Pack a standard FT8/FT4 message → bytes[10].

    *extra* may be a Maidenhead grid (``"FN31"``), signal report (``"+07"``,
    ``"-12"``), R-prefixed report (``"R+05"``), or token
    (``"RRR"``, ``"RR73"``, ``"73"``).  Pass ``""`` for no extra field.

    Raises ``ValueError`` if the callsigns cannot be encoded.
    """
    ...

def ft8_pack_free_text(text: str) -> bytes:
    """Pack a free-text FT8/FT4 message (up to 13 chars) → bytes[10].

    Raises ``ValueError`` if the text is too long or contains invalid characters.
    """
    ...

def ft8_pack_telemetry(data: bytes) -> bytes:
    """Pack a telemetry FT8/FT4 message (exactly 9 bytes) → bytes[10].

    Raises ``ValueError`` if *data* is not exactly 9 bytes.
    """
    ...

def ft8_unpack(payload: bytes) -> dict:
    """Unpack a 10-byte FT8/FT4 payload → dict.

    The ``"type"`` key indicates the message type:

    * ``"standard"``  — ``{"type", "call_to", "call_de", "extra"}``
    * ``"free_text"`` — ``{"type", "text"}``
    * ``"telemetry"`` — ``{"type", "data"}`` (bytes[9])
    * ``"nonstd"``    — ``{"type", "call_to", "call_de", "extra"}``
    * ``"unknown"``   — ``{"type", "payload"}`` (bytes[10])

    Raises ``ValueError`` if *payload* is not exactly 10 bytes.
    """
    ...

# ---------------------------------------------------------------------------
# PSK31 codec classes
# ---------------------------------------------------------------------------

class VaricodeEncoder:
    """PSK31 Varicode encoder: push bytes, drain bit stream."""

    def __init__(self) -> None: ...
    def push_preamble(self, n: int) -> None:
        """Append *n* zero bits as preamble."""
        ...
    def push_byte(self, b: int) -> None:
        """Encode byte *b* and append its Varicode bits."""
        ...
    def push_postamble(self, n: int) -> None:
        """Append *n* zero bits as postamble."""
        ...
    def drain_bits(self) -> NDArray[np.uint8]:
        """Drain all pending bits into a uint8 array."""
        ...
    def is_empty(self) -> bool: ...

class VaricodeDecoder:
    """PSK31 Varicode decoder: push bits, pop decoded bytes."""

    def __init__(self) -> None: ...
    def push_bits(self, bits: NDArray[np.uint8]) -> None:
        """Feed a uint8 array of bits (0/1) into the decoder."""
        ...
    def pop_bytes(self) -> bytes:
        """Drain all decoded bytes."""
        ...

# ---------------------------------------------------------------------------
# PSK31 modulators / demodulators
# ---------------------------------------------------------------------------

class Bpsk31Mod:
    """BPSK31 modulator: differential phase encoding with Hann pulse shaping."""

    def __init__(self, fs: float, rf_hz: float, gain: float = 1.0) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def reset(self) -> None: ...
    def modulate_text(
        self,
        text: bytes,
        preamble_bits: int = 32,
        postamble_bits: int = 32,
    ) -> NDArray[np.complex64]:
        """Encode text via Varicode and modulate to IQ."""
        ...
    def modulate_bits(self, bits: NDArray[np.uint8]) -> NDArray[np.complex64]:
        """Modulate raw differential bits to IQ."""
        ...

class Bpsk31Demod:
    """BPSK31 demodulator: matched-filter symbol detection."""

    def __init__(self, fs: float, rf_hz: float, gain: float = 1.0) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def reset(self) -> None: ...
    def process(self, iq: NDArray[np.complex64]) -> NDArray[np.float32]:
        """Demodulate IQ to soft bits (one float per symbol)."""
        ...

class Bpsk31Decider:
    """BPSK31 hard-decision slicer: threshold soft bits at 0."""

    def __init__(self) -> None: ...
    def process(self, soft: NDArray[np.float32]) -> NDArray[np.uint8]:
        """Threshold soft bits to hard decisions."""
        ...

class Qpsk31Mod:
    """QPSK31 modulator: convolutional encoding + DQPSK + Hann pulse shaping."""

    def __init__(self, fs: float, rf_hz: float, gain: float = 1.0) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def reset(self) -> None: ...
    def modulate_text(
        self,
        text: bytes,
        preamble_bits: int = 32,
        postamble_bits: int = 32,
    ) -> NDArray[np.complex64]:
        """Encode text via Varicode, convolutional-encode, and modulate to IQ."""
        ...
    def modulate_bits(self, bits: NDArray[np.uint8]) -> NDArray[np.complex64]:
        """Modulate raw bits (convolutional encoding + DQPSK) to IQ."""
        ...

class Qpsk31Demod:
    """QPSK31 demodulator with integrated Viterbi decider.

    Call ``process()`` to feed IQ samples (returns soft dibits for inspection),
    then ``flush()`` to run Viterbi and get decoded bits.
    """

    def __init__(self, fs: float, rf_hz: float, gain: float = 1.0) -> None: ...
    def set_gain(self, g: float) -> None: ...
    def reset(self) -> None: ...
    def process(self, iq: NDArray[np.complex64]) -> NDArray[np.float32]:
        """Demodulate IQ to soft dibits (interleaved Re/Im pairs)."""
        ...
    def flush(self) -> NDArray[np.uint8]:
        """Run Viterbi on accumulated dibits and return decoded bits."""
        ...

# ---------------------------------------------------------------------------
# PSK31 streaming decoder
# ---------------------------------------------------------------------------

class Psk31Stream:
    """Streaming PSK31 decoder: demod → decider/Viterbi → Varicode in one step.

    Use ``mode="bpsk"`` for BPSK31 or ``mode="qpsk"`` for QPSK31.
    """

    def __init__(
        self,
        mode: str,
        fs: float,
        carrier_hz: float,
        gain: float = 1.0,
    ) -> None: ...
    def feed(self, iq: NDArray[np.complex64]) -> str:
        """Feed IQ samples and return any newly decoded text."""
        ...
    def flush(self) -> str:
        """Flush the decoder and return any remaining text."""
        ...

# ---------------------------------------------------------------------------
# PSK31 sync functions
# ---------------------------------------------------------------------------

def psk31_sync(
    iq: NDArray[np.complex64],
    fs: float,
    base_hz: float,
    max_hz: float,
    min_carrier_syms: int = 8,
    peak_margin_db: float = 6.0,
    n_bits: int = 1024,
    max_cand: int = 10,
) -> list[dict]:
    """Scan for PSK31 carriers in an IQ buffer.

    Returns a list of candidate dicts::

        {
            "time_sym":   int,
            "freq_bin":   int,
            "carrier_hz": float,
            "score":      float,
            "soft_bits":  float32[N],
        }
    """
    ...

def best_psk31_sync(
    candidates: list[dict],
    carrier_hz: float,
    baud: float = 31.25,
) -> dict | None:
    """Pick the best PSK31 sync result nearest to *carrier_hz*.

    Takes the list returned by ``psk31_sync()`` and returns the best
    candidate dict, or ``None`` if no candidate is within 2×baud.
    """
    ...

# ---------------------------------------------------------------------------
# OFDM
# ---------------------------------------------------------------------------

class OfdmConfig:
    """OFDM waveform configuration: carrier plan + RF/constellation parameters.

    *data_carriers* and *pilot_carrier_indices* use the signed carrier-index
    convention (bin 0 = DC; e.g. ``-26..=26``). *pilot_carrier_indices* and
    *pilot_carrier_values* are parallel arrays of the same length — pass
    empty arrays for no pilots. *constellation* is one of ``"bpsk"``,
    ``"qpsk"``, ``"qam16"``, ``"qam64"``, ``"qam256"``.

    *edge_guard* (optional): when given, the data carriers are generated as a
    contiguous span leaving *edge_guard* null carriers at each band edge (DC
    excluded), skipping any pilot index — reducing out-of-band emission. In
    that mode *data_carriers* must be an empty array (the span is generated
    automatically). When omitted, *data_carriers* is used verbatim.

    Raises ``ValueError`` for an unknown constellation, an invalid carrier
    plan (overlapping data/pilot carriers, out-of-range indices, or an empty
    data set), or a non-empty *data_carriers* passed together with
    *edge_guard*.
    """

    def __init__(
        self,
        n_fft: int,
        cp_len: int,
        data_carriers: NDArray[np.int32],
        pilot_carrier_indices: NDArray[np.int32],
        pilot_carrier_values: NDArray[np.complex64],
        fs: float,
        rf_hz: float,
        gain: float,
        constellation: str,
        edge_guard: int | None = None,
    ) -> None: ...
    @property
    def bits_per_ofdm_symbol(self) -> int: ...
    @property
    def samples_per_ofdm_symbol(self) -> int: ...
    # ── COFDM frame-layer configuration (builder-style; each returns a new
    #    config with the field set, for the OfdmFrameMod/OfdmFrameStreamDemod). ──
    def with_outer_fec(self, kind: str, a: int = 0, b: int = 0) -> "OfdmConfig":
        """Set the outer FEC. *kind*: ``"none"`` | ``"bch"`` |
        ``"reed_solomon"``. For BCH, *a* is ``t``. For Reed–Solomon, *a* is
        ``n`` and *b* is ``n_parity`` (``= 2t``)."""
        ...
    def with_inner_fec(self, kind: str, code: str = "") -> "OfdmConfig":
        """Set the inner FEC. *kind*: ``"none"`` | ``"ldpc"`` |
        ``"convolutional"``. For LDPC, *code* is ``"n512r12"`` | ``"n576r23"``
        | ``"n512r34"``. For convolutional, *code* is a puncture rate
        ``"1/2"`` | ``"2/3"`` | ``"3/4"`` | ``"5/6"`` | ``"7/8"``."""
        ...
    def with_ldpc_decode_rule(
        self, kind: str, scale: float = 0.75
    ) -> "OfdmConfig":
        """Select the receiver's LDPC check-node decode rule: ``"sum_product"``
        (default, exact) | ``"min_sum"`` | ``"scaled_min_sum"``. *scale* applies
        only to ``"scaled_min_sum"`` (≈0.75 recovers most of the coding gain).
        Min-sum trades ≲0.3 dB of coding gain for ~2× decode throughput."""
        ...
    def with_rx_window_backoff(self, backoff: int) -> "OfdmConfig":
        """Set the receiver FFT-window back-off in samples (RX-only, default 0).
        Pulls the demod window earlier into the guard for multipath robustness
        and to make a matched TX symbol-window taper transparent. Only
        RX-transparent on the equalized (streaming/scattered) path."""
        ...
    def with_symbol_window(self, roll_off: int) -> "OfdmConfig":
        """Enable TX symbol windowing: a *roll_off*-sample raised-cosine edge
        taper per symbol (default 0 = off), reducing out-of-band emission. Only
        RX-transparent when paired with a matching ``with_rx_window_backoff``
        (``roll_off = cp_len/2`` with back-off ``cp_len/2``)."""
        ...
    def with_tx_lowpass(
        self, num_taps: int, stopband_db: float = 60.0
    ) -> "OfdmConfig":
        """Enable the TX baseband low-pass (spectral mask) applied across the
        assembled frame (default: off). The cutoff is placed against this plan's
        own occupied band edge; *num_taps* stays the caller's choice because it
        is what the cyclic-prefix budget constrains.

        Not bounded by the symbol-windowing ceiling — it attenuates out-of-band
        energy directly in the frequency domain, so its gain stacks on top of a
        taper's. It needs no decoding change at the receiver, but its group delay
        ``(num_taps - 1) // 2`` must fit the guard the receiver discards: pair it
        with ``with_rx_window_backoff`` and keep
        ``roll_off + group_delay <= min(cp_len - backoff, backoff)``."""
        ...
    def tx_lowpass_suggested_taps(self, stopband_db: float = 60.0) -> int:
        """The tap count whose transition just fits this plan's unoccupied band
        at *stopband_db* — a starting point for ``with_tx_lowpass``, to be
        checked against the guard budget with ``tx_lowpass_fits_guard``."""
        ...
    def tx_lowpass_group_delay(self, num_taps: int) -> int:
        """A mask's group delay in samples, ``(num_taps - 1) // 2`` after the
        odd/>=3 clamp — its reach on each side, and what the guard must cover."""
        ...
    def tx_lowpass_fits_guard(
        self, num_taps: int, roll_off: int = 0, backoff: int | None = None
    ) -> bool:
        """Whether a *num_taps* mask and a *roll_off*-sample taper both fit the
        guard a receiver at *backoff* discards: ``roll_off + group_delay <=
        min(cp_len - backoff, backoff)``, reading ``cp_len`` off this plan.
        *backoff* defaults to ``cp_len // 2``, where the slack is maximized.

        This is the check ``tx_lowpass_suggested_taps`` refers to: the suggestion
        sizes the transition against the *null band*, this says whether the length
        fits the *guard*. If it does not, a longer cyclic prefix (or a shallower
        *stopband_db*) is the lever."""
        ...
    @property
    def occupied_half_carriers(self) -> int:
        """The outermost occupied subcarrier's distance from DC, in carriers — the
        band edge a mask's transition is placed against. With *edge_guard* ``g`` on
        an *n_fft*-point plan this is ``n_fft//2 - 1 - g``, so it is also how to
        read back the guard a plan was built with."""
        ...
    def with_interleaver(self, stage: str, rows: int, cols: int) -> "OfdmConfig":
        """Set a rectangular block interleaver on *stage* (``"inner"`` |
        ``"outer"``); ``rows``/``cols`` = 0 disables it."""
        ...
    def with_payload_crc(self, kind: str) -> "OfdmConfig":
        """Set the payload CRC: ``"none"`` | ``"crc16"`` | ``"crc32"``."""
        ...
    def with_header_crc(self, kind: str) -> "OfdmConfig":
        """Set the header CRC: ``"none"`` | ``"crc16"`` | ``"crc32"``."""
        ...
    def with_header_format(self, kind: str) -> "OfdmConfig":
        """Set the header format: ``"orion_sdr"`` | ``"none"``."""
        ...
    def with_scrambler(
        self,
        poly: int,
        width: int,
        seed: int = 1,
        per_frame_random: bool = False,
        position: str = "before_outer",
    ) -> "OfdmConfig":
        """Set an additive PN scrambler (``poly`` = 0 disables). *position*:
        ``"before_outer"`` | ``"after_inner"``."""
        ...
    def validate_frame(self) -> None:
        """Raise ``ValueError`` on an inconsistent frame-layer configuration."""
        ...

class OfdmMod:
    """OFDM transmitter: fused mapper + resource-grid mapping + IFFT + cyclic
    prefix + optional RF upconversion.

    Input: uint8 array of bits (LSB of each byte); consumed
    ``bits_per_ofdm_symbol`` at a time, zero-padding a final partial symbol.
    Output: complex64 IQ array, ``samples_per_ofdm_symbol`` samples/symbol.
    """

    def __init__(self, cfg: OfdmConfig) -> None: ...
    def modulate(self, bits: NDArray[np.uint8]) -> NDArray[np.complex64]: ...

class OfdmDemod:
    """OFDM receiver: fused cyclic-prefix removal + FFT + channel
    equalization + resource-grid extraction + hard-decision decoding.

    *equalizer* selects the channel-estimation method:

    * ``"training_symbol"`` (the default) — one estimate per packet, held
      constant. Call ``estimate_channel()`` once with a demodulated training
      symbol before the first ``demodulate()``/``demodulate_soft()`` call.
    * ``"pilot_interp"`` — re-estimated every symbol from in-band pilots
      (frequency-domain linear interpolation); no separate estimation call
      needed.

    Input: complex64 IQ array, ``samples_per_ofdm_symbol`` samples/symbol.
    Output: uint8 array of bits, ``bits_per_ofdm_symbol`` per symbol.
    Raises ``ValueError`` if input is shorter than one OFDM symbol.
    """

    def __init__(self, cfg: OfdmConfig, equalizer: str = "training_symbol") -> None: ...
    def estimate_channel(self, training_iq: NDArray[np.complex64]) -> None:
        """Estimate and hold the channel from a demodulated training symbol.

        Only meaningful for the ``"training_symbol"`` equalizer; a no-op
        under ``"pilot_interp"``.
        """
        ...
    def demodulate(self, iq: NDArray[np.complex64]) -> NDArray[np.uint8]: ...
    def demodulate_soft(
        self, iq: NDArray[np.complex64]
    ) -> tuple[NDArray[np.complex64], NDArray[np.uint8]]:
        """Like ``demodulate()``, but also returns the pre-decision soft
        symbols (post-equalization, post-grid-extract) as
        ``(soft_symbols, bits)``, for building an ``OfdmRxFrame`` via
        ``build_ofdm_rx_frame``.
        """
        ...

class OfdmRxFrame:
    """Per-packet OFDM RX diagnostics.

    Fields that require acquisition or equalization stay ``None`` until the
    caller has actually run those stages.
    """

    @property
    def bits(self) -> NDArray[np.uint8]: ...
    @property
    def num_symbols(self) -> int: ...
    @property
    def evm_db(self) -> float | None: ...
    @property
    def cfo_hz(self) -> float | None: ...
    @property
    def timing_offset_samples(self) -> int | None: ...
    @property
    def channel_mse(self) -> float | None: ...

def build_ofdm_rx_frame(
    cfg: OfdmConfig,
    soft_symbols: NDArray[np.complex64],
    bits: NDArray[np.uint8],
) -> OfdmRxFrame:
    """Build an ``OfdmRxFrame`` from demodulated soft symbols and their
    corresponding hard-decided bits (as returned by
    ``OfdmDemod.demodulate_soft``, concatenated across all symbols in the
    packet). ``evm_db`` is always populated; ``cfo_hz``,
    ``timing_offset_samples``, and ``channel_mse`` require acquisition/
    equalization info not carried by this function alone and are ``None``.
    """
    ...

def ofdm_sync(
    iq: NDArray[np.complex64],
    fs: float,
    num_repeats: int,
    repeat_len: int,
    search_start: int,
    search_end: int,
    training_n_fft: int | None = None,
    training_cp_len: int | None = None,
) -> list[dict]:
    """Search an OFDM IQ buffer for a repeated-segment (Schmidl & Cox-style)
    preamble match.

    Pass *training_n_fft*/*training_cp_len* to enable wide-range integer-CFO
    recovery via a dedicated training symbol (must match the values used
    with ``generate_ofdm_preamble``); omit both for fractional-CFO-only
    acquisition (capture range ±½ the subcarrier spacing).

    Returns a list of dicts, sorted by descending score::

        {
            "start_sample":     int,    # sample offset of the preamble start
            "cfo_hz":           float,  # fractional CFO estimate (Hz)
            "integer_cfo_bins": int,    # whole subcarrier-spacing units
            "score":            float,  # normalized timing-metric score
        }

    Total CFO is ``cfo_hz + integer_cfo_bins * (fs / n_fft)``.
    ``integer_cfo_bins`` is always 0 unless a training symbol was supplied.
    """
    ...

def generate_ofdm_preamble(
    cfg: OfdmConfig,
    num_repeats: int,
    repeat_len: int,
    training_n_fft: int | None = None,
    training_cp_len: int | None = None,
) -> NDArray[np.complex64]:
    """Generate a repeated-segment preamble (plus training symbol, if
    *training_n_fft*/*training_cp_len* are given) for prepending before OFDM
    data symbols. See ``ofdm_sync`` for the matching acquisition function.
    """
    ...

# ── COFDM frame (MAC) layer ────────────────────────────────────────────────

class FramePacket:
    """A MAC-layer frame: an opaque byte payload plus metadata.

    *payload* is a uint8 array. *sequence_num*, *mcs_index*, and *flags* are
    carried in the frame header (for the ``"orion_sdr"`` header format).
    """

    def __init__(
        self,
        payload: NDArray[np.uint8],
        sequence_num: int = 0,
        mcs_index: int = 0,
        flags: int = 0,
    ) -> None: ...
    @property
    def payload(self) -> NDArray[np.uint8]: ...
    @property
    def sequence_num(self) -> int: ...
    @property
    def mcs_index(self) -> int: ...
    @property
    def flags(self) -> int: ...

class McsTable:
    """Maps each frame's ``mcs_index`` to a modulation-and-coding scheme
    (constellation + inner/outer FEC). The transmitter and receiver must share
    the same table.
    """

    def __init__(self) -> None: ...
    @staticmethod
    def default_ladder() -> "McsTable":
        """BPSK/QPSK/QAM-16/QAM-64, each with an LDPC(n512r12) inner code and a
        BCH(t=8) outer code."""
        ...
    def add(
        self,
        constellation: str,
        inner_kind: str = "none",
        inner_code: str = "",
        outer_kind: str = "none",
        outer_a: int = 0,
        outer_b: int = 0,
    ) -> None:
        """Append an MCS entry. *constellation* is ``"bpsk"``…``"qam256"``;
        *inner*/*outer* mirror ``OfdmConfig.with_inner_fec``/``with_outer_fec``.
        """
        ...
    @property
    def len(self) -> int: ...

class CodecCache:
    """A shared cache of constructed FEC codes (LDPC/BCH/Reed-Solomon).

    Building a code (the LDPC parity-check matrix especially) costs
    milliseconds and depends only on its parameters, so it need only be done
    once per link. Pass one ``CodecCache`` to an ``OfdmFrameMod``, an
    ``OfdmFrameStreamDemod``, and/or an ``OfdmFrameDemod`` (via ``cache=``) to
    build each code once and reuse it across all of them — a transmitter and
    receiver on the same MCS then share the built codes. Omitting ``cache=``
    gives each object its own private cache, which still amortizes across that
    object's own calls.
    """

    def __init__(self) -> None: ...

class OfdmFrameMod:
    """COFDM frame transmitter: serializes a ``FramePacket`` to a flat IQ
    stream (``[preamble + training][header][payload]``), applying the
    concatenated FEC chain configured on *cfg* and selected per frame by
    *mcs_table*.
    """

    def __init__(
        self,
        cfg: OfdmConfig,
        mcs_table: McsTable,
        num_repeats: int = 4,
        repeat_len: int = 16,
        cache: CodecCache | None = None,
    ) -> None: ...
    def modulate_frame(
        self, frame: FramePacket, per_frame_seed: int = 0
    ) -> NDArray[np.complex64]:
        """Modulate a whole frame into IQ. *per_frame_seed* supplies the
        scrambler seed for a per-frame-random configuration."""
        ...

class OfdmFrameStreamDemod:
    """Streaming COFDM frame receiver. Push IQ with ``feed()``; it locates
    preambles, corrects CFO, estimates the channel from the training symbol,
    decodes each frame, and returns the completed ones.
    """

    def __init__(
        self,
        cfg: OfdmConfig,
        mcs_table: McsTable,
        num_repeats: int = 4,
        repeat_len: int = 16,
        cache: CodecCache | None = None,
    ) -> None: ...
    def feed(self, iq: NDArray[np.complex64]) -> list[FramePacket]:
        """Feed IQ; return the frames that completed. Failed decodes are
        omitted (see ``feed_with_errors``)."""
        ...
    def feed_with_errors(
        self, iq: NDArray[np.complex64]
    ) -> list[tuple[FramePacket | None, str | None]]:
        """Like ``feed``, but each result is ``(frame_or_None, error_or_None)``
        so decode failures are observable."""
        ...
    def flush(self) -> list[FramePacket]:
        """Run a final decode pass over the residual buffer."""
        ...
    @property
    def buffered(self) -> int: ...
    def clear(self) -> None: ...

class OfdmFrameDemod:
    """Batch COFDM frame demodulator: decodes a single frame at a known start
    (*iq*[0] is the first sample after the preamble+training, already
    synchronized). The counterpart of ``OfdmFrameMod``; see
    ``OfdmFrameStreamDemod`` for the streaming path.
    """

    def __init__(
        self,
        cfg: OfdmConfig,
        mcs_table: McsTable,
        cache: CodecCache | None = None,
    ) -> None:
        """Build a batch demodulator. Pass ``cache=`` a ``CodecCache`` to reuse
        built FEC codes across calls (or share them with a modulator)."""
        ...
    def decode(self, iq: NDArray[np.complex64]) -> FramePacket:
        """Decode one frame whose IQ begins at the first post-preamble sample.
        Raises ``ValueError`` on a decode failure."""
        ...

# ---------------------------------------------------------------------------
# Conformant DVB-T on-air frame (EN 300 744)
# ---------------------------------------------------------------------------

class DvbTFrameParams:
    """Transmission parameters for a conformant DVB-T frame. *guard* is one of
    ``"1/32" | "1/16" | "1/8" | "1/4"``; *constellation* one of
    ``"qpsk" | "qam16" | "qam64"``; *code_rate* one of
    ``"1/2" | "2/3" | "3/4" | "5/6" | "7/8"``.
    """

    def __init__(
        self,
        guard: str,
        constellation: str,
        code_rate: str,
        frame_number: int = 0,
        cell_id: int = 0,
    ) -> None: ...
    @property
    def guard(self) -> str: ...
    @property
    def constellation(self) -> str: ...
    @property
    def code_rate(self) -> str: ...
    @property
    def frame_number(self) -> int: ...
    @property
    def cell_id(self) -> int: ...

class TpsWord:
    """The transmission parameters recovered from a frame's TPS carriers."""

    @property
    def frame_number(self) -> int: ...
    @property
    def constellation(self) -> str: ...
    @property
    def code_rate(self) -> str: ...
    @property
    def guard(self) -> str: ...
    @property
    def cell_id(self) -> int: ...

class DvbTFrame:
    """A modulated DVB-T frame: time-domain IQ plus its numerology."""

    @property
    def iq(self) -> NDArray[np.complex64]: ...
    @property
    def n_symbols(self) -> int: ...
    @property
    def samples_per_symbol(self) -> int: ...

class DvbTRxFrame:
    """The recovered contents of a DVB-T frame: TS payload and TPS word."""

    @property
    def payload(self) -> bytes: ...
    @property
    def tps(self) -> TpsWord: ...

class DvbTFrameMod:
    """A conformant, preamble-less DVB-T frame modulator. Built from
    ``DvbTFrameParams``; ``modulate`` produces one frame per call.
    Out-of-band spectral shaping is off by default — see ``with_symbol_window``
    and ``with_tx_lowpass``."""

    def __init__(self, params: DvbTFrameParams) -> None: ...
    def with_symbol_window(self, roll_off: int) -> DvbTFrameMod:
        """Return a modulator that applies a *roll_off*-sample raised-cosine taper
        to each symbol's edges (default 0 = off, on-air frame byte-identical).
        DVB-T is preamble-less, so every symbol is tapered. Only RX-transparent
        when paired with a matching ``DvbTFrameDemod.with_rx_window_backoff``."""
        ...
    def with_tx_lowpass(
        self, num_taps: int, stopband_db: float = 60.0
    ) -> DvbTFrameMod:
        """Return a modulator that applies a TX baseband low-pass (spectral mask)
        across the assembled frame, after any symbol taper (default: off). The
        cutoff is placed against DVB-T's fixed ±852-of-2048 band edge, so only the
        length and stop-band target are yours. Unlike the taper this is not bounded
        by the windowing ceiling, so its attenuation stacks on top. Size it with
        ``dvb_t_tx_lowpass_suggested_taps`` and check it with
        ``dvb_t_tx_lowpass_fits_guard``."""
        ...
    def modulate(self, payload: NDArray[np.uint8]) -> DvbTFrame:
        """Modulate *payload* (MPEG-TS payload bytes) into one conformant,
        preamble-less DVB-T frame."""
        ...

class DvbTFrameDemod:
    """A conformant, preamble-less DVB-T frame demodulator. Built from
    ``DvbTFrameParams``; ``decode`` recovers one frame per call. Integer-CFO
    correction is off by default — enable it with
    ``with_integer_cfo_correction(True)`` (a link-constant builder returning a new
    demod)."""

    def __init__(self, params: DvbTFrameParams) -> None: ...
    def with_integer_cfo_correction(self, on: bool) -> DvbTFrameDemod:
        """Return a demod with internal integer-CFO correction enabled/disabled.
        When on, ``decode`` estimates the whole-subcarrier offset from the
        continual pilots and rotates it out before demapping."""
        ...
    @property
    def integer_cfo_correction(self) -> bool: ...
    def with_rx_window_backoff(self, backoff: int) -> DvbTFrameDemod:
        """Return a demod whose per-symbol FFT window sits *backoff* samples
        earlier in the guard (default 0). The receiver half of the TX shaping
        pair: a taper and a mask both live in guard samples, and only a backed-off
        window leaves them outside the FFT. Capped at
        ``dvb_t_max_rx_window_backoff()`` by the scattered-pilot grid, not by the
        guard interval."""
        ...
    @property
    def rx_window_backoff(self) -> int: ...
    def decode(
        self,
        iq: NDArray[np.complex64],
        n_symbols: int,
        payload_len: int,
    ) -> DvbTRxFrame:
        """Demodulate one conformant DVB-T frame, acquiring the symbol grid from
        the guard interval (no preamble). *n_symbols* comes from the paired
        ``DvbTFrameMod.modulate`` result; *payload_len* is the original payload
        byte count. Raises ``ValueError`` on any acquisition/decode failure.
        """
        ...

def nb_bandwidth_fs(mode: str) -> float:
    """Sample rate (S/s) for a narrowband DVB-T mode: ``"333khz" | "1mhz" |
    "2mhz"``. ``fs = occupied_hz * 2048/1705``."""
    ...

def nb_bandwidth_occupied_hz(mode: str) -> float:
    """Nominal occupied RF bandwidth (Hz) for a narrowband DVB-T mode."""
    ...

# ---------------------------------------------------------------------------
# DVB-T spectral-shaping sizing helpers
#
# The arithmetic behind choosing *roll_off*, *num_taps* and *backoff*. ``TxLowpass``
# is not a Python class — DVB-T's band edge is fixed, so a mask is fully specified
# by its length and stop-band target — hence these are module functions.
# ---------------------------------------------------------------------------

def dvb_t_cp_len(guard: str) -> int:
    """Cyclic-prefix length in samples for a DVB-T 2K guard interval: 64 / 128 /
    256 / 512 for ``"1/32" | "1/16" | "1/8" | "1/4"``. This is the guard the two TX
    shaping levers and the RX window back-off share."""
    ...

def dvb_t_max_rx_window_backoff() -> int:
    """The largest usable RX FFT-window back-off for DVB-T 2K: **85 samples**,
    whatever the guard interval. The cap is the scattered-pilot grid, not the
    guard — the estimate is only sampled every 12 carriers, and past
    ``n_fft / (2 * 12)`` the interpolation aliases. So the shaping budget saturates
    at 32 / 64 / 85 / 85 for G1/32…G1/4, making G1/8 the sweet spot."""
    ...

def dvb_t_tx_lowpass_suggested_taps(stopband_db: float = 60.0) -> int:
    """The shortest mask whose transition fits inside DVB-T's null band (the 343 of
    2048 inactive bins) at *stopband_db* — a starting point for
    ``DvbTFrameMod.with_tx_lowpass``, to be checked with
    ``dvb_t_tx_lowpass_fits_guard``."""
    ...

def dvb_t_tx_lowpass_group_delay(num_taps: int) -> int:
    """A mask's group delay in samples, ``(num_taps - 1) // 2`` after the odd/>=3
    clamp — its reach on each side, and what the guard budget must cover."""
    ...

def dvb_t_tx_lowpass_fits_guard(
    guard: str, num_taps: int, roll_off: int, backoff: int
) -> bool:
    """Whether a *num_taps* mask and a *roll_off*-sample taper both fit the guard a
    receiver at *backoff* discards: ``roll_off + group_delay <= min(cp_len -
    backoff, backoff)``. Pass ``roll_off=0`` when windowing is off. Maximized at
    ``backoff = cp_len/2``, but only reachable up to
    ``dvb_t_max_rx_window_backoff()``."""
    ...

# ---------------------------------------------------------------------------
# Conformant DVB-T super-frame (four frames) and streaming receiver
# ---------------------------------------------------------------------------

class DvbTSuperFrameParams:
    """Transmission parameters for a conformant DVB-T super-frame. Like
    ``DvbTFrameParams`` but with the full 16-bit cell id (split across the four
    frames)."""

    def __init__(
        self,
        guard: str,
        constellation: str,
        code_rate: str,
        cell_id: int = 0,
    ) -> None: ...
    @property
    def guard(self) -> str: ...
    @property
    def constellation(self) -> str: ...
    @property
    def code_rate(self) -> str: ...
    @property
    def cell_id(self) -> int: ...

class DvbTSuperFrame:
    """A modulated DVB-T super-frame: the IQ of four consecutive frames plus the
    numerology to re-slice them."""

    @property
    def iq(self) -> NDArray[np.complex64]: ...
    @property
    def symbols_per_frame(self) -> int: ...
    @property
    def samples_per_symbol(self) -> int: ...
    @property
    def frame_payload_lens(self) -> list[int]: ...
    @property
    def n_symbols(self) -> int: ...

class DvbTRxSuperFrame:
    """The recovered contents of a DVB-T super-frame: concatenated payload and the
    reassembled 16-bit cell id."""

    @property
    def payload(self) -> bytes: ...
    @property
    def cell_id(self) -> int: ...

class DvbTSuperFrameMod:
    """A conformant DVB-T super-frame modulator (four frames, alternating TPS sync
    + a 16-bit cell id split across them). Built from ``DvbTSuperFrameParams``;
    ``modulate`` produces one super-frame per call."""

    def __init__(self, params: DvbTSuperFrameParams) -> None: ...
    def with_symbol_window(self, roll_off: int) -> DvbTSuperFrameMod:
        """Return a modulator that tapers every symbol of every constituent frame
        (see ``DvbTFrameMod.with_symbol_window``). Being per-symbol, the taper
        simply propagates to each frame."""
        ...
    def with_tx_lowpass(
        self, num_taps: int, stopband_db: float = 60.0
    ) -> DvbTSuperFrameMod:
        """Return a modulator that applies a TX baseband mask to the super-frame
        (see ``DvbTFrameMod.with_tx_lowpass`` for sizing). Note the scope: the mask
        runs **once over the four concatenated frames**, not per frame — the three
        interior seams are continuous on air, and per-frame filtering would leave
        the filter's edge transient at every one of them."""
        ...
    def modulate(self, payload: NDArray[np.uint8]) -> DvbTSuperFrame:
        """Modulate *payload* into one conformant DVB-T super-frame."""
        ...

class DvbTSuperFrameDemod:
    """A conformant DVB-T super-frame demodulator. Built from
    ``DvbTSuperFrameParams``; ``decode`` recovers one super-frame per call.
    Integer-CFO correction is off by default — enable it with
    ``with_integer_cfo_correction(True)`` (delegated to each constituent frame)."""

    def __init__(self, params: DvbTSuperFrameParams) -> None: ...
    def with_integer_cfo_correction(self, on: bool) -> DvbTSuperFrameDemod:
        """Return a super-frame demod with internal integer-CFO correction
        enabled/disabled on every constituent frame."""
        ...
    @property
    def integer_cfo_correction(self) -> bool: ...
    def with_rx_window_backoff(self, backoff: int) -> DvbTSuperFrameDemod:
        """Return a super-frame demod with the FFT-window back-off applied to every
        constituent frame (see ``DvbTFrameDemod.with_rx_window_backoff``)."""
        ...
    @property
    def rx_window_backoff(self) -> int: ...
    def decode(
        self,
        iq: NDArray[np.complex64],
        symbols_per_frame: int,
        frame_payload_lens: list[int],
    ) -> DvbTRxSuperFrame:
        """Demodulate one conformant DVB-T super-frame, verifying the frame-number
        sequence 0,1,2,3 and reassembling the 16-bit cell id. *symbols_per_frame*
        and *frame_payload_lens* come from the paired ``DvbTSuperFrameMod.modulate``
        result. Raises ``ValueError`` on failure.
        """
        ...

class DvbTFrameStreamDemod:
    """Streaming DVB-T receiver. Push IQ with ``feed()``; it guard-interval-
    acquires and decodes each fixed-size frame as its samples arrive, returning
    the completed ones. ``flush()`` runs a final pass over the residual buffer.
    Pass ``integer_cfo_correction=True`` to remove each frame's whole-subcarrier
    CFO internally, and ``rx_window_backoff=b`` to receive a spectrally-shaped
    stream (both link-constant knobs, set once here).
    """

    def __init__(
        self,
        params: DvbTFrameParams,
        n_symbols: int,
        payload_len: int,
        integer_cfo_correction: bool = False,
        rx_window_backoff: int = 0,
    ) -> None: ...
    @property
    def integer_cfo_correction(self) -> bool: ...
    @property
    def rx_window_backoff(self) -> int: ...
    def feed(self, iq: NDArray[np.complex64]) -> list[DvbTRxFrame]:
        """Feed IQ; return the frames that completed. Failed decodes are omitted
        (see ``feed_with_errors``)."""
        ...
    def feed_with_errors(
        self, iq: NDArray[np.complex64]
    ) -> list[tuple[DvbTRxFrame | None, str | None]]:
        """Like ``feed``, but each result is ``(frame_or_None, error_or_None)`` so
        decode failures are observable."""
        ...
    def flush(self) -> list[DvbTRxFrame]:
        """Run a final decode pass over the residual buffer."""
        ...
    @property
    def buffered(self) -> int: ...
    def clear(self) -> None: ...