librtlsdr-rs 0.2.3

Pure-Rust port of librtlsdr — RTL2832U USB control + tuner drivers, no C library required.
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
//! RTL-SDR device — high-level API for device control.
//!
//! Ports `rtlsdr_dev_t` struct and public API functions from librtlsdr.
//! Split into sub-modules for manageability:
//! - `enumerate`: device discovery and USB string queries
//! - `frequency`: center freq, sample rate, PPM correction, offset tuning
//! - `gain`: tuner gain, gain mode, bandwidth, AGC
//! - `sampling`: direct sampling, test mode, bias-T
//! - `eeprom`: EEPROM read/write
//! - `streaming`: buffer reset, sync/async read

mod eeprom;
mod enumerate;
mod frequency;
mod gain;
mod sampling;
mod streaming;

pub use enumerate::{
    DeviceInfo, get_device_count, get_device_name, get_device_usb_strings, get_index_by_serial,
    list_devices,
};
pub use streaming::SampleIter;

mod builder;
pub use builder::RtlSdrDeviceBuilder;

mod reader;
pub use reader::{ReaderIter, RtlSdrReader};

#[cfg(feature = "tokio")]
mod streaming_tokio;
#[cfg(feature = "tokio")]
pub use streaming_tokio::TokioSampleStream;

#[cfg(feature = "smol")]
mod streaming_smol;
#[cfg(feature = "smol")]
pub use streaming_smol::SmolSampleStream;

use crate::constants::*;
use crate::error::RtlSdrError;
use crate::reg::{AsyncStatus, Block, TunerType};
use crate::tuner::Tuner;
use crate::tuner::r82xx::{R82xxConfig, R82xxPriv};
use crate::usb;

/// RTL-SDR device handle.
///
/// Ports `struct rtlsdr_dev` from librtlsdr. Manages the USB connection,
/// baseband configuration, and tuner driver.
///
/// # Send + Sync
///
/// `RtlSdrDevice` is [`Send`] — you can move it across thread
/// boundaries (e.g. into a `std::thread::spawn` worker that owns
/// the device exclusively). It is **not** [`Sync`] — the inner
/// per-tuner driver behind a `Box<dyn Tuner>` doesn't
/// require `Sync`, so sharing `&RtlSdrDevice` between threads
/// would be unsound. (`Tuner` itself requires `Send` as a
/// supertrait, so the boxed object is `Send` by definition.)
///
/// The supported pattern is single-owner: one thread holds the
/// `RtlSdrDevice` and serialises every control method call.
/// For background bulk reads on a worker thread without giving
/// up `&mut` on the main thread, see [`Self::usb_handle`] /
/// [`Self::BULK_ENDPOINT`] and the threading caveats in the
/// crate-level docs.
pub struct RtlSdrDevice {
    pub(crate) handle: std::sync::Arc<rusb::DeviceHandle<rusb::GlobalContext>>,
    /// Per-device flag enforcing at most one active bulk-read on USB
    /// endpoint 0x81 across the device + all `RtlSdrReader` clones.
    /// Cloned into every reader; acquired via [`reader::ReaderBusyGuard`]
    /// at the top of each bulk-read entry point. Per #7.
    pub(crate) reader_busy: std::sync::Arc<std::sync::atomic::AtomicBool>,
    pub(crate) tuner_type: TunerType,
    pub(crate) tuner: Option<Box<dyn Tuner>>,

    // RTL demod context
    pub(crate) rtl_xtal: u32,
    pub(crate) tun_xtal: u32,
    pub(crate) rate: u32,
    pub(crate) freq: u32,
    pub(crate) bw: u32,
    pub(crate) offs_freq: u32,
    pub(crate) corr: i32,
    pub(crate) gain: i32,
    pub(crate) direct_sampling: i32,
    pub(crate) fir: [i32; FIR_LEN],

    // Async streaming state
    #[allow(dead_code)]
    pub(crate) async_status: AsyncStatus,

    // Device info
    pub(crate) manufact: String,
    pub(crate) product: String,
    pub(crate) serial: String,

