Skip to main content

Dac

Struct Dac 

Source
pub struct Dac { /* private fields */ }
Expand description

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.

Implementations§

Source§

impl Dac

Unavailable in this release; retained for source compatibility.

Source

pub fn djm_routing_discover( &self, ) -> Result<DjmRoutingProfile, RoutingSessionError>

Discover source-backed DJM choices on an exact, idle vendor PCM session. Discovery leaves the mixer’s routing intact.

Source

pub fn djm_routing_apply( &self, model: DjmModel, configuration: u8, key: DjmControlKey, option: u8, ) -> Result<(), RoutingSessionError>

Unavailable in this release; retained for source compatibility.

Send one explicitly selected DJM option after fresh model, configuration, claim and idle-alternate proof. option is a listed zero-based option ID. Success confirms USB acknowledgement. The mixer’s current routing remains unknown through this protocol.

Source

pub fn scarlett_gen1_read(&self) -> Result<Gen1Readback, RoutingSessionError>

Unavailable in this release; retained for source compatibility.

Read source-backed first-generation Focusrite controls using the already claimed AudioControl interface while idle. No vendor claim or probe write. Hardware behavior remains physically unvalidated.

Source

pub fn scarlett_gen1_apply( &self, expected: &Gen1Readback, edits: &[Gen1Edit], ) -> Result<Gen1Report, RoutingSessionError>

Unavailable in this release; retained for source compatibility.

Apply bounded typed Gen1 controls against a fresh readback on the live DAC. Verify each write and restore attempted controls on failure. Configured hand-back preserves external edits; no clock, preamp or persistent writes.

Source

pub fn scarlett_routing_capability( &self, ) -> Result<Option<ReadCapability>, RoutingSessionError>

Unavailable in this release; retained for source compatibility.

Inspect the exact Scarlett read candidate and required vendor claim, without initializing its protocol or reading proprietary state.

Source

pub fn scarlett_routing_read( &self, ) -> Result<RoutingReadback, RoutingSessionError>

Unavailable in this release; retained for source compatibility.

Initialize and read source-backed Scarlett routing while idle. Requires the host’s explicit vendor-interface claim. Exact-model firmware and live geometry guards apply before mux/mix controls become available. No route, volume or persistent setting writes are sent. Hardware behavior remains unvalidated.

Source

pub fn fcp_routing_read(&self) -> Result<FcpReadback, RoutingSessionError>

Unavailable in this release; retained for source compatibility.

Read firmware-defined modern Focusrite FCP pins, mux banks and mix rows. Requires idle ownership and an explicit exact-model vendor-interface claim. Does not send persistent configuration commands.

Source

pub fn fcp_routing_apply( &self, expected: &FcpReadback, routes: &[FcpRouteEdit], mixes: &[FcpMixEdit], ) -> Result<FcpWriteReport, RoutingSessionError>

Unavailable in this release; retained for source compatibility.

Apply typed firmware pin routes and mixer coefficients against a fresh readback. Requires idle ownership and explicit vendor claim. Verify every affected target, restore attempted targets on failure, and preserve external edits at hand-back. No persistent configuration commands are sent. Physically unvalidated.

Source

pub fn scarlett_mix_apply( &self, edit: &MixRowEdit, ) -> Result<MixWriteReport, RoutingSessionError>

Unavailable in this release; retained for source compatibility.

Apply bounded half-dB replacements to one complete Scarlett mixer row. Requires fresh expected raw coefficients, idle ownership and the explicit vendor claim. Verifies the whole row and attempts verified restoration after any attempted-write failure. Configured hand-back restores only rows still matching the last verified write. Source-backed, physically unverified; no mux bank or persistent configuration is written.

Source

pub fn scarlett_mux_read(&self) -> Result<MuxSnapshot, RoutingSessionError>

Unavailable in this release; retained for source compatibility.

Probe optional per-bank support and read every raw bank including padding. An unsupported response never enables writes; legacy reads remain usable.

Source

pub fn scarlett_mux_apply( &self, edit: &MuxEdit, ) -> Result<MuxWriteReport, RoutingSessionError>

Unavailable in this release; retained for source compatibility.

Apply explicit bank edits only after a fresh complete capability/geometry read equals the expected snapshot. Restore each attempted raw bank after any uncertain write. Configured hand-back preserves external edits. Source-backed; physical routing has not been validated.

Source

pub fn routing_discover(&self) -> Result<RoutingSnapshot, RoutingSessionError>

Discover standard UAC2 selectors and mixer crosspoints on claimed AudioControl interfaces in the active configuration. No vendor protocol is inferred. Requires an idle DAC, including no open capture stream.

Source

pub fn routing_discover_powered( &self, ) -> Result<RoutingSnapshot, RoutingSessionError>

Explicitly wake affected full ADC3 routing domains on entirely claimed idle functions. Restore checked original power after discovery, including failures. The snapshot does not retain a power lease.

Source

pub fn routing_read_powered( &self, snapshot: &RoutingSnapshot, key: ControlKey, ) -> Result<RouteValue, RoutingSessionError>

Revalidate the snapshot and acquire a fresh scoped ADC3 routing lease. Preserve external power drift instead of overwriting it on hand-back.

Source

pub fn routing_apply_powered( &self, snapshot: &RoutingSnapshot, edits: &[RouteEdit], ) -> Result<RouteReport, RoutingSessionError>

Apply the ordinary verified routing transaction with explicit scoped ADC3 wake. Restore original power after success or failure. Configured route hand-back reacquires power only for these opted-in edits.

Source

pub fn routing_read( &self, snapshot: &RoutingSnapshot, key: ControlKey, ) -> Result<RouteValue, RoutingSessionError>

Read a descriptor-backed control after checking the attachment, configuration, descriptors and discovered selector pins for drift.

Source

pub fn routing_apply( &self, snapshot: &RoutingSnapshot, edits: &[RouteEdit], ) -> Result<RouteReport, RoutingSessionError>

Apply bounded, verified routing edits only while idle. Each edit includes the expected current value from routing_read; stale values fail before writing. Rediscover after changing a selector. The configured HandBack policy controls route restoration on close; close_with overrides volume handling only. Feature Unit volume and mute settings are not changed.

Source§

impl Dac

Source

pub fn vendor_pcm_preflight( fd: RawFd, info: &DeviceInfo, ) -> Result<Option<(u8, u8)>>

Read-only proof of a fixed-rate vendor PCM profile. Returns the actual active configuration and the sole interface the host may claim.

Source

pub fn vendor_pcm_claims_preflight( fd: RawFd, info: &DeviceInfo, ) -> Result<Option<(u8, Vec<u8>)>>

Read-only descriptor proof of the exact active configuration and complete interface claim set for a fixed-rate vendor PCM profile.

Source

pub fn scarlett_routing_preflight( fd: RawFd, info: &DeviceInfo, ) -> Result<Option<ReadCapability>>

Prove the exact optional Scarlett vendor claim from actual USB descriptors. Requires the host-selected configuration; sends no proprietary requests.

Source

pub fn capture_preflight( fd: RawFd, info: &DeviceInfo, ) -> Result<(u8, Vec<u8>, Vec<u8>)>

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.

Examples found in repository?
examples/loopback_capture.rs (line 56)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    use std::{
6        fs::OpenOptions,
7        io::{Seek, SeekFrom, Write},
8        os::fd::AsRawFd,
9        time::{Duration, Instant},
10    };
11    use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12    let args: Vec<String> = std::env::args().collect();
13    if args.len() != 5 {
14        return Err(
15            "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16                .into(),
17        );
18    }
19    let rate: u32 = args[3].parse()?;
20    let seconds: u64 = args[4].parse()?;
21    if rate == 0 || !(1..=120).contains(&seconds) {
22        return Err("invalid capture duration/rate".into());
23    }
24    let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25    let fd = file.as_raw_fd();
26    // GET_DESCRIPTOR device: identity comes from the actual USB device.
27    #[repr(C)]
28    struct Control {
29        kind: u8,
30        request: u8,
31        value: u16,
32        index: u16,
33        length: u16,
34        timeout: u32,
35        data: *mut u8,
36    }
37    let mut descriptor = [0u8; 18];
38    let mut control = Control {
39        kind: 0x80,
40        request: 6,
41        value: 0x0100,
42        index: 0,
43        length: 18,
44        timeout: 1000,
45        data: descriptor.as_mut_ptr(),
46    };
47    if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48        return Err(std::io::Error::last_os_error().into());
49    }
50    let mut info = DeviceInfo::new(
51        u16::from_le_bytes([descriptor[8], descriptor[9]]),
52        u16::from_le_bytes([descriptor[10], descriptor[11]]),
53        "Independent loopback input",
54    )
55    .with_device_name(&args[1]);
56    let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57    let mut claims = control_interfaces;
58    claims.extend(input_interfaces);
59    claims.sort_unstable();
60    claims.dedup();
61    for &interface in &claims {
62        let interface = u32::from(interface);
63        if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64            return Err(std::io::Error::last_os_error().into());
65        }
66    }
67    info.configuration_id = Some(configuration);
68    info.claimed_interfaces = claims.clone();
69    let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70    let capture = dac.open_capture(
71        &CaptureRequest {
72            sample_rate: rate,
73            channels: 2,
74            valid_bits: 16,
75            channel_map: None,
76        },
77        rate as usize,
78    )?;
79    if capture.format().subslot_bytes() != 2 {
80        return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81    }
82    let mut output = OpenOptions::new()
83        .create_new(true)
84        .write(true)
85        .open(&args[2])?;
86    output.write_all(&[0u8; 44])?;
87    let mut buffer = [0u8; 8192];
88    let mut bytes = 0u32;
89    let started = Instant::now();
90    while started.elapsed() < Duration::from_secs(seconds) {
91        let frames = capture.read(&mut buffer)?;
92        let count = frames * capture.format().bytes_per_frame();
93        output.write_all(&buffer[..count])?;
94        bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95        std::thread::sleep(Duration::from_millis(2));
96    }
97    let stats = capture.stats();
98    capture.close()?;
99    dac.close()?;
100    if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101        return Err("capture did not retire; retain host claims".into());
102    }
103    for &interface in claims.iter().rev() {
104        let interface = u32::from(interface);
105        if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106            return Err(std::io::Error::last_os_error().into());
107        }
108    }
109    let mut header = Vec::with_capacity(44);
110    header.extend_from_slice(b"RIFF");
111    header.extend_from_slice(&(36 + bytes).to_le_bytes());
112    header.extend_from_slice(b"WAVEfmt ");
113    header.extend_from_slice(&16u32.to_le_bytes());
114    header.extend_from_slice(&1u16.to_le_bytes());
115    header.extend_from_slice(&2u16.to_le_bytes());
116    header.extend_from_slice(&rate.to_le_bytes());
117    header.extend_from_slice(&(rate * 4).to_le_bytes());
118    header.extend_from_slice(&4u16.to_le_bytes());
119    header.extend_from_slice(&16u16.to_le_bytes());
120    header.extend_from_slice(b"data");
121    header.extend_from_slice(&bytes.to_le_bytes());
122    output.seek(SeekFrom::Start(0))?;
123    output.write_all(&header)?;
124    output.flush()?;
125    let valid = bytes > 0
126        && stats.failed_transfers == 0
127        && stats.failed_packets == 0
128        && stats.missing_frames == 0
129        && stats.overrun_frames == 0
130        && stats.contention_frames == 0;
131    let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132    std::fs::write(
133        format!("{}.json", args[2]),
134        serde_json::to_vec_pretty(&metadata)?,
135    )?;
136    if !valid {
137        return Err(
138            "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139                .into(),
140        );
141    }
142    println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143    Ok(())
144}
Source

