usbdac-core 0.1.7

Direct USB DAC playback for Rust audio applications on Android and Linux, with PCM, DoP, native DSD and bit-perfect reporting.
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
//! The DAC handle.

mod routing;

use crate::capabilities::{Capabilities, DeviceInfo};
use crate::config::{CloseVolume, DacConfig, HandBack};
use crate::error::{Error, OrControl, Result};
use crate::events::{DacListener, EventHub, EventSink};
use crate::format::{StreamFormat, StreamRequest};
use crate::settings::{self, Settings};
use crate::stream::{DacStream, StreamInner};
use crate::transport;
use crate::volume::VolumeControl;
use parking_lot::Mutex;
use std::os::fd::RawFd;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;

/// How long `close` waits for the output thread to finish.
const CLOSE_TIMEOUT: Duration = Duration::from_secs(3);

/// Serializes `Dac::open`, so two concurrent opens cannot disturb each other's
/// settings.
static OPEN_GUARD: Mutex<()> = Mutex::new(());

fn reconfigure_or_restore<T>(
    requested: &StreamRequest,
    previous: &StreamRequest,
    mut attempt: impl FnMut(&StreamRequest) -> Result<T>,
) -> Result<(T, Option<Error>)> {
    match attempt(requested) {
        Ok(stream) => Ok((stream, None)),
        Err(error) => match attempt(previous) {
            Ok(stream) => Ok((stream, Some(error))),
            Err(rollback) => Err(Error::ReconfigureUnusable(format!(
                "requested format failed: {error}; rollback failed: {rollback}"
            ))),
        },
    }
}

/// State shared by the `Dac`, its streams and its volume handle.
pub(crate) struct DacShared {
    pub(crate) events: EventSink,
    pub(crate) context: Arc<transport::context::SessionContext>,
    pub(crate) info: DeviceInfo,
    pub(crate) config: DacConfig,
    closed: AtomicBool,
    pub(crate) control_guard: Mutex<()>,
    pub(crate) stream: Mutex<Option<Weak<StreamInner>>>,
    last_feedback_stream: Mutex<Option<(StreamFormat, Arc<transport::RuntimeStats>)>>,
}

impl DacShared {
    fn remember_feedback_stream(&self, format: &StreamFormat, stream: &StreamInner) {
        if stream.shared.stats.feedback_trace.is_some() {
            *self.last_feedback_stream.lock() =
                Some((format.clone(), Arc::clone(&stream.shared.stats)));
        }
    }

    pub(crate) fn enter(&self) -> Result<transport::context::Scope> {
        self.ensure_open()?;
        Ok(self.context.enter())
    }

    pub(crate) fn ensure_open(&self) -> Result<()> {
        if self.closed.load(Ordering::Acquire) {
            Err(Error::InvalidState("the DAC is closed".to_string()))
        } else {
            Ok(())
        }
    }

    /// The stream that is open now, if any.
    fn active_stream(&self) -> Option<Arc<StreamInner>> {
        self.stream
            .lock()
            .as_ref()
            .and_then(Weak::upgrade)
            .filter(|stream| !stream.is_closed())
    }

    /// Closes with what the configuration says about the original volume
    /// (`None`) or with what the host decided at close.
    fn shutdown(&self, volume: Option<CloseVolume>) -> Result<()> {
        let _control = self.control_guard.lock();
        let _scope = self.context.enter();
        if self.closed.swap(true, Ordering::AcqRel) {
            return Ok(());
        }
        if let Some(stream) = self.active_stream() {
            let _ = stream.close();
        }
        // A DAC that has gone cannot be written to, and what was recorded for
        // it must not survive into a later attachment: forget it, whatever was
        // asked for.
        let action = if self.events.device_lost() {
            transport::api::ORIGINAL_VOLUME_ACTION_FORGET
        } else {
            match volume {
                Some(CloseVolume::Restore) => transport::api::ORIGINAL_VOLUME_ACTION_RESTORE,
                Some(CloseVolume::Keep) => transport::api::ORIGINAL_VOLUME_ACTION_KEEP,
                Some(CloseVolume::Forget) => transport::api::ORIGINAL_VOLUME_ACTION_FORGET,
                None => match self.config.hand_back {
                    HandBack::RestoreOriginal => transport::api::ORIGINAL_VOLUME_ACTION_RESTORE,
                    HandBack::Keep => transport::api::ORIGINAL_VOLUME_ACTION_KEEP,
                },
            }
        };
        let stopped = transport::api::close_device(action, CLOSE_TIMEOUT);
        drop(_control);
        self.events.shutdown();
        if stopped {
            Ok(())
        } else {
            Err(Error::Transfer(
                "the USB output thread did not stop in time; the DAC stays busy until it does"
                    .to_string(),
            ))
        }
    }
}

/// An open USB DAC.
///
/// Distinct USB attachments have independent owners. Opening the same physical
/// attachment twice returns [`Error::Busy`] until its owner retires. The host keeps its
/// `UsbDeviceConnection` open until then.
pub struct Dac {
    shared: Arc<DacShared>,
}