    /// Device-disconnected flag. Set to `true` by the bulk-read
    /// path on `rusb::Error::NoDevice → RtlSdrError::DeviceLost`
    /// translation; read by [`Drop`] to skip cleanup writes
    /// against a vanished handle.
    ///
    /// `Arc<AtomicBool>` so streaming code (which only holds an
    /// `Arc<DeviceHandle>` via [`RtlSdrReader`]) can update the
    /// same flag the parent device's `Drop` reads. Per audit
    /// pass-2 #40 (was `bool` in 0.1.x-0.2.0; structurally dead —
    /// set once after `init_baseband` and never updated by the
    /// runtime, so hot-unplug produced a stream of cryptic
    /// "register access failed" lines from cleanup).
    pub(crate) dev_lost: std::sync::Arc<std::sync::atomic::AtomicBool>,
    pub(crate) driver_active: bool,
}

impl RtlSdrDevice {
    /// USB bulk-IN endpoint address for IQ sample reads.
    ///
    /// Exposed as a public constant so callers using the
    /// [`Self::usb_handle`] escape hatch to do their own raw
    /// `rusb::DeviceHandle::read_bulk` calls (e.g. an `rtl_tcp`
    /// server forwarding raw samples) don't need to hard-code the
    /// magic number. Universal across all RTL-SDR variants.
    pub const BULK_ENDPOINT: u8 = crate::constants::BULK_ENDPOINT;

    /// Start a [`RtlSdrDeviceBuilder`] for opening with named
    /// selectors (index or serial).
    ///
    /// See [`RtlSdrDeviceBuilder`] for usage. `RtlSdrDevice::open`
    /// remains the lowest-overhead path for the "open the first
    /// dongle" / "open by known index" cases; the builder is for
    /// when you want to address a specific dongle by serial in a
    /// multi-device setup.
    #[must_use]
    pub fn builder() -> RtlSdrDeviceBuilder {
        RtlSdrDeviceBuilder::default()
    }

    /// Enumerate all connected RTL-SDR dongles in one call.
    ///
    /// Convenience shortcut for [`list_devices`] for callers that
    /// already have `RtlSdrDevice` in scope and don't want to
    /// import the free function separately. See
    /// [`list_devices`]'s docs for the performance note (one USB
    /// descriptor read per dongle — cache the result).
    #[must_use]
    pub fn list() -> Vec<DeviceInfo> {
        enumerate::list_devices()
    }

    /// Build a streaming-focused [`RtlSdrReader`] handle.
    ///
    /// The reader is the right surface for moving the streaming
    /// path to another thread / async runtime while the parent
    /// retains `&mut self` for control methods like
    /// [`Self::set_center_freq`] and [`Self::set_tuner_gain`].
    /// See [`RtlSdrReader`]'s docs for the full pattern,
    /// concurrency-safety caveat, and examples.
    ///
    /// Cheap to call — clones the underlying `Arc<DeviceHandle>`,
    /// no USB traffic. Build a fresh reader anywhere you'd want
    /// to start a new streaming session; the reader's methods
    /// consume `self` so each session is its own handle.
    #[must_use]
    pub fn reader(&self) -> RtlSdrReader {
        RtlSdrReader {
            handle: std::sync::Arc::clone(&self.handle),
            busy: std::sync::Arc::clone(&self.reader_busy),
            dev_lost: std::sync::Arc::clone(&self.dev_lost),
        }
    }