pub fn open_capture_device( fd: RawFd, info: DeviceInfo, config: DacConfig, ) -> Result<Dac>

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.

Examples found in repository?
examples/loopback_capture.rs (line 69)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    use std::{
6        fs::OpenOptions,
7        io::{Seek, SeekFrom, Write},
8        os::fd::AsRawFd,
9        time::{Duration, Instant},
10    };
11    use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12    let args: Vec<String> = std::env::args().collect();
13    if args.len() != 5 {
14        return Err(
15            "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16                .into(),
17        );
18    }
19    let rate: u32 = args[3].parse()?;
20    let seconds: u64 = args[4].parse()?;
21    if rate == 0 || !(1..=120).contains(&seconds) {
22        return Err("invalid capture duration/rate".into());
23    }
24    let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25    let fd = file.as_raw_fd();
26    // GET_DESCRIPTOR device: identity comes from the actual USB device.
27    #[repr(C)]
28    struct Control {
29        kind: u8,
30        request: u8,
31        value: u16,
32        index: u16,
33        length: u16,
34        timeout: u32,
35        data: *mut u8,
36    }
37    let mut descriptor = [0u8; 18];
38    let mut control = Control {
39        kind: 0x80,
40        request: 6,
41        value: 0x0100,
42        index: 0,
43        length: 18,
44        timeout: 1000,
45        data: descriptor.as_mut_ptr(),
46    };
47    if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48        return Err(std::io::Error::last_os_error().into());
49    }
50    let mut info = DeviceInfo::new(
51        u16::from_le_bytes([descriptor[8], descriptor[9]]),
52        u16::from_le_bytes([descriptor[10], descriptor[11]]),
53        "Independent loopback input",
54    )
55    .with_device_name(&args[1]);
56    let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57    let mut claims = control_interfaces;
58    claims.extend(input_interfaces);
59    claims.sort_unstable();
60    claims.dedup();
61    for &interface in &claims {
62        let interface = u32::from(interface);
63        if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64            return Err(std::io::Error::last_os_error().into());
65        }
66    }
67    info.configuration_id = Some(configuration);
68    info.claimed_interfaces = claims.clone();
69    let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70    let capture = dac.open_capture(
71        &CaptureRequest {
72            sample_rate: rate,
73            channels: 2,
74            valid_bits: 16,
75            channel_map: None,
76        },
77        rate as usize,
78    )?;
79    if capture.format().subslot_bytes() != 2 {
80        return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81    }
82    let mut output = OpenOptions::new()
83        .create_new(true)
84        .write(true)
85        .open(&args[2])?;
86    output.write_all(&[0u8; 44])?;
87    let mut buffer = [0u8; 8192];
88    let mut bytes = 0u32;
89    let started = Instant::now();
90    while started.elapsed() < Duration::from_secs(seconds) {
91        let frames = capture.read(&mut buffer)?;
92        let count = frames * capture.format().bytes_per_frame();
93        output.write_all(&buffer[..count])?;
94        bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95        std::thread::sleep(Duration::from_millis(2));
96    }
97    let stats = capture.stats();
98    capture.close()?;
99    dac.close()?;
100    if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101        return Err("capture did not retire; retain host claims".into());
102    }
103    for &interface in claims.iter().rev() {
104        let interface = u32::from(interface);
105        if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106            return Err(std::io::Error::last_os_error().into());
107        }
108    }
109    let mut header = Vec::with_capacity(44);
110    header.extend_from_slice(b"RIFF");
111    header.extend_from_slice(&(36 + bytes).to_le_bytes());
112    header.extend_from_slice(b"WAVEfmt ");
113    header.extend_from_slice(&16u32.to_le_bytes());
114    header.extend_from_slice(&1u16.to_le_bytes());
115    header.extend_from_slice(&2u16.to_le_bytes());
116    header.extend_from_slice(&rate.to_le_bytes());
117    header.extend_from_slice(&(rate * 4).to_le_bytes());
118    header.extend_from_slice(&4u16.to_le_bytes());
119    header.extend_from_slice(&16u16.to_le_bytes());
120    header.extend_from_slice(b"data");
121    header.extend_from_slice(&bytes.to_le_bytes());
122    output.seek(SeekFrom::Start(0))?;
123    output.write_all(&header)?;
124    output.flush()?;
125    let valid = bytes > 0
126        && stats.failed_transfers == 0
127        && stats.failed_packets == 0
128        && stats.missing_frames == 0
129        && stats.overrun_frames == 0
130        && stats.contention_frames == 0;
131    let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132    std::fs::write(
133        format!("{}.json", args[2]),
134        serde_json::to_vec_pretty(&metadata)?,
135    )?;
136    if !valid {
137        return Err(
138            "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139                .into(),
140        );
141    }
142    println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143    Ok(())
144}
Source

pub fn open_capture( &self, request: &CaptureRequest, capacity_frames: usize, ) -> Result<DacCaptureStream>

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.

Examples found in repository?
examples/loopback_capture.rs (lines 70-78)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    use std::{
6        fs::OpenOptions,
7        io::{Seek, SeekFrom, Write},
8        os::fd::AsRawFd,
9        time::{Duration, Instant},
10    };
11    use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12    let args: Vec<String> = std::env::args().collect();
13    if args.len() != 5 {
14        return Err(
15            "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16                .into(),
17        );
18    }
19    let rate: u32 = args[3].parse()?;
20    let seconds: u64 = args[4].parse()?;
21    if rate == 0 || !(1..=120).contains(&seconds) {
22        return Err("invalid capture duration/rate".into());
23    }
24    let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25    let fd = file.as_raw_fd();
26    // GET_DESCRIPTOR device: identity comes from the actual USB device.
27    #[repr(C)]
28    struct Control {
29        kind: u8,
30        request: u8,
31        value: u16,
32        index: u16,
33        length: u16,
34        timeout: u32,
35        data: *mut u8,
36    }
37    let mut descriptor = [0u8; 18];
38    let mut control = Control {
39        kind: 0x80,
40        request: 6,
41        value: 0x0100,
42        index: 0,
43        length: 18,
44        timeout: 1000,
45        data: descriptor.as_mut_ptr(),
46    };
47    if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48        return Err(std::io::Error::last_os_error().into());
49    }
50    let mut info = DeviceInfo::new(
51        u16::from_le_bytes([descriptor[8], descriptor[9]]),
52        u16::from_le_bytes([descriptor[10], descriptor[11]]),
53        "Independent loopback input",
54    )
55    .with_device_name(&args[1]);
56    let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57    let mut claims = control_interfaces;
58    claims.extend(input_interfaces);
59    claims.sort_unstable();
60    claims.dedup();
61    for &interface in &claims {
62        let interface = u32::from(interface);
63        if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64            return Err(std::io::Error::last_os_error().into());
65        }
66    }
67    info.configuration_id = Some(configuration);
68    info.claimed_interfaces = claims.clone();
69    let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70    let capture = dac.open_capture(
71        &CaptureRequest {
72            sample_rate: rate,
73            channels: 2,
74            valid_bits: 16,
75            channel_map: None,
76        },
77        rate as usize,
78    )?;
79    if capture.format().subslot_bytes() != 2 {
80        return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81    }
82    let mut output = OpenOptions::new()
83        .create_new(true)
84        .write(true)
85        .open(&args[2])?;
86    output.write_all(&[0u8; 44])?;
87    let mut buffer = [0u8; 8192];
88    let mut bytes = 0u32;
89    let started = Instant::now();
90    while started.elapsed() < Duration::from_secs(seconds) {
91        let frames = capture.read(&mut buffer)?;
92        let count = frames * capture.format().bytes_per_frame();
93        output.write_all(&buffer[..count])?;
94        bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95        std::thread::sleep(Duration::from_millis(2));
96    }
97    let stats = capture.stats();
98    capture.close()?;
99    dac.close()?;
100    if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101        return Err("capture did not retire; retain host claims".into());
102    }
103    for &interface in claims.iter().rev() {
104        let interface = u32::from(interface);
105        if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106            return Err(std::io::Error::last_os_error().into());
107        }
108    }
109    let mut header = Vec::with_capacity(44);
110    header.extend_from_slice(b"RIFF");
111    header.extend_from_slice(&(36 + bytes).to_le_bytes());
112    header.extend_from_slice(b"WAVEfmt ");
113    header.extend_from_slice(&16u32.to_le_bytes());
114    header.extend_from_slice(&1u16.to_le_bytes());
115    header.extend_from_slice(&2u16.to_le_bytes());
116    header.extend_from_slice(&rate.to_le_bytes());
117    header.extend_from_slice(&(rate * 4).to_le_bytes());
118    header.extend_from_slice(&4u16.to_le_bytes());
119    header.extend_from_slice(&16u16.to_le_bytes());
120    header.extend_from_slice(b"data");
121    header.extend_from_slice(&bytes.to_le_bytes());
122    output.seek(SeekFrom::Start(0))?;
123    output.write_all(&header)?;
124    output.flush()?;
125    let valid = bytes > 0
126        && stats.failed_transfers == 0
127        && stats.failed_packets == 0
128        && stats.missing_frames == 0
129        && stats.overrun_frames == 0
130        && stats.contention_frames == 0;
131    let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132    std::fs::write(
133        format!("{}.json", args[2]),
134        serde_json::to_vec_pretty(&metadata)?,
135    )?;
136    if !valid {
137        return Err(
138            "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139                .into(),
140        );
141    }
142    println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143    Ok(())
144}
Source

pub fn retirement(&self) -> UsbRetirement

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.

Examples found in repository?
examples/two_dac_smoke.rs (line 134)
121    pub fn run() -> Result<(), Box<dyn std::error::Error>> {
122        let (first_fd, first, first_stream, first_original) = open("/dev/bus/usb/001/002")?;
123        let (second_fd, second, second_stream, second_original) = open("/dev/bus/usb/001/003")?;
124        feed(&[&first_stream, &second_stream], Duration::from_secs(2))?;
125        let a = first_stream.stats();
126        let b = second_stream.stats();
127        assert!(
128            a.played_frames > 20_000
129                && b.played_frames > 20_000
130                && a.lost_frames == 0
131                && b.lost_frames == 0
132        );
133        let second_level = volume(second_fd.as_raw_fd())?;
134        let first_retirement = first.retirement();
135        first_stream.close()?;
136        first.close()?;
137        assert!(first_retirement.wait(Duration::from_secs(2)));
138        assert_eq!(alternate(first_fd.as_raw_fd())?, 0);
139        assert_eq!(volume(first_fd.as_raw_fd())?, first_original);
140        assert_eq!(alternate(second_fd.as_raw_fd())?, 1);
141        assert_eq!(
142            volume(second_fd.as_raw_fd())?,
143            second_level,
144            "first close changed second volume"
145        );
146        feed(&[&second_stream], Duration::from_secs(1))?;
147        let after = second_stream.stats();
148        assert!(after.played_frames > b.played_frames && after.lost_frames == 0);
149        let second_retirement = second.retirement();
150        second_stream.close()?;
151        second.close()?;
152        assert!(second_retirement.wait(Duration::from_secs(2)));
153        assert_eq!(alternate(second_fd.as_raw_fd())?, 0);
154        assert_eq!(volume(second_fd.as_raw_fd())?, second_original);
155        release(&first_fd)?;
156        release(&second_fd)?;
157        println!("TWO_DACS_PASS first_frames={} second_frames={} independent volume/alt-zero/retirement/duplicate protection",a.played_frames,after.played_frames);
158        Ok(())
159    }
Source

