seify 0.25.0

Shiny Samples from your Rusty SDR
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
use libbladerf_rs::bladerf1::{
    BladeRf1, ExpansionBoard, GainDb, GainMode, RfLinkSession, RxStream, SampleFormat, TuningMode,
    TxStream,
};
use libbladerf_rs::Channel;
use num_complex::Complex32;
use std::future::IntoFuture;

use super::common::*;
#[cfg(target_arch = "wasm32")]
use crate::dev::WebUsbDeviceFilter;
use crate::{
    async_compat::{timeout_from_micros, with_timeout, Shared, TimeoutResult},
    dev::AsyncTypedDeviceBackend,
    Args, AsyncAgcControl, AsyncAntennaControl, AsyncBandwidthControl, AsyncDeviceInfo,
    AsyncFrequencyControl, AsyncGainControl, AsyncRxDevice, AsyncSampleRateControl, AsyncTxDevice,
    Capability, Direction, Driver, DriverError, Error, Range,
};

/// Asynchronous bladeRF 1 device backend.
#[derive(Clone)]
pub struct AsyncBladeRf {
    device_slot: Shared<AsyncSlot<Box<BladeRf1>>>,
    abandoned_rx: Shared<AsyncSlot<RxStream>>,
    abandoned_tx: Shared<AsyncSlot<TxStream>>,
    serial: String,
}

/// bladeRF 1 asynchronous receive streamer.
///
/// The streamer owns the USB bulk queue; the device is only leased for
/// `activate`/`deactivate`. Dropping a streamer without deactivating it
/// defers stream teardown to the next asynchronous device operation.
#[must_use = "deactivate the bladeRF stream before dropping it"]
pub struct AsyncBladeRfRxStreamer {
    device_slot: Shared<AsyncSlot<Box<BladeRf1>>>,
    abandoned: Shared<AsyncSlot<RxStream>>,
    stream: Option<RxStream>,
    converter: RxConverter,
}

/// bladeRF 1 asynchronous transmit streamer.
#[must_use = "deactivate the bladeRF stream before dropping it"]
pub struct AsyncBladeRfTxStreamer {
    device_slot: Shared<AsyncSlot<Box<BladeRf1>>>,
    abandoned: Shared<AsyncSlot<TxStream>>,
    stream: Option<TxStream>,
    format: SampleFormat,
}

#[cfg(not(target_arch = "wasm32"))]
struct AsyncSlot<T>(std::sync::Mutex<Option<T>>);

#[cfg(target_arch = "wasm32")]
struct AsyncSlot<T>(std::cell::RefCell<Option<T>>);

impl<T> AsyncSlot<T> {
    fn new(value: T) -> Self {
        let slot = Self::empty();
        let result = slot.put(value);
        debug_assert!(result.is_ok());
        slot
    }