/// A replacement stream on the same physical handle, paused with zero-based counters.
/// A failed requested format can still return a successfully restored old-format stream.
#[derive(Debug)]
pub struct StreamReconfiguration {
    pub stream: DacStream,
    /// The requested-format error when rollback restored the old format; `None` on success.
    pub rollback_cause: Option<Error>,
}

impl std::fmt::Debug for Dac {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Dac")
            .field("info", &self.shared.info)
            .finish_non_exhaustive()
    }
}

impl Dac {
    /// Read-only proof of a fixed-rate vendor PCM profile. Returns the actual
    /// active configuration and the sole interface the host may claim.
    pub fn vendor_pcm_preflight(fd: RawFd, info: &DeviceInfo) -> Result<Option<(u8, u8)>> {
        let _guard = OPEN_GUARD.lock();
        let context = transport::context::SessionContext::reserve(fd)?;
        let _scope = context.enter();
        if transport::session::session_registered() {
            return Err(Error::Busy);
        }
        transport::api::vendor_pcm_preflight(fd, info)
    }

    /// Read-only descriptor proof of the exact active configuration and complete
    /// interface claim set for a fixed-rate vendor PCM profile.
    pub fn vendor_pcm_claims_preflight(
        fd: RawFd,
        info: &DeviceInfo,
    ) -> Result<Option<(u8, Vec<u8>)>> {
        let _guard = OPEN_GUARD.lock();
        let context = transport::context::SessionContext::reserve(fd)?;
        let _scope = context.enter();
        if transport::session::session_registered() {
            return Err(Error::Busy);
        }
        transport::api::vendor_pcm_claims_preflight(fd, info)
    }

    /// Prove the exact optional Scarlett vendor claim from actual USB descriptors.
    /// Requires the host-selected configuration; sends no proprietary requests.
    pub fn scarlett_routing_preflight(
        fd: RawFd,
        info: &DeviceInfo,
    ) -> Result<Option<crate::scarlett::ReadCapability>> {
        let _guard = OPEN_GUARD.lock();
        let context = transport::context::SessionContext::reserve(fd)?;
        let _scope = context.enter();
        if transport::session::session_registered() {
            return Err(Error::Busy);
        }
        transport::routing_hw::scarlett_preflight(fd, info)
    }

    /// Read the active configuration's explicit PCM IN claim plan before the
    /// host claims its AudioControl and input streaming interfaces. Returns
    /// `(configuration, control_interfaces, input_interfaces)` without audio.
    pub fn capture_preflight(fd: RawFd, info: &DeviceInfo) -> Result<(u8, Vec<u8>, Vec<u8>)> {
        let _guard = OPEN_GUARD.lock();
        let context = transport::context::SessionContext::reserve(fd)?;
        let _scope = context.enter();
        if transport::session::session_registered() {
            return Err(Error::Busy);
        }
        let device = transport::api::capture_preflight_device(fd, info)?;
        Ok(device)
    }
    /// Register an explicitly claimed capture device, including an input-only
    /// device. Claim its IN AudioStreaming interfaces and their owning
    /// AudioControl interfaces before calling; no playback claim is needed.
    /// This entry point performs no output-volume setup. Android/JNI capture
    /// permission and claim orchestration is a separate integration step.
    pub fn open_capture_device(fd: RawFd, info: DeviceInfo, config: DacConfig) -> Result<Dac> {
        config.validate()?;
        let _guard = OPEN_GUARD.lock();
        let context = transport::context::SessionContext::reserve(fd)?;
        let _scope = context.enter();
        if transport::session::session_registered() {
            return Err(Error::Busy);
        }
        settings::install(Settings::for_device(config.clone(), &info));
        if let Err(error) = transport::api::open_capture_device(fd, &info) {
            settings::reset();
            return Err(error);
        }
        context.admit();
        Ok(Dac {
            shared: Arc::new(DacShared {
                context: transport::context::current(),
                events: EventHub::start(),
                info,
                config,
                closed: AtomicBool::new(false),
                control_guard: Mutex::new(()),
                stream: Mutex::new(None),
                last_feedback_stream: Mutex::new(None),
            }),
        })
    }

    /// Start standalone, exact-format PCM capture on a claimed IN interface.
    /// The capture worker exclusively owns USB until all transfers retire;
    /// concurrent playback, duplex and routing changes are refused.
    pub fn open_capture(
        &self,
        request: &crate::capture::CaptureRequest,
        capacity_frames: usize,
    ) -> Result<crate::capture::DacCaptureStream> {
        let _control = self.shared.control_guard.lock();
        let _scope = self.shared.enter()?;
        let handle = transport::capture_stream::open_capture(
            request,
            capacity_frames,
            self.shared.events.clone(),
        )?;
        Ok(crate::capture::DacCaptureStream::new(
            Arc::clone(&self.shared),
            handle,
        ))
    }

    /// Capture owner-specific retirement evidence before consuming `close`.
    /// Retain this token with this device's claims/FD after a close timeout;
    /// another open device does not affect its result.
    pub fn retirement(&self) -> UsbRetirement {
        UsbRetirement {
            context: self.shared.context.clone(),
        }
    }