    /// Open an RTL-SDR device by index.
    ///
    /// Ports `rtlsdr_open`. Initializes the baseband, probes the tuner,
    /// and configures the device for SDR mode.
    pub fn open(index: u32) -> Result<Self, RtlSdrError> {
        let (device, _dd) = enumerate::find_device_by_index(index)?;

        let handle = device.open()?;

        // Check for kernel driver
        let driver_active = handle.kernel_driver_active(0).unwrap_or(false);
        if driver_active {
            let _ = handle.detach_kernel_driver(0);
        }

        handle.claim_interface(0)?;

        let mut dev = Self {
            handle: std::sync::Arc::new(handle),
            reader_busy: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            tuner_type: TunerType::Unknown,
            tuner: None,
            rtl_xtal: DEF_RTL_XTAL_FREQ,
            tun_xtal: DEF_RTL_XTAL_FREQ,
            rate: 0,
            freq: 0,
            bw: 0,
            offs_freq: 0,
            corr: 0,
            gain: 0,
            direct_sampling: 0,
            fir: FIR_DEFAULT,
            async_status: AsyncStatus::Inactive,
            manufact: String::new(),
            product: String::new(),
            serial: String::new(),
            dev_lost: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)),
            driver_active,
        };

        // Perform a dummy write to test connectivity; reset if it fails
        if usb::write_reg(
            &dev.handle,
            Block::Usb,
            crate::reg::usb_reg::USB_SYSCTL,
            0x09,
            1,
        )
        .is_err()
        {
            tracing::warn!("dummy write failed, resetting device");
            let _ = dev.handle.reset();
        }

        // Initialize baseband
        usb::init_baseband(&dev.handle, &dev.fir)?;
        dev.dev_lost
            .store(false, std::sync::atomic::Ordering::Release);

        // Get device manufacturer, product, and serial strings
        if let Ok(dd) = dev.handle.device().device_descriptor() {
            dev.manufact = dev
                .handle
                .read_manufacturer_string_ascii(&dd)
                .unwrap_or_default();
            dev.product = dev
                .handle
                .read_product_string_ascii(&dd)
                .unwrap_or_default();
            dev.serial = dev
                .handle
                .read_serial_number_string_ascii(&dd)
                .unwrap_or_default();
        }

        // Probe tuners
        usb::set_i2c_repeater(&dev.handle, true)?;
        dev.probe_tuner();

        // Use RTL clock value by default for tuner
        // (may have been changed by probe_tuner for R828D)
        if dev.tun_xtal == DEF_RTL_XTAL_FREQ {
            dev.tun_xtal = dev.rtl_xtal;
        }

        // Tuner-specific post-init configuration
        match dev.tuner_type {
            TunerType::R828D | TunerType::R820T => {
                // Disable Zero-IF mode
                usb::demod_write_reg(&dev.handle, 1, 0xb1, 0x1a, 1)?;
                // Only enable In-phase ADC input
                usb::demod_write_reg(&dev.handle, 0, 0x08, 0x4d, 1)?;
                // Set R82XX IF frequency
                dev.set_if_freq(R82XX_IF_FREQ)?;
                // Enable spectrum inversion
                usb::demod_write_reg(&dev.handle, 1, 0x15, 0x01, 1)?;
            }
            TunerType::Unknown => {
                // No tuner found — enable direct sampling mode
                tracing::warn!("No supported tuner found, enabling direct sampling");
                let _ = dev.set_direct_sampling(1);
            }
            _ => {}
        }

        // Initialize tuner driver
        if let Some(tuner) = &mut dev.tuner {
            tuner.init(&dev.handle)?;
        }

        usb::set_i2c_repeater(&dev.handle, false)?;

        Ok(dev)
    }

    /// Probe for supported tuner ICs.
    ///
    /// Ports the tuner probing sequence from `rtlsdr_open`.
    fn probe_tuner(&mut self) {
        // Try E4000
        if let Ok(reg) = usb::i2c_read_reg(&self.handle, E4K_I2C_ADDR, E4K_CHECK_ADDR)
            && reg == E4K_CHECK_VAL
        {
            tracing::info!("Found Elonics E4000 tuner");
            self.tuner_type = TunerType::E4000;
            return;
        }

        // Try FC0013
        if let Ok(reg) = usb::i2c_read_reg(&self.handle, FC0013_I2C_ADDR, FC0013_CHECK_ADDR)
            && reg == FC0013_CHECK_VAL
        {
            tracing::info!("Found Fitipower FC0013 tuner");
            self.tuner_type = TunerType::Fc0013;
            return;
        }

        // Try R820T
        if let Ok(reg) = usb::i2c_read_reg(&self.handle, R820T_I2C_ADDR, R82XX_CHECK_ADDR)
            && reg == R82XX_CHECK_VAL
        {
            tracing::info!("Found Rafael Micro R820T tuner");
            self.tuner_type = TunerType::R820T;
            self.create_r82xx_tuner();
            return;
        }

        // Try R828D
        if let Ok(reg) = usb::i2c_read_reg(&self.handle, R828D_I2C_ADDR, R82XX_CHECK_ADDR)
            && reg == R82XX_CHECK_VAL
        {
            tracing::info!("Found Rafael Micro R828D tuner");
            let is_v4 = self.is_blog_v4();
            if is_v4 {
                tracing::info!("RTL-SDR Blog V4 Detected");
            }
            self.tuner_type = TunerType::R828D;
            self.create_r82xx_tuner();
            return;
        }

        // Initialize GPIOs before probing remaining tuners
        let _ = usb::set_gpio_output(&self.handle, 4);
        // Reset tuner
        let _ = usb::set_gpio_bit(&self.handle, 4, true);
        let _ = usb::set_gpio_bit(&self.handle, 4, false);

        // Try FC2580
        if let Ok(reg) = usb::i2c_read_reg(&self.handle, FC2580_I2C_ADDR, FC2580_CHECK_ADDR)
            && (reg & 0x7f) == FC2580_CHECK_VAL
        {
            tracing::info!("Found FCI 2580 tuner");
            self.tuner_type = TunerType::Fc2580;
            return;
        }

        // Try FC0012
        if let Ok(reg) = usb::i2c_read_reg(&self.handle, FC0012_I2C_ADDR, FC0012_CHECK_ADDR)
            && reg == FC0012_CHECK_VAL
        {
            tracing::info!("Found Fitipower FC0012 tuner");
            let _ = usb::set_gpio_output(&self.handle, 6);
            self.tuner_type = TunerType::Fc0012;
            return;
        }

        tracing::warn!("No supported tuner found");
    }

    /// Create R82XX tuner driver instance.
    fn create_r82xx_tuner(&mut self) {
        let (i2c_addr, chip) = match self.tuner_type {
            TunerType::R828D => {
                let is_v4 = self.is_blog_v4();
                if !is_v4 {
                    self.tun_xtal = R828D_XTAL_FREQ;
                }
                (
                    R828D_I2C_ADDR,
                    crate::tuner::r82xx::constants::R82xxChip::R828D,
                )
            }
            _ => (
                R820T_I2C_ADDR,
                crate::tuner::r82xx::constants::R82xxChip::R820T,
            ),
        };

        let xtal = self.get_tuner_xtal();
        let config = R82xxConfig {
            i2c_addr,
            xtal,
            rafael_chip: chip,
            max_i2c_msg_len: 8,
            use_predetect: false,
        };

        let mut r82xx = R82xxPriv::new(&config);
        let is_v4 = self.is_blog_v4();
        r82xx.set_blog_v4(is_v4);
        self.tuner = Some(Box::new(r82xx));
    }

    // --- Internal helpers ---

    /// Set IF frequency.
    ///
    /// Ports `rtlsdr_set_if_freq`.
    pub(crate) fn set_if_freq(&self, freq: u32) -> Result<(), RtlSdrError> {
        let rtl_xtal = self.get_rtl_xtal();
        let if_freq = -((f64::from(freq) * (1u64 << 22) as f64) / f64::from(rtl_xtal)) as i32;

        let tmp = ((if_freq >> 16) & 0x3f) as u16;
        usb::demod_write_reg(&self.handle, 1, 0x19, tmp, 1)?;
        let tmp = ((if_freq >> 8) & 0xff) as u16;
        usb::demod_write_reg(&self.handle, 1, 0x1a, tmp, 1)?;
        let tmp = (if_freq & 0xff) as u16;
        usb::demod_write_reg(&self.handle, 1, 0x1b, tmp, 1)?;

        Ok(())
    }

    /// Set sample frequency correction in PPM.
    ///
    /// Ports `rtlsdr_set_sample_freq_correction`.
    pub(crate) fn set_sample_freq_correction(&self, ppm: i32) -> Result<(), RtlSdrError> {
        let offs = (f64::from(-ppm) * (1u64 << 24) as f64 / 1_000_000.0) as i16;

        let tmp = (offs & 0xff) as u16;
        usb::demod_write_reg(&self.handle, 1, 0x3f, tmp, 1)?;
        let tmp = ((offs >> 8) & 0x3f) as u16;
        usb::demod_write_reg(&self.handle, 1, 0x3e, tmp, 1)?;

        Ok(())
    }

    /// Get corrected RTL crystal frequency.
    ///
    /// Ports `APPLY_PPM_CORR` macro from `rtlsdr_get_xtal_freq`.
    pub(crate) fn get_rtl_xtal(&self) -> u32 {
        (f64::from(self.rtl_xtal) * (1.0 + f64::from(self.corr) / 1e6)) as u32
    }

    /// Get corrected tuner crystal frequency.
    pub(crate) fn get_tuner_xtal(&self) -> u32 {
        (f64::from(self.tun_xtal) * (1.0 + f64::from(self.corr) / 1e6)) as u32
    }

    // --- Public getters ---

    /// Get the tuner type.
    #[must_use]
    pub fn tuner_type(&self) -> TunerType {
        self.tuner_type
    }

    /// Get available gain values (tenths of dB).
    ///
    /// Returns a `'static` slice (the tables in
    /// [`TunerType::gains`] are static const data) — callers can
    /// stash the slice across the device's lifetime without a
    /// reborrow. Per audit issue #19.
    #[must_use]
    pub fn tuner_gains(&self) -> &'static [i32] {
        self.tuner_type.gains()
    }

    /// Find the closest available tuner gain to a desired value.
    ///
    /// `desired_tenths_db` is the target gain in tenths-of-dB (the
    /// same unit [`Self::set_tuner_gain`] takes). Returns the
    /// gain step from [`Self::tuner_gains`] that's nearest to the
    /// requested value. Ties go to the lower step (deterministic
    /// `min_by_key` behaviour). Useful when an app's UI lets the
    /// user pick a "rough" dB value (slider, dropdown of round
    /// numbers) and you want the actual closest hardware-accepted
    /// step without rolling your own search over the gain table.
    ///
    /// Each tuner family has its own discrete gain table — the
    /// R820T2 has 29 steps from 0.0 to 49.6 dB, the E4000 has 14
    /// steps from -1 to 49 dB, etc. The result is always one of
    /// those exact values, never an interpolation.
    ///
    /// Returns `None` when the tuner has no gain table at all (in
    /// practice only the `Unknown` tuner type, which means the
    /// device hasn't been probed or the IC isn't in our
    /// known-tuners list).
    ///
    /// `closest_gain` itself is a pure static-table lookup — it
    /// doesn't touch the device, doesn't depend on AGC state,
    /// and is safe to call before `open()` if you have a
    /// [`crate::TunerType`] in hand. **Setting the gain is
    /// what requires manual mode** — the example below enables
    /// manual mode just before `set_tuner_gain` for that reason,
    /// not because `closest_gain` cares. In AGC mode the tuner
    /// picks its own gain and ignores `set_tuner_gain`.
    ///
    /// **Since 0.2 (per #16):** returns `Option<i32>` instead of
    /// `i32`. In 0.1.x this method returned `0` for both "no gain
    /// table" and "0 was the closest step", which was ambiguous.
    /// The 0.1.x `try_closest_gain` companion is removed; this is
    /// now the only spelling.
    ///
    /// ```no_run
    /// # use librtlsdr_rs::{RtlSdrDevice, RtlSdrError};
    /// # fn main() -> Result<(), RtlSdrError> {
    /// let mut dev = RtlSdrDevice::open(0)?;
    /// // User picked "around 15 dB" in the UI; pick the actual step
    /// // from the device's gain table (pure lookup, no I/O).
    /// if let Some(step) = dev.closest_gain(150) {
    ///     // Enable manual mode just before applying the gain — AGC
    ///     // mode would ignore the next call.
    ///     dev.set_tuner_gain_mode(true)?;
    ///     dev.set_tuner_gain(step)?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn closest_gain(&self, desired_tenths_db: i32) -> Option<i32> {
        closest_gain_in(self.tuner_gains(), desired_tenths_db)
    }

    /// Get device manufacturer string.
    #[must_use]
    pub fn manufacturer(&self) -> &str {
        &self.manufact
    }

    /// Get device product string.
    #[must_use]
    pub fn product(&self) -> &str {
        &self.product
    }

    /// Get device serial string.
    #[must_use]
    pub fn serial(&self) -> &str {
        &self.serial
    }

    /// Get the current center frequency.
    #[must_use]
    pub fn center_freq(&self) -> u32 {
        self.freq
    }

    /// Get the current sample rate.
    #[must_use]
    pub fn sample_rate(&self) -> u32 {
        self.rate
    }

    /// Get the current frequency correction in PPM.
    #[must_use]
    pub fn freq_correction(&self) -> i32 {
        self.corr
    }

    /// Get the current tuner gain.
    #[must_use]
    pub fn tuner_gain(&self) -> i32 {
        self.gain
    }

    /// Get the current direct sampling mode.
    #[must_use]
    pub fn direct_sampling(&self) -> i32 {
        self.direct_sampling
    }

    /// Get the current offset tuning state.
    #[must_use]
    pub fn offset_tuning(&self) -> bool {
        self.offs_freq > 0
    }

    /// Get corrected xtal frequencies.
    ///
    /// Ports `rtlsdr_get_xtal_freq`.
    #[must_use]
    pub fn xtal_freq(&self) -> (u32, u32) {
        (self.get_rtl_xtal(), self.get_tuner_xtal())
    }

    /// Set RTL and/or tuner crystal frequencies.
    ///
    /// Ports `rtlsdr_set_xtal_freq`.
    ///
    /// # Sentinel: pass `0` to leave a value unchanged
    ///
    /// `rtl_freq == 0` skips the RTL-side update; `tuner_freq == 0`
    /// resets the tuner xtal to track the (current) RTL xtal value
    /// rather than installing a literal 0 Hz crystal. This matches
    /// the C upstream's `rtlsdr_set_xtal_freq` semantics — pass `0`
    /// to mean "don't change this side." Per audit issue #18.
    pub fn set_xtal_freq(&mut self, rtl_freq: u32, tuner_freq: u32) -> Result<(), RtlSdrError> {
        if rtl_freq > 0 && (rtl_freq < MIN_RTL_XTAL_FREQ || rtl_freq > MAX_RTL_XTAL_FREQ) {
            return Err(RtlSdrError::InvalidParameter(format!(
                "RTL xtal freq out of range: {rtl_freq}"
            )));
        }

        tracing::info!(
            "set_xtal_freq: rtl={rtl_freq} Hz, tuner={tuner_freq} Hz \
             (rtl 0 = unchanged; tuner 0 = follow current RTL xtal)"
        );

        if rtl_freq > 0 && self.rtl_xtal != rtl_freq {
            // Stash for rollback on failure: `set_sample_rate`
            // reads `self.rtl_xtal` internally, so we have to
            // assign before the call — but if the call fails,
            // a stale cache that claimed the new value while
            // the hardware was still on the old rate would
            // corrupt subsequent `xtal_freq()` reads. Mirror
            // the #11 pattern: roll back on `Err`. Per audit
            // pass-2 #44.
            let old_rtl_xtal = self.rtl_xtal;
            self.rtl_xtal = rtl_freq;
            if self.rate > 0 {
                if let Err(e) = self.set_sample_rate(self.rate) {
                    self.rtl_xtal = old_rtl_xtal;
                    return Err(e);
                }
            }
        }

        // Compare against the *effective* new value, not the
        // raw `0` sentinel. CodeRabbit on PR #80: pre-fix,
        // `set_xtal_freq(0, 0)` on a device where `tun_xtal`
        // already tracked `rtl_xtal` (the typical case after
        // `open()`) would still trigger a retune even though
        // the effective value didn't change.
        let new_tun_xtal = if tuner_freq == 0 {
            self.rtl_xtal
        } else {
            tuner_freq
        };
        if self.tun_xtal != new_tun_xtal {
            // Same rollback shape for the tuner-side state.
            // We mutate three things before the fallible
            // `set_center_freq`: `self.tun_xtal`, the tuner
            // driver's internal xtal, and (transitively via
            // PPM correction) the corrected value `set_xtal`
            // saw. On failure, restore all three. Per audit
            // pass-2 #44 + #39.
            let old_tun_xtal = self.tun_xtal;
            let old_corrected_xtal = self.get_tuner_xtal();
            self.tun_xtal = new_tun_xtal;

            // Push the new (PPM-corrected) tuner xtal into the
            // backend's PLL state. C upstream does this in
            // `rtlsdr_set_xtal_freq` (librtlsdr.c:752-754).
            // Per audit pass-2 #39.
            let new_corrected_xtal = self.get_tuner_xtal();
            if let Some(tuner) = &mut self.tuner {
                tuner.set_xtal(new_corrected_xtal);
            }

            if self.freq > 0 {
                if let Err(e) = self.set_center_freq(self.freq) {
                    self.tun_xtal = old_tun_xtal;
                    if let Some(tuner) = &mut self.tuner {
                        tuner.set_xtal(old_corrected_xtal);
                    }
                    return Err(e);
                }
            }
        }

        Ok(())
    }

    /// Check if this is an RTL-SDR Blog V4 device.
    #[must_use]
    pub fn is_blog_v4(&self) -> bool {
        self.manufact == "RTLSDRBlog" && self.product == "Blog V4"
    }

    /// Check if the device matches a manufacturer/product pair.
    ///
    /// Ports `rtlsdr_check_dongle_model`.
    #[must_use]
    pub fn check_dongle_model(&self, manufact: &str, product: &str) -> bool {
        self.manufact == manufact && self.product == product
    }
}