    fn empty() -> Self {
        Self(Default::default())
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn take(&self) -> Option<T> {
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
    }

    #[cfg(target_arch = "wasm32")]
    fn take(&self) -> Option<T> {
        self.0.borrow_mut().take()
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn put(&self, value: T) -> Result<(), T> {
        let mut slot = self
            .0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if slot.is_some() {
            Err(value)
        } else {
            *slot = Some(value);
            Ok(())
        }
    }

    #[cfg(target_arch = "wasm32")]
    fn put(&self, value: T) -> Result<(), T> {
        let mut slot = self.0.borrow_mut();
        if slot.is_some() {
            Err(value)
        } else {
            *slot = Some(value);
            Ok(())
        }
    }
}

struct AsyncSlotLease<T> {
    slot: Shared<AsyncSlot<T>>,
    value: Option<T>,
}

impl<T> AsyncSlotLease<T> {
    fn acquire(slot: &Shared<AsyncSlot<T>>) -> Result<Self, Error> {
        let value = slot.take().ok_or(Error::Busy)?;
        Ok(Self {
            slot: Shared::clone(slot),
            value: Some(value),
        })
    }

    fn value_mut(&mut self) -> &mut T {
        self.value.as_mut().expect("slot lease always owns a value")
    }
}

impl<T> Drop for AsyncSlotLease<T> {
    fn drop(&mut self) {
        if let Some(value) = self.value.take() {
            let result = self.slot.put(value);
            debug_assert!(result.is_ok(), "async slot was unexpectedly occupied");
        }
    }
}

type DeviceLease = AsyncSlotLease<Box<BladeRf1>>;

async fn session(dev: &mut DeviceLease) -> Result<RfLinkSession<'_>, Error> {
    dev.value_mut().rf_link_session().await.map_err(bladerf_err)
}

async fn cleanup_abandoned(
    dev: &mut DeviceLease,
    rx: &Shared<AsyncSlot<RxStream>>,
    tx: &Shared<AsyncSlot<TxStream>>,
) -> Result<(), Error> {
    if let Ok(mut stream) = AsyncSlotLease::acquire(rx) {
        let mut rf = session(dev).await?;
        stream
            .value_mut()
            .close(&mut rf)
            .await
            .map_err(bladerf_err)?;
        stream.value = None;
    }
    if let Ok(mut stream) = AsyncSlotLease::acquire(tx) {
        let mut rf = session(dev).await?;
        stream
            .value_mut()
            .close(&mut rf)
            .await
            .map_err(bladerf_err)?;
        stream.value = None;
    }
    Ok(())
}

impl AsyncBladeRf {
    /// Return descriptors for detected bladeRF 1 devices asynchronously.
    ///
    /// On WebUSB only devices the page has already been granted are listed;
    /// call `AsyncRegistry::request_permission`
    /// from a user gesture first.
    #[cfg(not(target_os = "android"))]
    pub async fn probe(args: &Args) -> Result<Vec<Args>, Error> {
        let selector = device_selector(args)?;
        let descriptors = BladeRf1::list_bladerf1()
            .await
            .map_err(|_| Error::DeviceNotFound)?
            .map(|info| probe_descriptor(&info))
            .collect();
        Ok(filter_descriptors(&selector, descriptors))
    }

    /// Returns no descriptors on Android, which requires [`Self::from_fd`].
    #[cfg(target_os = "android")]
    pub async fn probe(_args: &Args) -> Result<Vec<Args>, Error> {
        Ok(Vec::new())
    }

    /// Open a bladeRF 1 device from arguments asynchronously.
    #[cfg(not(target_os = "android"))]
    pub async fn open<A: TryInto<Args>>(args: A) -> Result<Self, Error> {
        let args: Args = args
            .try_into()
            .map_err(|_| Error::invalid_argument("args", "failed to convert args"))?;
        Self::init_and_wrap(open_selected_device(device_selector(&args)?).await?).await
    }

    /// Reports that Android opening requires [`Self::from_fd`].
    ///
    /// # Errors
    /// Returns an unsupported-operation error because Android cannot enumerate USB devices.
    #[cfg(target_os = "android")]
    pub async fn open<A: TryInto<Args>>(_args: A) -> Result<Self, Error> {
        Err(Error::unsupported_reason(
            Capability::DriverOperation,
            "Android requires AsyncBladeRf::from_fd with an owned USB connection",
        ))
    }

    /// Opens a bladeRF 1 asynchronously from an owned USB file descriptor.
    ///
    /// Android applications obtain USB permission before calling this constructor.
    /// Duplicate the descriptor first if Java retains its connection ownership.
    ///
    /// # Examples
    /// ```no_run
    /// # async fn open(fd: std::os::fd::OwnedFd) -> Result<seify::DynAsyncDevice, seify::Error> {
    /// let backend = seify::impls::AsyncBladeRf::from_fd(fd).await?;
    /// Ok(seify::DynAsyncDevice::from_impl(backend))
    /// # }
    /// ```
    ///
    /// # Errors
    /// Propagates USB opening, interface claiming, and initialization failures.
    #[cfg(any(target_os = "linux", target_os = "android"))]
    pub async fn from_fd(fd: std::os::fd::OwnedFd) -> Result<Self, Error> {
        Self::init_and_wrap(BladeRf1::from_fd(fd).await.map_err(bladerf_err)?).await
    }

    async fn init_and_wrap(mut dev: BladeRf1) -> Result<Self, Error> {
        dev.rf_link_session()
            .await
            .map_err(bladerf_err)?
            .initialize(false)
            .await
            .map_err(bladerf_err)?;
        let serial = dev.serial().await.map_err(bladerf_err)?;
        Ok(Self {
            device_slot: Shared::new(AsyncSlot::new(Box::new(dev))),
            abandoned_rx: Shared::new(AsyncSlot::empty()),
            abandoned_tx: Shared::new(AsyncSlot::empty()),
            serial,
        })
    }

