Skip to main content

rtlsdr_nusb/
config.rs

1//! Validated configuration, independent of USB access.
2
3use crate::{Error, Result};
4use std::marker::PhantomData;
5
6/// Representation delivered to the application.
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
8pub enum SampleFormat {
9    /// Interleaved unsigned eight-bit I/Q pairs, as delivered by USB.
10    RawIq,
11    /// Complex floats, with each component mapped from `0..=255` to `-1..=1`.
12    F32Iq,
13}
14
15mod private {
16    pub trait Sealed {
17        type Processor: crate::rx::processing::Processor;
18    }
19}
20/// Sealed compile-time sample format used by devices and streams.
21pub trait SampleMode: private::Sealed + Copy + core::fmt::Debug + Eq + 'static {
22    /// Runtime equivalent of this mode.
23    const FORMAT: SampleFormat;
24}
25/// Raw unsigned eight-bit complex samples.
26#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
27pub struct RawIq;
28/// Converted complex `f32` samples (the default).
29#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
30pub struct F32Iq;
31impl private::Sealed for RawIq {
32    type Processor = crate::rx::processing::RawProcessor;
33}
34impl private::Sealed for F32Iq {
35    type Processor = crate::rx::processing::IqProcessor;
36}
37impl SampleMode for RawIq {
38    const FORMAT: SampleFormat = SampleFormat::RawIq;
39}
40impl SampleMode for F32Iq {
41    const FORMAT: SampleFormat = SampleFormat::F32Iq;
42}
43
44/// Tuner gain policy. Manual gain is approximate, using the reference driver's
45/// measured 2.3 dB LNA and 1.2 dB mixer steps with a fixed VGA setting.
46#[derive(Clone, Copy, Debug, Default, PartialEq)]
47pub enum GainConfig {
48    /// Let the tuner control LNA and mixer gain automatically.
49    #[default]
50    Auto,
51    /// Requested LNA + mixer gain in dB, in `0.0..=52.5`.
52    Manual(f32),
53}
54
55/// Direct ADC input for frequencies below 28.8 MHz on non-V4 dongles.
56/// Requires appropriate board wiring. Blog V4 uses its own upconverter instead.
57#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
58pub enum DirectSampling {
59    /// Use the RF tuner; reject frequencies below its supported range.
60    #[default]
61    Off,
62    /// Use ADC I below 28.8 MHz, automatically returning to the tuner above it.
63    I,
64    /// Use ADC Q below 28.8 MHz, automatically returning to the tuner above it.
65    Q,
66}
67
68#[derive(Clone, Debug, PartialEq)]
69pub(crate) struct Settings {
70    pub frequency_hz: u64,
71    pub sample_rate_hz: u32,
72    pub gain: GainConfig,
73    pub correction_ppm: i32,
74    pub bias_tee: bool,
75    pub direct_sampling: DirectSampling,
76}
77impl Default for Settings {
78    fn default() -> Self {
79        Self {
80            frequency_hz: 100_000_000,
81            sample_rate_hz: 2_048_000,
82            gain: GainConfig::Auto,
83            correction_ppm: 0,
84            bias_tee: false,
85            direct_sampling: DirectSampling::Off,
86        }
87    }
88}
89impl Settings {
90    pub(crate) fn validate(&self) -> Result<()> {
91        if !(1..=1_766_000_000).contains(&self.frequency_hz) {
92            return Err(Error::invalid_config(
93                "frequency_hz",
94                "must be in 1..=1766000000; the actual minimum depends on the tuner and direct sampling",
95            ));
96        }
97        if !(900_001..=3_200_000).contains(&self.sample_rate_hz) {
98            return Err(Error::invalid_config(
99                "sample_rate_hz",
100                "must be in 900001..=3200000 samples/s",
101            ));
102        }
103        if let GainConfig::Manual(db) = self.gain
104            && (!db.is_finite() || !(0.0..=52.5).contains(&db))
105        {
106            return Err(Error::invalid_config(
107                "gain",
108                "manual gain must be finite and in 0..=52.5 dB",
109            ));
110        }
111        if !(-488..=488).contains(&self.correction_ppm) {
112            return Err(Error::invalid_config(
113                "correction_ppm",
114                "must be in -488..=488 for the signed 14-bit correction register",
115            ));
116        }
117        Ok(())
118    }
119}
120
121/// Complete, statically validated receiver configuration.
122///
123/// Device-dependent frequency validation happens during open/configuration.
124/// The first release supports sample rates in `900001..=3200000` samples/s;
125/// rates above 2.4 MS/s may lose samples depending on the host and receiver.
126#[derive(Clone, Debug, PartialEq)]
127pub struct Config<M: SampleMode = F32Iq> {
128    pub(crate) settings: Settings,
129    mode: PhantomData<fn() -> M>,
130}
131impl<M: SampleMode> Default for Config<M> {
132    fn default() -> Self {
133        Self {
134            settings: Settings::default(),
135            mode: PhantomData,
136        }
137    }
138}
139impl Config<F32Iq> {
140    /// Start building a configuration without touching hardware.
141    pub fn builder() -> ConfigBuilder<F32Iq> {
142        ConfigBuilder::default()
143    }
144}
145impl<M: SampleMode> Config<M> {
146    /// Requested center frequency in Hz.
147    pub fn frequency_hz(&self) -> u64 {
148        self.settings.frequency_hz
149    }
150    /// Requested complex sample rate in samples/s.
151    pub fn sample_rate_hz(&self) -> u32 {
152        self.settings.sample_rate_hz
153    }
154    /// Selected sample representation.
155    pub fn sample_format(&self) -> SampleFormat {
156        M::FORMAT
157    }
158    /// Gain policy.
159    pub fn gain(&self) -> GainConfig {
160        self.settings.gain
161    }
162    /// Crystal correction in parts per million.
163    pub fn correction_ppm(&self) -> i32 {
164        self.settings.correction_ppm
165    }
166    /// Whether RF bias power is requested.
167    pub fn bias_tee(&self) -> bool {
168        self.settings.bias_tee
169    }
170    /// Low-frequency direct sampling policy.
171    pub fn direct_sampling(&self) -> DirectSampling {
172        self.settings.direct_sampling
173    }
174}
175
176/// Builder for reusable receiver configurations.
177#[derive(Clone, Debug)]
178pub struct ConfigBuilder<M: SampleMode = F32Iq> {
179    config: Config<M>,
180}
181impl Default for ConfigBuilder<F32Iq> {
182    fn default() -> Self {
183        Self {
184            config: Config::default(),
185        }
186    }
187}
188impl<M: SampleMode> ConfigBuilder<M> {
189    /// Set center frequency in Hz (hardware-specific limits are checked on open).
190    pub fn frequency_hz(mut self, value: u64) -> Self {
191        self.config.settings.frequency_hz = value;
192        self
193    }
194    /// Set the sample rate in `900001..=3200000` complex samples/s.
195    pub fn sample_rate_hz(mut self, value: u32) -> Self {
196        self.config.settings.sample_rate_hz = value;
197        self
198    }
199    /// Set tuner gain policy.
200    pub fn gain(mut self, value: GainConfig) -> Self {
201        self.config.settings.gain = value;
202        self
203    }
204    /// Set crystal correction in parts per million.
205    pub fn correction_ppm(mut self, value: i32) -> Self {
206        self.config.settings.correction_ppm = value;
207        self
208    }
209    /// Enable or disable GPIO 0 RF bias power (off by default).
210    pub fn bias_tee(mut self, value: bool) -> Self {
211        self.config.settings.bias_tee = value;
212        self
213    }
214    /// Select automatic low-frequency direct sampling behavior.
215    pub fn direct_sampling(mut self, value: DirectSampling) -> Self {
216        self.config.settings.direct_sampling = value;
217        self
218    }
219    /// Validate and build the configuration.
220    pub fn build(self) -> Result<Config<M>> {
221        self.config.settings.validate()?;
222        Ok(self.config)
223    }
224}
225impl ConfigBuilder<F32Iq> {
226    /// Deliver raw unsigned eight-bit I/Q blocks instead of complex floats.
227    pub fn raw_iq(self) -> ConfigBuilder<RawIq> {
228        ConfigBuilder {
229            config: Config {
230                settings: self.config.settings,
231                mode: PhantomData,
232            },
233        }
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    #[test]
241    fn invalid_settings_are_rejected_before_open() {
242        for hz in [0, 1_766_000_001, u64::MAX] {
243            assert!(Config::builder().frequency_hz(hz).build().is_err());
244        }
245        for rate in [0, 900_000, 3_200_001, u32::MAX] {
246            assert!(Config::builder().sample_rate_hz(rate).build().is_err());
247        }
248        for gain in [f32::NAN, f32::INFINITY, -0.1, 52.6] {
249            assert!(
250                Config::builder()
251                    .gain(GainConfig::Manual(gain))
252                    .build()
253                    .is_err()
254            );
255        }
256        for ppm in [-489, 489, i32::MIN, i32::MAX] {
257            assert!(Config::builder().correction_ppm(ppm).build().is_err());
258        }
259    }
260    #[test]
261    fn sample_rate_limits_are_independent_of_ppm() {
262        for ppm in [-488, -100, 0, 100, 488] {
263            for (rate, accepted) in [
264                (900_000, false),
265                (900_001, true),
266                (3_200_000, true),
267                (3_200_001, false),
268            ] {
269                assert_eq!(
270                    Config::builder()
271                        .sample_rate_hz(rate)
272                        .correction_ppm(ppm)
273                        .build()
274                        .is_ok(),
275                    accepted
276                );
277            }
278        }
279    }
280}