orion-sdr 0.0.69

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
// Copyright (c) 2026 G & R Associates LLC
// SPDX-License-Identifier: MIT OR Apache-2.0

// src/python/ofdm_frame.rs — PyO3 bindings for the COFDM frame (MAC) layer.
//
// Exposes the frame modulator (`OfdmFrameMod`) and the streaming frame
// receiver (`OfdmFrameStreamDemod`, feed/flush like `Psk31Stream`), plus the
// `FramePacket`/`Mcs` support types. The FEC/interleaver/scrambler/CRC/header
// scheme is configured on `OfdmConfig` via its `with_*` methods (see
// `python/ofdm.rs`); an `McsTable` maps each frame's `mcs_index` to a
// (constellation, inner FEC, outer FEC) triple.

use num_complex::Complex32;
use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;

use super::ofdm::PyOfdmConfig;
use crate::demodulate::{OfdmFrameDemod, OfdmFrameStreamDemod};
use crate::fec::{
    ConvCode, FrameMetadata, FramePacket, InnerFec, LdpcCode, OuterFec, PunctureRate,
};
use crate::modulate::{CodecCache, ConstellationOrder, Mcs, McsTable, OfdmFrameMod};
use crate::sync::OfdmPreamble;
use std::sync::Arc;

// ── FramePacket ─────────────────────────────────────────────────────────────

/// A MAC-layer frame: metadata (sequence number, MCS index, flags) plus an
/// opaque byte payload.
#[pyclass(name = "FramePacket", skip_from_py_object)]
#[derive(Clone)]
pub struct PyFramePacket {
    sequence_num: u32,
    mcs_index: u8,
    flags: u8,
    payload: Vec<u8>,
}

#[pymethods]
impl PyFramePacket {
    #[new]
    #[pyo3(signature = (payload, sequence_num = 0, mcs_index = 0, flags = 0))]
    fn new(
        payload: PyReadonlyArray1<'_, u8>,
        sequence_num: u32,
        mcs_index: u8,
        flags: u8,
    ) -> PyResult<Self> {
        Ok(Self {
            sequence_num,
            mcs_index,
            flags,
            payload: payload.as_slice()?.to_vec(),
        })
    }

    #[getter]
    fn payload<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<u8>> {
        self.payload.clone().into_pyarray(py)
    }
    #[getter]
    fn sequence_num(&self) -> u32 {
        self.sequence_num
    }
    #[getter]
    fn mcs_index(&self) -> u8 {
        self.mcs_index
    }
    #[getter]
    fn flags(&self) -> u8 {
        self.flags
    }
}

impl PyFramePacket {
    fn to_frame(&self) -> FramePacket {
        FramePacket {
            metadata: FrameMetadata {
                sequence_num: self.sequence_num,
                mcs_index: self.mcs_index,
                flags: self.flags,
            },
            payload: self.payload.clone(),
        }
    }

    fn from_frame(frame: FramePacket) -> Self {
        Self {
            sequence_num: frame.metadata.sequence_num,
            mcs_index: frame.metadata.mcs_index,
            flags: frame.metadata.flags,
            payload: frame.payload,
        }
    }
}

// ── McsTable ──────────────────────────────────────────────────────────────

/// Maps each frame's `mcs_index` to a modulation-and-coding scheme. Build it
/// by adding entries; the sender and receiver must share the same table.
#[pyclass(name = "McsTable", skip_from_py_object)]
#[derive(Clone)]
pub struct PyMcsTable {
    entries: Vec<Mcs>,
}

#[pymethods]
impl PyMcsTable {
    #[new]
    fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// The default ladder: BPSK/QPSK/QAM-16/QAM-64, each with an LDPC(n512r12)
    /// inner code and a BCH(t=8) outer code.
    #[staticmethod]
    fn default_ladder() -> Self {
        let t = McsTable::default_ladder();
        // Reconstruct entries via public accessors.
        let mut entries = Vec::new();
        for i in 0..t.len() {
            entries.push(t.get(i as u8).unwrap());
        }
        Self { entries }
    }