    /// Wait until all process USB owners retire. For a particular connection,
    /// use [`Dac::retirement`] so another active DAC does not block hand-back.
    ///
    /// After [`Dac::close`] returns a transfer timeout, retain all host ownership
    /// and call this until it returns `true`. This does not require a live `Dac` handle.
    /// Check retirement using the actual host connection FD after a failed open.
    /// The host must keep this FD valid; caller-supplied USB names are not identity.
    pub fn await_connection_retirement(fd: RawFd, timeout: Duration) -> Result<bool> {
        transport::context::await_connection_retirement(fd, timeout)
    }

    pub fn await_usb_retirement(timeout: Duration) -> bool {
        transport::context::await_all_retirement(timeout)
    }

    /// Identify optional capture interfaces after the host claims the base audio interfaces.
    /// Returns the active configuration ID and source interface numbers without starting audio.
    pub fn feedback_preflight(fd: RawFd, info: &DeviceInfo) -> Result<(u8, Vec<u8>)> {
        let _guard = OPEN_GUARD.lock();
        let context = transport::context::SessionContext::reserve(fd)?;
        let _scope = context.enter();
        if transport::session::session_registered() {
            return Err(Error::Busy);
        }
        transport::api::feedback_preflight(fd, info)
    }

    /// Opens the DAC behind `fd`.
    ///
    /// `fd` is the usbfs file descriptor of the device (on Android
    /// `UsbDeviceConnection.getFileDescriptor()`); the library duplicates it, so
    /// the host keeps ownership of its own. `info.claimed_interfaces` must be
    /// the AudioControl and playback AudioStreaming interfaces plus any
    /// optional capture sources identified by [`Dac::feedback_preflight`].
    ///
    /// Opening scans the descriptors, finds the hardware volume control, records
    /// the DAC's current level and, with the default
    /// [`StartupVolume::Attenuate`](crate::StartupVolume::Attenuate), lowers every
    /// channel to at most -40 dB and verifies it, so that no stream can start
    /// at the DAC's own (often full-scale) level. It does not touch the clock or
    /// start any audio. [`VolumeControl::startup`](crate::VolumeControl::startup)
    /// says what it did.
    pub fn open(fd: RawFd, info: DeviceInfo, config: DacConfig) -> Result<Dac> {
        Self::open_playback_device(fd, info, config, false)
    }

    /// Explicit duplex registration. Claim the base playback interfaces and all
    /// IN/control interfaces returned by capture_preflight for the same configuration.
    /// Ordinary playback registration retains its narrower optional-IN policy.
    pub fn open_duplex_device(fd: RawFd, info: DeviceInfo, config: DacConfig) -> Result<Dac> {
        Self::open_playback_device(fd, info, config, true)
    }

    fn open_playback_device(
        fd: RawFd,
        info: DeviceInfo,
        config: DacConfig,
        duplex: bool,
    ) -> Result<Dac> {
        config.validate()?;
        let _guard = OPEN_GUARD.lock();
        let context = transport::context::SessionContext::reserve(fd)?;
        let _scope = context.enter();
        if transport::session::session_registered() {
            return Err(Error::Busy);
        }
        settings::install(Settings::for_device(config.clone(), &info));
        let registration = if duplex {
            transport::api::open_duplex_device(fd, &info)
        } else {
            transport::api::open_device(fd, &info)
        };
        if let Err(error) = registration {
            settings::reset();
            return Err(error);
        }
        context.admit();
        let events = EventHub::start();
        // The start-up step lowered the level before this handle existed: tell
        // the first listener, as a change made through the library.
        if let Some(state) = transport::volume_hw::startup_lowered_volume() {
            events.emit_dac_or_hold(crate::events::DacEvent::VolumeChanged(state));
        }
        Ok(Dac {
            shared: Arc::new(DacShared {
                context: transport::context::current(),
                events,
                info,
                config,
                closed: AtomicBool::new(false),
                control_guard: Mutex::new(()),
                stream: Mutex::new(None),
                last_feedback_stream: Mutex::new(None),
            }),
        })
    }

    /// The identity the host gave at open.
    pub fn info(&self) -> &DeviceInfo {
        &self.shared.info
    }

    /// Export the last stream's opt-in support capture, even after the stream
    /// has closed. A new successfully opened stream replaces it.
    pub fn feedback_trace(&self) -> Option<crate::FeedbackTrace> {
        let (format, stats) = self.shared.last_feedback_stream.lock().clone()?;
        let explicit = *stats.explicit_feedback_diagnostics.lock();
        Some(stats.feedback_trace.as_ref()?.snapshot(format, explicit))
    }

    /// What the DAC offers, from the descriptors scanned at open.
    pub fn capabilities(&self) -> Result<Capabilities> {
        let _scope = self.shared.enter()?;
        transport::api::capabilities()
    }