    async fn lease_device(&self) -> Result<DeviceLease, Error> {
        let mut dev = AsyncSlotLease::acquire(&self.device_slot)?;
        cleanup_abandoned(&mut dev, &self.abandoned_rx, &self.abandoned_tx).await?;
        Ok(dev)
    }
}

#[cfg(not(target_os = "android"))]
async fn open_selected_device(selector: DeviceSelector) -> Result<BladeRf1, Error> {
    match selector {
        #[cfg(target_os = "linux")]
        DeviceSelector::Fd(fd) => {
            use std::os::fd::{FromRawFd, OwnedFd};
            let fd = unsafe { OwnedFd::from_raw_fd(fd) };
            BladeRf1::from_fd(fd).await
        }
        #[cfg(not(target_arch = "wasm32"))]
        DeviceSelector::BusAddr(bus_id, address) => BladeRf1::from_bus_addr(&bus_id, address).await,
        DeviceSelector::Serial(serial) => BladeRf1::from_serial(&serial).await,
        DeviceSelector::First => BladeRf1::from_first().await,
    }
    .map_err(bladerf_err)
}

impl AsyncBladeRf {
    fn driver(&self) -> Driver {
        Driver::BladeRf
    }

    async fn id(&self) -> Result<String, Error> {
        Ok(self.serial.clone())
    }

    async fn info(&self) -> Result<Args, Error> {
        let mut dev = self.lease_device().await?;
        let firmware = dev
            .value_mut()
            .fx3_firmware_version()
            .await
            .map_err(bladerf_err)?;
        let mut args = Args::default();
        args.set("driver", "bladerf");
        args.set("serial", self.serial.clone());
        args.set("firmware version", firmware);
        Ok(args)
    }

    async fn num_channels(&self, _direction: Direction) -> Result<usize, Error> {
        Ok(1)
    }

    async fn full_duplex(&self) -> Result<bool, Error> {
        Ok(true)
    }

    async fn antennas(&self, _direction: Direction, _channel: usize) -> Result<Vec<String>, Error> {
        Err(Error::unsupported(Capability::Antenna))
    }

    async fn antenna(&self, _direction: Direction, _channel: usize) -> Result<String, Error> {
        Err(Error::unsupported(Capability::Antenna))
    }

    async fn set_antenna(
        &self,
        _direction: Direction,
        _channel: usize,
        _name: &str,
    ) -> Result<(), Error> {
        Err(Error::unsupported(Capability::Antenna))
    }

    async fn agc_available(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        Ok(ch(direction, channel)? == Channel::Rx)
    }

    async fn set_agc_enabled(
        &self,
        direction: Direction,
        channel: usize,
        agc: bool,
    ) -> Result<(), Error> {
        let channel = ch(direction, channel)?;
        if channel != Channel::Rx {
            return Err(Error::unsupported(Capability::Agc));
        }
        let mode = if agc {
            GainMode::Default
        } else {
            GainMode::Mgc
        };
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        rf.set_gain_mode(channel, mode).await.map_err(bladerf_err)
    }

    async fn agc_enabled(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        if ch(direction, channel)? != Channel::Rx {
            return Err(Error::unsupported(Capability::Agc));
        }
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        Ok(rf.get_gain_mode().await.map_err(bladerf_err)? == GainMode::Default)
    }

    async fn gain_elements(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<String>, Error> {
        Ok(RfLinkSession::get_gain_stages(ch(direction, channel)?)
            .iter()
            .map(|s| <&str>::from(*s).to_string())
            .collect())
    }

    async fn set_gain(&self, direction: Direction, channel: usize, gain: f64) -> Result<(), Error> {
        let channel = ch(direction, channel)?;
        let range = RfLinkSession::get_gain_range(channel);
        let min = range.min().unwrap_or(f64::MIN);
        let max = range.max().unwrap_or(f64::MAX);
        let clamped = gain.clamp(min, max);
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        rf.set_gain(channel, GainDb::from(clamped as i8))
            .await
            .map_err(bladerf_err)
    }

    async fn gain(&self, direction: Direction, channel: usize) -> Result<Option<f64>, Error> {
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        Ok(Some(
            rf.get_gain(ch(direction, channel)?)
                .await
                .map_err(bladerf_err)?
                .db() as f64,
        ))
    }

    async fn gain_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
        RfLinkSession::get_gain_range(ch(direction, channel)?).try_into()
    }