    /// Appends an MCS entry. `constellation` is `"bpsk"|"qpsk"|"qam16"|
    /// "qam64"|"qam256"`; `inner`/`outer` mirror
    /// `OfdmConfig.with_inner_fec`/`with_outer_fec` (`inner_kind`, `inner_code`,
    /// `outer_kind`, `outer_a`, `outer_b`).
    #[pyo3(signature = (constellation, inner_kind = "none", inner_code = "", outer_kind = "none", outer_a = 0, outer_b = 0))]
    #[allow(clippy::too_many_arguments)]
    fn add(
        &mut self,
        constellation: &str,
        inner_kind: &str,
        inner_code: &str,
        outer_kind: &str,
        outer_a: usize,
        outer_b: usize,
    ) -> PyResult<()> {
        let c = match constellation {
            "bpsk" => ConstellationOrder::Bpsk,
            "qpsk" => ConstellationOrder::Qpsk,
            "qam16" => ConstellationOrder::Qam16,
            "qam64" => ConstellationOrder::Qam64,
            "qam256" => ConstellationOrder::Qam256,
            other => {
                return Err(PyValueError::new_err(format!(
                    "McsTable.add: unknown constellation {other:?}"
                )));
            }
        };
        let inner = match inner_kind {
            "none" => InnerFec::None,
            "ldpc" => InnerFec::Ldpc(parse_ldpc(inner_code)?),
            "convolutional" | "conv" => InnerFec::Convolutional {
                rate: parse_rate(inner_code)?,
                code: ConvCode::K5,
            },
            "convolutional_k7" | "conv_k7" | "dvb_t" => InnerFec::Convolutional {
                rate: parse_rate(inner_code)?,
                code: ConvCode::DvbK7,
            },
            other => {
                return Err(PyValueError::new_err(format!(
                    "McsTable.add: unknown inner FEC {other:?}"
                )));
            }
        };
        let outer = match outer_kind {
            "none" => OuterFec::None,
            "bch" => OuterFec::Bch { t: outer_a },
            "reed_solomon" | "rs" => OuterFec::ReedSolomon {
                n: outer_a,
                n_parity: outer_b,
            },
            other => {
                return Err(PyValueError::new_err(format!(
                    "McsTable.add: unknown outer FEC {other:?}"
                )));
            }
        };
        self.entries.push(Mcs::new(c, inner, outer));
        Ok(())
    }

    #[getter]
    fn len(&self) -> usize {
        self.entries.len()
    }
}

impl PyMcsTable {
    fn to_table(&self) -> PyResult<McsTable> {
        if self.entries.is_empty() {
            return Err(PyValueError::new_err(
                "McsTable must have at least one entry",
            ));
        }
        Ok(McsTable::new(self.entries.clone()))
    }
}

fn parse_ldpc(s: &str) -> PyResult<LdpcCode> {
    match s {
        "n512r12" => Ok(LdpcCode::N512R12),
        "n576r23" => Ok(LdpcCode::N576R23),
        "n512r34" => Ok(LdpcCode::N512R34),
        other => Err(PyValueError::new_err(format!(
            "unknown LDPC code {other:?}"
        ))),
    }
}

fn parse_rate(s: &str) -> PyResult<PunctureRate> {
    match s {
        "1/2" => Ok(PunctureRate::R1_2),
        "2/3" => Ok(PunctureRate::R2_3),
        "3/4" => Ok(PunctureRate::R3_4),
        "5/6" => Ok(PunctureRate::R5_6),
        "7/8" => Ok(PunctureRate::R7_8),
        other => Err(PyValueError::new_err(format!(
            "unknown puncture rate {other:?}"
        ))),
    }
}

fn build_preamble(
    num_repeats: usize,
    repeat_len: usize,
    n_fft: usize,
    cp_len: usize,
) -> OfdmPreamble {
    OfdmPreamble::new(num_repeats, repeat_len).with_training_symbol(n_fft, cp_len)
}

