Skip to main content

usbdac_core/
dac.rs

1//! The DAC handle.
2
3mod routing;
4
5use crate::capabilities::{Capabilities, DeviceInfo};
6use crate::config::{CloseVolume, DacConfig, HandBack};
7use crate::error::{Error, Result};
8use crate::events::{DacListener, EventHub, EventSink};
9use crate::format::{StreamFormat, StreamRequest};
10use crate::settings::{self, Settings};
11use crate::stream::{DacStream, StreamInner};
12use crate::transport;
13use crate::volume::VolumeControl;
14use parking_lot::Mutex;
15use std::os::fd::RawFd;
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::sync::{Arc, Weak};
18use std::time::Duration;
19
20/// How long `close` waits for the output thread to finish.
21const CLOSE_TIMEOUT: Duration = Duration::from_secs(3);
22
23/// Serializes `Dac::open`, so two concurrent opens cannot disturb each other's
24/// settings.
25static OPEN_GUARD: Mutex<()> = Mutex::new(());
26
27#[cfg(test)]
28fn reconfigure_or_restore<T>(
29    requested: &StreamRequest,
30    previous: &StreamRequest,
31    mut attempt: impl FnMut(&StreamRequest) -> Result<T>,
32) -> Result<(T, Option<Error>)> {
33    match attempt(requested) {
34        Ok(stream) => Ok((stream, None)),
35        Err(error) => match attempt(previous) {
36            Ok(stream) => Ok((stream, Some(error))),
37            Err(rollback) => Err(Error::ReconfigureUnusable(format!(
38                "requested format failed: {error}; rollback failed: {rollback}"
39            ))),
40        },
41    }
42}
43
44enum CandidateFailure {
45    Clean(Error),
46    Terminal(Error),
47}
48
49// The attempt closure is the production negotiate/open boundary. Only its
50// private transport certificate permits the next candidate or final rollback.
51fn reconfigure_candidates_or_restore<T>(
52    requests: &[StreamRequest],
53    previous: &StreamRequest,
54    mut attempt: impl FnMut(&StreamRequest) -> std::result::Result<T, CandidateFailure>,
55) -> Result<(T, Option<Error>)> {
56    let mut first = None;
57    for request in requests {
58        match attempt(request) {
59            Ok(stream) => return Ok((stream, None)),
60            Err(CandidateFailure::Clean(error)) => {
61                if first.is_none() {
62                    first = Some(error);
63                }
64            }
65            Err(CandidateFailure::Terminal(error)) => {
66                return Err(Error::ReconfigureUnusable(format!(
67                    "candidate outcome is not proven idle; explicit close required: {error}"
68                )))
69            }
70        }
71    }
72    let first = first.expect("validated nonempty candidate list");
73    match attempt(previous) {
74        Ok(stream) => Ok((stream, Some(first))),
75        Err(CandidateFailure::Clean(rollback) | CandidateFailure::Terminal(rollback)) => {
76            Err(Error::ReconfigureUnusable(format!(
77                "requested format failed: {first}; rollback failed: {rollback}"
78            )))
79        }
80    }
81}
82
83fn validate_reconfigure_candidates(requests: &[StreamRequest]) -> Result<()> {
84    if requests.is_empty() || requests.len() > 4 {
85        return Err(Error::InvalidArgument(
86            "expected one to four reconfiguration candidates".into(),
87        ));
88    }
89    for request in requests {
90        transport::api::playback_format_from_request(request)?;
91    }
92    if requests.len() > 1 {
93        let first = requests[0];
94        if first.encoding != crate::Encoding::Pcm
95            || first.rate_policy != crate::RatePolicy::Exact
96            || requests
97                .windows(2)
98                .any(|pair| pair[0].bit_depth >= pair[1].bit_depth)
99            || requests.iter().any(|r| {
100                r.encoding != first.encoding
101                    || r.sample_rate != first.sample_rate
102                    || r.channels != first.channels
103                    || r.rate_policy != crate::RatePolicy::Exact
104            })
105        {
106            return Err(Error::InvalidArgument(
107                "candidates must be ascending same-rate, same-channel PCM widening".into(),
108            ));
109        }
110    }
111    Ok(())
112}
113
114/// State shared by the `Dac`, its streams and its volume handle.
115pub(crate) struct DacShared {
116    pub(crate) events: EventSink,
117    pub(crate) context: Arc<transport::context::SessionContext>,
118    pub(crate) info: DeviceInfo,
119    pub(crate) config: DacConfig,
120    closed: AtomicBool,
121    pub(crate) control_guard: Mutex<()>,
122    pub(crate) stream: Mutex<Option<Weak<StreamInner>>>,
123    reconfigure: Mutex<Option<Arc<()>>>,
124    last_feedback_stream: Mutex<Option<(StreamFormat, Arc<transport::RuntimeStats>)>>,
125}
126
127struct ReconfigureReservation<'a> {
128    shared: &'a DacShared,
129    token: Arc<()>,
130}
131
132impl Drop for ReconfigureReservation<'_> {
133    fn drop(&mut self) {
134        let mut reservation = self.shared.reconfigure.lock();
135        if reservation
136            .as_ref()
137            .is_some_and(|token| Arc::ptr_eq(token, &self.token))
138        {
139            *reservation = None;
140        }
141    }
142}
143
144impl DacShared {
145    pub(crate) fn reject_reconfigure(&self) -> Result<()> {
146        if self.reconfigure.lock().is_some() {
147            Err(Error::Busy)
148        } else {
149            Ok(())
150        }
151    }
152
153    fn remember_feedback_stream(&self, format: &StreamFormat, stream: &StreamInner) {
154        if stream.shared.stats.feedback_trace.is_some() {
155            *self.last_feedback_stream.lock() =
156                Some((format.clone(), Arc::clone(&stream.shared.stats)));
157        }
158    }
159
160    pub(crate) fn enter(&self) -> Result<transport::context::Scope> {
161        self.ensure_open()?;
162        Ok(self.context.enter())
163    }
164
165    pub(crate) fn ensure_open(&self) -> Result<()> {
166        if self.closed.load(Ordering::Acquire) {
167            Err(Error::InvalidState("the DAC is closed".to_string()))
168        } else {
169            Ok(())
170        }
171    }
172
173    /// The stream that is open now, if any.
174    fn active_stream(&self) -> Option<Arc<StreamInner>> {
175        self.stream
176            .lock()
177            .as_ref()
178            .and_then(Weak::upgrade)
179            .filter(|stream| !stream.is_closed())
180    }
181
182    /// Closes with what the configuration says about the original volume
183    /// (`None`) or with what the host decided at close.
184    fn shutdown(&self, volume: Option<CloseVolume>) -> Result<()> {
185        let _control = self.control_guard.lock();
186        let _scope = self.context.enter();
187        *self.reconfigure.lock() = None;
188        if self.closed.swap(true, Ordering::AcqRel) {
189            return Ok(());
190        }
191        if let Some(stream) = self.active_stream() {
192            let _ = stream.close();
193        }
194        // A DAC that has gone cannot be written to, and what was recorded for
195        // it must not survive into a later attachment: forget it, whatever was
196        // asked for.
197        let action = if self.events.device_lost() {
198            transport::api::ORIGINAL_VOLUME_ACTION_FORGET
199        } else {
200            match volume {
201                Some(CloseVolume::Restore) => transport::api::ORIGINAL_VOLUME_ACTION_RESTORE,
202                Some(CloseVolume::Keep) => transport::api::ORIGINAL_VOLUME_ACTION_KEEP,
203                Some(CloseVolume::Forget) => transport::api::ORIGINAL_VOLUME_ACTION_FORGET,
204                None => match self.config.hand_back {
205                    HandBack::RestoreOriginal => transport::api::ORIGINAL_VOLUME_ACTION_RESTORE,
206                    HandBack::Keep => transport::api::ORIGINAL_VOLUME_ACTION_KEEP,
207                },
208            }
209        };
210        let stopped = transport::api::close_device(action, CLOSE_TIMEOUT);
211        drop(_control);
212        self.events.shutdown();
213        if stopped {
214            Ok(())
215        } else {
216            Err(Error::Transfer(
217                "the USB output thread did not stop in time; the DAC stays busy until it does"
218                    .to_string(),
219            ))
220        }
221    }
222}
223
224/// An open USB DAC.
225///
226/// Distinct USB attachments have independent owners. Opening the same physical
227/// attachment twice returns [`Error::Busy`] until its owner retires. The host keeps its
228/// `UsbDeviceConnection` open until then.
229pub struct Dac {
230    shared: Arc<DacShared>,
231}
232
233/// A replacement stream on the same physical handle, paused with zero-based counters.
234/// A failed requested format can still return a successfully restored old-format stream.
235#[derive(Debug)]
236pub struct StreamReconfiguration {
237    pub stream: DacStream,
238    /// The requested-format error when rollback restored the old format; `None` on success.
239    pub rollback_cause: Option<Error>,
240}
241
242impl std::fmt::Debug for Dac {
243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244        f.debug_struct("Dac")
245            .field("info", &self.shared.info)
246            .finish_non_exhaustive()
247    }
248}
249
250impl Dac {
251    /// Read-only proof of a fixed-rate vendor PCM profile. Returns the actual
252    /// active configuration and the sole interface the host may claim.
253    pub fn vendor_pcm_preflight(fd: RawFd, info: &DeviceInfo) -> Result<Option<(u8, u8)>> {
254        let _guard = OPEN_GUARD.lock();
255        let context = transport::context::SessionContext::reserve(fd)?;
256        let _scope = context.enter();
257        if transport::session::session_registered() {
258            return Err(Error::Busy);
259        }
260        transport::api::vendor_pcm_preflight(fd, info)
261    }
262
263    /// Read-only descriptor proof of the exact active configuration and complete
264    /// interface claim set for a fixed-rate vendor PCM profile.
265    pub fn vendor_pcm_claims_preflight(
266        fd: RawFd,
267        info: &DeviceInfo,
268    ) -> Result<Option<(u8, Vec<u8>)>> {
269        let _guard = OPEN_GUARD.lock();
270        let context = transport::context::SessionContext::reserve(fd)?;
271        let _scope = context.enter();
272        if transport::session::session_registered() {
273            return Err(Error::Busy);
274        }
275        transport::api::vendor_pcm_claims_preflight(fd, info)
276    }
277
278    /// Prove the exact optional Scarlett vendor claim from actual USB descriptors.
279    /// Requires the host-selected configuration; sends no proprietary requests.
280    pub fn scarlett_routing_preflight(
281        fd: RawFd,
282        info: &DeviceInfo,
283    ) -> Result<Option<crate::scarlett::ReadCapability>> {
284        let _guard = OPEN_GUARD.lock();
285        let context = transport::context::SessionContext::reserve(fd)?;
286        let _scope = context.enter();
287        if transport::session::session_registered() {
288            return Err(Error::Busy);
289        }
290        transport::routing_hw::scarlett_preflight(fd, info)
291    }
292
293    /// Read the active configuration's explicit PCM IN claim plan before the
294    /// host claims its AudioControl and input streaming interfaces. Returns
295    /// `(configuration, control_interfaces, input_interfaces)` without audio.
296    pub fn capture_preflight(fd: RawFd, info: &DeviceInfo) -> Result<(u8, Vec<u8>, Vec<u8>)> {
297        let _guard = OPEN_GUARD.lock();
298        let context = transport::context::SessionContext::reserve(fd)?;
299        let _scope = context.enter();
300        if transport::session::session_registered() {
301            return Err(Error::Busy);
302        }
303        let device = transport::api::capture_preflight_device(fd, info)?;
304        Ok(device)
305    }
306    /// Register an explicitly claimed capture device, including an input-only
307    /// device. Claim its IN AudioStreaming interfaces and their owning
308    /// AudioControl interfaces before calling; no playback claim is needed.
309    /// This entry point performs no output-volume setup. Android/JNI capture
310    /// permission and claim orchestration is a separate integration step.
311    pub fn open_capture_device(fd: RawFd, info: DeviceInfo, config: DacConfig) -> Result<Dac> {
312        config.validate()?;
313        let _guard = OPEN_GUARD.lock();
314        let context = transport::context::SessionContext::reserve(fd)?;
315        let _scope = context.enter();
316        if transport::session::session_registered() {
317            return Err(Error::Busy);
318        }
319        settings::install(Settings::for_device(config.clone(), &info));
320        if let Err(error) = transport::api::open_capture_device(fd, &info) {
321            settings::reset();
322            return Err(error);
323        }
324        context.admit();
325        Ok(Dac {
326            shared: Arc::new(DacShared {
327                context: transport::context::current(),
328                events: EventHub::start(),
329                info,
330                config,
331                closed: AtomicBool::new(false),
332                control_guard: Mutex::new(()),
333                stream: Mutex::new(None),
334                reconfigure: Mutex::new(None),
335                last_feedback_stream: Mutex::new(None),
336            }),
337        })
338    }
339
340    /// Start standalone, exact-format PCM capture on a claimed IN interface.
341    /// The capture worker exclusively owns USB until all transfers retire;
342    /// concurrent playback, duplex and routing changes are refused.
343    pub fn open_capture(
344        &self,
345        request: &crate::capture::CaptureRequest,
346        capacity_frames: usize,
347    ) -> Result<crate::capture::DacCaptureStream> {
348        let _control = self.shared.control_guard.lock();
349        self.shared.reject_reconfigure()?;
350        let _scope = self.shared.enter()?;
351        let handle = transport::capture_stream::open_capture(
352            request,
353            capacity_frames,
354            self.shared.events.clone(),
355        )?;
356        Ok(crate::capture::DacCaptureStream::new(
357            Arc::clone(&self.shared),
358            handle,
359        ))
360    }
361
362    /// Capture owner-specific retirement evidence before consuming `close`.
363    /// Retain this token with this device's claims/FD after a close timeout;
364    /// another open device does not affect its result.
365    pub fn retirement(&self) -> UsbRetirement {
366        UsbRetirement {
367            context: self.shared.context.clone(),
368        }
369    }
370
371    /// Wait until all process USB owners retire. For a particular connection,
372    /// use [`Dac::retirement`] so another active DAC does not block hand-back.
373    ///
374    /// After [`Dac::close`] returns a transfer timeout, retain all host ownership
375    /// and call this until it returns `true`. This does not require a live `Dac` handle.
376    /// Check retirement using the actual host connection FD after a failed open.
377    /// The host must keep this FD valid; caller-supplied USB names are not identity.
378    pub fn await_connection_retirement(fd: RawFd, timeout: Duration) -> Result<bool> {
379        transport::context::await_connection_retirement(fd, timeout)
380    }
381
382    pub fn await_usb_retirement(timeout: Duration) -> bool {
383        transport::context::await_all_retirement(timeout)
384    }
385
386    /// Identify optional capture interfaces after the host claims the base audio interfaces.
387    /// Returns the active configuration ID and source interface numbers without starting audio.
388    pub fn feedback_preflight(fd: RawFd, info: &DeviceInfo) -> Result<(u8, Vec<u8>)> {
389        let _guard = OPEN_GUARD.lock();
390        let context = transport::context::SessionContext::reserve(fd)?;
391        let _scope = context.enter();
392        if transport::session::session_registered() {
393            return Err(Error::Busy);
394        }
395        transport::api::feedback_preflight(fd, info)
396    }
397
398    /// Opens the DAC behind `fd`.
399    ///
400    /// `fd` is the usbfs file descriptor of the device (on Android
401    /// `UsbDeviceConnection.getFileDescriptor()`); the library duplicates it, so
402    /// the host keeps ownership of its own. `info.claimed_interfaces` must be
403    /// the AudioControl and playback AudioStreaming interfaces plus any
404    /// optional capture sources identified by [`Dac::feedback_preflight`].
405    ///
406    /// Opening scans the descriptors, finds the hardware volume control, records
407    /// the DAC's current level and, with the default
408    /// [`StartupVolume::Attenuate`](crate::StartupVolume::Attenuate), lowers every
409    /// channel to at most -40 dB and verifies it, so that no stream can start
410    /// at the DAC's own (often full-scale) level. It does not touch the clock or
411    /// start any audio. [`VolumeControl::startup`](crate::VolumeControl::startup)
412    /// says what it did.
413    pub fn open(fd: RawFd, info: DeviceInfo, config: DacConfig) -> Result<Dac> {
414        Self::open_playback_device(fd, info, config, false)
415    }
416
417    /// Open a fresh macOS libusb attachment for direct playback. When
418    /// `allow_capture` is true libusb may take the whole USB device away from
419    /// its kernel driver, subject to macOS authorization.
420    #[cfg(target_os = "macos")]
421    pub fn open_darwin(
422        attachment: crate::darwin_discovery::Attachment,
423        config: DacConfig,
424        allow_capture: bool,
425    ) -> Result<Dac> {
426        config.validate()?;
427        let _guard = OPEN_GUARD.lock();
428        let context = transport::context::SessionContext::reserve_darwin(attachment.device())?;
429        let _scope = context.enter();
430        if transport::session::session_registered() {
431            return Err(Error::Busy);
432        }
433        let (device, info) = transport::usbfs::open_darwin_device(&attachment, allow_capture)?;
434        settings::install(Settings::for_device(config.clone(), &info));
435        if let Err(error) = transport::api::register_darwin_device(device, &info) {
436            settings::reset();
437            return Err(error);
438        }
439        context.admit();
440        let events = EventHub::start();
441        if let Some(state) = transport::volume_hw::startup_lowered_volume() {
442            events.emit_dac_or_hold(crate::events::DacEvent::VolumeChanged(state));
443        }
444        Ok(Dac {
445            shared: Arc::new(DacShared {
446                context: transport::context::current(),
447                events,
448                info,
449                config,
450                closed: AtomicBool::new(false),
451                control_guard: Mutex::new(()),
452                stream: Mutex::new(None),
453                reconfigure: Mutex::new(None),
454                last_feedback_stream: Mutex::new(None),
455            }),
456        })
457    }
458
459    /// Explicit duplex registration. Claim the base playback interfaces and all
460    /// IN/control interfaces returned by capture_preflight for the same configuration.
461    /// Ordinary playback registration retains its narrower optional-IN policy.
462    pub fn open_duplex_device(fd: RawFd, info: DeviceInfo, config: DacConfig) -> Result<Dac> {
463        Self::open_playback_device(fd, info, config, true)
464    }
465
466    fn open_playback_device(
467        fd: RawFd,
468        info: DeviceInfo,
469        config: DacConfig,
470        duplex: bool,
471    ) -> Result<Dac> {
472        config.validate()?;
473        let _guard = OPEN_GUARD.lock();
474        let context = transport::context::SessionContext::reserve(fd)?;
475        let _scope = context.enter();
476        if transport::session::session_registered() {
477            return Err(Error::Busy);
478        }
479        settings::install(Settings::for_device(config.clone(), &info));
480        let registration = if duplex {
481            transport::api::open_duplex_device(fd, &info)
482        } else {
483            transport::api::open_device(fd, &info)
484        };
485        if let Err(error) = registration {
486            settings::reset();
487            return Err(error);
488        }
489        context.admit();
490        let events = EventHub::start();
491        // The start-up step lowered the level before this handle existed: tell
492        // the first listener, as a change made through the library.
493        if let Some(state) = transport::volume_hw::startup_lowered_volume() {
494            events.emit_dac_or_hold(crate::events::DacEvent::VolumeChanged(state));
495        }
496        Ok(Dac {
497            shared: Arc::new(DacShared {
498                context: transport::context::current(),
499                events,
500                info,
501                config,
502                closed: AtomicBool::new(false),
503                control_guard: Mutex::new(()),
504                stream: Mutex::new(None),
505                reconfigure: Mutex::new(None),
506                last_feedback_stream: Mutex::new(None),
507            }),
508        })
509    }
510
511    /// The identity the host gave at open.
512    pub fn info(&self) -> &DeviceInfo {
513        &self.shared.info
514    }
515
516    /// Export the last stream's opt-in support capture, even after the stream
517    /// has closed. A new successfully opened stream replaces it.
518    pub fn feedback_trace(&self) -> Option<crate::FeedbackTrace> {
519        let (format, stats) = self.shared.last_feedback_stream.lock().clone()?;
520        let explicit = *stats.explicit_feedback_diagnostics.lock();
521        Some(stats.feedback_trace.as_ref()?.snapshot(format, explicit))
522    }
523
524    /// What the DAC offers, from the descriptors scanned at open.
525    pub fn capabilities(&self) -> Result<Capabilities> {
526        let _scope = self.shared.enter()?;
527        transport::api::capabilities()
528    }
529
530    /// Settles the wire format for `request`.
531    ///
532    /// This programs the DAC's sampling frequency and reads it back (it is the
533    /// step that can fail with [`Error::ClockUnverified`] later), so it takes
534    /// 100 ms or more. It fails with [`Error::InvalidState`] while a stream is
535    /// open. Nothing is resampled: with [`RatePolicy::Exact`] a rate the DAC
536    /// cannot run is [`Error::Unsupported`]; with `NearestSupported` the
537    /// returned format carries the rate the DAC will run.
538    ///
539    /// [`RatePolicy::Exact`]: crate::RatePolicy::Exact
540    pub fn negotiate(&self, request: &StreamRequest) -> Result<StreamFormat> {
541        let _control = self.shared.control_guard.lock();
542        self.shared.reject_reconfigure()?;
543        self.negotiate_locked(request)
544    }
545
546    /// Negotiate a bounded, ordered list of exact PCM formats on one retained owner.
547    /// A later candidate is considered only after a certified clean refusal.
548    pub fn negotiate_candidates(&self, requests: &[StreamRequest]) -> Result<StreamFormat> {
549        let _control = self.shared.control_guard.lock();
550        self.shared.reject_reconfigure()?;
551        let _scope = self.shared.enter()?;
552        transport::api::negotiate_candidates(requests)
553    }
554
555    fn negotiate_locked(&self, request: &StreamRequest) -> Result<StreamFormat> {
556        let _scope = self.shared.enter()?;
557        transport::api::negotiate(request)
558    }
559
560    /// Opens the output stream for a negotiated format and starts the output
561    /// thread. The stream plays as soon as the ring holds the start threshold
562    /// ([`DacConfig::start_threshold_ms`]) of audio. Only one stream can be open
563    /// at a time.
564    ///
565    /// Fails with [`Error::VolumeUnavailable`] when the stream's own route has
566    /// no usable hardware volume control and
567    /// [`DacConfig::require_hardware_volume`] is on; nothing is programmed and
568    /// no output thread starts.
569    ///
570    /// `listener` receives the stream's events; see [`DacListener`].
571    pub fn open_stream(
572        &self,
573        format: &StreamFormat,
574        listener: Arc<dyn DacListener>,
575    ) -> Result<DacStream> {
576        let _control = self.shared.control_guard.lock();
577        self.shared.reject_reconfigure()?;
578        self.open_stream_locked(format, listener)
579    }
580
581    fn open_stream_locked(
582        &self,
583        format: &StreamFormat,
584        listener: Arc<dyn DacListener>,
585    ) -> Result<DacStream> {
586        let _scope = self.shared.enter()?;
587        let mut slot = self.shared.stream.lock();
588        if slot
589            .as_ref()
590            .and_then(Weak::upgrade)
591            .is_some_and(|stream| !stream.is_closed())
592        {
593            return Err(Error::InvalidState("a stream is already open".to_string()));
594        }
595        self.shared.events.set_stream_listener(Some(listener));
596        let handle = match transport::api::open_stream(format, self.shared.events.clone()) {
597            Ok(handle) => handle,
598            Err(error) => {
599                self.shared.events.set_stream_listener(None);
600                return Err(error);
601            }
602        };
603        let inner = StreamInner::new(Arc::clone(&self.shared), handle, format.clone());
604        self.shared.remember_feedback_stream(format, &inner);
605        *slot = Some(Arc::downgrade(&inner));
606        drop(slot);
607        inner.start_events();
608        Ok(DacStream::from_inner(inner))
609    }
610
611    /// Drain and replace a playback-only stream without reopening the physical USB handle or host claims.
612    ///
613    /// Stop the writer before calling. The stream must belong to this DAC. Drain temporarily plays
614    /// a paused stream so queued audio can complete. A drain timeout retains the original open
615    /// stream in draining state; the caller still owns it and may wait, flush or close it.
616    ///
617    /// After retirement, normal lock-requested cleanup retains the exact libusb owner in IDLE_LOCK.
618    /// Every negotiation/open must reuse that identity; losing it is an unusable-state error, never
619    /// an implicit physical reopen. No volume initialization/hand-back occurs. Success or rollback
620    /// returns a paused replacement with zero-based counters; supply/reseek PCM and explicitly play.
621    /// A rollback failure returns `ReconfigureUnusable` and requires closing the DAC.
622    pub fn reconfigure_stream(
623        &self,
624        current: &DacStream,
625        request: &StreamRequest,
626        listener: Arc<dyn DacListener>,
627        drain_timeout: Duration,
628    ) -> Result<StreamReconfiguration> {
629        self.reconfigure_stream_candidates(
630            current,
631            std::slice::from_ref(request),
632            listener,
633            drain_timeout,
634        )
635    }
636
637    /// Replace once using a bounded list of equivalent-rate lossless widening candidates.
638    /// Continue only after a certified clean refusal. A terminal failure requires
639    /// explicit close; exhaustion restores the previous request once.
640    pub fn reconfigure_stream_candidates(
641        &self,
642        current: &DacStream,
643        requests: &[StreamRequest],
644        listener: Arc<dyn DacListener>,
645        drain_timeout: Duration,
646    ) -> Result<StreamReconfiguration> {
647        validate_reconfigure_candidates(requests)?;
648        let request = &requests[0];
649        let control = self.shared.control_guard.lock();
650        self.shared.reject_reconfigure()?;
651        let _scope = self.shared.enter()?;
652        transport::api::playback_format_from_request(request)?;
653        let identity = current.reconfigure_identity(&self.shared)?;
654        if !current.is_current(&self.shared) {
655            return Err(Error::InvalidState("stream is no longer current".into()));
656        }
657        let token = Arc::new(());
658        *self.shared.reconfigure.lock() = Some(Arc::clone(&token));
659        let reservation = ReconfigureReservation {
660            shared: &self.shared,
661            token,
662        };
663        let previous = current.format().request;
664        let deadline = std::time::Instant::now()
665            .checked_add(drain_timeout)
666            .ok_or_else(|| {
667                Error::InvalidArgument("drain timeout overflows monotonic clock".into())
668            })?;
669        let volume_route = transport::api::volume_route_signature();
670        if !current.is_drained() {
671            current.drain()?;
672            current.play()?;
673        }
674        drop(control);
675        while !current.is_drained() {
676            if self.shared.events.device_lost() || self.shared.closed.load(Ordering::Acquire) {
677                return Err(Error::ReconfigureUnusable(
678                    "DAC closed or detached during drain".into(),
679                ));
680            }
681            if matches!(
682                current.state(),
683                crate::StreamState::Failed | crate::StreamState::Closed
684            ) {
685                return Err(Error::ReconfigureUnusable("original stream failed during drain; retained stream remains available for explicit close".into()));
686            }
687            if std::time::Instant::now() >= deadline {
688                return Err(Error::ReconfigureDrainTimeout);
689            }
690            std::thread::sleep(Duration::from_millis(2));
691        }
692        let _control = self.shared.control_guard.lock();
693        self.shared.ensure_open()?;
694        let retirement = current.lock_retirement();
695        if self.shared.events.device_lost()
696            || !self
697                .shared
698                .reconfigure
699                .lock()
700                .as_ref()
701                .is_some_and(|token| Arc::ptr_eq(token, &reservation.token))
702            || !current.is_current(&self.shared)
703            || current.reconfigure_identity(&self.shared)? != identity
704            || !current.is_drained()
705            || matches!(
706                current.state(),
707                crate::StreamState::Failed | crate::StreamState::Closed
708            )
709            || transport::api::volume_route_signature() != volume_route
710        {
711            return Err(Error::ReconfigureUnusable(
712                "stream ownership, state, or volume route changed during drain".into(),
713            ));
714        }
715        current
716            .retire_for_reconfigure_locked()
717            .map_err(|error| Error::ReconfigureUnusable(error.to_string()))?;
718        drop(retirement);
719        if transport::api::retained_usb_handle_identity() != Some(identity) {
720            return Err(Error::ReconfigureUnusable(
721                "old USB owner was not retained after retirement".into(),
722            ));
723        }
724        let mut batch = transport::negotiate::RetryBaseline::new(identity);
725        let mut candidate_reservation = Some(
726            transport::api::reserve_candidates()
727                .map_err(|error| Error::ReconfigureUnusable(error.to_string()))?,
728        );
729        let mut attempt =
730            |target: &StreamRequest| -> std::result::Result<DacStream, CandidateFailure> {
731                if transport::api::retained_usb_handle_identity() != Some(identity) {
732                    return Err(CandidateFailure::Terminal(Error::ReconfigureUnusable(
733                        "retained USB owner was lost before negotiation".into(),
734                    )));
735                }
736                let format = match transport::api::negotiate_attempt(target, &mut batch, identity) {
737                    Ok(format) => format,
738                    Err(failure) => {
739                        return if failure
740                            .clean
741                            .is_some_and(|proof| proof.belongs_to(identity))
742                            && transport::api::retained_usb_handle_identity() == Some(identity)
743                            && transport::api::volume_route_signature() == volume_route
744                            && !self.shared.events.device_lost()
745                            && !self.shared.closed.load(Ordering::Acquire)
746                        {
747                            Err(CandidateFailure::Clean(failure.error))
748                        } else {
749                            Err(CandidateFailure::Terminal(failure.error))
750                        };
751                    }
752                };
753                if transport::api::retained_usb_handle_identity() != Some(identity) {
754                    return Err(CandidateFailure::Terminal(Error::ReconfigureUnusable(
755                        "negotiation replaced or lost the USB owner".into(),
756                    )));
757                }
758                // Stream start acquires its own session guard; all candidate
759                // negotiations above share the reservation until this commit.
760                drop(candidate_reservation.take());
761                let opened = self
762                    .open_stream_locked(&format, listener.clone())
763                    .map_err(CandidateFailure::Terminal)?;
764                if !matches!(opened.reconfigure_identity(&self.shared), Ok(found) if found == identity)
765                {
766                    let _ = opened.retire_for_reconfigure();
767                    drop(opened);
768                    return Err(CandidateFailure::Terminal(Error::ReconfigureUnusable(
769                        "replacement used a different physical USB owner".into(),
770                    )));
771                }
772                if let Err(error) = opened.pause() {
773                    let _ = opened.retire_for_reconfigure();
774                    return Err(CandidateFailure::Terminal(error));
775                }
776                if transport::api::volume_route_signature() != volume_route {
777                    let _ = opened.retire_for_reconfigure();
778                    drop(opened);
779                    return Err(CandidateFailure::Terminal(Error::Control(
780                    "reconfiguration changed the hardware volume route; explicit close required".into(),
781                )));
782                }
783                Ok(opened)
784            };
785        let (stream, rollback_cause) =
786            reconfigure_candidates_or_restore(requests, &previous, &mut attempt)?;
787        Ok(StreamReconfiguration {
788            stream,
789            rollback_cause,
790        })
791    }
792
793    /// Open playback and PCM capture atomically on one USB worker.
794    ///
795    /// The output must have a current negotiated format. Shared source clocks
796    /// require equal wire rates; distinct proven clock sources retain their own
797    /// rates and position counters. Capture never supplies playback timing unless
798    /// it exactly matches playback's already selected implicit feedback source.
799    /// Closing either stream stops both endpoints and retires their transfers.
800    pub fn open_duplex(
801        &self,
802        format: &StreamFormat,
803        capture: &crate::capture::CaptureRequest,
804        capacity_frames: usize,
805        listener: Arc<dyn DacListener>,
806    ) -> Result<(DacStream, crate::capture::DacCaptureStream)> {
807        let _control = self.shared.control_guard.lock();
808        self.shared.reject_reconfigure()?;
809
810        let _scope = self.shared.enter()?;
811        let mut slot = self.shared.stream.lock();
812        if slot
813            .as_ref()
814            .and_then(Weak::upgrade)
815            .is_some_and(|stream| !stream.is_closed())
816        {
817            return Err(Error::Busy);
818        }
819        self.shared.events.set_stream_listener(Some(listener));
820        let (output, input) = match transport::duplex::open(
821            format,
822            capture,
823            capacity_frames,
824            self.shared.events.clone(),
825        ) {
826            Ok(pair) => pair,
827            Err(error) => {
828                self.shared.events.set_stream_listener(None);
829                return Err(error);
830            }
831        };
832        let inner = StreamInner::new(Arc::clone(&self.shared), output, format.clone());
833        self.shared.remember_feedback_stream(format, &inner);
834        *slot = Some(Arc::downgrade(&inner));
835        drop(slot);
836        inner.start_events();
837        Ok((
838            DacStream::from_inner(inner),
839            crate::capture::DacCaptureStream::new(Arc::clone(&self.shared), input),
840        ))
841    }
842
843    /// The hardware volume control, if the DAC has a writable one.
844    pub fn volume(&self) -> Option<VolumeControl> {
845        let _scope = self.shared.enter().ok()?;
846        if !transport::volume_hw::has_hardware_volume() {
847            return None;
848        }
849        Some(VolumeControl::new(Arc::clone(&self.shared)))
850    }
851
852    /// Sets the listener for events about the device itself (volume changes,
853    /// device loss) while no stream is open. While a stream is open its
854    /// listener gets those events too.
855    pub fn set_listener(&self, listener: Option<Arc<dyn DacListener>>) {
856        self.shared.events.set_dac_listener(listener);
857    }
858
859    /// Closes the DAC: stops the stream if one is open, hands the volume back
860    /// as [`DacConfig::hand_back`] says, and releases the session so another
861    /// [`Dac::open`] can succeed. The host may then release its interfaces and
862    /// close its connection after success. If closing times out, keep all host
863    /// claims and the connection until [`Dac::await_usb_retirement`] returns
864    /// `true`. Dropping the `Dac` initiates the same cleanup, but cannot report
865    /// a timeout; hosts must still wait for retirement before releasing claims.
866    pub fn close(self) -> Result<()> {
867        self.shared.shutdown(None)
868    }
869
870    /// Like [`close`](Self::close), but the host says what becomes of the level
871    /// the DAC had before the library first changed it, instead of
872    /// [`DacConfig::hand_back`] deciding at open: write it back (another driver
873    /// gets the DAC), keep the record (the host holds on to the DAC or takes it
874    /// straight back) or forget it (the DAC was unplugged).
875    ///
876    /// A DAC the library saw disappear is always forgotten: nothing can be
877    /// written to it and a later attachment must start fresh.
878    pub fn close_with(self, volume: CloseVolume) -> Result<()> {
879        self.shared.shutdown(Some(volume))
880    }
881
882    /// Changes the native DSD overrides of the open DAC ([`DacConfig::dsd_big_endian`]
883    /// and [`DacConfig::dsd_subslot`]), for a host whose user can change them
884    /// while the DAC stays open. `None` goes back to the device quirk.
885    ///
886    /// They are read when a format is negotiated and when a stream is opened: a
887    /// stream that is already open keeps what it started with, and
888    /// [`capabilities`](Self::capabilities) reflects a new subslot size after the
889    /// next [`negotiate`](Self::negotiate). `subslot` must be 1, 2 or 4.
890    pub fn set_dsd_overrides(&self, big_endian: Option<bool>, subslot: Option<u8>) -> Result<()> {
891        let _control = self.shared.control_guard.lock();
892        self.shared.reject_reconfigure()?;
893        let _scope = self.shared.enter()?;
894        if subslot.is_some_and(|size| !matches!(size, 1 | 2 | 4)) {
895            return Err(Error::InvalidArgument(
896                "dsd_subslot must be 1, 2 or 4".to_string(),
897            ));
898        }
899        settings::update(|config| {
900            config.dsd_big_endian = big_endian;
901            config.dsd_subslot = subslot;
902        });
903        Ok(())
904    }
905}
906
907/// A particular DAC owner's USB retirement, independent of other devices.
908#[derive(Clone)]
909pub struct UsbRetirement {
910    context: Arc<transport::context::SessionContext>,
911}
912impl UsbRetirement {
913    pub fn wait(&self, timeout: Duration) -> bool {
914        self.context.retired(timeout)
915    }
916
917    /// Routing hand-back outcome after this owner has retired. None means no
918    /// route changes were recorded; a pending owner is an explicit error.
919    pub fn routing_hand_back_report(
920        &self,
921    ) -> Result<Option<crate::routing::RoutingHandBackReport>> {
922        if !self.context.retired(Duration::ZERO) {
923            return Err(Error::InvalidState("USB owner has not retired".into()));
924        }
925        Ok(self.context.routing_hand_back_report())
926    }
927}
928
929impl Drop for Dac {
930    fn drop(&mut self) {
931        if let Err(error) = self.shared.shutdown(None) {
932            log::warn!("closing the DAC: {error}");
933        }
934    }
935}
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940    use crate::capabilities::DeviceInfo;
941
942    use crate::transport::session::PAYLOAD_LATCH_TEST_LOCK as SESSION_TEST_LOCK;
943
944    #[test]
945    fn another_owner_does_not_hide_an_invalid_device_descriptor() {
946        let _serial = SESSION_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
947        let _registered = transport::session::TestSession::install();
948        let info = DeviceInfo::new(1, 2, "Fake DAC");
949        let error = Dac::open(-1, info, DacConfig::default()).unwrap_err();
950        assert!(matches!(error, Error::Claim(_)));
951        assert_eq!(error.code(), "claim");
952    }
953
954    #[test]
955    fn a_failed_open_leaves_nothing_registered() {
956        let _serial = SESSION_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
957        let info = DeviceInfo::new(1, 2, "Fake DAC");
958        let error = Dac::open(-1, info, DacConfig::default()).unwrap_err();
959        // No usbfs here (or an invalid descriptor): not Busy, and the slot is free.
960        assert!(
961            matches!(error, Error::PlatformUnsupported | Error::Claim(_)),
962            "{error:?}"
963        );
964        assert!(!transport::session::session_registered());
965    }
966
967    #[test]
968    fn an_invalid_config_is_rejected_before_anything_is_touched() {
969        let _serial = SESSION_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
970        let config = DacConfig {
971            buffer_target_ms: 900,
972            ..DacConfig::default()
973        };
974        let error = Dac::open(-1, DeviceInfo::new(1, 2, "x"), config).unwrap_err();
975        assert!(matches!(error, Error::InvalidArgument(_)));
976    }
977
978    /// A `Dac` over the fake registered session.
979    fn fake_dac_handle(config: DacConfig) -> Dac {
980        Dac {
981            shared: Arc::new(DacShared {
982                context: transport::context::current(),
983                events: EventHub::start(),
984                info: DeviceInfo::new(0x1234, 0x5678, "test DAC"),
985                config,
986                closed: AtomicBool::new(false),
987                control_guard: Mutex::new(()),
988                stream: Mutex::new(None),
989                reconfigure: Mutex::new(None),
990                last_feedback_stream: Mutex::new(None),
991            }),
992        }
993    }
994
995    /// A DAC whose level the library lowered, with the true original on record.
996    fn lowered_with_a_record() -> crate::transport::fake_dac::Registered {
997        use crate::transport::fake_dac::{Registered, ORIGINAL_RAW};
998        let fake = Registered::new(false, true);
999        fake.set_levels(ORIGINAL_RAW, ORIGINAL_RAW);
1000        fake.record_original();
1001        crate::transport::volume_hw::write_volume_db(-40.0).unwrap();
1002        assert_ne!(fake.raw(), vec![ORIGINAL_RAW; 2]);
1003        fake
1004    }
1005
1006    #[test]
1007    fn close_with_restore_writes_the_original_back_and_ends_the_record() {
1008        use crate::transport::fake_dac::ORIGINAL_RAW;
1009        let fake = lowered_with_a_record();
1010        // The configuration says keep: the host's decision at close wins.
1011        let dac = fake_dac_handle(DacConfig {
1012            hand_back: HandBack::Keep,
1013            ..DacConfig::default()
1014        });
1015        dac.close_with(CloseVolume::Restore).unwrap();
1016        assert_eq!(fake.raw(), vec![ORIGINAL_RAW; 2]);
1017        assert!(!fake.original_recorded());
1018        assert!(!transport::session::session_registered());
1019    }
1020
1021    #[test]
1022    fn close_with_keep_leaves_the_level_and_the_record() {
1023        use crate::transport::fake_dac::ORIGINAL_RAW;
1024        let fake = lowered_with_a_record();
1025        let lowered = fake.raw();
1026        // The configuration says restore: again the host's decision wins.
1027        let dac = fake_dac_handle(DacConfig::default());
1028        dac.close_with(CloseVolume::Keep).unwrap();
1029        assert_eq!(fake.raw(), lowered, "the level was not touched");
1030        assert_ne!(lowered, vec![ORIGINAL_RAW; 2]);
1031        assert!(
1032            fake.original_recorded(),
1033            "a later open still knows the true original"
1034        );
1035        assert!(!transport::session::session_registered());
1036    }
1037
1038    #[test]
1039    fn close_with_forget_ends_the_record_without_writing() {
1040        let fake = lowered_with_a_record();
1041        let lowered = fake.raw();
1042        let writes = fake.dac.lock().unwrap().volume_writes.len();
1043        let dac = fake_dac_handle(DacConfig::default());
1044        dac.close_with(CloseVolume::Forget).unwrap();
1045        assert_eq!(fake.raw(), lowered);
1046        assert_eq!(
1047            fake.dac.lock().unwrap().volume_writes.len(),
1048            writes,
1049            "nothing was written"
1050        );
1051        assert!(!fake.original_recorded());
1052    }
1053
1054    #[test]
1055    fn a_dac_the_library_saw_disappear_is_forgotten_whatever_close_asked_for() {
1056        let fake = lowered_with_a_record();
1057        let lowered = fake.raw();
1058        let dac = fake_dac_handle(DacConfig::default());
1059        dac.shared
1060            .events
1061            .emit_dac(crate::events::DacEvent::DeviceLost);
1062        dac.close_with(CloseVolume::Restore).unwrap();
1063        assert_eq!(fake.raw(), lowered, "no write to a DAC that is gone");
1064        assert!(!fake.original_recorded());
1065    }
1066
1067    #[test]
1068    fn a_plain_close_still_follows_the_configuration() {
1069        use crate::transport::fake_dac::ORIGINAL_RAW;
1070        let fake = lowered_with_a_record();
1071        fake_dac_handle(DacConfig::default()).close().unwrap();
1072        assert_eq!(
1073            fake.raw(),
1074            vec![ORIGINAL_RAW; 2],
1075            "the default is to restore"
1076        );
1077        drop(fake);
1078
1079        let fake = lowered_with_a_record();
1080        let lowered = fake.raw();
1081        fake_dac_handle(DacConfig {
1082            hand_back: HandBack::Keep,
1083            ..DacConfig::default()
1084        })
1085        .close()
1086        .unwrap();
1087        assert_eq!(fake.raw(), lowered);
1088        assert!(fake.original_recorded());
1089    }
1090
1091    #[test]
1092    fn dsd_overrides_change_the_settings_of_the_open_dac_and_are_validated() {
1093        let fake = crate::transport::fake_dac::Registered::new(false, false);
1094        fake.configure(DacConfig::default());
1095        let dac = fake_dac_handle(DacConfig::default());
1096        assert!(!settings::settings().dsd_big_endian());
1097        assert_eq!(settings::settings().dsd_subslot_override(), None);
1098
1099        dac.set_dsd_overrides(Some(true), Some(2)).unwrap();
1100        assert!(settings::settings().dsd_big_endian());
1101        assert_eq!(settings::settings().dsd_subslot_override(), Some(2));
1102
1103        assert!(matches!(
1104            dac.set_dsd_overrides(None, Some(3)),
1105            Err(Error::InvalidArgument(_))
1106        ));
1107        assert_eq!(
1108            settings::settings().dsd_subslot_override(),
1109            Some(2),
1110            "a refused call changes nothing"
1111        );
1112
1113        dac.set_dsd_overrides(None, None).unwrap();
1114        assert!(!settings::settings().dsd_big_endian());
1115        assert_eq!(settings::settings().dsd_subslot_override(), None);
1116        dac.close().unwrap();
1117        drop(fake);
1118    }
1119
1120    #[test]
1121    fn dsd_overrides_keep_the_quirks_resolved_for_the_device() {
1122        let fake = crate::transport::fake_dac::Registered::new(false, false);
1123        fake.configure(DacConfig {
1124            quirks: vec![crate::config::QuirkOverride {
1125                vendor_id: 0x1234,
1126                product_id: 0x5678,
1127                name_contains: None,
1128                quirks: vec![
1129                    crate::quirk::Quirk::SettleDelayMs(80),
1130                    crate::quirk::Quirk::DsdBigEndian,
1131                ],
1132            }],
1133            ..DacConfig::default()
1134        });
1135        let dac = fake_dac_handle(DacConfig::default());
1136        // The quirk gives big-endian; an override of "little-endian" wins over it.
1137        assert!(settings::settings().dsd_big_endian());
1138        dac.set_dsd_overrides(Some(false), None).unwrap();
1139        assert!(!settings::settings().dsd_big_endian());
1140        assert_eq!(
1141            settings::settings().settle_delay_ms(),
1142            80,
1143            "the device quirk is still there"
1144        );
1145        // `None` goes back to the quirk.
1146        dac.set_dsd_overrides(None, None).unwrap();
1147        assert!(settings::settings().dsd_big_endian());
1148        dac.close().unwrap();
1149        drop(fake);
1150    }
1151
1152    #[test]
1153    fn the_volume_handle_works_without_a_stream_and_reports_changes() {
1154        use crate::events::DacEvent;
1155        use crate::transport::fake_dac::Registered;
1156        use crate::volume::VolumeControl;
1157
1158        struct Seen(Mutex<Vec<DacEvent>>);
1159        impl DacListener for Seen {
1160            fn on_event(&self, event: DacEvent) {
1161                self.0.lock().push(event);
1162            }
1163        }
1164
1165        // Holds the process-wide test lock for the whole test.
1166        let fake = Registered::new(false, true);
1167        let events = EventHub::start();
1168        let seen = Arc::new(Seen(Mutex::new(Vec::new())));
1169        events.set_dac_listener(Some(seen.clone()));
1170        let shared = Arc::new(DacShared {
1171            context: transport::context::current(),
1172            events: events.clone(),
1173            info: DeviceInfo::new(0x1234, 0x5678, "test DAC"),
1174            config: DacConfig::default(),
1175            closed: AtomicBool::new(false),
1176            control_guard: Mutex::new(()),
1177            stream: Mutex::new(None),
1178            reconfigure: Mutex::new(None),
1179            last_feedback_stream: Mutex::new(None),
1180        });
1181        let volume = VolumeControl::new(shared.clone());
1182
1183        let range = volume.range().unwrap();
1184        assert_eq!(
1185            (range.min_db, range.max_db, range.res_db),
1186            (-80.0, 0.0, 1.0)
1187        );
1188        let initial = volume.get().unwrap();
1189        assert_eq!(initial.db, -64.0);
1190        assert_eq!(initial.muted, Some(false));
1191
1192        let set = volume.set_db(-30.0).unwrap();
1193        assert_eq!(set.db, -30.0);
1194        assert_eq!(fake.raw(), vec![-30 * 256, -30 * 256]);
1195        let up = volume.step(1, 0).unwrap();
1196        assert!(up.db > -30.0, "{up:?}");
1197        let half = volume.set_fraction(0.5).unwrap();
1198        assert!((half.fraction - 0.5).abs() < 0.01, "{half:?}");
1199        assert_eq!(volume.set_mute(true).unwrap().muted, Some(true));
1200        assert_eq!(
1201            volume.original_db(),
1202            None,
1203            "nothing was recorded by the fake"
1204        );
1205
1206        // An unreachable DAC fails the call; the handle stays usable.
1207        fake.dac.lock().unwrap().unreachable = true;
1208        assert!(volume.get().is_err());
1209        fake.dac.lock().unwrap().unreachable = false;
1210
1211        for _ in 0..200 {
1212            if seen.0.lock().len() >= 4 {
1213                break;
1214            }
1215            std::thread::sleep(Duration::from_millis(5));
1216        }
1217        events.shutdown();
1218        let changes: Vec<f64> = seen
1219            .0
1220            .lock()
1221            .iter()
1222            .filter_map(|event| match event {
1223                DacEvent::VolumeChanged(state) => Some(state.db),
1224                _ => None,
1225            })
1226            .collect();
1227        assert_eq!(
1228            changes.len(),
1229            4,
1230            "set_db, step, set_fraction, set_mute: {changes:?}"
1231        );
1232        assert_eq!(changes[0], -30.0);
1233
1234        shared.closed.store(true, Ordering::Release);
1235        assert!(matches!(volume.get(), Err(Error::InvalidState(_))));
1236    }
1237    #[test]
1238    fn nonblocking_volume_is_bounded_ordered_and_keeps_verified_writes() {
1239        let fake = transport::fake_dac::Registered::new(false, true);
1240        let dac = fake_dac_handle(DacConfig::default());
1241        let volume = dac.volume().unwrap().nonblocking().unwrap();
1242        let (arrived_tx, arrived_rx) = crossbeam_channel::bounded(1);
1243        let (release_tx, release_rx) = crossbeam_channel::bounded(1);
1244        fake.dac.lock().unwrap().hold_next_volume_write = Some((arrived_tx, release_rx));
1245        let mut first = volume.set_db(-30.0).unwrap();
1246        // Submission returned while the actual verified USB write is held.
1247        arrived_rx.recv_timeout(Duration::from_secs(2)).unwrap();
1248        assert!(first.try_result().is_none());
1249        let mut queued = Vec::new();
1250        for _ in 0..32 {
1251            queued.push(volume.set_db(-40.0).unwrap());
1252        }
1253        assert!(matches!(volume.set_db(-50.0), Err(Error::Busy)));
1254        release_tx.send(()).unwrap();
1255        assert_eq!(first.wait().unwrap().db, -30.0);
1256        for operation in queued {
1257            assert_eq!(operation.wait().unwrap().db, -40.0);
1258        }
1259        assert_eq!(fake.raw(), vec![-40 * 256, -40 * 256]);
1260        let result = volume.get().unwrap();
1261        // A completion can be observed with polling and then cannot be awaited twice.
1262        let state = result.wait().unwrap();
1263        assert_eq!(state.db, -40.0);
1264        dac.close().unwrap();
1265        assert!(matches!(
1266            volume.set_db(-20.0).unwrap().wait(),
1267            Err(Error::InvalidState(_))
1268        ));
1269    }
1270
1271    #[test]
1272    fn reserved_transition_allows_volume_rejects_negotiate_and_close_invalidates_it() {
1273        let fake = transport::fake_dac::Registered::new(false, true);
1274        let dac = fake_dac_handle(DacConfig::default());
1275        let volume = dac.volume().unwrap();
1276        // Represent the interval after reconfigure has reserved the owner and
1277        // released the control gate to wait for the active stream to drain.
1278        let control = dac.shared.control_guard.lock();
1279        let token = Arc::new(());
1280        *dac.shared.reconfigure.lock() = Some(token.clone());
1281        let reservation = ReconfigureReservation {
1282            shared: &dac.shared,
1283            token,
1284        };
1285        drop(control);
1286        std::thread::scope(|scope| {
1287            let operation = scope.spawn(|| volume.set_db(-30.0));
1288            assert_eq!(operation.join().unwrap().unwrap().db, -30.0);
1289            assert!(matches!(
1290                dac.negotiate(&StreamRequest::pcm(48_000, 2, 16)),
1291                Err(Error::Busy)
1292            ));
1293        });
1294        assert_eq!(fake.raw(), vec![-30 * 256, -30 * 256]);
1295        dac.shared.shutdown(Some(CloseVolume::Keep)).unwrap();
1296        assert!(dac.shared.reconfigure.lock().is_none());
1297        drop(reservation);
1298        assert!(dac.shared.reconfigure.lock().is_none());
1299    }
1300
1301    #[test]
1302    fn reconfigure_reservation_drop_releases_busy_state() {
1303        let fake = transport::fake_dac::Registered::new(false, true);
1304        let dac = fake_dac_handle(DacConfig::default());
1305        let token = Arc::new(());
1306        *dac.shared.reconfigure.lock() = Some(token.clone());
1307        let reservation = ReconfigureReservation {
1308            shared: &dac.shared,
1309            token,
1310        };
1311        assert!(matches!(dac.shared.reject_reconfigure(), Err(Error::Busy)));
1312        drop(reservation);
1313        assert!(dac.shared.reject_reconfigure().is_ok());
1314        dac.close().unwrap();
1315        drop(fake);
1316    }
1317
1318    #[test]
1319    fn reconfigure_coordinator_tries_only_certified_refusals_and_rolls_back_once() {
1320        let old = StreamRequest::pcm(48_000, 2, 32);
1321        let requests = [
1322            StreamRequest::pcm(48_000, 2, 16),
1323            StreamRequest::pcm(48_000, 2, 24),
1324        ];
1325        let mut calls = Vec::new();
1326        let (value, cause) = reconfigure_candidates_or_restore(&requests, &old, |request| {
1327            calls.push(request.bit_depth);
1328            if request.bit_depth == 16 {
1329                Err(CandidateFailure::Clean(Error::Control(
1330                    "unavailable".into(),
1331                )))
1332            } else {
1333                Ok(request.bit_depth)
1334            }
1335        })
1336        .unwrap();
1337        assert_eq!(value, 24);
1338        assert!(cause.is_none());
1339        assert_eq!(calls, vec![16, 24]);
1340        calls.clear();
1341        let (_, cause) = reconfigure_candidates_or_restore(&requests, &old, |request| {
1342            calls.push(request.bit_depth);
1343            if request.bit_depth == 32 {
1344                Ok(())
1345            } else {
1346                Err(CandidateFailure::Clean(Error::Control(
1347                    "unavailable".into(),
1348                )))
1349            }
1350        })
1351        .unwrap();
1352        assert!(cause.is_some());
1353        assert_eq!(calls, vec![16, 24, 32]);
1354        calls.clear();
1355        let result: Result<((), Option<Error>)> =
1356            reconfigure_candidates_or_restore(&requests, &old, |request| {
1357                calls.push(request.bit_depth);
1358                Err(CandidateFailure::Terminal(Error::Control(
1359                    "unknown SET".into(),
1360                )))
1361            });
1362        assert!(matches!(result, Err(Error::ReconfigureUnusable(_))));
1363        assert_eq!(calls, vec![16]);
1364    }
1365
1366    #[test]
1367    fn widening_candidates_must_be_bounded_ordered_and_same_source_shape() {
1368        let a = StreamRequest::pcm(48_000, 2, 16);
1369        let b = StreamRequest::pcm(48_000, 2, 24);
1370        let c = StreamRequest::pcm(48_000, 2, 32);
1371        assert!(validate_reconfigure_candidates(&[a, b, c]).is_ok());
1372        assert!(validate_reconfigure_candidates(&[]).is_err());
1373        assert!(validate_reconfigure_candidates(&[b, a]).is_err());
1374        assert!(validate_reconfigure_candidates(&[a, StreamRequest::pcm(96_000, 2, 24)]).is_err());
1375        assert!(validate_reconfigure_candidates(&[a, StreamRequest::pcm(48_000, 1, 24)]).is_err());
1376        assert!(
1377            validate_reconfigure_candidates(&[a, StreamRequest::pcm_float32(48_000, 2)]).is_err()
1378        );
1379    }
1380
1381    #[test]
1382    fn reconfigure_transaction_attempts_requested_then_previous_and_reports_both_failures() {
1383        let old = StreamRequest::pcm(44_100, 2, 16);
1384        let new = StreamRequest::pcm_float32(96_000, 2);
1385        let mut calls = Vec::new();
1386        let (restored, cause) = reconfigure_or_restore(&new, &old, |request| {
1387            calls.push(*request);
1388            if *request == new {
1389                Err(Error::Unsupported {
1390                    reason: "no float alternate".into(),
1391                    offered: vec![],
1392                })
1393            } else {
1394                Ok("restored paused stream")
1395            }
1396        })
1397        .unwrap();
1398        assert_eq!(calls, vec![new, old]);
1399        assert_eq!(restored, "restored paused stream");
1400        assert_eq!(cause.unwrap().code(), "unsupported");
1401        let error = reconfigure_or_restore::<()>(&new, &old, |_| {
1402            Err(Error::Control("clock failed".into()))
1403        })
1404        .unwrap_err();
1405        assert_eq!(error.code(), "reconfigure_unusable");
1406        let mut calls = Vec::new();
1407        let (_, cause) = reconfigure_or_restore(&new, &old, |request| {
1408            calls.push(*request);
1409            Ok(())
1410        })
1411        .unwrap();
1412        assert_eq!(calls, vec![new]);
1413        assert!(cause.is_none());
1414    }
1415}