    async fn set_gain_element(
        &self,
        direction: Direction,
        channel: usize,
        name: &str,
        gain: f64,
    ) -> Result<(), Error> {
        let stage = gain_stage(direction, channel, name)?;
        let range = RfLinkSession::get_gain_stage_range(stage);
        let min = range.min().unwrap_or(f64::MIN);
        let max = range.max().unwrap_or(f64::MAX);
        let clamped = gain.clamp(min, max);
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        rf.set_gain_stage(stage, GainDb::from(clamped as i8))
            .await
            .map_err(bladerf_err)
    }

    async fn gain_element(
        &self,
        direction: Direction,
        channel: usize,
        name: &str,
    ) -> Result<Option<f64>, Error> {
        let stage = gain_stage(direction, channel, name)?;
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        Ok(Some(
            rf.get_gain_stage(stage).await.map_err(bladerf_err)?.db() as f64,
        ))
    }

    async fn gain_element_range(
        &self,
        direction: Direction,
        channel: usize,
        name: &str,
    ) -> Result<Range, Error> {
        let stage = gain_stage(direction, channel, name)?;
        RfLinkSession::get_gain_stage_range(stage).try_into()
    }

    async fn frequency_range(
        &self,
        _direction: Direction,
        _channel: usize,
    ) -> Result<Range, Error> {
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        rf.get_frequency_range()
            .await
            .map_err(bladerf_err)?
            .try_into()
    }

    async fn frequency(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        Ok(rf
            .get_frequency(ch(direction, channel)?)
            .await
            .map_err(bladerf_err)? as f64)
    }

    async fn set_frequency(
        &self,
        direction: Direction,
        channel: usize,
        frequency: f64,
        _args: Args,
    ) -> Result<(), Error> {
        let ch = ch(direction, channel)?;
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        let f_range = rf.get_frequency_range().await.map_err(bladerf_err)?;
        if frequency < f_range.min().unwrap_or(f64::MIN) {
            log::trace!("Frequency {frequency} requires XB200 expansion board");
            if rf.expansion_get_attached().await.map_err(bladerf_err)? != ExpansionBoard::Xb200 {
                log::debug!("Automatically attaching XB200 expansion board");
                rf.expansion_attach(ExpansionBoard::Xb200)
                    .await
                    .map_err(bladerf_err)?;
            }
        }
        log::trace!("Setting frequency to {frequency}");
        if rf
            .set_frequency(ch, frequency as u64, TuningMode::Fpga)
            .await
            .is_err()
        {
            log::warn!("FPGA retune failed, falling back to host tuning");
            rf.set_frequency(ch, frequency as u64, TuningMode::Host)
                .await
                .map_err(bladerf_err)?;
        }
        Ok(())
    }

    async fn frequency_components(
        &self,
        _direction: Direction,
        _channel: usize,
    ) -> Result<Vec<String>, Error> {
        Err(Error::unsupported(Capability::Frequency))
    }

    async fn component_frequency_range(
        &self,
        _direction: Direction,
        _channel: usize,
        _name: &str,
    ) -> Result<Range, Error> {
        Err(Error::unsupported(Capability::Frequency))
    }

    async fn component_frequency(
        &self,
        _direction: Direction,
        _channel: usize,
        _name: &str,
    ) -> Result<f64, Error> {
        Err(Error::unsupported(Capability::Frequency))
    }

    async fn set_component_frequency(
        &self,
        _direction: Direction,
        _channel: usize,
        _name: &str,
        _frequency: f64,
    ) -> Result<(), Error> {
        Err(Error::unsupported(Capability::Frequency))
    }

    async fn sample_rate(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        Ok(rf
            .get_sample_rate(ch(direction, channel)?)
            .await
            .map_err(bladerf_err)? as f64)
    }