impl Drop for RtlSdrDevice {
    fn drop(&mut self) {
        // Drop-time errors aren't actionable (we can't return them
        // to the caller, and panicking from Drop is undefined
        // behavior under unwinding). Log at `tracing::debug!` so a
        // post-mortem inspection has at least *something* to go on
        // when cleanup misbehaves. Per audit slice A M-7 / #9.
        if !self.dev_lost.load(std::sync::atomic::Ordering::Acquire) {
            // Wait for async to complete
            // (in practice async is handled by the caller stopping first)

            // Deinit tuner
            if let Some(tuner) = &mut self.tuner {
                if let Err(e) = usb::set_i2c_repeater(&self.handle, true) {
                    tracing::debug!("RtlSdrDevice::drop: set_i2c_repeater(true) failed: {e}");
                }
                if let Err(e) = tuner.exit(&self.handle) {
                    tracing::debug!("RtlSdrDevice::drop: tuner.exit failed: {e}");
                }
                if let Err(e) = usb::set_i2c_repeater(&self.handle, false) {
                    tracing::debug!("RtlSdrDevice::drop: set_i2c_repeater(false) failed: {e}");
                }
            }

            // Power off demod
            if let Err(e) = usb::deinit_baseband(&self.handle) {
                tracing::debug!("RtlSdrDevice::drop: deinit_baseband failed: {e}");
            }
        }

        // Release interface
        if let Err(e) = self.handle.release_interface(0) {
            tracing::debug!("RtlSdrDevice::drop: release_interface failed: {e}");
        }

        // Reattach kernel driver if we detached it
        if self.driver_active {
            if let Err(e) = self.handle.attach_kernel_driver(0) {
                tracing::debug!("RtlSdrDevice::drop: attach_kernel_driver failed: {e}");
            }
        }
    }
}