pub fn await_connection_retirement(fd: RawFd, timeout: Duration) -> Result<bool>

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.

Source

pub fn await_usb_retirement(timeout: Duration) -> bool

Examples found in repository?
examples/guide_player.rs (line 396)
381pub fn shutdown(player: Player<DacStream>, dac: Dac, device_lost: bool) -> Result<()> {
382    let stream = player.stop(); // joins the writer thread
383    let stream_result = match Arc::try_unwrap(stream) {
384        Ok(stream) => stream.close(),
385        Err(_) => Err(Error::InvalidState(
386            "the stream is still shared".to_string(),
387        )),
388    };
389    let dac_result = if device_lost {
390        dac.close_with(CloseVolume::Forget)
391    } else {
392        dac.close()
393    };
394    if matches!(dac_result, Err(Error::Transfer(_))) {
395        // The output thread did not stop in time. Keep every claim and the descriptor until it has.
396        while !Dac::await_usb_retirement(Duration::from_secs(1)) {}
397    }
398    stream_result.and(dac_result)
399}
More examples
Hide additional examples
examples/qemu_smoke.rs (line 200)
68fn main() -> Result<(), Box<dyn std::error::Error>> {
69    log::set_logger(&LOGGER).unwrap();
70    log::set_max_level(log::LevelFilter::Info);
71    println!(
72        "SOURCE {}; QEMU null audio backend",
73        option_env!("USBDAC_PROBE_REVISION").unwrap_or("unrecorded")
74    );
75    let f = OpenOptions::new()
76        .read(true)
77        .write(true)
78        .open("/dev/bus/usb/001/002")?;
79    let fd = f.as_raw_fd();
80    for i in [0u32, 1] {
81        let r = unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &i) };
82        println!("CLAIM interface={i} result={r}");
83        if r != 0 {
84            return Err(std::io::Error::last_os_error().into());
85        }
86    }
87    assert_eq!(alt(fd), 0);
88    let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
89        .with_claimed_interfaces(vec![0u8, 1])
90        .with_device_name("/dev/bus/usb/001/002");
91    let before = volume(fd)?;
92    let dac = Dac::open(fd, info, DacConfig::default())?;
93    let capabilities = dac.capabilities()?;
94    assert_eq!(
95        capabilities.uac_version,
96        usbdac_core::UacVersion::V1,
97        "this probe proves UAC1 only"
98    );
99    println!("CAPABILITIES {capabilities:?}");
100    let exact = StreamRequest::pcm(44_100, 2, 16);
101    assert!(
102        matches!(
103            dac.negotiate(&exact),
104            Err(usbdac_core::Error::Unsupported { .. })
105        ),
106        "48 kHz-only QEMU alternate must reject 44.1 kHz exact"
107    );
108    let adaptive = StreamRequest {
109        rate_policy: usbdac_core::RatePolicy::NearestSupported,
110        ..exact
111    };
112    let fmt = dac.negotiate(&adaptive)?;
113    assert_eq!(
114        fmt.sample_rate, 48_000,
115        "adaptive QEMU setup must use the supported wire rate"
116    );
117    println!("QEMU_RATE_POLICY_PASS exact=44100-rejected adaptive=48000");
118    println!("FORMAT {fmt:?}");
119    let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
120    let mut stream = dac.open_stream(&fmt, listener.clone())?;
121    let mut data = Vec::new();
122    for i in 0..4800i32 {
123        let v = (((i % 96) - 48) * 20) as i16;
124        data.extend_from_slice(&v.to_le_bytes());
125        data.extend_from_slice(&(-v).to_le_bytes());
126    }
127    for _ in 0..3 {
128        println!("PRIME {}", stream.write(&data)?);
129    }
130    stream.play()?;
131    let start = Instant::now();
132    while start.elapsed() < Duration::from_secs(2) {
133        let n = stream.writable_bytes().min(data.len());
134        if n >= 4 {
135            stream.write(&data[..n - n % 4])?;
136        }
137        thread::sleep(Duration::from_millis(2));
138    }
139    let st = stream.stats();
140    println!("PCM_STATS {st:?}");
141    let good = st.played_frames > 20_000
142        && st.completed_transfers > 0
143        && st.lost_frames == 0
144        && st.underruns == 0
145        && st.urb_timeouts == 0
146        && st.short_packets == 0
147        && st.zero_packets == 0;
148    stream.pause()?;
149    let held_volume = volume(fd)?;
150    let replacement = dac.reconfigure_stream(
151        &stream,
152        &StreamRequest::pcm(48_000, 2, 16),
153        listener.clone(),
154        Duration::from_secs(3),
155    )?;
156    assert!(replacement.rollback_cause.is_none());
157    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
158    assert_eq!(replacement.stream.state(), usbdac_core::StreamState::Paused);
159    assert_eq!(replacement.stream.played_frames(), 0);
160    assert_eq!(
161        volume(fd)?,
162        held_volume,
163        "reconfigure changed hardware volume"
164    );
165    stream = replacement.stream;
166    println!("RECONFIGURE_SAME_OWNER_PASS rate=48000 paused=true volume=unchanged");
167    // The QEMU descriptor exposes signed16 only: this is a valid request with no matching alternate.
168    let rollback = dac.reconfigure_stream(
169        &stream,
170        &StreamRequest::pcm_float32(48_000, 2),
171        listener.clone(),
172        Duration::from_secs(3),
173    )?;
174    assert_eq!(
175        rollback.rollback_cause.as_ref().map(|e| e.code()),
176        Some("unsupported")
177    );
178    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
179    assert_eq!(rollback.stream.state(), usbdac_core::StreamState::Paused);
180    assert_eq!(
181        rollback.stream.format().request,
182        StreamRequest::pcm(48_000, 2, 16)
183    );
184    assert_eq!(volume(fd)?, held_volume, "rollback changed hardware volume");
185    stream = rollback.stream;
186    for _ in 0..3 {
187        stream.write(&data)?;
188    }
189    stream.play()?;
190    thread::sleep(Duration::from_millis(100));
191    assert!(
192        stream.played_frames() > 0,
193        "rolled-back stream did not resume real completions"
194    );
195    assert_eq!(stream.stats().lost_frames, 0);
196    println!("RECONFIGURE_ROLLBACK_PASS rate=48000 cause=unsupported resumed=true");
197    stream.pause()?;
198    stream.close()?;
199    dac.close()?;
200    assert!(Dac::await_usb_retirement(Duration::from_secs(2)));
201    println!("RETIRED true");
202    assert_eq!(alt(fd), 0);
203    let after = volume(fd)?;
204    assert_eq!(
205        after, before,
206        "original per-channel volume was not restored"
207    );
208    println!("VOLUME_RESTORED {after:?}");
209    for i in [1u32, 0] {
210        let r = unsafe { libc::ioctl(fd, 0x80045510u32 as _, &i) };
211        println!("RELEASE interface={i} result={r}");
212        assert_eq!(r, 0);
213    }
214    assert!(good, "no proven lossless media completions");
215    println!("QEMU_PCM_PASS");
216    Ok(())
217}
examples/loopback_capture.rs (line 100)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    use std::{
6        fs::OpenOptions,
7        io::{Seek, SeekFrom, Write},
8        os::fd::AsRawFd,
9        time::{Duration, Instant},
10    };
11    use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12    let args: Vec<String> = std::env::args().collect();
13    if args.len() != 5 {
14        return Err(
15            "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16                .into(),
17        );
18    }
19    let rate: u32 = args[3].parse()?;
20    let seconds: u64 = args[4].parse()?;
21    if rate == 0 || !(1..=120).contains(&seconds) {
22        return Err("invalid capture duration/rate".into());
23    }
24    let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25    let fd = file.as_raw_fd();
26    // GET_DESCRIPTOR device: identity comes from the actual USB device.
27    #[repr(C)]
28    struct Control {
29        kind: u8,
30        request: u8,
31        value: u16,
32        index: u16,
33        length: u16,
34        timeout: u32,
35        data: *mut u8,
36    }
37    let mut descriptor = [0u8; 18];
38    let mut control = Control {
39        kind: 0x80,
40        request: 6,
41        value: 0x0100,
42        index: 0,
43        length: 18,
44        timeout: 1000,
45        data: descriptor.as_mut_ptr(),
46    };
47    if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48        return Err(std::io::Error::last_os_error().into());
49    }
50    let mut info = DeviceInfo::new(
51        u16::from_le_bytes([descriptor[8], descriptor[9]]),
52        u16::from_le_bytes([descriptor[10], descriptor[11]]),
53        "Independent loopback input",
54    )
55    .with_device_name(&args[1]);
56    let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57    let mut claims = control_interfaces;
58    claims.extend(input_interfaces);
59    claims.sort_unstable();
60    claims.dedup();
61    for &interface in &claims {
62        let interface = u32::from(interface);
63        if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64            return Err(std::io::Error::last_os_error().into());
65        }
66    }
67    info.configuration_id = Some(configuration);
68    info.claimed_interfaces = claims.clone();
69    let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70    let capture = dac.open_capture(
71        &CaptureRequest {
72            sample_rate: rate,
73            channels: 2,
74            valid_bits: 16,
75            channel_map: None,
76        },
77        rate as usize,
78    )?;
79    if capture.format().subslot_bytes() != 2 {
80        return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81    }
82    let mut output = OpenOptions::new()
83        .create_new(true)
84        .write(true)
85        .open(&args[2])?;
86    output.write_all(&[0u8; 44])?;
87    let mut buffer = [0u8; 8192];
88    let mut bytes = 0u32;
89    let started = Instant::now();
90    while started.elapsed() < Duration::from_secs(seconds) {
91        let frames = capture.read(&mut buffer)?;
92        let count = frames * capture.format().bytes_per_frame();
93        output.write_all(&buffer[..count])?;
94        bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95        std::thread::sleep(Duration::from_millis(2));
96    }
97    let stats = capture.stats();
98    capture.close()?;
99    dac.close()?;
100    if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101        return Err("capture did not retire; retain host claims".into());
102    }
103    for &interface in claims.iter().rev() {
104        let interface = u32::from(interface);
105        if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106            return Err(std::io::Error::last_os_error().into());
107        }
108    }
109    let mut header = Vec::with_capacity(44);
110    header.extend_from_slice(b"RIFF");
111    header.extend_from_slice(&(36 + bytes).to_le_bytes());
112    header.extend_from_slice(b"WAVEfmt ");
113    header.extend_from_slice(&16u32.to_le_bytes());
114    header.extend_from_slice(&1u16.to_le_bytes());
115    header.extend_from_slice(&2u16.to_le_bytes());
116    header.extend_from_slice(&rate.to_le_bytes());
117    header.extend_from_slice(&(rate * 4).to_le_bytes());
118    header.extend_from_slice(&4u16.to_le_bytes());
119    header.extend_from_slice(&16u16.to_le_bytes());
120    header.extend_from_slice(b"data");
121    header.extend_from_slice(&bytes.to_le_bytes());
122    output.seek(SeekFrom::Start(0))?;
123    output.write_all(&header)?;
124    output.flush()?;
125    let valid = bytes > 0
126        && stats.failed_transfers == 0
127        && stats.failed_packets == 0
128        && stats.missing_frames == 0
129        && stats.overrun_frames == 0
130        && stats.contention_frames == 0;
131    let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132    std::fs::write(
133        format!("{}.json", args[2]),
134        serde_json::to_vec_pretty(&metadata)?,
135    )?;
136    if !valid {
137        return Err(
138            "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139                .into(),
140        );
141    }
142    println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143    Ok(())
144}
Source