    async fn set_sample_rate(
        &self,
        direction: Direction,
        channel: usize,
        rate: f64,
    ) -> Result<(), Error> {
        let ch = ch(direction, channel)?;
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        let actual = rf
            .set_sample_rate(ch, rate as u32)
            .await
            .map_err(bladerf_err)?;
        if actual != rate as u32 {
            log::debug!("Requested sample rate {rate}, actual {actual}");
        }
        let bw_actual = rf.set_bandwidth(ch, actual).await.map_err(bladerf_err)?;
        if bw_actual != actual {
            log::debug!("Auto-set bandwidth to {bw_actual} (requested {actual})");
        }
        Ok(())
    }

    async fn get_sample_rate_range(
        &self,
        _direction: Direction,
        _channel: usize,
    ) -> Result<Range, Error> {
        RfLinkSession::get_sample_rate_range().try_into()
    }

    async fn bandwidth(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        Ok(rf
            .get_bandwidth(ch(direction, channel)?)
            .await
            .map_err(bladerf_err)? as f64)
    }

    async fn set_bandwidth(
        &self,
        direction: Direction,
        channel: usize,
        bw: f64,
    ) -> Result<(), Error> {
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        let actual = rf
            .set_bandwidth(ch(direction, channel)?, bw as u32)
            .await
            .map_err(bladerf_err)?;
        if actual != bw as u32 {
            log::debug!("Requested bandwidth {bw}, actual {actual}");
        }
        Ok(())
    }

    async fn get_bandwidth_range(
        &self,
        _direction: Direction,
        _channel: usize,
    ) -> Result<Range, Error> {
        RfLinkSession::get_bandwidth_range().try_into()
    }
}

impl AsyncDeviceInfo for AsyncBladeRf {
    fn driver(&self) -> Driver {
        AsyncBladeRf::driver(self)
    }

    async fn async_id(&self) -> Result<String, Error> {
        AsyncBladeRf::id(self).await
    }

    async fn async_info(&self) -> Result<Args, Error> {
        AsyncBladeRf::info(self).await
    }

    async fn async_num_channels(&self, direction: Direction) -> Result<usize, Error> {
        AsyncBladeRf::num_channels(self, direction).await
    }

    async fn async_full_duplex(&self) -> Result<bool, Error> {
        AsyncBladeRf::full_duplex(self).await
    }
}

crate::impl_dyn_async_device_backend!(
    AsyncBladeRf => [rx, tx, antenna, agc, gain, frequency, sample_rate, bandwidth]
);

impl AsyncRxDevice for AsyncBladeRf {
    type RxStreamer = AsyncBladeRfRxStreamer;

    async fn async_rx_streamer(
        &self,
        channels: &[usize],
        _args: Args,
    ) -> Result<Self::RxStreamer, Error> {
        check_channels(channels, "RX")?;
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        let stream = RxStream::builder(&mut rf)
            .buffer_size(BUFFER_SIZE)
            .buffer_count(BUFFER_COUNT)
            .format(STREAM_FORMAT)
            .build()
            .await
            .map_err(bladerf_err)?;
        Ok(AsyncBladeRfRxStreamer {
            device_slot: Shared::clone(&self.device_slot),
            abandoned: Shared::clone(&self.abandoned_rx),
            stream: Some(stream),
            converter: RxConverter::new(STREAM_FORMAT),
        })
    }
}

impl AsyncTxDevice for AsyncBladeRf {
    type TxStreamer = AsyncBladeRfTxStreamer;