/// Find the closest entry in a tuner-gain table to `desired`,
/// returning `None` for an empty table. Pulled out of
/// [`RtlSdrDevice::closest_gain`] so the algorithm can be unit-
/// tested without constructing a live device.
///
/// Ties go to the lower step (deterministic `min_by_key` —
/// stable iterator order means the first equally-distant entry
/// in the table wins, and tables are stored in ascending order).
///
/// The distance is computed in `i64` to avoid `i32` overflow on
/// extreme inputs — `(g - desired).abs()` panics in debug builds
/// when the subtraction overflows (e.g. `desired == i32::MIN`)
/// and silently wraps in release. Real callers won't pass such
/// values, but the algorithm shouldn't be a footgun.
fn closest_gain_in(gains: &[i32], desired: i32) -> Option<i32> {
    gains
        .iter()
        .copied()
        .min_by_key(|&g| (i64::from(g) - i64::from(desired)).abs())
}

// Pin the `Send`-but-not-`Sync` contract documented on the
// `RtlSdrDevice` struct. If a future field change ever adds a
// non-`Send` member (e.g. a `Cell<…>` or `Rc<…>`), this assertion
// fires at compile time so we notice before semver-breaking
// downstream consumers who relied on moving the device into a
// worker thread.
const _: fn() = || {
    fn assert_send<T: Send>() {}
    assert_send::<RtlSdrDevice>();
};