    /// Settles the wire format for `request`.
    ///
    /// This programs the DAC's sampling frequency and reads it back (it is the
    /// step that can fail with [`Error::ClockUnverified`] later), so it takes
    /// 100 ms or more. It fails with [`Error::InvalidState`] while a stream is
    /// open. Nothing is resampled: with [`RatePolicy::Exact`] a rate the DAC
    /// cannot run is [`Error::Unsupported`]; with `NearestSupported` the
    /// returned format carries the rate the DAC will run.
    ///
    /// [`RatePolicy::Exact`]: crate::RatePolicy::Exact
    pub fn negotiate(&self, request: &StreamRequest) -> Result<StreamFormat> {
        let _control = self.shared.control_guard.lock();
        self.negotiate_locked(request)
    }

    fn negotiate_locked(&self, request: &StreamRequest) -> Result<StreamFormat> {
        let _scope = self.shared.enter()?;
        transport::api::negotiate(request)
    }

    /// Opens the output stream for a negotiated format and starts the output
    /// thread. The stream plays as soon as the ring holds the start threshold
    /// ([`DacConfig::start_threshold_ms`]) of audio. Only one stream can be open
    /// at a time.
    ///
    /// Fails with [`Error::VolumeUnavailable`] when the stream's own route has
    /// no usable hardware volume control and
    /// [`DacConfig::require_hardware_volume`] is on; nothing is programmed and
    /// no output thread starts.
    ///
    /// `listener` receives the stream's events; see [`DacListener`].
    pub fn open_stream(
        &self,
        format: &StreamFormat,
        listener: Arc<dyn DacListener>,
    ) -> Result<DacStream> {
        let _control = self.shared.control_guard.lock();
        self.open_stream_locked(format, listener)
    }

    fn open_stream_locked(
        &self,
        format: &StreamFormat,
        listener: Arc<dyn DacListener>,
    ) -> Result<DacStream> {
        let _scope = self.shared.enter()?;
        let mut slot = self.shared.stream.lock();
        if slot
            .as_ref()
            .and_then(Weak::upgrade)
            .is_some_and(|stream| !stream.is_closed())
        {
            return Err(Error::InvalidState("a stream is already open".to_string()));
        }
        self.shared.events.set_stream_listener(Some(listener));
        let handle = match transport::api::open_stream(format, self.shared.events.clone()) {
            Ok(handle) => handle,
            Err(error) => {
                self.shared.events.set_stream_listener(None);
                return Err(error);
            }
        };
        let inner = StreamInner::new(Arc::clone(&self.shared), handle, format.clone());
        self.shared.remember_feedback_stream(format, &inner);
        *slot = Some(Arc::downgrade(&inner));
        drop(slot);
        inner.start_events();
        Ok(DacStream::from_inner(inner))
    }

    /// Drain and replace a playback-only stream without reopening the physical USB handle or host claims.
    ///
    /// Stop the writer before calling. The stream must belong to this DAC. Drain temporarily plays
    /// a paused stream so queued audio can complete. A drain timeout retains the original open
    /// stream in draining state; the caller still owns it and may wait, flush or close it.
    ///
    /// After retirement, normal lock-requested cleanup retains the exact libusb owner in IDLE_LOCK.
    /// Every negotiation/open must reuse that identity; losing it is an unusable-state error, never
    /// an implicit physical reopen. No volume initialization/hand-back occurs. Success or rollback
    /// returns a paused replacement with zero-based counters; supply/reseek PCM and explicitly play.
    /// A rollback failure returns `ReconfigureUnusable` and requires closing the DAC.
    pub fn reconfigure_stream(
        &self,
        current: &DacStream,
        request: &StreamRequest,
        listener: Arc<dyn DacListener>,
        drain_timeout: Duration,
    ) -> Result<StreamReconfiguration> {
        let _control = self.shared.control_guard.lock();
        let _scope = self.shared.enter()?;
        transport::api::playback_format_from_request(request)?;
        let identity = current.reconfigure_identity(&self.shared)?;
        let previous = current.format().request;
        let deadline = std::time::Instant::now()
            .checked_add(drain_timeout)
            .ok_or_else(|| {
                Error::InvalidArgument("drain timeout overflows monotonic clock".into())
            })?;
        let volume_route = transport::api::volume_route_signature();
        let volume_before = if volume_route.is_some() {
            Some(transport::volume_hw::read_volume_state().or_control()?)
        } else {
            None
        };
        current.drain()?;
        current.play()?;
        while !current.is_drained() {
            if matches!(
                current.state(),
                crate::StreamState::Failed | crate::StreamState::Closed
            ) {
                return Err(Error::ReconfigureUnusable("original stream failed during drain; retained stream remains available for explicit close".into()));
            }
            if std::time::Instant::now() >= deadline {
                return Err(Error::ReconfigureDrainTimeout);
            }
            std::thread::sleep(Duration::from_millis(2));
        }
        current
            .retire_for_reconfigure()
            .map_err(|error| Error::ReconfigureUnusable(error.to_string()))?;
        if transport::api::retained_usb_handle_identity() != Some(identity) {
            return Err(Error::ReconfigureUnusable(
                "old USB owner was not retained after retirement".into(),
            ));
        }
        let mut attempt = |target: &StreamRequest| -> Result<DacStream> {
            if transport::api::retained_usb_handle_identity() != Some(identity) {
                return Err(Error::ReconfigureUnusable(
                    "retained USB owner was lost before negotiation".into(),
                ));
            }
            let format = self.negotiate_locked(target)?;
            if transport::api::retained_usb_handle_identity() != Some(identity) {
                return Err(Error::ReconfigureUnusable(
                    "negotiation replaced or lost the USB owner".into(),
                ));
            }
            let opened = self.open_stream_locked(&format, listener.clone())?;
            if opened.reconfigure_identity(&self.shared)? != identity {
                drop(opened);
                return Err(Error::ReconfigureUnusable(
                    "replacement used a different physical USB owner".into(),
                ));
            }
            opened.pause()?;
            if transport::api::volume_route_signature() != volume_route {
                drop(opened);
                return Err(Error::Control(
                    "reconfiguration changed the hardware volume route; rollback required".into(),
                ));
            }
            let volume_after = if volume_route.is_some() {
                Some(transport::volume_hw::read_volume_state().or_control()?)
            } else {
                None
            };
            if volume_after != volume_before {
                drop(opened);
                return Err(Error::Control(
                    "hardware volume changed during reconfiguration; preservation not proved"
                        .into(),
                ));
            }
            Ok(opened)
        };
        let (stream, rollback_cause) = reconfigure_or_restore(request, &previous, &mut attempt)?;
        Ok(StreamReconfiguration {
            stream,
            rollback_cause,
        })
    }