pub fn feedback_preflight(fd: RawFd, info: &DeviceInfo) -> Result<(u8, Vec<u8>)>

Identify optional capture interfaces after the host claims the base audio interfaces. Returns the active configuration ID and source interface numbers without starting audio.

Examples found in repository?
examples/guide_open.rs (line 39)
35pub fn open_dac(host: &mut dyn UsbHost, identity: DeviceInfo, config: DacConfig) -> Result<Dac> {
36    let mut info = identity.with_claimed_interfaces(host.claim_audio_interfaces()?);
37    if !config.disable_feedback {
38        // Read-only: it names the active configuration and the IN interfaces a DAC may pace itself with.
39        let (configuration, candidates) = Dac::feedback_preflight(host.fd(), &info)?;
40        let got = host.claim_optional(&candidates);
41        info.configuration_id = Some(configuration);
42        info.unavailable_feedback_interfaces = candidates
43            .iter()
44            .copied()
45            .filter(|n| !got.contains(n))
46            .collect();
47        info.claimed_interfaces.extend(got);
48    }
49    // Lowers the DAC to at most -40 dB, verifies it, and touches neither the clock nor the audio.
50    Dac::open(host.fd(), info, config)
51}
Source

pub fn open(fd: RawFd, info: DeviceInfo, config: DacConfig) -> Result<Dac>

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, 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 says what it did.

Examples found in repository?
examples/guide_open.rs (line 50)
35pub fn open_dac(host: &mut dyn UsbHost, identity: DeviceInfo, config: DacConfig) -> Result<Dac> {
36    let mut info = identity.with_claimed_interfaces(host.claim_audio_interfaces()?);
37    if !config.disable_feedback {
38        // Read-only: it names the active configuration and the IN interfaces a DAC may pace itself with.
39        let (configuration, candidates) = Dac::feedback_preflight(host.fd(), &info)?;
40        let got = host.claim_optional(&candidates);
41        info.configuration_id = Some(configuration);
42        info.unavailable_feedback_interfaces = candidates
43            .iter()
44            .copied()
45            .filter(|n| !got.contains(n))
46            .collect();
47        info.claimed_interfaces.extend(got);
48    }
49    // Lowers the DAC to at most -40 dB, verifies it, and touches neither the clock nor the audio.
50    Dac::open(host.fd(), info, config)
51}
More examples
Hide additional examples
examples/two_dac_smoke.rs (line 80)
61    fn open(path: &str) -> Result<OpenedDac, Box<dyn std::error::Error>> {
62        let file = OpenOptions::new().read(true).write(true).open(path)?;
63        let fd = file.as_raw_fd();
64        let mut descriptor = [0; 18];
65        read(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?;
66        assert_eq!(
67            &descriptor[8..12],
68            &[0xf4, 0x46, 0x02, 0x00],
69            "probe is restricted to QEMU USB Audio"
70        );
71        for interface in [0u32, 1] {
72            if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
73                return Err(std::io::Error::last_os_error().into());
74            }
75        }
76        let before = volume(fd)?;
77        let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
78            .with_device_name(path)
79            .with_claimed_interfaces(vec![0u8, 1]);
80        let dac = Dac::open(fd, info.clone(), DacConfig::default())?;
81        assert!(
82            matches!(Dac::open(fd, info, DacConfig::default()), Err(Error::Busy)),
83            "duplicate attachment was admitted"
84        );
85        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
86        let stream = dac.open_stream(&format, Arc::new(|event| eprintln!("{event:?}")))?;
87        Ok((file, dac, stream, before))
88    }
examples/qemu_smoke.rs (line 92)
68fn main() -> Result<(), Box<dyn std::error::Error>> {
69    log::set_logger(&LOGGER).unwrap();
70    log::set_max_level(log::LevelFilter::Info);
71    println!(
72        "SOURCE {}; QEMU null audio backend",
73        option_env!("USBDAC_PROBE_REVISION").unwrap_or("unrecorded")
74    );
75    let f = OpenOptions::new()
76        .read(true)
77        .write(true)
78        .open("/dev/bus/usb/001/002")?;
79    let fd = f.as_raw_fd();
80    for i in [0u32, 1] {
81        let r = unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &i) };
82        println!("CLAIM interface={i} result={r}");
83        if r != 0 {
84            return Err(std::io::Error::last_os_error().into());
85        }
86    }
87    assert_eq!(alt(fd), 0);
88    let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
89        .with_claimed_interfaces(vec![0u8, 1])
90        .with_device_name("/dev/bus/usb/001/002");
91    let before = volume(fd)?;
92    let dac = Dac::open(fd, info, DacConfig::default())?;
93    let capabilities = dac.capabilities()?;
94    assert_eq!(
95        capabilities.uac_version,
96        usbdac_core::UacVersion::V1,
97        "this probe proves UAC1 only"
98    );
99    println!("CAPABILITIES {capabilities:?}");
100    let exact = StreamRequest::pcm(44_100, 2, 16);
101    assert!(
102        matches!(
103            dac.negotiate(&exact),
104            Err(usbdac_core::Error::Unsupported { .. })
105        ),
106        "48 kHz-only QEMU alternate must reject 44.1 kHz exact"
107    );
108    let adaptive = StreamRequest {
109        rate_policy: usbdac_core::RatePolicy::NearestSupported,
110        ..exact
111    };
112    let fmt = dac.negotiate(&adaptive)?;
113    assert_eq!(
114        fmt.sample_rate, 48_000,
115        "adaptive QEMU setup must use the supported wire rate"
116    );
117    println!("QEMU_RATE_POLICY_PASS exact=44100-rejected adaptive=48000");
118    println!("FORMAT {fmt:?}");
119    let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
120    let mut stream = dac.open_stream(&fmt, listener.clone())?;
121    let mut data = Vec::new();
122    for i in 0..4800i32 {
123        let v = (((i % 96) - 48) * 20) as i16;
124        data.extend_from_slice(&v.to_le_bytes());
125        data.extend_from_slice(&(-v).to_le_bytes());
126    }
127    for _ in 0..3 {
128        println!("PRIME {}", stream.write(&data)?);
129    }
130    stream.play()?;
131    let start = Instant::now();
132    while start.elapsed() < Duration::from_secs(2) {
133        let n = stream.writable_bytes().min(data.len());
134        if n >= 4 {
135            stream.write(&data[..n - n % 4])?;
136        }
137        thread::sleep(Duration::from_millis(2));
138    }
139    let st = stream.stats();
140    println!("PCM_STATS {st:?}");
141    let good = st.played_frames > 20_000
142        && st.completed_transfers > 0
143        && st.lost_frames == 0
144        && st.underruns == 0
145        && st.urb_timeouts == 0
146        && st.short_packets == 0
147        && st.zero_packets == 0;
148    stream.pause()?;
149    let held_volume = volume(fd)?;
150    let replacement = dac.reconfigure_stream(
151        &stream,
152        &StreamRequest::pcm(48_000, 2, 16),
153        listener.clone(),
154        Duration::from_secs(3),
155    )?;
156    assert!(replacement.rollback_cause.is_none());
157    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
158    assert_eq!(replacement.stream.state(), usbdac_core::StreamState::Paused);
159    assert_eq!(replacement.stream.played_frames(), 0);
160    assert_eq!(
161        volume(fd)?,
162        held_volume,
163        "reconfigure changed hardware volume"
164    );
165    stream = replacement.stream;
166    println!("RECONFIGURE_SAME_OWNER_PASS rate=48000 paused=true volume=unchanged");
167    // The QEMU descriptor exposes signed16 only: this is a valid request with no matching alternate.
168    let rollback = dac.reconfigure_stream(
169        &stream,
170        &StreamRequest::pcm_float32(48_000, 2),
171        listener.clone(),
172        Duration::from_secs(3),
173    )?;
174    assert_eq!(
175        rollback.rollback_cause.as_ref().map(|e| e.code()),
176        Some("unsupported")
177    );
178    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
179    assert_eq!(rollback.stream.state(), usbdac_core::StreamState::Paused);
180    assert_eq!(
181        rollback.stream.format().request,
182        StreamRequest::pcm(48_000, 2, 16)
183    );
184    assert_eq!(volume(fd)?, held_volume, "rollback changed hardware volume");
185    stream = rollback.stream;
186    for _ in 0..3 {
187        stream.write(&data)?;
188    }
189    stream.play()?;
190    thread::sleep(Duration::from_millis(100));
191    assert!(
192        stream.played_frames() > 0,
193        "rolled-back stream did not resume real completions"
194    );
195    assert_eq!(stream.stats().lost_frames, 0);
196    println!("RECONFIGURE_ROLLBACK_PASS rate=48000 cause=unsupported resumed=true");
197    stream.pause()?;
198    stream.close()?;
199    dac.close()?;
200    assert!(Dac::await_usb_retirement(Duration::from_secs(2)));
201    println!("RETIRED true");
202    assert_eq!(alt(fd), 0);
203    let after = volume(fd)?;
204    assert_eq!(
205        after, before,
206        "original per-channel volume was not restored"
207    );
208    println!("VOLUME_RESTORED {after:?}");
209    for i in [1u32, 0] {
210        let r = unsafe { libc::ioctl(fd, 0x80045510u32 as _, &i) };
211        println!("RELEASE interface={i} result={r}");
212        assert_eq!(r, 0);
213    }
214    assert!(good, "no proven lossless media completions");
215    println!("QEMU_PCM_PASS");
216    Ok(())
217}
Source

pub fn open_duplex_device( fd: RawFd, info: DeviceInfo, config: DacConfig, ) -> Result<Dac>

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.

Source

pub fn info(&self) -> &DeviceInfo

The identity the host gave at open.

Source

pub fn feedback_trace(&self) -> Option<FeedbackTrace>

Export the last stream’s opt-in support capture, even after the stream has closed. A new successfully opened stream replaces it.

Source