/// Manual [`Debug`] impl for [`RtlSdrDevice`] — `#[derive(Debug)]`
/// can't be used because two fields don't implement `Debug`:
///
/// - `handle: Arc<rusb::DeviceHandle<...>>` — `rusb::DeviceHandle`
///   has no `Debug` impl. Substituted with the `Arc`'s pointer
///   address as a stable identifier.
/// - `tuner: Option<Box<dyn Tuner>>` — the `Tuner` trait
///   (`pub(crate)`) doesn't require `Debug` as a supertrait
///   (would force all 5 backends to derive it on their large
///   register arrays for marginal benefit). Substituted with the
///   tuner-presence boolean alongside the explicit `tuner_type`
///   field, which already names the backend.
///
/// Per audit issue #19: gives consumers `dbg!(&device)` and
/// `#[derive(Debug)]` on parent structs without leaking the
/// internal trait shape.
impl std::fmt::Debug for RtlSdrDevice {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RtlSdrDevice")
            .field("handle_ptr", &std::sync::Arc::as_ptr(&self.handle))
            .field("reader_busy", &self.reader_busy)
            .field("tuner_type", &self.tuner_type)
            .field("tuner_present", &self.tuner.is_some())
            .field("rtl_xtal", &self.rtl_xtal)
            .field("tun_xtal", &self.tun_xtal)
            .field("rate", &self.rate)
            .field("freq", &self.freq)
            .field("bw", &self.bw)
            .field("offs_freq", &self.offs_freq)
            .field("corr", &self.corr)
            .field("gain", &self.gain)
            .field("direct_sampling", &self.direct_sampling)
            .field("fir", &self.fir)
            .field("async_status", &self.async_status)
            .field("manufact", &self.manufact)
            .field("product", &self.product)
            .field("serial", &self.serial)
            .field(
                "dev_lost",
                &self.dev_lost.load(std::sync::atomic::Ordering::Relaxed),
            )
            .field("driver_active", &self.driver_active)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::closest_gain_in;