    async fn async_tx_streamer(
        &self,
        channels: &[usize],
        _args: Args,
    ) -> Result<Self::TxStreamer, Error> {
        check_channels(channels, "TX")?;
        let mut dev = self.lease_device().await?;
        let mut rf = session(&mut dev).await?;
        let stream = TxStream::builder(&mut rf)
            .buffer_size(BUFFER_SIZE)
            .buffer_count(BUFFER_COUNT)
            .format(STREAM_FORMAT)
            .build()
            .await
            .map_err(bladerf_err)?;
        Ok(AsyncBladeRfTxStreamer {
            device_slot: Shared::clone(&self.device_slot),
            abandoned: Shared::clone(&self.abandoned_tx),
            stream: Some(stream),
            format: STREAM_FORMAT,
        })
    }
}

impl AsyncAntennaControl for AsyncBladeRf {
    async fn async_antennas(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<String>, Error> {
        AsyncBladeRf::antennas(self, direction, channel).await
    }

    async fn async_antenna(&self, direction: Direction, channel: usize) -> Result<String, Error> {
        AsyncBladeRf::antenna(self, direction, channel).await
    }

    async fn async_set_antenna(
        &self,
        direction: Direction,
        channel: usize,
        name: &str,
    ) -> Result<(), Error> {
        AsyncBladeRf::set_antenna(self, direction, channel, name).await
    }
}

impl AsyncAgcControl for AsyncBladeRf {
    async fn async_agc_available(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<bool, Error> {
        AsyncBladeRf::agc_available(self, direction, channel).await
    }

    async fn async_agc_enabled(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        AsyncBladeRf::agc_enabled(self, direction, channel).await
    }

    async fn async_set_agc_enabled(
        &self,
        direction: Direction,
        channel: usize,
        enabled: bool,
    ) -> Result<(), Error> {
        AsyncBladeRf::set_agc_enabled(self, direction, channel, enabled).await
    }
}

impl AsyncGainControl for AsyncBladeRf {
    async fn async_gain_elements(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<String>, Error> {
        AsyncBladeRf::gain_elements(self, direction, channel).await
    }

    async fn async_set_gain(
        &self,
        direction: Direction,
        channel: usize,
        gain: f64,
    ) -> Result<(), Error> {
        AsyncBladeRf::set_gain(self, direction, channel, gain).await
    }

    async fn async_gain(&self, direction: Direction, channel: usize) -> Result<Option<f64>, Error> {
        AsyncBladeRf::gain(self, direction, channel).await
    }

    async fn async_gain_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
        AsyncBladeRf::gain_range(self, direction, channel).await
    }

    async fn async_set_gain_element(
        &self,
        direction: Direction,
        channel: usize,
        name: &str,
        gain: f64,
    ) -> Result<(), Error> {
        AsyncBladeRf::set_gain_element(self, direction, channel, name, gain).await
    }

    async fn async_gain_element(
        &self,
        direction: Direction,
        channel: usize,
        name: &str,
    ) -> Result<Option<f64>, Error> {
        AsyncBladeRf::gain_element(self, direction, channel, name).await
    }