pub fn capabilities(&self) -> Result<Capabilities>

What the DAC offers, from the descriptors scanned at open.

Examples found in repository?
examples/qemu_smoke.rs (line 93)
68fn main() -> Result<(), Box<dyn std::error::Error>> {
69    log::set_logger(&LOGGER).unwrap();
70    log::set_max_level(log::LevelFilter::Info);
71    println!(
72        "SOURCE {}; QEMU null audio backend",
73        option_env!("USBDAC_PROBE_REVISION").unwrap_or("unrecorded")
74    );
75    let f = OpenOptions::new()
76        .read(true)
77        .write(true)
78        .open("/dev/bus/usb/001/002")?;
79    let fd = f.as_raw_fd();
80    for i in [0u32, 1] {
81        let r = unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &i) };
82        println!("CLAIM interface={i} result={r}");
83        if r != 0 {
84            return Err(std::io::Error::last_os_error().into());
85        }
86    }
87    assert_eq!(alt(fd), 0);
88    let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
89        .with_claimed_interfaces(vec![0u8, 1])
90        .with_device_name("/dev/bus/usb/001/002");
91    let before = volume(fd)?;
92    let dac = Dac::open(fd, info, DacConfig::default())?;
93    let capabilities = dac.capabilities()?;
94    assert_eq!(
95        capabilities.uac_version,
96        usbdac_core::UacVersion::V1,
97        "this probe proves UAC1 only"
98    );
99    println!("CAPABILITIES {capabilities:?}");
100    let exact = StreamRequest::pcm(44_100, 2, 16);
101    assert!(
102        matches!(
103            dac.negotiate(&exact),
104            Err(usbdac_core::Error::Unsupported { .. })
105        ),
106        "48 kHz-only QEMU alternate must reject 44.1 kHz exact"
107    );
108    let adaptive = StreamRequest {
109        rate_policy: usbdac_core::RatePolicy::NearestSupported,
110        ..exact
111    };
112    let fmt = dac.negotiate(&adaptive)?;
113    assert_eq!(
114        fmt.sample_rate, 48_000,
115        "adaptive QEMU setup must use the supported wire rate"
116    );
117    println!("QEMU_RATE_POLICY_PASS exact=44100-rejected adaptive=48000");
118    println!("FORMAT {fmt:?}");
119    let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
120    let mut stream = dac.open_stream(&fmt, listener.clone())?;
121    let mut data = Vec::new();
122    for i in 0..4800i32 {
123        let v = (((i % 96) - 48) * 20) as i16;
124        data.extend_from_slice(&v.to_le_bytes());
125        data.extend_from_slice(&(-v).to_le_bytes());
126    }
127    for _ in 0..3 {
128        println!("PRIME {}", stream.write(&data)?);
129    }
130    stream.play()?;
131    let start = Instant::now();
132    while start.elapsed() < Duration::from_secs(2) {
133        let n = stream.writable_bytes().min(data.len());
134        if n >= 4 {
135            stream.write(&data[..n - n % 4])?;
136        }
137        thread::sleep(Duration::from_millis(2));
138    }
139    let st = stream.stats();
140    println!("PCM_STATS {st:?}");
141    let good = st.played_frames > 20_000
142        && st.completed_transfers > 0
143        && st.lost_frames == 0
144        && st.underruns == 0
145        && st.urb_timeouts == 0
146        && st.short_packets == 0
147        && st.zero_packets == 0;
148    stream.pause()?;
149    let held_volume = volume(fd)?;
150    let replacement = dac.reconfigure_stream(
151        &stream,
152        &StreamRequest::pcm(48_000, 2, 16),
153        listener.clone(),
154        Duration::from_secs(3),
155    )?;
156    assert!(replacement.rollback_cause.is_none());
157    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
158    assert_eq!(replacement.stream.state(), usbdac_core::StreamState::Paused);
159    assert_eq!(replacement.stream.played_frames(), 0);
160    assert_eq!(
161        volume(fd)?,
162        held_volume,
163        "reconfigure changed hardware volume"
164    );
165    stream = replacement.stream;
166    println!("RECONFIGURE_SAME_OWNER_PASS rate=48000 paused=true volume=unchanged");
167    // The QEMU descriptor exposes signed16 only: this is a valid request with no matching alternate.
168    let rollback = dac.reconfigure_stream(
169        &stream,
170        &StreamRequest::pcm_float32(48_000, 2),
171        listener.clone(),
172        Duration::from_secs(3),
173    )?;
174    assert_eq!(
175        rollback.rollback_cause.as_ref().map(|e| e.code()),
176        Some("unsupported")
177    );
178    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
179    assert_eq!(rollback.stream.state(), usbdac_core::StreamState::Paused);
180    assert_eq!(
181        rollback.stream.format().request,
182        StreamRequest::pcm(48_000, 2, 16)
183    );
184    assert_eq!(volume(fd)?, held_volume, "rollback changed hardware volume");
185    stream = rollback.stream;
186    for _ in 0..3 {
187        stream.write(&data)?;
188    }
189    stream.play()?;
190    thread::sleep(Duration::from_millis(100));
191    assert!(
192        stream.played_frames() > 0,
193        "rolled-back stream did not resume real completions"
194    );
195    assert_eq!(stream.stats().lost_frames, 0);
196    println!("RECONFIGURE_ROLLBACK_PASS rate=48000 cause=unsupported resumed=true");
197    stream.pause()?;
198    stream.close()?;
199    dac.close()?;
200    assert!(Dac::await_usb_retirement(Duration::from_secs(2)));
201    println!("RETIRED true");
202    assert_eq!(alt(fd), 0);
203    let after = volume(fd)?;
204    assert_eq!(
205        after, before,
206        "original per-channel volume was not restored"
207    );
208    println!("VOLUME_RESTORED {after:?}");
209    for i in [1u32, 0] {
210        let r = unsafe { libc::ioctl(fd, 0x80045510u32 as _, &i) };
211        println!("RELEASE interface={i} result={r}");
212        assert_eq!(r, 0);
213    }
214    assert!(good, "no proven lossless media completions");
215    println!("QEMU_PCM_PASS");
216    Ok(())
217}
Source

pub fn negotiate(&self, request: &StreamRequest) -> Result<StreamFormat>

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.

Examples found in repository?
examples/guide_open.rs (line 99)
91pub fn negotiate(dac: &Dac, track: TrackFormat, allow_nearest: bool) -> Result<Negotiated> {
92    let policy = if allow_nearest {
93        RatePolicy::NearestSupported
94    } else {
95        RatePolicy::Exact
96    };
97    let request =
98        StreamRequest::pcm(track.sample_rate, track.channels, track.bits).with_rate_policy(policy);
99    let format = dac.negotiate(&request)?;
100    let resample_to = format
101        .rate_differs_from_request()
102        .then_some(format.sample_rate);
103    Ok(Negotiated {
104        format,
105        resample_to,
106    })
107}
More examples
Hide additional examples
examples/two_dac_smoke.rs (line 85)
61    fn open(path: &str) -> Result<OpenedDac, Box<dyn std::error::Error>> {
62        let file = OpenOptions::new().read(true).write(true).open(path)?;
63        let fd = file.as_raw_fd();
64        let mut descriptor = [0; 18];
65        read(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?;
66        assert_eq!(
67            &descriptor[8..12],
68            &[0xf4, 0x46, 0x02, 0x00],
69            "probe is restricted to QEMU USB Audio"
70        );
71        for interface in [0u32, 1] {
72            if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
73                return Err(std::io::Error::last_os_error().into());
74            }
75        }
76        let before = volume(fd)?;
77        let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
78            .with_device_name(path)
79            .with_claimed_interfaces(vec![0u8, 1]);
80        let dac = Dac::open(fd, info.clone(), DacConfig::default())?;
81        assert!(
82            matches!(Dac::open(fd, info, DacConfig::default()), Err(Error::Busy)),
83            "duplicate attachment was admitted"
84        );
85        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
86        let stream = dac.open_stream(&format, Arc::new(|event| eprintln!("{event:?}")))?;
87        Ok((file, dac, stream, before))
88    }
examples/qemu_smoke.rs (line 103)
68fn main() -> Result<(), Box<dyn std::error::Error>> {
69    log::set_logger(&LOGGER).unwrap();
70    log::set_max_level(log::LevelFilter::Info);
71    println!(
72        "SOURCE {}; QEMU null audio backend",
73        option_env!("USBDAC_PROBE_REVISION").unwrap_or("unrecorded")
74    );
75    let f = OpenOptions::new()
76        .read(true)
77        .write(true)
78        .open("/dev/bus/usb/001/002")?;
79    let fd = f.as_raw_fd();
80    for i in [0u32, 1] {
81        let r = unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &i) };
82        println!("CLAIM interface={i} result={r}");
83        if r != 0 {
84            return Err(std::io::Error::last_os_error().into());
85        }
86    }
87    assert_eq!(alt(fd), 0);
88    let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
89        .with_claimed_interfaces(vec![0u8, 1])
90        .with_device_name("/dev/bus/usb/001/002");
91    let before = volume(fd)?;
92    let dac = Dac::open(fd, info, DacConfig::default())?;
93    let capabilities = dac.capabilities()?;
94    assert_eq!(
95        capabilities.uac_version,
96        usbdac_core::UacVersion::V1,
97        "this probe proves UAC1 only"
98    );
99    println!("CAPABILITIES {capabilities:?}");
100    let exact = StreamRequest::pcm(44_100, 2, 16);
101    assert!(
102        matches!(
103            dac.negotiate(&exact),
104            Err(usbdac_core::Error::Unsupported { .. })
105        ),
106        "48 kHz-only QEMU alternate must reject 44.1 kHz exact"
107    );
108    let adaptive = StreamRequest {
109        rate_policy: usbdac_core::RatePolicy::NearestSupported,
110        ..exact
111    };
112    let fmt = dac.negotiate(&adaptive)?;
113    assert_eq!(
114        fmt.sample_rate, 48_000,
115        "adaptive QEMU setup must use the supported wire rate"
116    );
117    println!("QEMU_RATE_POLICY_PASS exact=44100-rejected adaptive=48000");
118    println!("FORMAT {fmt:?}");
119    let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
120    let mut stream = dac.open_stream(&fmt, listener.clone())?;
121    let mut data = Vec::new();
122    for i in 0..4800i32 {
123        let v = (((i % 96) - 48) * 20) as i16;
124        data.extend_from_slice(&v.to_le_bytes());
125        data.extend_from_slice(&(-v).to_le_bytes());
126    }
127    for _ in 0..3 {
128        println!("PRIME {}", stream.write(&data)?);
129    }
130    stream.play()?;
131    let start = Instant::now();
132    while start.elapsed() < Duration::from_secs(2) {
133        let n = stream.writable_bytes().min(data.len());
134        if n >= 4 {
135            stream.write(&data[..n - n % 4])?;
136        }
137        thread::sleep(Duration::from_millis(2));
138    }
139    let st = stream.stats();
140    println!("PCM_STATS {st:?}");
141    let good = st.played_frames > 20_000
142        && st.completed_transfers > 0
143        && st.lost_frames == 0
144        && st.underruns == 0
145        && st.urb_timeouts == 0
146        && st.short_packets == 0
147        && st.zero_packets == 0;
148    stream.pause()?;
149    let held_volume = volume(fd)?;
150    let replacement = dac.reconfigure_stream(
151        &stream,
152        &StreamRequest::pcm(48_000, 2, 16),
153        listener.clone(),
154        Duration::from_secs(3),
155    )?;
156    assert!(replacement.rollback_cause.is_none());
157    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
158    assert_eq!(replacement.stream.state(), usbdac_core::StreamState::Paused);
159    assert_eq!(replacement.stream.played_frames(), 0);
160    assert_eq!(
161        volume(fd)?,
162        held_volume,
163        "reconfigure changed hardware volume"
164    );
165    stream = replacement.stream;
166    println!("RECONFIGURE_SAME_OWNER_PASS rate=48000 paused=true volume=unchanged");
167    // The QEMU descriptor exposes signed16 only: this is a valid request with no matching alternate.
168    let rollback = dac.reconfigure_stream(
169        &stream,
170        &StreamRequest::pcm_float32(48_000, 2),
171        listener.clone(),
172        Duration::from_secs(3),
173    )?;
174    assert_eq!(
175        rollback.rollback_cause.as_ref().map(|e| e.code()),
176        Some("unsupported")
177    );
178    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
179    assert_eq!(rollback.stream.state(), usbdac_core::StreamState::Paused);
180    assert_eq!(
181        rollback.stream.format().request,
182        StreamRequest::pcm(48_000, 2, 16)
183    );
184    assert_eq!(volume(fd)?, held_volume, "rollback changed hardware volume");
185    stream = rollback.stream;
186    for _ in 0..3 {
187        stream.write(&data)?;
188    }
189    stream.play()?;
190    thread::sleep(Duration::from_millis(100));
191    assert!(
192        stream.played_frames() > 0,
193        "rolled-back stream did not resume real completions"
194    );
195    assert_eq!(stream.stats().lost_frames, 0);
196    println!("RECONFIGURE_ROLLBACK_PASS rate=48000 cause=unsupported resumed=true");
197    stream.pause()?;
198    stream.close()?;
199    dac.close()?;
200    assert!(Dac::await_usb_retirement(Duration::from_secs(2)));
201    println!("RETIRED true");
202    assert_eq!(alt(fd), 0);
203    let after = volume(fd)?;
204    assert_eq!(
205        after, before,
206        "original per-channel volume was not restored"
207    );
208    println!("VOLUME_RESTORED {after:?}");
209    for i in [1u32, 0] {
210        let r = unsafe { libc::ioctl(fd, 0x80045510u32 as _, &i) };
211        println!("RELEASE interface={i} result={r}");
212        assert_eq!(r, 0);
213    }
214    assert!(good, "no proven lossless media completions");
215    println!("QEMU_PCM_PASS");
216    Ok(())
217}
Source