    // R820T2 gain table (29 steps, tenths of dB) — pinned here
    // rather than imported so the test exercises a known-real
    // table shape independent of any future tuner-table edits.
    const R820T2_GAINS: &[i32] = &[
        0, 9, 14, 27, 37, 77, 87, 125, 144, 157, 166, 197, 207, 229, 254, 280, 297, 328, 338, 364,
        372, 386, 402, 421, 434, 439, 445, 480, 496,
    ];

    /// Since 0.2 (#16): empty table returns `None` instead of
    /// overloading `0`. Distinguishes "no gain table" from
    /// "0 was the closest step" — formerly the role of
    /// `try_closest_gain_in`, now the only spelling.
    #[test]
    fn empty_table_returns_none() {
        assert_eq!(closest_gain_in(&[], 250), None);
        assert_eq!(closest_gain_in(&[], 0), None);
        assert_eq!(closest_gain_in(&[], -100), None);
        assert_eq!(closest_gain_in(&[], i32::MIN), None);
    }

    #[test]
    fn exact_match_returns_self() {
        for &g in R820T2_GAINS {
            assert_eq!(
                closest_gain_in(R820T2_GAINS, g),
                Some(g),
                "exact value {g} should round to itself"
            );
        }
    }

    #[test]
    fn rounds_to_nearest_step() {
        // 150 is between 144 and 157 — closer to 144 (|150-144|=6
        // vs |150-157|=7), so 144 wins.
        assert_eq!(closest_gain_in(R820T2_GAINS, 150), Some(144));

        // 152: |152-144|=8 vs |152-157|=5 → 157.
        assert_eq!(closest_gain_in(R820T2_GAINS, 152), Some(157));

        // 100: |100-87|=13 vs |100-125|=25 → 87.
        assert_eq!(closest_gain_in(R820T2_GAINS, 100), Some(87));
    }