    async fn async_gain_element_range(
        &self,
        direction: Direction,
        channel: usize,
        name: &str,
    ) -> Result<Range, Error> {
        AsyncBladeRf::gain_element_range(self, direction, channel, name).await
    }
}

impl AsyncFrequencyControl for AsyncBladeRf {
    async fn async_frequency_range(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Range, Error> {
        AsyncBladeRf::frequency_range(self, direction, channel).await
    }

    async fn async_frequency(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        AsyncBladeRf::frequency(self, direction, channel).await
    }

    async fn async_set_frequency(
        &self,
        direction: Direction,
        channel: usize,
        frequency: f64,
        args: Args,
    ) -> Result<(), Error> {
        AsyncBladeRf::set_frequency(self, direction, channel, frequency, args).await
    }

    async fn async_frequency_components(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<String>, Error> {
        AsyncBladeRf::frequency_components(self, direction, channel).await
    }

    async fn async_component_frequency_range(
        &self,
        direction: Direction,
        channel: usize,
        name: &str,
    ) -> Result<Range, Error> {
        AsyncBladeRf::component_frequency_range(self, direction, channel, name).await
    }

    async fn async_component_frequency(
        &self,
        direction: Direction,
        channel: usize,
        name: &str,
    ) -> Result<f64, Error> {
        AsyncBladeRf::component_frequency(self, direction, channel, name).await
    }

    async fn async_set_component_frequency(
        &self,
        direction: Direction,
        channel: usize,
        name: &str,
        frequency: f64,
    ) -> Result<(), Error> {
        AsyncBladeRf::set_component_frequency(self, direction, channel, name, frequency).await
    }
}

impl AsyncSampleRateControl for AsyncBladeRf {
    async fn async_sample_rate(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        AsyncBladeRf::sample_rate(self, direction, channel).await
    }

    async fn async_set_sample_rate(
        &self,
        direction: Direction,
        channel: usize,
        rate: f64,
    ) -> Result<(), Error> {
        AsyncBladeRf::set_sample_rate(self, direction, channel, rate).await
    }

    async fn async_get_sample_rate_range(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Range, Error> {
        AsyncBladeRf::get_sample_rate_range(self, direction, channel).await
    }
}

impl AsyncBandwidthControl for AsyncBladeRf {
    async fn async_bandwidth(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        AsyncBladeRf::bandwidth(self, direction, channel).await
    }

    async fn async_set_bandwidth(
        &self,
        direction: Direction,
        channel: usize,
        bw: f64,
    ) -> Result<(), Error> {
        AsyncBladeRf::set_bandwidth(self, direction, channel, bw).await
    }

    async fn async_get_bandwidth_range(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Range, Error> {
        AsyncBladeRf::get_bandwidth_range(self, direction, channel).await
    }
}

impl crate::AsyncRxStreamer for AsyncBladeRfRxStreamer {
    async fn mtu(&self) -> Result<usize, Error> {
        Ok(BUFFER_SIZE / STREAM_FORMAT.sample_size())
    }

    async fn activate_at(&mut self, time_ns: Option<i64>) -> Result<(), Error> {
        if time_ns.is_some() {
            return Err(Error::unsupported(Capability::TimedActivation));
        }
        let stream = self.stream.as_mut().ok_or(Error::DeviceDisconnected)?;
        let mut dev = AsyncSlotLease::acquire(&self.device_slot)?;
        let mut rf = session(&mut dev).await?;
        match stream.start(&mut rf).await {
            Ok(()) | Err(libbladerf_rs::Error::StreamAlreadyStarted) => Ok(()),
            Err(error) => Err(bladerf_err(error)),
        }
    }

    async fn deactivate_at(&mut self, time_ns: Option<i64>) -> Result<(), Error> {
        if time_ns.is_some() {
            return Err(Error::unsupported(Capability::TimedDeactivation));
        }
        let stream = self.stream.as_mut().ok_or(Error::DeviceDisconnected)?;
        if let Some(buffer) = self.converter.take_pending() {
            stream.recycle(buffer);
        }
        let mut dev = AsyncSlotLease::acquire(&self.device_slot)?;
        let mut rf = session(&mut dev).await?;
        match stream.stop(&mut rf).await {
            Ok(()) | Err(libbladerf_rs::Error::StreamNotStarted) => Ok(()),
            Err(error) => Err(bladerf_err(error)),
        }
    }

    async fn read<'a>(
        &'a mut self,
        buffers: &'a mut [&'a mut [Complex32]],
        timeout_us: i64,
    ) -> Result<usize, Error> {
        check_buffer_count(buffers.len())?;
        let out = &mut buffers[0];
        if out.is_empty() {
            return Ok(0);
        }
        let stream = self.stream.as_mut().ok_or(Error::DeviceDisconnected)?;

        let (mut written, recycled) = self.converter.drain_pending(out)?;
        if let Some(buf) = recycled {
            stream.recycle(buf);
        }
        if written >= out.len() {
            return Ok(written);
        }

        let dma_buffer = match with_timeout(
            stream.read(None).into_future(),
            timeout_from_micros(timeout_us),
        )
        .await
        {
            TimeoutResult::Completed(buffer) => buffer.map_err(bladerf_err)?,
            TimeoutResult::TimedOut => return Ok(written),
        };
        let (n, recycled) = self.converter.consume(dma_buffer, &mut out[written..])?;
        if let Some(buf) = recycled {
            stream.recycle(buf);
        }
        written += n;
        Ok(written)
    }
}

impl Drop for AsyncBladeRfRxStreamer {
    fn drop(&mut self) {
        if let Some(mut stream) = self.stream.take() {
            if let Some(buffer) = self.converter.take_pending() {
                stream.recycle(buffer);
            }
            let result = self.abandoned.put(stream);
            debug_assert!(
                result.is_ok(),
                "abandoned RX slot was unexpectedly occupied"
            );
        }
    }
}

impl crate::AsyncTxStreamer for AsyncBladeRfTxStreamer {
    async fn mtu(&self) -> Result<usize, Error> {
        Ok(BUFFER_SIZE / self.format.sample_size())
    }

    async fn activate_at(&mut self, time_ns: Option<i64>) -> Result<(), Error> {
        if time_ns.is_some() {
            return Err(Error::unsupported(Capability::TimedActivation));
        }
        let stream = self.stream.as_mut().ok_or(Error::DeviceDisconnected)?;
        let mut dev = AsyncSlotLease::acquire(&self.device_slot)?;
        let mut rf = session(&mut dev).await?;
        match stream.start(&mut rf).await {
            Ok(()) | Err(libbladerf_rs::Error::StreamAlreadyStarted) => Ok(()),
            Err(error) => Err(bladerf_err(error)),
        }
    }

    async fn deactivate_at(&mut self, time_ns: Option<i64>) -> Result<(), Error> {
        if time_ns.is_some() {
            return Err(Error::unsupported(Capability::TimedDeactivation));
        }
        let stream = self.stream.as_mut().ok_or(Error::DeviceDisconnected)?;
        let mut dev = AsyncSlotLease::acquire(&self.device_slot)?;
        let mut rf = session(&mut dev).await?;
        match stream.stop(&mut rf).await {
            Ok(()) | Err(libbladerf_rs::Error::StreamNotStarted) => Ok(()),
            Err(error) => Err(bladerf_err(error)),
        }
    }

    async fn write<'a>(
        &'a mut self,
        buffers: &'a [&'a [Complex32]],
        _at_ns: Option<i64>,
        _end_burst: bool,
        timeout_us: i64,
    ) -> Result<usize, Error> {
        check_buffer_count(buffers.len())?;
        if buffers[0].is_empty() {
            return Ok(0);
        }
        let stream = self.stream.as_mut().ok_or(Error::DeviceDisconnected)?;
        let bytes_per_sample = self.format.sample_size();
        let samples_to_write = buffers[0].len().min(BUFFER_SIZE / bytes_per_sample);
        let bytes_needed = samples_to_write * bytes_per_sample;

        let mut dma_buffer = match with_timeout(
            stream.get_buffer(None).into_future(),
            timeout_from_micros(timeout_us),
        )
        .await
        {
            TimeoutResult::Completed(buffer) => buffer.map_err(bladerf_err)?,
            TimeoutResult::TimedOut => return Err(Error::Timeout),
        };
        dma_buffer.clear();
        let converted = convert_complex32_to_bytes(
            self.format,
            &buffers[0][..samples_to_write],
            dma_buffer.extend_fill(bytes_needed, 0),
        )?;
        if converted != samples_to_write {
            stream.recycle(dma_buffer);
            return Err(Error::Driver(DriverError::Other(
                "sample conversion produced a short TX buffer".into(),
            )));
        }
        stream
            .submit(dma_buffer, bytes_needed)
            .map_err(bladerf_err)?;
        Ok(samples_to_write)
    }
}

impl Drop for AsyncBladeRfTxStreamer {
    fn drop(&mut self) {
        if let Some(stream) = self.stream.take() {
            let result = self.abandoned.put(stream);
            debug_assert!(
                result.is_ok(),
                "abandoned TX slot was unexpectedly occupied"
            );
        }
    }
}

impl AsyncTypedDeviceBackend for AsyncBladeRf {
    fn driver() -> Driver {
        Driver::BladeRf
    }

    #[cfg(target_arch = "wasm32")]
    fn webusb_filters(args: &Args) -> Result<Vec<WebUsbDeviceFilter>, Error> {
        let filter = WebUsbDeviceFilter::new().with_vendor_product(USB_VID, USB_PID);
        Ok(vec![match device_selector(args)? {
            DeviceSelector::Serial(serial) => filter.with_serial_number(serial),
            DeviceSelector::First => filter,
        }])
    }

    async fn async_probe(args: &Args) -> Result<Vec<Args>, Error> {
        Self::probe(args).await
    }

    async fn async_open(args: &Args) -> Result<Self, Error> {
        Self::open(args.clone()).await
    }
}

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

    #[test]
    fn dropping_async_slot_lease_returns_value() {
        let slot = Shared::new(AsyncSlot::new(7));

        let lease = AsyncSlotLease::acquire(&slot).expect("acquire slot lease");
        assert!(matches!(AsyncSlotLease::acquire(&slot), Err(Error::Busy)));
        drop(lease);

        let lease = AsyncSlotLease::acquire(&slot).expect("reacquire slot lease");
        assert_eq!(*lease.value.as_ref().expect("lease owns value"), 7);
    }
}