pub fn negotiate_candidates( &self, requests: &[StreamRequest], ) -> Result<StreamFormat>

Negotiate a bounded, ordered list of exact PCM formats on one retained owner. A later candidate is considered only after a certified clean refusal.

Source

pub fn open_stream( &self, format: &StreamFormat, listener: Arc<dyn DacListener>, ) -> Result<DacStream>

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.

Examples found in repository?
examples/guide_player.rs (line 406)
404pub fn play_one(dac: Dac, format: &StreamFormat, source: Box<dyn Source>) -> Result<()> {
405    let (listener, events) = event_channel();
406    let stream = dac.open_stream(format, listener)?;
407    let shape = Shape::from(stream.format());
408    let player = Player::start(Arc::new(stream), shape, source);
409    let mut device_lost = false;
410    while !player.finished() {
411        match events.recv_timeout(Duration::from_millis(100)).map(react) {
412            Ok(Reaction::Pause(reason)) => {
413                log::warn!("{reason}");
414                device_lost = true;
415                break;
416            }
417            Ok(Reaction::Failed(error)) => {
418                device_lost = error == Error::DeviceLost;
419                log::warn!("the stream failed: {error}");
420                break;
421            }
422            _ => {}
423        }
424    }
425    log::info!("{}", status_line(player.ring(), true, false));
426    shutdown(player, dac, device_lost)
427}
More examples
Hide additional examples
examples/two_dac_smoke.rs (line 86)
61    fn open(path: &str) -> Result<OpenedDac, Box<dyn std::error::Error>> {
62        let file = OpenOptions::new().read(true).write(true).open(path)?;
63        let fd = file.as_raw_fd();
64        let mut descriptor = [0; 18];
65        read(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?;
66        assert_eq!(
67            &descriptor[8..12],
68            &[0xf4, 0x46, 0x02, 0x00],
69            "probe is restricted to QEMU USB Audio"
70        );
71        for interface in [0u32, 1] {
72            if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
73                return Err(std::io::Error::last_os_error().into());
74            }
75        }
76        let before = volume(fd)?;
77        let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
78            .with_device_name(path)
79            .with_claimed_interfaces(vec![0u8, 1]);
80        let dac = Dac::open(fd, info.clone(), DacConfig::default())?;
81        assert!(
82            matches!(Dac::open(fd, info, DacConfig::default()), Err(Error::Busy)),
83            "duplicate attachment was admitted"
84        );
85        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
86        let stream = dac.open_stream(&format, Arc::new(|event| eprintln!("{event:?}")))?;
87        Ok((file, dac, stream, before))
88    }
examples/qemu_smoke.rs (line 120)
68fn main() -> Result<(), Box<dyn std::error::Error>> {
69    log::set_logger(&LOGGER).unwrap();
70    log::set_max_level(log::LevelFilter::Info);
71    println!(
72        "SOURCE {}; QEMU null audio backend",
73        option_env!("USBDAC_PROBE_REVISION").unwrap_or("unrecorded")
74    );
75    let f = OpenOptions::new()
76        .read(true)
77        .write(true)
78        .open("/dev/bus/usb/001/002")?;
79    let fd = f.as_raw_fd();
80    for i in [0u32, 1] {
81        let r = unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &i) };
82        println!("CLAIM interface={i} result={r}");
83        if r != 0 {
84            return Err(std::io::Error::last_os_error().into());
85        }
86    }
87    assert_eq!(alt(fd), 0);
88    let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
89        .with_claimed_interfaces(vec![0u8, 1])
90        .with_device_name("/dev/bus/usb/001/002");
91    let before = volume(fd)?;
92    let dac = Dac::open(fd, info, DacConfig::default())?;
93    let capabilities = dac.capabilities()?;
94    assert_eq!(
95        capabilities.uac_version,
96        usbdac_core::UacVersion::V1,
97        "this probe proves UAC1 only"
98    );
99    println!("CAPABILITIES {capabilities:?}");
100    let exact = StreamRequest::pcm(44_100, 2, 16);
101    assert!(
102        matches!(
103            dac.negotiate(&exact),
104            Err(usbdac_core::Error::Unsupported { .. })
105        ),
106        "48 kHz-only QEMU alternate must reject 44.1 kHz exact"
107    );
108    let adaptive = StreamRequest {
109        rate_policy: usbdac_core::RatePolicy::NearestSupported,
110        ..exact
111    };
112    let fmt = dac.negotiate(&adaptive)?;
113    assert_eq!(
114        fmt.sample_rate, 48_000,
115        "adaptive QEMU setup must use the supported wire rate"
116    );
117    println!("QEMU_RATE_POLICY_PASS exact=44100-rejected adaptive=48000");
118    println!("FORMAT {fmt:?}");
119    let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
120    let mut stream = dac.open_stream(&fmt, listener.clone())?;
121    let mut data = Vec::new();
122    for i in 0..4800i32 {
123        let v = (((i % 96) - 48) * 20) as i16;
124        data.extend_from_slice(&v.to_le_bytes());
125        data.extend_from_slice(&(-v).to_le_bytes());
126    }
127    for _ in 0..3 {
128        println!("PRIME {}", stream.write(&data)?);
129    }
130    stream.play()?;
131    let start = Instant::now();
132    while start.elapsed() < Duration::from_secs(2) {
133        let n = stream.writable_bytes().min(data.len());
134        if n >= 4 {
135            stream.write(&data[..n - n % 4])?;
136        }
137        thread::sleep(Duration::from_millis(2));
138    }
139    let st = stream.stats();
140    println!("PCM_STATS {st:?}");
141    let good = st.played_frames > 20_000
142        && st.completed_transfers > 0
143        && st.lost_frames == 0
144        && st.underruns == 0
145        && st.urb_timeouts == 0
146        && st.short_packets == 0
147        && st.zero_packets == 0;
148    stream.pause()?;
149    let held_volume = volume(fd)?;
150    let replacement = dac.reconfigure_stream(
151        &stream,
152        &StreamRequest::pcm(48_000, 2, 16),
153        listener.clone(),
154        Duration::from_secs(3),
155    )?;
156    assert!(replacement.rollback_cause.is_none());
157    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
158    assert_eq!(replacement.stream.state(), usbdac_core::StreamState::Paused);
159    assert_eq!(replacement.stream.played_frames(), 0);
160    assert_eq!(
161        volume(fd)?,
162        held_volume,
163        "reconfigure changed hardware volume"
164    );
165    stream = replacement.stream;
166    println!("RECONFIGURE_SAME_OWNER_PASS rate=48000 paused=true volume=unchanged");
167    // The QEMU descriptor exposes signed16 only: this is a valid request with no matching alternate.
168    let rollback = dac.reconfigure_stream(
169        &stream,
170        &StreamRequest::pcm_float32(48_000, 2),
171        listener.clone(),
172        Duration::from_secs(3),
173    )?;
174    assert_eq!(
175        rollback.rollback_cause.as_ref().map(|e| e.code()),
176        Some("unsupported")
177    );
178    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
179    assert_eq!(rollback.stream.state(), usbdac_core::StreamState::Paused);
180    assert_eq!(
181        rollback.stream.format().request,
182        StreamRequest::pcm(48_000, 2, 16)
183    );
184    assert_eq!(volume(fd)?, held_volume, "rollback changed hardware volume");
185    stream = rollback.stream;
186    for _ in 0..3 {
187        stream.write(&data)?;
188    }
189    stream.play()?;
190    thread::sleep(Duration::from_millis(100));
191    assert!(
192        stream.played_frames() > 0,
193        "rolled-back stream did not resume real completions"
194    );
195    assert_eq!(stream.stats().lost_frames, 0);
196    println!("RECONFIGURE_ROLLBACK_PASS rate=48000 cause=unsupported resumed=true");
197    stream.pause()?;
198    stream.close()?;
199    dac.close()?;
200    assert!(Dac::await_usb_retirement(Duration::from_secs(2)));
201    println!("RETIRED true");
202    assert_eq!(alt(fd), 0);
203    let after = volume(fd)?;
204    assert_eq!(
205        after, before,
206        "original per-channel volume was not restored"
207    );
208    println!("VOLUME_RESTORED {after:?}");
209    for i in [1u32, 0] {
210        let r = unsafe { libc::ioctl(fd, 0x80045510u32 as _, &i) };
211        println!("RELEASE interface={i} result={r}");
212        assert_eq!(r, 0);
213    }
214    assert!(good, "no proven lossless media completions");
215    println!("QEMU_PCM_PASS");
216    Ok(())
217}
Source

