rtlsdr_nusb/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, RawIq, 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. RTL-SDR 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 /// RTL-SDR 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 /// Counters accumulated across reads, stops and restarts.
115 pub fn stats(&self) -> StreamingStats {
116 self.inner.current_stats()
117 }
118
119 /// Start reception and the persistent USB transfer queue.
120 ///
121 /// A stream requiring cleanup must be stopped before restarting.
122 ///
123 /// Call [`MaybeFuture::wait`] for blocking operation on native targets, or
124 /// await the returned operation for asynchronous operation.
125 pub fn start(&mut self) -> impl MaybeFuture<Output = Result<()>> + '_ {
126 self.inner.start()
127 }
128
129 /// Stop reception and return accumulated streaming counters.
130 ///
131 /// This preserves the stream for restart, retains its exclusive claim, and
132 /// leaves RF bias power unchanged.
133 /// If this operation fails or is canceled after it starts, retry `stop`
134 /// before reading or restarting.
135 pub fn stop(&mut self) -> impl MaybeFuture<Output = Result<StreamingStats>> + '_ {
136 self.inner.stop()
137 }
138
139 /// Consume the stream, stop reception, and return accumulated statistics.
140 ///
141 /// The returned operation owns the stream immediately, but retires its USB
142 /// queue and attempts receiver-off only when polled or waited. Success
143 /// releases the exclusive claim and the stream's device reference.
144 ///
145 /// Failure returns the original error; the stream cannot be retried. Failure
146 /// or cancellation invokes best-effort drop cleanup, as does dropping an
147 /// unpolled operation. WebUSB runs that fallback in the background and keeps
148 /// the claim reserved until its attempt finishes.
149 ///
150 /// Native callers may wait or await regardless of earlier operations.
151 /// WebUSB supports awaiting only.
152 ///
153 /// Close moves the stream even before the operation is polled:
154 ///
155 /// ```compile_fail,E0382
156 /// # use rtlsdr_nusb::RxStream;
157 /// fn example(mut rx: RxStream) {
158 /// let close = rx.close();
159 /// let _ = rx.start(); // rx was moved into close
160 /// }
161 /// ```
162 ///
163 /// A completed close cannot be called again:
164 ///
165 /// ```compile_fail,E0382
166 /// # use rtlsdr_nusb::{RawIq, RxStream};
167 /// async fn example(rx: RxStream<RawIq>) {
168 /// let _ = rx.close().await;
169 /// let _ = rx.close().await; // rx was consumed
170 /// }
171 /// ```
172 pub fn close(self) -> impl MaybeFuture<Output = Result<StreamingStats>> + 'static {
173 self.inner.close()
174 }
175}
176
177impl RxStream<RawIq> {
178 /// Read the next zero-copy raw I/Q USB block.
179 ///
180 /// The returned block borrows one buffer from the fixed transfer pool. Its
181 /// buffer is resubmitted on the next call. For blocking operation, `timeout`
182 /// bounds the wait and [`None`] waits indefinitely. The timeout is ignored
183 /// when this operation is awaited, which waits for the next USB completion.
184 /// The steady-state asynchronous path uses a concrete future without a
185 /// per-call future allocation; restarting a failed stream may rebuild its USB queue.
186 pub fn next_block(
187 &mut self,
188 timeout: Option<Duration>,
189 ) -> impl MaybeFuture<Output = Result<Option<SampleBlock<'_>>>> + '_ {
190 self.inner.next_block(timeout)
191 }
192}
193
194impl RxStream<F32Iq> {
195 /// Convert samples directly into the caller-provided complex output slice.
196 ///
197 /// Both blocking and asynchronous reads drain buffered samples or process at
198 /// most one new usable USB completion. The returned count may be smaller
199 /// than `out.len()`; loop when a full slice is required. An empty slice
200 /// returns zero without waiting.
201 ///
202 /// `timeout` bounds blocking waits; [`None`] waits indefinitely. Awaited
203 /// reads ignore this argument and can be canceled by an external timeout.
204 /// Steady-state reads do not allocate a future or an output scratch buffer.
205 pub fn read<'a>(
206 &'a mut self,
207 out: &'a mut [Complex32],
208 timeout: Option<Duration>,
209 ) -> impl MaybeFuture<Output = Result<usize>> + 'a {
210 self.inner.read(out, timeout)
211 }
212}
213
214#[cfg(all(test, not(target_arch = "wasm32")))]
215mod tests;