    #[test]
    fn out_of_range_clamps_to_endpoint() {
        assert_eq!(closest_gain_in(R820T2_GAINS, -1000), Some(0));
        assert_eq!(closest_gain_in(R820T2_GAINS, 10_000), Some(496));
    }

    #[test]
    fn ties_resolve_deterministically() {
        // Symmetric gap: 50 is exactly between 0 and 100. With
        // `min_by_key` over a stable iterator, the first
        // equally-distant entry wins → 0.
        let table = &[0, 100];
        assert_eq!(closest_gain_in(table, 50), Some(0));
    }

    #[test]
    fn i32_min_does_not_overflow() {
        // Regression: `(g - desired).abs()` in `i32` panics in
        // debug / wraps in release when `desired == i32::MIN`,
        // because `0 - i32::MIN` and `i32::MIN.abs()` both
        // overflow. The fix promotes the distance to `i64` —
        // pin it so we don't regress. Per #631 CR round 1.
        assert_eq!(closest_gain_in(R820T2_GAINS, i32::MIN), Some(0));
        assert_eq!(closest_gain_in(R820T2_GAINS, i32::MAX), Some(496));
    }

    /// Pin that `Some(0)` is a real picked-step result, not a
    /// confused empty-table sentinel — the disambiguation #16 is
    /// supposed to enable.
    #[test]
    fn zero_step_is_distinguishable_from_empty_table() {
        assert_eq!(closest_gain_in(R820T2_GAINS, 0), Some(0));
        assert_eq!(closest_gain_in(&[], 0), None);
    }
}