// ── CodecCache ──────────────────────────────────────────────────────────────

/// A shared cache of constructed FEC codes (LDPC/BCH/Reed–Solomon).
///
/// Building a code — the LDPC parity-check matrix above all — costs
/// milliseconds and is a pure function of its parameters, so it need only be
/// done once per link. Pass one `CodecCache` to an `OfdmFrameMod`, an
/// `OfdmFrameStreamDemod`, and/or an `OfdmFrameDemod` (via their `cache=`
/// argument) to build each code once and reuse it across all of them — e.g. 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.
#[pyclass(name = "CodecCache")]
pub struct PyCodecCache {
    inner: Arc<CodecCache>,
}

#[pymethods]
impl PyCodecCache {
    #[new]
    fn new() -> Self {
        Self {
            inner: Arc::new(CodecCache::new()),
        }
    }
}

// ── OfdmFrameMod ────────────────────────────────────────────────────────────

/// COFDM frame transmitter: serializes a `FramePacket` to a flat IQ stream
/// (`[preamble + training][header][payload]`), applying the concatenated FEC
/// chain configured on the `OfdmConfig` and selected per frame by the MCS
/// table.
#[pyclass(name = "OfdmFrameMod")]
pub struct PyOfdmFrameMod {
    inner: OfdmFrameMod,
}

#[pymethods]
impl PyOfdmFrameMod {
    /// The preamble is `num_repeats` × `repeat_len` Schmidl & Cox segments
    /// followed by a training symbol sized to the config's FFT/CP. Pass
    /// `cache=` a `CodecCache` to share built FEC codes with other frame objects.
    #[new]
    #[pyo3(signature = (cfg, mcs_table, num_repeats = 4, repeat_len = 16, cache = None))]
    fn new(
        cfg: &PyOfdmConfig,
        mcs_table: &PyMcsTable,
        num_repeats: usize,
        repeat_len: usize,
        cache: Option<&PyCodecCache>,
    ) -> PyResult<Self> {
        let config = cfg.inner_config();
        let pre = build_preamble(
            num_repeats,
            repeat_len,
            config.carrier_plan.n_fft(),
            config.carrier_plan.cp_len(),
        );
        let cache = cache
            .map(|c| Arc::clone(&c.inner))
            .unwrap_or_else(|| Arc::new(CodecCache::new()));
        Ok(Self {
            inner: OfdmFrameMod::with_cache(config, mcs_table.to_table()?, pre, cache),
        })
    }

    /// Modulates a whole frame into IQ. `per_frame_seed` supplies the
    /// scrambler seed for a per-frame-random configuration (ignored otherwise).
    #[pyo3(signature = (frame, per_frame_seed = 0))]
    fn modulate_frame<'py>(
        &self,
        py: Python<'py>,
        frame: &PyFramePacket,
        per_frame_seed: u32,
    ) -> Bound<'py, PyArray1<Complex32>> {
        let iq = self.inner.modulate_frame(&frame.to_frame(), per_frame_seed);
        iq.into_pyarray(py)
    }
}

// ── 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. `flush()` runs a final
/// pass over the residual buffer.
#[pyclass(name = "OfdmFrameStreamDemod")]
pub struct PyOfdmFrameStreamDemod {
    inner: OfdmFrameStreamDemod,
}

#[pymethods]
impl PyOfdmFrameStreamDemod {
    /// Pass `cache=` a `CodecCache` to share built FEC codes with other frame
    /// objects (e.g. the paired `OfdmFrameMod`).
    #[new]
    #[pyo3(signature = (cfg, mcs_table, num_repeats = 4, repeat_len = 16, cache = None))]
    fn new(
        cfg: &PyOfdmConfig,
        mcs_table: &PyMcsTable,
        num_repeats: usize,
        repeat_len: usize,
        cache: Option<&PyCodecCache>,
    ) -> PyResult<Self> {
        let config = cfg.inner_config();
        let pre = build_preamble(
            num_repeats,
            repeat_len,
            config.carrier_plan.n_fft(),
            config.carrier_plan.cp_len(),
        );
        let cache = cache
            .map(|c| Arc::clone(&c.inner))
            .unwrap_or_else(|| Arc::new(CodecCache::new()));
        Ok(Self {
            inner: OfdmFrameStreamDemod::with_cache(config, mcs_table.to_table()?, pre, cache),
        })
    }

