Skip to main content

hydrasdr_rs/rx/
mod.rs

1//! Typed receive streams backed by one persistent USB queue.
2
3pub(crate) mod processing;
4mod queue;
5mod receiver;
6
7use crate::{
8    Complex32,
9    config::{F32Iq, RawAdc, SampleMode},
10    errors::Result,
11    session::RxStreamClaim,
12    usb::NusbTransport,
13};
14use nusb::MaybeFuture;
15pub use queue::MAX_F32_IQ_SAMPLES_PER_TRANSFER;
16use receiver::Receiver;
17use std::time::Duration;
18
19/// Counters collected during a receive stream.
20///
21/// These counters describe USB completions observed by the host. RFOne bulk data
22/// has no sequence number, so the driver cannot detect samples lost in the device
23/// before a USB transfer completes (for example, when the application stops
24/// polling long enough to exhaust the host transfer queue).
25#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
26pub struct StreamingStats {
27    /// Number of USB completions consumed by the driver.
28    pub buffers_received: u64,
29    /// Number of buffers successfully processed by the streaming layer.
30    pub buffers_processed: u64,
31    /// Number of observed completions not delivered because of an error or controlled restart.
32    ///
33    /// This does not include device-side loss that happened before USB completion.
34    pub buffers_dropped: u64,
35    /// Number of dropped buffers that belonged to the queue retained across a restart.
36    ///
37    /// This is a subset of [`StreamingStats::buffers_dropped`]. On backends without
38    /// transfer cancellation, including WebUSB, consuming these old submissions may
39    /// delay the first fresh block after restarting.
40    pub buffers_discarded_on_restart: u64,
41}
42
43impl StreamingStats {
44    pub(crate) fn accumulate(&mut self, other: Self) {
45        self.buffers_received += other.buffers_received;
46        self.buffers_processed += other.buffers_processed;
47        self.buffers_dropped += other.buffers_dropped;
48        self.buffers_discarded_on_restart += other.buffers_discarded_on_restart;
49    }
50
51    pub(crate) fn combined(mut self, other: Self) -> Self {
52        self.accumulate(other);
53        self
54    }
55}
56
57/// Borrowed view of one raw receive block.
58#[derive(Clone, Copy, Debug, Eq, PartialEq)]
59pub struct SampleBlock<'a> {
60    raw: &'a [u8],
61    sample_count: usize,
62    dropped_samples: u64,
63}
64
65impl<'a> SampleBlock<'a> {
66    pub(crate) const fn new(raw: &'a [u8], sample_count: usize, dropped_samples: u64) -> Self {
67        Self {
68            raw,
69            sample_count,
70            dropped_samples,
71        }
72    }
73
74    /// Raw USB bytes for this sample block.
75    pub const fn raw_bytes(&self) -> &'a [u8] {
76        self.raw
77    }
78
79    /// Sample count reported for this block.
80    pub const fn sample_count(&self) -> usize {
81        self.sample_count
82    }
83
84    /// Estimated sample count represented by USB buffers the driver discarded.
85    ///
86    /// RFOne transfers have no sequence numbers, so this cannot include samples
87    /// lost inside the device while the host transfer queue was exhausted.
88    pub const fn dropped_samples(&self) -> u64 {
89        self.dropped_samples
90    }
91}
92
93/// Owned receive stream for sample mode `M`, defaulting to [`F32Iq`].
94///
95/// Create this stream with [`crate::Device::rx_stream`]. On native targets,
96/// each operation may be waited or awaited. Both mechanisms use the same
97/// persistent queue, including when used sequentially on one stream.
98///
99/// The stream keeps its device alive and can still start, stop, and restart
100/// after the public device handle is dropped. Configured RF bias power remains
101/// enabled until explicit device shutdown or the final owner is dropped.
102#[must_use = "RX streams retain the device's exclusive stream claim until closed or dropped"]
103pub struct RxStream<M: SampleMode = F32Iq> {
104    inner: Receiver<NusbTransport, M>,
105}
106
107impl<M: SampleMode> RxStream<M> {
108    pub(crate) fn new(claim: RxStreamClaim<NusbTransport>) -> Self {
109        Self {
110            inner: Receiver::new(claim),
111        }
112    }
113
114    /// Start reception and the persistent USB transfer queue.
115    ///
116    /// A stream requiring cleanup must be stopped before restarting.
117    ///
118    /// Call [`MaybeFuture::wait`] for blocking operation on native targets, or
119    /// await the returned operation for asynchronous operation.
120    pub fn start(&mut self) -> impl MaybeFuture<Output = Result<()>> + '_ {
121        self.inner.start()
122    }
123
124    /// Stop reception and return accumulated streaming counters.
125    ///
126    /// This preserves the stream for restart, retains its exclusive claim, and
127    /// leaves RF bias power unchanged.
128    /// If this operation fails or is canceled after it starts, retry `stop`
129    /// before reading or restarting.
130    pub fn stop(&mut self) -> impl MaybeFuture<Output = Result<StreamingStats>> + '_ {
131        self.inner.stop()
132    }
133
134    /// Consume the stream, stop reception, and return accumulated statistics.
135    ///
136    /// The returned operation owns the stream immediately, but retires its USB
137    /// queue and attempts receiver-off only when polled or waited. Success
138    /// releases the exclusive claim and the stream's device reference.
139    ///
140    /// Failure returns the original error; the stream cannot be retried. Failure
141    /// or cancellation invokes best-effort drop cleanup, as does dropping an
142    /// unpolled operation. WebUSB runs that fallback in the background and keeps
143    /// the claim reserved until its attempt finishes.
144    ///
145    /// Native callers may wait or await regardless of earlier operations.
146    /// WebUSB supports awaiting only.
147    ///
148    /// Close moves the stream even before the operation is polled:
149    ///
150    /// ```compile_fail,E0382
151    /// # use hydrasdr_rs::RxStream;
152    /// fn example(mut rx: RxStream) {
153    ///     let close = rx.close();
154    ///     let _ = rx.start(); // rx was moved into close
155    /// }
156    /// ```
157    ///
158    /// A completed close cannot be called again:
159    ///
160    /// ```compile_fail,E0382
161    /// # use hydrasdr_rs::{RawAdc, RxStream};
162    /// async fn example(rx: RxStream<RawAdc>) {
163    ///     let _ = rx.close().await;
164    ///     let _ = rx.close().await; // rx was consumed
165    /// }
166    /// ```
167    pub fn close(self) -> impl MaybeFuture<Output = Result<StreamingStats>> + 'static {
168        self.inner.close()
169    }
170}
171
172impl RxStream<RawAdc> {
173    /// Read the next zero-copy raw ADC USB block.
174    ///
175    /// The returned block borrows one buffer from the fixed transfer pool. Its
176    /// buffer is resubmitted on the next call. For blocking operation, `timeout`
177    /// bounds the wait and [`None`] waits indefinitely. The timeout is ignored
178    /// when this operation is awaited, which waits for the next USB completion.
179    /// The steady-state asynchronous path uses a concrete future without a
180    /// per-call future allocation; changing raw packing may allocate while the
181    /// USB queue is rebuilt.
182    pub fn next_block(
183        &mut self,
184        timeout: Option<Duration>,
185    ) -> impl MaybeFuture<Output = Result<Option<SampleBlock<'_>>>> + '_ {
186        self.inner.next_block(timeout)
187    }
188}
189
190impl RxStream<F32Iq> {
191    /// Convert samples directly into the caller-provided complex output slice.
192    ///
193    /// Both blocking and asynchronous reads drain buffered samples or process at
194    /// most one new usable USB completion. The returned count may be smaller
195    /// than `out.len()`; loop when a full slice is required. An empty slice
196    /// returns zero without waiting.
197    ///
198    /// `timeout` bounds blocking waits; [`None`] waits indefinitely. Awaited
199    /// reads ignore this argument and can be canceled by an external timeout.
200    /// Steady-state reads do not allocate a future or an output scratch buffer.
201    pub fn read<'a>(
202        &'a mut self,
203        out: &'a mut [Complex32],
204        timeout: Option<Duration>,
205    ) -> impl MaybeFuture<Output = Result<usize>> + 'a {
206        self.inner.read(out, timeout)
207    }
208}
209
210#[cfg(all(test, not(target_arch = "wasm32")))]
211mod data_tests;
212#[cfg(all(test, not(target_arch = "wasm32")))]
213mod tests;