    /// Open playback and PCM capture atomically on one USB worker.
    ///
    /// The output must have a current negotiated format. Shared source clocks
    /// require equal wire rates; distinct proven clock sources retain their own
    /// rates and position counters. Capture never supplies playback timing unless
    /// it exactly matches playback's already selected implicit feedback source.
    /// Closing either stream stops both endpoints and retires their transfers.
    pub fn open_duplex(
        &self,
        format: &StreamFormat,
        capture: &crate::capture::CaptureRequest,
        capacity_frames: usize,
        listener: Arc<dyn DacListener>,
    ) -> Result<(DacStream, crate::capture::DacCaptureStream)> {
        let _control = self.shared.control_guard.lock();

        let _scope = self.shared.enter()?;
        let mut slot = self.shared.stream.lock();
        if slot
            .as_ref()
            .and_then(Weak::upgrade)
            .is_some_and(|stream| !stream.is_closed())
        {
            return Err(Error::Busy);
        }
        self.shared.events.set_stream_listener(Some(listener));
        let (output, input) = match transport::duplex::open(
            format,
            capture,
            capacity_frames,
            self.shared.events.clone(),
        ) {
            Ok(pair) => pair,
            Err(error) => {
                self.shared.events.set_stream_listener(None);
                return Err(error);
            }
        };
        let inner = StreamInner::new(Arc::clone(&self.shared), output, format.clone());
        self.shared.remember_feedback_stream(format, &inner);
        *slot = Some(Arc::downgrade(&inner));
        drop(slot);
        inner.start_events();
        Ok((
            DacStream::from_inner(inner),
            crate::capture::DacCaptureStream::new(Arc::clone(&self.shared), input),
        ))
    }

    /// The hardware volume control, if the DAC has a writable one.
    pub fn volume(&self) -> Option<VolumeControl> {
        let _scope = self.shared.enter().ok()?;
        if !transport::volume_hw::has_hardware_volume() {
            return None;
        }
        Some(VolumeControl::new(Arc::clone(&self.shared)))
    }

    /// Sets the listener for events about the device itself (volume changes,
    /// device loss) while no stream is open. While a stream is open its
    /// listener gets those events too.
    pub fn set_listener(&self, listener: Option<Arc<dyn DacListener>>) {
        self.shared.events.set_dac_listener(listener);
    }

    /// Closes the DAC: stops the stream if one is open, hands the volume back
    /// as [`DacConfig::hand_back`] says, and releases the session so another
    /// [`Dac::open`] can succeed. The host may then release its interfaces and
    /// close its connection after success. If closing times out, keep all host
    /// claims and the connection until [`Dac::await_usb_retirement`] returns
    /// `true`. Dropping the `Dac` initiates the same cleanup, but cannot report
    /// a timeout; hosts must still wait for retirement before releasing claims.
    pub fn close(self) -> Result<()> {
        self.shared.shutdown(None)
    }

    /// Like [`close`](Self::close), but the host says what becomes of the level
    /// the DAC had before the library first changed it, instead of
    /// [`DacConfig::hand_back`] deciding at open: write it back (another driver
    /// gets the DAC), keep the record (the host holds on to the DAC or takes it
    /// straight back) or forget it (the DAC was unplugged).
    ///
    /// A DAC the library saw disappear is always forgotten: nothing can be
    /// written to it and a later attachment must start fresh.
    pub fn close_with(self, volume: CloseVolume) -> Result<()> {
        self.shared.shutdown(Some(volume))
    }