pub fn reconfigure_stream( &self, current: &DacStream, request: &StreamRequest, listener: Arc<dyn DacListener>, drain_timeout: Duration, ) -> Result<StreamReconfiguration>

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.

Examples found in repository?
examples/qemu_smoke.rs (lines 150-155)
68fn main() -> Result<(), Box<dyn std::error::Error>> {
69    log::set_logger(&LOGGER).unwrap();
70    log::set_max_level(log::LevelFilter::Info);
71    println!(
72        "SOURCE {}; QEMU null audio backend",
73        option_env!("USBDAC_PROBE_REVISION").unwrap_or("unrecorded")
74    );
75    let f = OpenOptions::new()
76        .read(true)
77        .write(true)
78        .open("/dev/bus/usb/001/002")?;
79    let fd = f.as_raw_fd();
80    for i in [0u32, 1] {
81        let r = unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &i) };
82        println!("CLAIM interface={i} result={r}");
83        if r != 0 {
84            return Err(std::io::Error::last_os_error().into());
85        }
86    }
87    assert_eq!(alt(fd), 0);
88    let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
89        .with_claimed_interfaces(vec![0u8, 1])
90        .with_device_name("/dev/bus/usb/001/002");
91    let before = volume(fd)?;
92    let dac = Dac::open(fd, info, DacConfig::default())?;
93    let capabilities = dac.capabilities()?;
94    assert_eq!(
95        capabilities.uac_version,
96        usbdac_core::UacVersion::V1,
97        "this probe proves UAC1 only"
98    );
99    println!("CAPABILITIES {capabilities:?}");
100    let exact = StreamRequest::pcm(44_100, 2, 16);
101    assert!(
102        matches!(
103            dac.negotiate(&exact),
104            Err(usbdac_core::Error::Unsupported { .. })
105        ),
106        "48 kHz-only QEMU alternate must reject 44.1 kHz exact"
107    );
108    let adaptive = StreamRequest {
109        rate_policy: usbdac_core::RatePolicy::NearestSupported,
110        ..exact
111    };
112    let fmt = dac.negotiate(&adaptive)?;
113    assert_eq!(
114        fmt.sample_rate, 48_000,
115        "adaptive QEMU setup must use the supported wire rate"
116    );
117    println!("QEMU_RATE_POLICY_PASS exact=44100-rejected adaptive=48000");
118    println!("FORMAT {fmt:?}");
119    let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
120    let mut stream = dac.open_stream(&fmt, listener.clone())?;
121    let mut data = Vec::new();
122    for i in 0..4800i32 {
123        let v = (((i % 96) - 48) * 20) as i16;
124        data.extend_from_slice(&v.to_le_bytes());
125        data.extend_from_slice(&(-v).to_le_bytes());
126    }
127    for _ in 0..3 {
128        println!("PRIME {}", stream.write(&data)?);
129    }
130    stream.play()?;
131    let start = Instant::now();
132    while start.elapsed() < Duration::from_secs(2) {
133        let n = stream.writable_bytes().min(data.len());
134        if n >= 4 {
135            stream.write(&data[..n - n % 4])?;
136        }
137        thread::sleep(Duration::from_millis(2));
138    }
139    let st = stream.stats();
140    println!("PCM_STATS {st:?}");
141    let good = st.played_frames > 20_000
142        && st.completed_transfers > 0
143        && st.lost_frames == 0
144        && st.underruns == 0
145        && st.urb_timeouts == 0
146        && st.short_packets == 0
147        && st.zero_packets == 0;
148    stream.pause()?;
149    let held_volume = volume(fd)?;
150    let replacement = dac.reconfigure_stream(
151        &stream,
152        &StreamRequest::pcm(48_000, 2, 16),
153        listener.clone(),
154        Duration::from_secs(3),
155    )?;
156    assert!(replacement.rollback_cause.is_none());
157    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
158    assert_eq!(replacement.stream.state(), usbdac_core::StreamState::Paused);
159    assert_eq!(replacement.stream.played_frames(), 0);
160    assert_eq!(
161        volume(fd)?,
162        held_volume,
163        "reconfigure changed hardware volume"
164    );
165    stream = replacement.stream;
166    println!("RECONFIGURE_SAME_OWNER_PASS rate=48000 paused=true volume=unchanged");
167    // The QEMU descriptor exposes signed16 only: this is a valid request with no matching alternate.
168    let rollback = dac.reconfigure_stream(
169        &stream,
170        &StreamRequest::pcm_float32(48_000, 2),
171        listener.clone(),
172        Duration::from_secs(3),
173    )?;
174    assert_eq!(
175        rollback.rollback_cause.as_ref().map(|e| e.code()),
176        Some("unsupported")
177    );
178    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
179    assert_eq!(rollback.stream.state(), usbdac_core::StreamState::Paused);
180    assert_eq!(
181        rollback.stream.format().request,
182        StreamRequest::pcm(48_000, 2, 16)
183    );
184    assert_eq!(volume(fd)?, held_volume, "rollback changed hardware volume");
185    stream = rollback.stream;
186    for _ in 0..3 {
187        stream.write(&data)?;
188    }
189    stream.play()?;
190    thread::sleep(Duration::from_millis(100));
191    assert!(
192        stream.played_frames() > 0,
193        "rolled-back stream did not resume real completions"
194    );
195    assert_eq!(stream.stats().lost_frames, 0);
196    println!("RECONFIGURE_ROLLBACK_PASS rate=48000 cause=unsupported resumed=true");
197    stream.pause()?;
198    stream.close()?;
199    dac.close()?;
200    assert!(Dac::await_usb_retirement(Duration::from_secs(2)));
201    println!("RETIRED true");
202    assert_eq!(alt(fd), 0);
203    let after = volume(fd)?;
204    assert_eq!(
205        after, before,
206        "original per-channel volume was not restored"
207    );
208    println!("VOLUME_RESTORED {after:?}");
209    for i in [1u32, 0] {
210        let r = unsafe { libc::ioctl(fd, 0x80045510u32 as _, &i) };
211        println!("RELEASE interface={i} result={r}");
212        assert_eq!(r, 0);
213    }
214    assert!(good, "no proven lossless media completions");
215    println!("QEMU_PCM_PASS");
216    Ok(())
217}
Source

pub fn reconfigure_stream_candidates( &self, current: &DacStream, requests: &[StreamRequest], listener: Arc<dyn DacListener>, drain_timeout: Duration, ) -> Result<StreamReconfiguration>

Replace once using a bounded list of equivalent-rate lossless widening candidates. Continue only after a certified clean refusal. A terminal failure requires explicit close; exhaustion restores the previous request once.

Source

pub fn open_duplex( &self, format: &StreamFormat, capture: &CaptureRequest, capacity_frames: usize, listener: Arc<dyn DacListener>, ) -> Result<(DacStream, DacCaptureStream)>

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.

Source

pub fn volume(&self) -> Option<VolumeControl>

The hardware volume control, if the DAC has a writable one.

Source

pub fn set_listener(&self, listener: Option<Arc<dyn DacListener>>)

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.

Source

pub fn close(self) -> Result<()>

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.