    /// Feeds IQ and returns the frames that completed. Frames that failed to
    /// decode (bad CRC/FEC/header) are omitted; use `feed_with_errors` to see
    /// the error reasons.
    fn feed<'py>(
        &mut self,
        py: Python<'py>,
        iq: PyReadonlyArray1<'py, Complex32>,
    ) -> PyResult<Vec<PyFramePacket>> {
        let results = self.inner.feed(iq.as_slice()?);
        let _ = py;
        Ok(results
            .into_iter()
            .filter_map(|r| r.ok().map(|f| PyFramePacket::from_frame(f.packet)))
            .collect())
    }

    /// Like `feed`, but returns a list of `(frame_or_None, error_or_None)`
    /// tuples so callers can observe decode failures.
    fn feed_with_errors(
        &mut self,
        iq: PyReadonlyArray1<'_, Complex32>,
    ) -> PyResult<Vec<(Option<PyFramePacket>, Option<String>)>> {
        let results = self.inner.feed(iq.as_slice()?);
        Ok(results
            .into_iter()
            .map(|r| match r {
                Ok(f) => (Some(PyFramePacket::from_frame(f.packet)), None),
                Err(e) => (None, Some(e.to_string())),
            })
            .collect())
    }

    /// Runs a final decode pass over the residual buffer.
    fn flush(&mut self) -> Vec<PyFramePacket> {
        self.inner
            .flush()
            .into_iter()
            .filter_map(|r| r.ok().map(|f| PyFramePacket::from_frame(f.packet)))
            .collect()
    }

    /// Number of accumulated (not-yet-consumed) samples.
    #[getter]
    fn buffered(&self) -> usize {
        self.inner.len()
    }

    /// Discards the accumulated buffer.
    fn clear(&mut self) {
        self.inner.clear();
    }
}

// ── OfdmFrameDemod (batch) ──────────────────────────────────────────────────

/// The 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`. Pass `cache=` a `CodecCache`
/// to reuse built FEC codes across calls (or share them with a modulator).
#[pyclass(name = "OfdmFrameDemod")]
pub struct PyOfdmFrameDemod {
    inner: OfdmFrameDemod,
}

#[pymethods]
impl PyOfdmFrameDemod {
    #[new]
    #[pyo3(signature = (cfg, mcs_table, cache = None))]
    fn new(
        cfg: &PyOfdmConfig,
        mcs_table: &PyMcsTable,
        cache: Option<&PyCodecCache>,
    ) -> PyResult<Self> {
        let config = cfg.inner_config();
        let cache = cache
            .map(|c| Arc::clone(&c.inner))
            .unwrap_or_else(|| Arc::new(CodecCache::new()));
        Ok(Self {
            inner: OfdmFrameDemod::with_cache(config, mcs_table.to_table()?, cache),
        })
    }

    /// Decodes one frame whose IQ begins at the first post-preamble sample.
    /// Raises `ValueError` on a decode failure.
    fn decode(&self, iq: PyReadonlyArray1<'_, Complex32>) -> PyResult<PyFramePacket> {
        let frame = self
            .inner
            .decode(iq.as_slice()?)
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(PyFramePacket::from_frame(frame))
    }
}

pub(crate) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyCodecCache>()?;
    m.add_class::<PyFramePacket>()?;
    m.add_class::<PyMcsTable>()?;
    m.add_class::<PyOfdmFrameMod>()?;
    m.add_class::<PyOfdmFrameStreamDemod>()?;
    m.add_class::<PyOfdmFrameDemod>()?;
    Ok(())
}