    /// Changes the native DSD overrides of the open DAC ([`DacConfig::dsd_big_endian`]
    /// and [`DacConfig::dsd_subslot`]), for a host whose user can change them
    /// while the DAC stays open. `None` goes back to the device quirk.
    ///
    /// They are read when a format is negotiated and when a stream is opened: a
    /// stream that is already open keeps what it started with, and
    /// [`capabilities`](Self::capabilities) reflects a new subslot size after the
    /// next [`negotiate`](Self::negotiate). `subslot` must be 1, 2 or 4.
    pub fn set_dsd_overrides(&self, big_endian: Option<bool>, subslot: Option<u8>) -> Result<()> {
        let _scope = self.shared.enter()?;
        if subslot.is_some_and(|size| !matches!(size, 1 | 2 | 4)) {
            return Err(Error::InvalidArgument(
                "dsd_subslot must be 1, 2 or 4".to_string(),
            ));
        }
        settings::update(|config| {
            config.dsd_big_endian = big_endian;
            config.dsd_subslot = subslot;
        });
        Ok(())
    }
}

/// A particular DAC owner's USB retirement, independent of other devices.
#[derive(Clone)]
pub struct UsbRetirement {
    context: Arc<transport::context::SessionContext>,
}
impl UsbRetirement {
    pub fn wait(&self, timeout: Duration) -> bool {
        self.context.retired(timeout)
    }
}

