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
//! Streaming-focused handle that runs concurrently with control.
//!
//! See [`RtlSdrReader`] and [`RtlSdrDevice::reader`].
use Arc;
use ;
use crateRtlSdrError;
// Brought into scope only so this file's intra-doc links
// (`[`RtlSdrDevice::reader`]`, etc.) resolve under
// `cargo doc -D warnings`. The type is not referenced by name in
// any module-level code path here — clippy's `unused_imports` lint
// flags this without the explicit allow. Per Code Rabbit on #23.
use RtlSdrDevice;
/// RAII guard for the per-device reader-busy flag. Acquiring sets
/// the flag to `true` via `compare_exchange`; dropping clears it.
///
/// Used to ensure at most one bulk-read activity (sync read,
/// blocking iterator, async stream) is in flight on USB endpoint
/// 0x81 at a time. Concurrent bulk reads on the same endpoint
/// silently split the contiguous IQ stream between callers — each
/// thread sees valid bytes for its own transfer, but neither has
/// the complete signal. Per #7.
///
/// Constructed via [`Self::try_acquire`]; never instantiated
/// directly.
//
// `dead_code` allow lifts in the follow-up commits that wire the
// guard into `RtlSdrDevice` + `RtlSdrReader` bulk-read entry points.
// Per #7 plan; remove this allow when those callers exist.
pub
/// Streaming-focused handle. Acquired via [`RtlSdrDevice::reader`].
///
/// `RtlSdrReader` exists to resolve the design tension between
/// Rust's ownership model (control methods like
/// [`RtlSdrDevice::set_center_freq`] take `&mut self`; concurrent
/// streaming would require holding `self` for the duration) and
/// the underlying USB protocol's reality (bulk reads use endpoint
/// 0x81; control transfers use endpoint 0x00 — different
/// endpoints, no conflict on real hardware).
///
/// The reader internally clones the device's
/// `Arc<rusb::DeviceHandle>`, then exposes the streaming surface
/// (sync iterator + per-runtime async streams) by consuming the
/// reader. The parent retains the [`RtlSdrDevice`] for control:
///
/// ```no_run
/// # use librtlsdr_rs::{RtlSdrDevice, RtlSdrError};
/// # fn example() -> Result<(), RtlSdrError> {
/// let mut device = RtlSdrDevice::open(0)?;
/// device.set_sample_rate(2_400_000)?;
/// device.set_center_freq(100_000_000)?;
/// device.reset_buffer()?;
///
/// // Hand a reader to a worker thread.
/// let reader = device.reader();
/// let thread = std::thread::spawn(move || {
/// for chunk in reader.iter_samples(262_144) {
/// match chunk {
/// Ok(buf) => { /* push to ring / DSP */ let _ = buf; }
/// Err(e) => { eprintln!("read error: {e}"); break; }
/// }
/// }
/// });
///
/// // Parent thread retains control of the device while the reader
/// // streams — separate USB endpoints, no rusb-level conflict.
/// device.set_center_freq(101_000_000)?;
/// device.set_tuner_gain(150)?;
/// # let _ = thread;
/// # Ok(())
/// # }
/// ```
///
/// # Concurrency safety
///
/// The shared-handle pattern (one `Arc<DeviceHandle>` reffed by
/// both the parent device and any reader) is what upstream
/// `librtlsdr`'s reference implementations have used for years.
/// Bulk reads on endpoint 0x81 don't interfere with control
/// transfers on endpoint 0x00 at the libusb level on real hardware.
///
/// **However**, libusb's documentation does not formally
/// guarantee that concurrent bulk and control transfers on a
/// single device handle are safe. The shared-handle pattern is a
/// practical convention rather than a documented promise. If you
/// need strict by-the-book safety, sequence the operations from
/// a single thread (e.g. fully drop the reader before retuning,
/// then build a new reader). For the typical "stream while
/// retuning the satellite at AOS" pattern this works reliably on
/// the dongles in active use; verify against your specific
/// hardware in production.
///
/// # Single active streaming session
///
/// At most one bulk-read activity may be in flight on the device
/// at a time — across `RtlSdrDevice::{read_sync, iter_samples,
/// read_async_blocking}` and `RtlSdrReader::{read_sync,
/// iter_samples, stream_samples_tokio, stream_samples_smol}`.
/// Concurrent attempts return [`RtlSdrError::DeviceBusy`].
///
/// This invariant exists because libusb permits concurrent submits
/// on the same endpoint, but the resulting transfer responses
/// interleave non-deterministically — each thread sees valid
/// bytes for its own libusb transfer, but neither has the
/// complete IQ stream. The runtime guard makes the contention
/// observable as a typed error rather than as silent
/// sample-stream corruption.
///
/// `RtlSdrDevice::usb_handle()` is the documented escape hatch and
/// is *not* gated; bypassing the typed reader path lets you
/// re-create the corruption hazard. See its method docs.
///
/// # Cheap clone via the device
///
/// A [`RtlSdrReader`] is just an `Arc` clone of the device's USB
/// handle plus the per-device busy-flag. Build one via
/// [`RtlSdrDevice::reader`] any time you need a fresh streaming
/// handle — the cost is two atomic increments. Cloning is allowed
/// (and cheap), but only one clone may have an active streaming
/// session at a time; the rest get [`RtlSdrError::DeviceBusy`].
/// Owned, sendable iterator over IQ-sample buffers, returned by
/// [`RtlSdrReader::iter_samples`].
///
/// Differs from [`crate::SampleIter`] in that it owns the reader
/// (and thus the underlying `Arc<DeviceHandle>` clone) rather
/// than borrowing the device — so it satisfies `'static` and can
/// be sent to other threads / async runtimes. Same
/// `FusedIterator` contract: `None` permanently after the first
/// error or zero read.