Examples found in repository?
examples/guide_player.rs (line 392)
381pub fn shutdown(player: Player<DacStream>, dac: Dac, device_lost: bool) -> Result<()> {
382    let stream = player.stop(); // joins the writer thread
383    let stream_result = match Arc::try_unwrap(stream) {
384        Ok(stream) => stream.close(),
385        Err(_) => Err(Error::InvalidState(
386            "the stream is still shared".to_string(),
387        )),
388    };
389    let dac_result = if device_lost {
390        dac.close_with(CloseVolume::Forget)
391    } else {
392        dac.close()
393    };
394    if matches!(dac_result, Err(Error::Transfer(_))) {
395        // The output thread did not stop in time. Keep every claim and the descriptor until it has.
396        while !Dac::await_usb_retirement(Duration::from_secs(1)) {}
397    }
398    stream_result.and(dac_result)
399}
More examples
Hide additional examples
examples/two_dac_smoke.rs (line 136)
121    pub fn run() -> Result<(), Box<dyn std::error::Error>> {
122        let (first_fd, first, first_stream, first_original) = open("/dev/bus/usb/001/002")?;
123        let (second_fd, second, second_stream, second_original) = open("/dev/bus/usb/001/003")?;
124        feed(&[&first_stream, &second_stream], Duration::from_secs(2))?;
125        let a = first_stream.stats();
126        let b = second_stream.stats();
127        assert!(
128            a.played_frames > 20_000
129                && b.played_frames > 20_000
130                && a.lost_frames == 0
131                && b.lost_frames == 0
132        );
133        let second_level = volume(second_fd.as_raw_fd())?;
134        let first_retirement = first.retirement();
135        first_stream.close()?;
136        first.close()?;
137        assert!(first_retirement.wait(Duration::from_secs(2)));
138        assert_eq!(alternate(first_fd.as_raw_fd())?, 0);
139        assert_eq!(volume(first_fd.as_raw_fd())?, first_original);
140        assert_eq!(alternate(second_fd.as_raw_fd())?, 1);
141        assert_eq!(
142            volume(second_fd.as_raw_fd())?,
143            second_level,
144            "first close changed second volume"
145        );
146        feed(&[&second_stream], Duration::from_secs(1))?;
147        let after = second_stream.stats();
148        assert!(after.played_frames > b.played_frames && after.lost_frames == 0);
149        let second_retirement = second.retirement();
150        second_stream.close()?;
151        second.close()?;
152        assert!(second_retirement.wait(Duration::from_secs(2)));
153        assert_eq!(alternate(second_fd.as_raw_fd())?, 0);
154        assert_eq!(volume(second_fd.as_raw_fd())?, second_original);
155        release(&first_fd)?;
156        release(&second_fd)?;
157        println!("TWO_DACS_PASS first_frames={} second_frames={} independent volume/alt-zero/retirement/duplicate protection",a.played_frames,after.played_frames);
158        Ok(())
159    }
examples/qemu_smoke.rs (line 199)
68fn main() -> Result<(), Box<dyn std::error::Error>> {
69    log::set_logger(&LOGGER).unwrap();
70    log::set_max_level(log::LevelFilter::Info);
71    println!(
72        "SOURCE {}; QEMU null audio backend",
73        option_env!("USBDAC_PROBE_REVISION").unwrap_or("unrecorded")
74    );
75    let f = OpenOptions::new()
76        .read(true)
77        .write(true)
78        .open("/dev/bus/usb/001/002")?;
79    let fd = f.as_raw_fd();
80    for i in [0u32, 1] {
81        let r = unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &i) };
82        println!("CLAIM interface={i} result={r}");
83        if r != 0 {
84            return Err(std::io::Error::last_os_error().into());
85        }
86    }
87    assert_eq!(alt(fd), 0);
88    let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
89        .with_claimed_interfaces(vec![0u8, 1])
90        .with_device_name("/dev/bus/usb/001/002");
91    let before = volume(fd)?;
92    let dac = Dac::open(fd, info, DacConfig::default())?;
93    let capabilities = dac.capabilities()?;
94    assert_eq!(
95        capabilities.uac_version,
96        usbdac_core::UacVersion::V1,
97        "this probe proves UAC1 only"
98    );
99    println!("CAPABILITIES {capabilities:?}");
100    let exact = StreamRequest::pcm(44_100, 2, 16);
101    assert!(
102        matches!(
103            dac.negotiate(&exact),
104            Err(usbdac_core::Error::Unsupported { .. })
105        ),
106        "48 kHz-only QEMU alternate must reject 44.1 kHz exact"
107    );
108    let adaptive = StreamRequest {
109        rate_policy: usbdac_core::RatePolicy::NearestSupported,
110        ..exact
111    };
112    let fmt = dac.negotiate(&adaptive)?;
113    assert_eq!(
114        fmt.sample_rate, 48_000,
115        "adaptive QEMU setup must use the supported wire rate"
116    );
117    println!("QEMU_RATE_POLICY_PASS exact=44100-rejected adaptive=48000");
118    println!("FORMAT {fmt:?}");
119    let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
120    let mut stream = dac.open_stream(&fmt, listener.clone())?;
121    let mut data = Vec::new();
122    for i in 0..4800i32 {
123        let v = (((i % 96) - 48) * 20) as i16;
124        data.extend_from_slice(&v.to_le_bytes());
125        data.extend_from_slice(&(-v).to_le_bytes());
126    }
127    for _ in 0..3 {
128        println!("PRIME {}", stream.write(&data)?);
129    }
130    stream.play()?;
131    let start = Instant::now();
132    while start.elapsed() < Duration::from_secs(2) {
133        let n = stream.writable_bytes().min(data.len());
134        if n >= 4 {
135            stream.write(&data[..n - n % 4])?;
136        }
137        thread::sleep(Duration::from_millis(2));
138    }
139    let st = stream.stats();
140    println!("PCM_STATS {st:?}");
141    let good = st.played_frames > 20_000
142        && st.completed_transfers > 0
143        && st.lost_frames == 0
144        && st.underruns == 0
145        && st.urb_timeouts == 0
146        && st.short_packets == 0
147        && st.zero_packets == 0;
148    stream.pause()?;
149    let held_volume = volume(fd)?;
150    let replacement = dac.reconfigure_stream(
151        &stream,
152        &StreamRequest::pcm(48_000, 2, 16),
153        listener.clone(),
154        Duration::from_secs(3),
155    )?;
156    assert!(replacement.rollback_cause.is_none());
157    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
158    assert_eq!(replacement.stream.state(), usbdac_core::StreamState::Paused);
159    assert_eq!(replacement.stream.played_frames(), 0);
160    assert_eq!(
161        volume(fd)?,
162        held_volume,
163        "reconfigure changed hardware volume"
164    );
165    stream = replacement.stream;
166    println!("RECONFIGURE_SAME_OWNER_PASS rate=48000 paused=true volume=unchanged");
167    // The QEMU descriptor exposes signed16 only: this is a valid request with no matching alternate.
168    let rollback = dac.reconfigure_stream(
169        &stream,
170        &StreamRequest::pcm_float32(48_000, 2),
171        listener.clone(),
172        Duration::from_secs(3),
173    )?;
174    assert_eq!(
175        rollback.rollback_cause.as_ref().map(|e| e.code()),
176        Some("unsupported")
177    );
178    assert_eq!(stream.state(), usbdac_core::StreamState::Closed);
179    assert_eq!(rollback.stream.state(), usbdac_core::StreamState::Paused);
180    assert_eq!(
181        rollback.stream.format().request,
182        StreamRequest::pcm(48_000, 2, 16)
183    );
184    assert_eq!(volume(fd)?, held_volume, "rollback changed hardware volume");
185    stream = rollback.stream;
186    for _ in 0..3 {
187        stream.write(&data)?;
188    }
189    stream.play()?;
190    thread::sleep(Duration::from_millis(100));
191    assert!(
192        stream.played_frames() > 0,
193        "rolled-back stream did not resume real completions"
194    );
195    assert_eq!(stream.stats().lost_frames, 0);
196    println!("RECONFIGURE_ROLLBACK_PASS rate=48000 cause=unsupported resumed=true");
197    stream.pause()?;
198    stream.close()?;
199    dac.close()?;
200    assert!(Dac::await_usb_retirement(Duration::from_secs(2)));
201    println!("RETIRED true");
202    assert_eq!(alt(fd), 0);
203    let after = volume(fd)?;
204    assert_eq!(
205        after, before,
206        "original per-channel volume was not restored"
207    );
208    println!("VOLUME_RESTORED {after:?}");
209    for i in [1u32, 0] {
210        let r = unsafe { libc::ioctl(fd, 0x80045510u32 as _, &i) };
211        println!("RELEASE interface={i} result={r}");
212        assert_eq!(r, 0);
213    }
214    assert!(good, "no proven lossless media completions");
215    println!("QEMU_PCM_PASS");
216    Ok(())
217}
examples/loopback_capture.rs (line 99)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    use std::{
6        fs::OpenOptions,
7        io::{Seek, SeekFrom, Write},
8        os::fd::AsRawFd,
9        time::{Duration, Instant},
10    };
11    use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12    let args: Vec<String> = std::env::args().collect();
13    if args.len() != 5 {
14        return Err(
15            "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16                .into(),
17        );
18    }
19    let rate: u32 = args[3].parse()?;
20    let seconds: u64 = args[4].parse()?;
21    if rate == 0 || !(1..=120).contains(&seconds) {
22        return Err("invalid capture duration/rate".into());
23    }
24    let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25    let fd = file.as_raw_fd();
26    // GET_DESCRIPTOR device: identity comes from the actual USB device.
27    #[repr(C)]
28    struct Control {
29        kind: u8,
30        request: u8,
31        value: u16,
32        index: u16,
33        length: u16,
34        timeout: u32,
35        data: *mut u8,
36    }
37    let mut descriptor = [0u8; 18];
38    let mut control = Control {
39        kind: 0x80,
40        request: 6,
41        value: 0x0100,
42        index: 0,
43        length: 18,
44        timeout: 1000,
45        data: descriptor.as_mut_ptr(),
46    };
47    if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48        return Err(std::io::Error::last_os_error().into());
49    }
50    let mut info = DeviceInfo::new(
51        u16::from_le_bytes([descriptor[8], descriptor[9]]),
52        u16::from_le_bytes([descriptor[10], descriptor[11]]),
53        "Independent loopback input",
54    )
55    .with_device_name(&args[1]);
56    let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57    let mut claims = control_interfaces;
58    claims.extend(input_interfaces);
59    claims.sort_unstable();
60    claims.dedup();
61    for &interface in &claims {
62        let interface = u32::from(interface);
63        if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64            return Err(std::io::Error::last_os_error().into());
65        }
66    }
67    info.configuration_id = Some(configuration);
68    info.claimed_interfaces = claims.clone();
69    let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70    let capture = dac.open_capture(
71        &CaptureRequest {
72            sample_rate: rate,
73            channels: 2,
74            valid_bits: 16,
75            channel_map: None,
76        },
77        rate as usize,
78    )?;
79    if capture.format().subslot_bytes() != 2 {
80        return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81    }
82    let mut output = OpenOptions::new()
83        .create_new(true)
84        .write(true)
85        .open(&args[2])?;
86    output.write_all(&[0u8; 44])?;
87    let mut buffer = [0u8; 8192];
88    let mut bytes = 0u32;
89    let started = Instant::now();
90    while started.elapsed() < Duration::from_secs(seconds) {
91        let frames = capture.read(&mut buffer)?;
92        let count = frames * capture.format().bytes_per_frame();
93        output.write_all(&buffer[..count])?;
94        bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95        std::thread::sleep(Duration::from_millis(2));
96    }
97    let stats = capture.stats();
98    capture.close()?;
99    dac.close()?;
100    if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101        return Err("capture did not retire; retain host claims".into());
102    }
103    for &interface in claims.iter().rev() {
104        let interface = u32::from(interface);
105        if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106            return Err(std::io::Error::last_os_error().into());
107        }
108    }
109    let mut header = Vec::with_capacity(44);
110    header.extend_from_slice(b"RIFF");
111    header.extend_from_slice(&(36 + bytes).to_le_bytes());
112    header.extend_from_slice(b"WAVEfmt ");
113    header.extend_from_slice(&16u32.to_le_bytes());
114    header.extend_from_slice(&1u16.to_le_bytes());
115    header.extend_from_slice(&2u16.to_le_bytes());
116    header.extend_from_slice(&rate.to_le_bytes());
117    header.extend_from_slice(&(rate * 4).to_le_bytes());
118    header.extend_from_slice(&4u16.to_le_bytes());
119    header.extend_from_slice(&16u16.to_le_bytes());
120    header.extend_from_slice(b"data");
121    header.extend_from_slice(&bytes.to_le_bytes());
122    output.seek(SeekFrom::Start(0))?;
123    output.write_all(&header)?;
124    output.flush()?;
125    let valid = bytes > 0
126        && stats.failed_transfers == 0
127        && stats.failed_packets == 0
128        && stats.missing_frames == 0
129        && stats.overrun_frames == 0
130        && stats.contention_frames == 0;
131    let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132    std::fs::write(
133        format!("{}.json", args[2]),
134        serde_json::to_vec_pretty(&metadata)?,
135    )?;
136    if !valid {
137        return Err(
138            "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139                .into(),
140        );
141    }
142    println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143    Ok(())
144}
Source

pub fn close_with(self, volume: CloseVolume) -> Result<()>

Like 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.

Examples found in repository?
examples/guide_player.rs (line 390)
381pub fn shutdown(player: Player<DacStream>, dac: Dac, device_lost: bool) -> Result<()> {
382    let stream = player.stop(); // joins the writer thread
383    let stream_result = match Arc::try_unwrap(stream) {
384        Ok(stream) => stream.close(),
385        Err(_) => Err(Error::InvalidState(
386            "the stream is still shared".to_string(),
387        )),
388    };
389    let dac_result = if device_lost {
390        dac.close_with(CloseVolume::Forget)
391    } else {
392        dac.close()
393    };
394    if matches!(dac_result, Err(Error::Transfer(_))) {
395        // The output thread did not stop in time. Keep every claim and the descriptor until it has.
396        while !Dac::await_usb_retirement(Duration::from_secs(1)) {}
397    }
398    stream_result.and(dac_result)
399}
Source

pub fn set_dsd_overrides( &self, big_endian: Option<bool>, subslot: Option<u8>, ) -> Result<()>

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 reflects a new subslot size after the next negotiate. subslot must be 1, 2 or 4.

Trait Implementations§

Source§

impl Debug for Dac

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Dac

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl PlaybackDevice for Dac

Auto Trait Implementations§

§

impl !RefUnwindSafe for Dac

§

impl !UnwindSafe for Dac

§

impl Forget for Dac

§

impl Freeze for Dac

§

impl Move for Dac

§

impl Send for Dac

§

impl Sync for Dac

§

impl Unpin for Dac

§

impl UnsafeUnpin for Dac

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.