impl Drop for Dac {
    fn drop(&mut self) {
        if let Err(error) = self.shared.shutdown(None) {
            log::warn!("closing the DAC: {error}");
        }
    }
}

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

    use crate::transport::session::PAYLOAD_LATCH_TEST_LOCK as SESSION_TEST_LOCK;

    #[test]
    fn another_owner_does_not_hide_an_invalid_device_descriptor() {
        let _serial = SESSION_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _registered = transport::session::TestSession::install();
        let info = DeviceInfo::new(1, 2, "Fake DAC");
        let error = Dac::open(-1, info, DacConfig::default()).unwrap_err();
        assert!(matches!(error, Error::Claim(_)));
        assert_eq!(error.code(), "claim");
    }

    #[test]
    fn a_failed_open_leaves_nothing_registered() {
        let _serial = SESSION_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let info = DeviceInfo::new(1, 2, "Fake DAC");
        let error = Dac::open(-1, info, DacConfig::default()).unwrap_err();
        // No usbfs here (or an invalid descriptor): not Busy, and the slot is free.
        assert!(
            matches!(error, Error::PlatformUnsupported | Error::Claim(_)),
            "{error:?}"
        );
        assert!(!transport::session::session_registered());
    }

    #[test]
    fn an_invalid_config_is_rejected_before_anything_is_touched() {
        let _serial = SESSION_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let config = DacConfig {
            buffer_target_ms: 900,
            ..DacConfig::default()
        };
        let error = Dac::open(-1, DeviceInfo::new(1, 2, "x"), config).unwrap_err();
        assert!(matches!(error, Error::InvalidArgument(_)));
    }

    /// A `Dac` over the fake registered session.
    fn fake_dac_handle(config: DacConfig) -> Dac {
        Dac {
            shared: Arc::new(DacShared {
                context: transport::context::current(),
                events: EventHub::start(),
                info: DeviceInfo::new(0x1234, 0x5678, "test DAC"),
                config,
                closed: AtomicBool::new(false),
                control_guard: Mutex::new(()),
                stream: Mutex::new(None),
                last_feedback_stream: Mutex::new(None),
            }),
        }
    }

    /// A DAC whose level the library lowered, with the true original on record.
    fn lowered_with_a_record() -> crate::transport::fake_dac::Registered {
        use crate::transport::fake_dac::{Registered, ORIGINAL_RAW};
        let fake = Registered::new(false, true);
        fake.set_levels(ORIGINAL_RAW, ORIGINAL_RAW);
        fake.record_original();
        crate::transport::volume_hw::write_volume_db(-40.0).unwrap();
        assert_ne!(fake.raw(), vec![ORIGINAL_RAW; 2]);
        fake
    }

    #[test]
    fn close_with_restore_writes_the_original_back_and_ends_the_record() {
        use crate::transport::fake_dac::ORIGINAL_RAW;
        let fake = lowered_with_a_record();
        // The configuration says keep: the host's decision at close wins.
        let dac = fake_dac_handle(DacConfig {
            hand_back: HandBack::Keep,
            ..DacConfig::default()
        });
        dac.close_with(CloseVolume::Restore).unwrap();
        assert_eq!(fake.raw(), vec![ORIGINAL_RAW; 2]);
        assert!(!fake.original_recorded());
        assert!(!transport::session::session_registered());
    }

    #[test]
    fn close_with_keep_leaves_the_level_and_the_record() {
        use crate::transport::fake_dac::ORIGINAL_RAW;
        let fake = lowered_with_a_record();
        let lowered = fake.raw();
        // The configuration says restore: again the host's decision wins.
        let dac = fake_dac_handle(DacConfig::default());
        dac.close_with(CloseVolume::Keep).unwrap();
        assert_eq!(fake.raw(), lowered, "the level was not touched");
        assert_ne!(lowered, vec![ORIGINAL_RAW; 2]);
        assert!(
            fake.original_recorded(),
            "a later open still knows the true original"
        );
        assert!(!transport::session::session_registered());
    }

    #[test]
    fn close_with_forget_ends_the_record_without_writing() {
        let fake = lowered_with_a_record();
        let lowered = fake.raw();
        let writes = fake.dac.lock().unwrap().volume_writes.len();
        let dac = fake_dac_handle(DacConfig::default());
        dac.close_with(CloseVolume::Forget).unwrap();
        assert_eq!(fake.raw(), lowered);
        assert_eq!(
            fake.dac.lock().unwrap().volume_writes.len(),
            writes,
            "nothing was written"
        );
        assert!(!fake.original_recorded());
    }

    #[test]
    fn a_dac_the_library_saw_disappear_is_forgotten_whatever_close_asked_for() {
        let fake = lowered_with_a_record();
        let lowered = fake.raw();
        let dac = fake_dac_handle(DacConfig::default());
        dac.shared
            .events
            .emit_dac(crate::events::DacEvent::DeviceLost);
        dac.close_with(CloseVolume::Restore).unwrap();
        assert_eq!(fake.raw(), lowered, "no write to a DAC that is gone");
        assert!(!fake.original_recorded());
    }

    #[test]
    fn a_plain_close_still_follows_the_configuration() {
        use crate::transport::fake_dac::ORIGINAL_RAW;
        let fake = lowered_with_a_record();
        fake_dac_handle(DacConfig::default()).close().unwrap();
        assert_eq!(
            fake.raw(),
            vec![ORIGINAL_RAW; 2],
            "the default is to restore"
        );
        drop(fake);

        let fake = lowered_with_a_record();
        let lowered = fake.raw();
        fake_dac_handle(DacConfig {
            hand_back: HandBack::Keep,
            ..DacConfig::default()
        })
        .close()
        .unwrap();
        assert_eq!(fake.raw(), lowered);
        assert!(fake.original_recorded());
    }

    #[test]
    fn dsd_overrides_change_the_settings_of_the_open_dac_and_are_validated() {
        let fake = crate::transport::fake_dac::Registered::new(false, false);
        fake.configure(DacConfig::default());
        let dac = fake_dac_handle(DacConfig::default());
        assert!(!settings::settings().dsd_big_endian());
        assert_eq!(settings::settings().dsd_subslot_override(), None);

        dac.set_dsd_overrides(Some(true), Some(2)).unwrap();
        assert!(settings::settings().dsd_big_endian());
        assert_eq!(settings::settings().dsd_subslot_override(), Some(2));

        assert!(matches!(
            dac.set_dsd_overrides(None, Some(3)),
            Err(Error::InvalidArgument(_))
        ));
        assert_eq!(
            settings::settings().dsd_subslot_override(),
            Some(2),
            "a refused call changes nothing"
        );

        dac.set_dsd_overrides(None, None).unwrap();
        assert!(!settings::settings().dsd_big_endian());
        assert_eq!(settings::settings().dsd_subslot_override(), None);
        dac.close().unwrap();
        drop(fake);
    }

    #[test]
    fn dsd_overrides_keep_the_quirks_resolved_for_the_device() {
        let fake = crate::transport::fake_dac::Registered::new(false, false);
        fake.configure(DacConfig {
            quirks: vec![crate::config::QuirkOverride {
                vendor_id: 0x1234,
                product_id: 0x5678,
                name_contains: None,
                quirks: vec![
                    crate::quirk::Quirk::SettleDelayMs(80),
                    crate::quirk::Quirk::DsdBigEndian,
                ],
            }],
            ..DacConfig::default()
        });
        let dac = fake_dac_handle(DacConfig::default());
        // The quirk gives big-endian; an override of "little-endian" wins over it.
        assert!(settings::settings().dsd_big_endian());
        dac.set_dsd_overrides(Some(false), None).unwrap();
        assert!(!settings::settings().dsd_big_endian());
        assert_eq!(
            settings::settings().settle_delay_ms(),
            80,
            "the device quirk is still there"
        );
        // `None` goes back to the quirk.
        dac.set_dsd_overrides(None, None).unwrap();
        assert!(settings::settings().dsd_big_endian());
        dac.close().unwrap();
        drop(fake);
    }

    #[test]
    fn the_volume_handle_works_without_a_stream_and_reports_changes() {
        use crate::events::DacEvent;
        use crate::transport::fake_dac::Registered;
        use crate::volume::VolumeControl;

        struct Seen(Mutex<Vec<DacEvent>>);
        impl DacListener for Seen {
            fn on_event(&self, event: DacEvent) {
                self.0.lock().push(event);
            }
        }

        // Holds the process-wide test lock for the whole test.
        let fake = Registered::new(false, true);
        let events = EventHub::start();
        let seen = Arc::new(Seen(Mutex::new(Vec::new())));
        events.set_dac_listener(Some(seen.clone()));
        let shared = Arc::new(DacShared {
            context: transport::context::current(),
            events: events.clone(),
            info: DeviceInfo::new(0x1234, 0x5678, "test DAC"),
            config: DacConfig::default(),
            closed: AtomicBool::new(false),
            control_guard: Mutex::new(()),
            stream: Mutex::new(None),
            last_feedback_stream: Mutex::new(None),
        });
        let volume = VolumeControl::new(shared.clone());

        let range = volume.range().unwrap();
        assert_eq!(
            (range.min_db, range.max_db, range.res_db),
            (-80.0, 0.0, 1.0)
        );
        let initial = volume.get().unwrap();
        assert_eq!(initial.db, -64.0);
        assert_eq!(initial.muted, Some(false));

        let set = volume.set_db(-30.0).unwrap();
        assert_eq!(set.db, -30.0);
        assert_eq!(fake.raw(), vec![-30 * 256, -30 * 256]);
        let up = volume.step(1, 0).unwrap();
        assert!(up.db > -30.0, "{up:?}");
        let half = volume.set_fraction(0.5).unwrap();
        assert!((half.fraction - 0.5).abs() < 0.01, "{half:?}");
        assert_eq!(volume.set_mute(true).unwrap().muted, Some(true));
        assert_eq!(
            volume.original_db(),
            None,
            "nothing was recorded by the fake"
        );

        // An unreachable DAC fails the call; the handle stays usable.
        fake.dac.lock().unwrap().unreachable = true;
        assert!(volume.get().is_err());
        fake.dac.lock().unwrap().unreachable = false;

        for _ in 0..200 {
            if seen.0.lock().len() >= 4 {
                break;
            }
            std::thread::sleep(Duration::from_millis(5));
        }
        events.shutdown();
        let changes: Vec<f64> = seen
            .0
            .lock()
            .iter()
            .filter_map(|event| match event {
                DacEvent::VolumeChanged(state) => Some(state.db),
                _ => None,
            })
            .collect();
        assert_eq!(
            changes.len(),
            4,
            "set_db, step, set_fraction, set_mute: {changes:?}"
        );
        assert_eq!(changes[0], -30.0);

        shared.closed.store(true, Ordering::Release);
        assert!(matches!(volume.get(), Err(Error::InvalidState(_))));
    }
    #[test]
    fn nonblocking_volume_is_bounded_ordered_and_keeps_verified_writes() {
        let fake = transport::fake_dac::Registered::new(false, true);
        let dac = fake_dac_handle(DacConfig::default());
        let volume = dac.volume().unwrap().nonblocking().unwrap();
        let (arrived_tx, arrived_rx) = crossbeam_channel::bounded(1);
        let (release_tx, release_rx) = crossbeam_channel::bounded(1);
        fake.dac.lock().unwrap().hold_next_volume_write = Some((arrived_tx, release_rx));
        let mut first = volume.set_db(-30.0).unwrap();
        // Submission returned while the actual verified USB write is held.
        arrived_rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert!(first.try_result().is_none());
        let mut queued = Vec::new();
        for _ in 0..32 {
            queued.push(volume.set_db(-40.0).unwrap());
        }
        assert!(matches!(volume.set_db(-50.0), Err(Error::Busy)));
        release_tx.send(()).unwrap();
        assert_eq!(first.wait().unwrap().db, -30.0);
        for operation in queued {
            assert_eq!(operation.wait().unwrap().db, -40.0);
        }
        assert_eq!(fake.raw(), vec![-40 * 256, -40 * 256]);
        let result = volume.get().unwrap();
        // A completion can be observed with polling and then cannot be awaited twice.
        let state = result.wait().unwrap();
        assert_eq!(state.db, -40.0);
        dac.close().unwrap();
        assert!(matches!(
            volume.set_db(-20.0).unwrap().wait(),
            Err(Error::InvalidState(_))
        ));
    }

    #[test]
    fn reconfigure_transaction_attempts_requested_then_previous_and_reports_both_failures() {
        let old = StreamRequest::pcm(44_100, 2, 16);
        let new = StreamRequest::pcm_float32(96_000, 2);
        let mut calls = Vec::new();
        let (restored, cause) = reconfigure_or_restore(&new, &old, |request| {
            calls.push(*request);
            if *request == new {
                Err(Error::Unsupported {
                    reason: "no float alternate".into(),
                    offered: vec![],
                })
            } else {
                Ok("restored paused stream")
            }
        })
        .unwrap();
        assert_eq!(calls, vec![new, old]);
        assert_eq!(restored, "restored paused stream");
        assert_eq!(cause.unwrap().code(), "unsupported");
        let error = reconfigure_or_restore::<()>(&new, &old, |_| {
            Err(Error::Control("clock failed".into()))
        })
        .unwrap_err();
        assert_eq!(error.code(), "reconfigure_unusable");
        let mut calls = Vec::new();
        let (_, cause) = reconfigure_or_restore(&new, &old, |request| {
            calls.push(*request);
            Ok(())
        })
        .unwrap();
        assert_eq!(calls, vec![new]);
        assert!(cause.is_none());
    }
}