Skip to main content

DacStream

Struct DacStream 

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

An open output stream. Dropping it closes it.

All methods take &self, so a stream can be shared between the host’s writer thread and its control thread behind an Arc.

§Sample layout

write takes wire-layout bytes: the bytes exactly as they go into the USB packets, in whole wire frames (format.bytes_per_frame() = subslot_bytes * channels bytes, channels interleaved in the DAC’s channel order). Samples are little-endian.

  • PCM — each sample is subslot_bytes bytes, a signed two’s-complement integer, left-justified: the sign bit is the top bit of the subslot and unused low bits are zero. 16-bit audio in a 2-byte subslot is a plain i16; 24-bit audio in a 3-byte subslot is a packed i24; 24-bit audio in a 4-byte subslot is the i24 shifted left by 8 (low byte zero); 32-bit audio is an i32. With the layout the DAC advertises, the bytes written are the bytes on the wire.
  • Unsigned 8-bit PCM — one unsigned byte per sample, silence 0x80. Bytes are retained exactly.
  • IEEE float32 PCM — one little-endian binary32 bit pattern per sample. NaN payloads, signed zero, infinity and subnormals are retained without a numeric conversion. Silence is +0. For these two explicit encodings, use write; write_i32 and nonunity software gain refuse.
  • DoP — each sample is the DoP word in the same subslot layout, the 16 DSD bits in the top two bytes below the marker: for a 3-byte subslot [dsd_low, dsd_high, marker], for a 4-byte subslot [0, dsd_low, dsd_high, marker]. dsd_high holds the older 8 DSD bits (MSB first). The marker byte is ignored and overwritten: the library owns the 0x05/0xFA alternation so the phase survives pause, flush and underrun. DoP uses PCM framing even on UAC3; carrier capability does not prove that the device decodes the markers.
  • Native DSD — raw DSD bytes, MSB first (the oldest bit in bit 7), interleaved one byte per channel: [ch0, ch1, ch0, ch1, ...] in stream order. A wire frame is subslot_bytes * channels such bytes (one wire word per channel); the library groups consecutive bytes of a channel into the wire word. Standard UAC3 DSD uses 8-byte words at bit_rate / 64, D63 oldest, emitted little-endian (LE64): each channel’s eight chronological input bytes are reversed on the wire. Legacy 1-, 2- and 4-byte formats retain byte-order and bit-reversal quirks/config; those overrides do not change the standard UAC3 layout.

write_i32 takes the ring’s own sample unit instead: PCM as full-scale 32-bit left-justified i32 (the encoder keeps the top valid_bits bits), DoP as i32 words with the DSD bits in bits 23..8 (bits 31..24 are overwritten with the marker), native DSD as one DSD byte per i32 in bits 7..0.

Implementations§

Source§

impl DacStream

Source

pub fn format(&self) -> &StreamFormat

The wire format this stream runs.

Examples found in repository?
examples/pull_adapter.rs (line 105)
102    fn position_seconds(&self) -> f64 {
103        let base = lock(&self.state).base_seconds;
104        base + self.stream.played_frames() as f64
105            / f64::from(self.stream.format().counter_rate_hz())
106    }
107
108    /// The decoder is at the end of the track and the DAC has played it all.
109    fn finished(&self) -> bool {
110        lock(&self.state).ended && self.stream.is_drained()
111    }
112}
113
114impl Drop for PullAdapter {
115    fn drop(&mut self) {
116        self.stop.store(true, Ordering::Release);
117        if let Some(writer) = self.writer.take() {
118            let _ = writer.join();
119        }
120    }
121}
122
123fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
124    let frame = stream.format().bytes_per_frame();
125    // About 10 ms per render call.
126    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
127    let mut scratch = vec![0u8; chunk_frames * frame];
128    while !stop.load(Ordering::Acquire) {
129        let mut state = lock(state);
130        if state.ended {
131            drop(state);
132            thread::sleep(Duration::from_millis(10));
133            continue;
134        }
135        // Render only when the ring wants more, so the decoder is never ahead of
136        // the configured buffer depth (and a seek never has much to throw away).
137        if state.taken == state.chunk.len() {
138            if stream.writable_bytes() < scratch.len() {
139                drop(state);
140                thread::sleep(Duration::from_millis(2));
141                continue;
142            }
143            let rendered = state.source.render(&mut scratch);
144            if rendered == 0 {
145                // No more audio: let the ring play out, even a short tail.
146                if stream.drain().is_ok() {
147                    state.ended = true;
148                }
149                continue;
150            }
151            state.chunk.clear();
152            state.chunk.extend_from_slice(&scratch[..rendered]);
153            state.taken = 0;
154        }
155        match stream.write(&state.chunk[state.taken..]) {
156            Ok(0) => {
157                drop(state);
158                thread::sleep(Duration::from_millis(2));
159            }
160            Ok(taken) => state.taken += taken,
161            Err(error) => {
162                // The stream closed or failed; the listener has the details.
163                eprintln!("writer stopping: {error}");
164                return;
165            }
166        }
167    }
168}
More examples
Hide additional examples
examples/guide_player.rs (line 407)
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}
examples/qemu_smoke.rs (line 181)
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/usbip_lifecycle.rs (line 564)
520    fn reconfigure(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
521        use usbdac_core::StreamState;
522        let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
523        let initial = dac.negotiate(&StreamRequest::pcm(96_000, 2, 16))?;
524        assert_eq!(
525            (
526                initial.sample_rate,
527                initial.interface_number,
528                initial.alt_setting
529            ),
530            (96_000, 1, 1)
531        );
532        let previous = dac.open_stream(&initial, listener.clone())?;
533        let pcm = test_pcm();
534        for _ in 0..3 {
535            previous.write(&pcm)?;
536        }
537        previous.play()?;
538        let start = Instant::now();
539        while start.elapsed() < Duration::from_secs(5) && previous.played_frames() == 0 {
540            feed(&previous, &pcm)?;
541            thread::sleep(Duration::from_millis(5));
542        }
543        assert!(
544            previous.played_frames() > 0,
545            "original playback never completed"
546        );
547        out_of_band("reset")?;
548        println!("RECONFIGURE_PHASE_BEGIN from=96000 to=48000");
549        let request = StreamRequest::pcm(48_000, 2, 16);
550        let replacement = dac.reconfigure_stream_candidates(
551            &previous,
552            &[request],
553            listener,
554            Duration::from_secs(3),
555        )?;
556        println!("RECONFIGURE_PHASE_END from=96000 to=48000");
557        assert!(
558            replacement.rollback_cause.is_none(),
559            "unexpected rollback: {:?}",
560            replacement.rollback_cause
561        );
562        assert_eq!(previous.state(), StreamState::Closed);
563        assert_eq!(replacement.stream.state(), StreamState::Paused);
564        assert_eq!(replacement.stream.format().sample_rate, 48_000);
565        assert_eq!(replacement.stream.played_frames(), 0);
566        assert_eq!(alt(fd)?, 1);
567        let transitions = out_of_band("snapshot")?;
568        let alt_history = transitions
569            .split("alts=[")
570            .nth(1)
571            .ok_or("missing alternate history")?
572            .split(']')
573            .next()
574            .ok_or("missing alternate terminator")?;
575        let unlink_count: u64 = transitions
576            .split("unlinks=")
577            .nth(1)
578            .ok_or("missing unlink count")?
579            .parse()?;
580        assert!(
581            unlink_count <= 16,
582            "more than one bounded transfer set cancelled: {transitions}"
583        );
584        let mut alts: Vec<_> = alt_history.split(", ").collect();
585        alts.dedup();
586        assert_eq!(
587            alts,
588            ["0", "1"],
589            "unexpected alternate transitions: {transitions}"
590        );
591        // USB-level count of the live 96 -> 48 kHz replacement on interface 1 and
592        // clock 16. ALSA's UAC2 prepare deselects the alternate first, writes the
593        // rate, and enables the alternate last (sound/usb/endpoint.c
594        // snd_usb_endpoint_prepare:1498-1530, endpoint_set_interface:917-951).
595        // ALSA elides a SET_INTERFACE to the alternate it already holds
596        // (endpoint.c:926-927); usbdac re-asserts alt 0 at stop, before and after
597        // the read-only negotiation and before activation, which is idempotent.
598        let sequence = out_of_band("sequence")?;
599        let writes: Vec<_> = sequence
600            .strip_prefix("seq=[")
601            .and_then(|rest| rest.strip_suffix(']'))
602            .ok_or("missing write sequence")?
603            .split(", ")
604            .collect();
605        let count = |w: &str| writes.iter().filter(|x| **x == w).count();
606        assert_eq!(
607            (
608                count("alt0"),
609                count("alt1"),
610                count("rate48000"),
611                writes.len()
612            ),
613            (4, 1, 2, 7),
614            "unexpected replacement write counts: {sequence}"
615        );
616        assert_eq!(
617            writes.first(),
618            Some(&"alt0"),
619            "old alternate not deselected first: {sequence}"
620        );
621        assert_eq!(
622            writes.last(),
623            Some(&"alt1"),
624            "alternate not enabled last: {sequence}"
625        );
626        assert!(
627            !writes
628                .iter()
629                .any(|w| w.starts_with("rate") && *w != "rate48000"),
630            "a rate other than 48 kHz was written: {sequence}"
631        );
632        // Fresh post-replacement evidence: the DAC's clock reads back 48 kHz at alt 1.
633        let mut current = [0u8; 4];
634        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
635        assert_eq!(u32::from_le_bytes(current), 48_000);
636        println!(
637            "RECONFIGURE_USB_WRITES {sequence} clock_readback=48000 alt={}",
638            alt(fd)?
639        );
640        let stream = replacement.stream;
641        for _ in 0..3 {
642            stream.write(&pcm)?;
643        }
644        stream.play()?;
645        let start = Instant::now();
646        while start.elapsed() < Duration::from_secs(5)
647            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
648        {
649            feed(&stream, &pcm)?;
650            thread::sleep(Duration::from_millis(5));
651        }
652        assert!(
653            stream.played_frames() > 0 && stream.stats().completed_transfers > 0,
654            "replacement playback never completed"
655        );
656        let stats = stream.stats();
657        assert!(stats.played_frames <= stats.frames_written);
658        assert!(stats.queued_frames <= stats.frames_written);
659        assert!(
660            stats.underruns <= 50,
661            "USB/IP replacement exceeded 50 underruns: {stats:?}"
662        );
663        let mut current = [0u8; 4];
664        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
665        assert_eq!(
666            u32::from_le_bytes(current),
667            48_000,
668            "clock drifted during replacement playback"
669        );
670        let fixture_stats = out_of_band("snapshot")?;
671        assert!(
672            !fixture_stats.contains("out_completions=0"),
673            "replacement has no completed OUT URB: {fixture_stats}"
674        );
675        println!(
676            "RECONFIGURE_PLAYBACK_PASS stats={stats:?} underrun_limit=50 fixture={fixture_stats}"
677        );
678        stream.close()?;
679        let retirement = dac.retirement();
680        dac.close()?;
681        assert!(retirement.wait(Duration::from_secs(3)));
682        assert_eq!(alt(fd)?, 0);
683        for interface in [1, 0] {
684            claim(fd, interface, false)?;
685        }
686        println!("USBIP_LIFECYCLE_PASS mode=reconfigure retired=true alt=0");
687        Ok(())
688    }
Source

pub fn write(&self, data: &[u8]) -> Result<usize>

Appends wire-layout bytes (see the type-level documentation). Never blocks. Returns the number of bytes taken: a whole number of wire frames, as many as fit in the ring; a partial or zero count means the ring is full, so retry with the remainder later. Input shorter than one wire frame is not taken.

Error::InvalidState after drain (until flush), or once the stream has closed or failed.

Examples found in repository?
examples/two_dac_smoke.rs (line 98)
89    fn feed(streams: &[&DacStream], duration: Duration) -> Result<(), Error> {
90        let mut audio = Vec::new();
91        for sample in 0..4800i16 {
92            let value = (sample % 96 - 48) * 20;
93            audio.extend_from_slice(&value.to_le_bytes());
94            audio.extend_from_slice(&(-value).to_le_bytes());
95        }
96        for stream in streams {
97            for _ in 0..3 {
98                stream.write(&audio)?;
99            }
100        }
101        let start = Instant::now();
102        while start.elapsed() < duration {
103            for stream in streams {
104                let bytes = stream.writable_bytes().min(audio.len()) / 4 * 4;
105                if bytes > 0 {
106                    stream.write(&audio[..bytes])?;
107                }
108            }
109            std::thread::sleep(Duration::from_millis(2));
110        }
111        Ok(())
112    }
More examples
Hide additional examples
examples/pull_adapter.rs (line 155)
123fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
124    let frame = stream.format().bytes_per_frame();
125    // About 10 ms per render call.
126    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
127    let mut scratch = vec![0u8; chunk_frames * frame];
128    while !stop.load(Ordering::Acquire) {
129        let mut state = lock(state);
130        if state.ended {
131            drop(state);
132            thread::sleep(Duration::from_millis(10));
133            continue;
134        }
135        // Render only when the ring wants more, so the decoder is never ahead of
136        // the configured buffer depth (and a seek never has much to throw away).
137        if state.taken == state.chunk.len() {
138            if stream.writable_bytes() < scratch.len() {
139                drop(state);
140                thread::sleep(Duration::from_millis(2));
141                continue;
142            }
143            let rendered = state.source.render(&mut scratch);
144            if rendered == 0 {
145                // No more audio: let the ring play out, even a short tail.
146                if stream.drain().is_ok() {
147                    state.ended = true;
148                }
149                continue;
150            }
151            state.chunk.clear();
152            state.chunk.extend_from_slice(&scratch[..rendered]);
153            state.taken = 0;
154        }
155        match stream.write(&state.chunk[state.taken..]) {
156            Ok(0) => {
157                drop(state);
158                thread::sleep(Duration::from_millis(2));
159            }
160            Ok(taken) => state.taken += taken,
161            Err(error) => {
162                // The stream closed or failed; the listener has the details.
163                eprintln!("writer stopping: {error}");
164                return;
165            }
166        }
167    }
168}
examples/usbip_lifecycle.rs (line 123)
79    fn badd(
80        dac: &Dac,
81        fd: i32,
82        caps: &usbdac_core::Capabilities,
83    ) -> Result<(), Box<dyn std::error::Error>> {
84        assert_eq!(caps.uac_version, UacVersion::V3);
85        assert_eq!(caps.link_speed, LinkSpeed::High);
86        assert_eq!(caps.pcm_sample_rates, [48_000]);
87        assert!(matches!(
88            dac.negotiate(&StreamRequest::pcm(96_000, 2, 16)),
89            Err(Error::Unsupported { .. })
90        ));
91        let format = dac.negotiate(
92            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
93        )?;
94        assert_eq!(
95            (
96                format.sample_rate,
97                format.channels,
98                format.valid_bits,
99                format.subslot_bytes,
100                format.interface_number,
101                format.alt_setting,
102                format.endpoint_address
103            ),
104            (48_000, 2, 16, 2, 1, 1, 1)
105        );
106        assert!(
107            format.explicit_feedback,
108            "BADD profile must expose feedback"
109        );
110        println!("BADD_FORMAT {format:?}");
111        let stream = dac.open_stream(
112            &format,
113            Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}")),
114        )?;
115        assert_eq!(alt(fd)?, 1);
116        let mut pcm = Vec::with_capacity(4800 * 4);
117        for i in 0..4800i32 {
118            let v = (((i % 96) - 48) * 20) as i16;
119            pcm.extend_from_slice(&v.to_le_bytes());
120            pcm.extend_from_slice(&(-v).to_le_bytes());
121        }
122        for _ in 0..3 {
123            stream.write(&pcm)?;
124        }
125        stream.play()?;
126        let start = Instant::now();
127        while start.elapsed() < Duration::from_secs(3)
128            && (stream.played_frames() == 0
129                || stream.stats().completed_transfers == 0
130                || stream.stats().feedback_reports == 0)
131        {
132            let n = stream.writable_bytes().min(pcm.len());
133            if n >= 4 {
134                stream.write(&pcm[..n - n % 4])?;
135            }
136            thread::sleep(Duration::from_millis(2));
137        }
138        let stats = stream.stats();
139        println!("BADD_PCM_STATS {stats:?}");
140        assert!(
141            stats.played_frames > 0 && stats.completed_transfers > 0 && stats.feedback_reports > 0,
142            "BADD playback or feedback has no real completions"
143        );
144        stream.close()?;
145        Ok(())
146    }
147
148    fn full_uac3(
149        dac: Dac,
150        fd: i32,
151        caps: &usbdac_core::Capabilities,
152        volatile: bool,
153    ) -> Result<(), Box<dyn std::error::Error>> {
154        use usbdac_core::routing::{
155            ControlKey, Entity, RouteEdit, RouteValue, RoutingHandBackOutcome,
156        };
157        assert_eq!(caps.uac_version, UacVersion::V3);
158        assert_eq!(caps.link_speed, LinkSpeed::High);
159        let key = ControlKey::Selector(Entity {
160            interface: 0,
161            id: 8,
162        });
163        assert_eq!(power(fd)?, 2, "initial power must be D2");
164        let snapshot = dac.routing_discover_powered()?;
165        println!("UAC3_ROUTING snapshot={snapshot:?}");
166        assert_eq!(snapshot.configuration(), 3);
167        assert_eq!(power(fd)?, 2, "discovery must restore D2");
168        assert_eq!(
169            dac.routing_read_powered(&snapshot, key)?,
170            RouteValue::SelectorPin(1)
171        );
172        assert_eq!(power(fd)?, 2, "read must restore D2");
173        let report = dac.routing_apply_powered(
174            &snapshot,
175            &[RouteEdit {
176                key,
177                expected: RouteValue::SelectorPin(1),
178                value: RouteValue::SelectorPin(2),
179            }],
180        )?;
181        assert_eq!(report.changed, vec![key]);
182        let applied = out_of_band("snapshot")?;
183        assert!(
184            applied.contains("selector=[2]"),
185            "fixture selector was not written: {applied}"
186        );
187        assert!(
188            applied.contains(if volatile {
189                "selector_state=1"
190            } else {
191                "selector_state=2"
192            }),
193            "unexpected fixture selector after D2: {applied}"
194        );
195        assert_eq!(power(fd)?, 2, "apply must restore D2");
196        let updated = dac.routing_discover_powered()?;
197        assert_eq!(
198            dac.routing_read_powered(&updated, key)?,
199            RouteValue::SelectorPin(if volatile { 1 } else { 2 }),
200            "selector readback must reflect the fixture's D2 behavior"
201        );
202        assert_eq!(power(fd)?, 2);
203        dac.close()?;
204        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
205        let hand_back = snapshot
206            .hand_back_report()
207            .ok_or("missing routing hand-back report")?;
208        println!("UAC3_HAND_BACK {hand_back:?}");
209        if !volatile {
210            assert!(
211                hand_back
212                    .controls
213                    .contains(&(key, RoutingHandBackOutcome::Restored)),
214                "selector hand-back was not verified"
215            );
216        }
217        assert_eq!(power(fd)?, 2, "final power must be D2");
218        assert!(
219            out_of_band("snapshot")?.contains("selector_state=1"),
220            "fixture selector was not restored"
221        );
222        assert_eq!(alt(fd)?, 0);
223        for interface in [1, 0] {
224            claim(fd, interface, false)?;
225        }
226        println!("USBIP_LIFECYCLE_PASS mode=full-uac3 selector=restored power=D2 retired=true");
227        Ok(())
228    }
229
230    // Full UAC3 whose clock RANGE lists only 48 kHz behind a powered route that
231    // cannot certify a live refusal. The cached model excludes 44.1 kHz, so the
232    // ranked loop and the playback candidates must skip it without any USB request,
233    // as ALSA never offers a rate absent from its format table (pcm.c hw_rule_rate).
234    fn full_uac3_nearest(
235        dac: Dac,
236        fd: i32,
237        caps: &usbdac_core::Capabilities,
238    ) -> Result<(), Box<dyn std::error::Error>> {
239        use usbdac_core::playback::PlaybackPolicy;
240        assert_eq!(caps.uac_version, UacVersion::V3);
241        assert_eq!(caps.link_speed, LinkSpeed::High);
242        let mut rates = caps.pcm_sample_rates.clone();
243        rates.sort_unstable();
244        rates.dedup();
245        assert_eq!(rates, [48_000], "unexpected full-UAC3 fixture rates");
246        let no_44k = |snapshot: &str| -> Result<(), Box<dyn std::error::Error>> {
247            let sets = snapshot.split(';').next().ok_or("missing rate snapshot")?;
248            if sets
249                .split(|c: char| !c.is_ascii_digit())
250                .any(|v| v == "44100")
251            {
252                return Err(format!("model-excluded 44100 Hz was programmed: {snapshot}").into());
253            }
254            Ok(())
255        };
256        out_of_band("reset")?;
257        let format = dac.negotiate(
258            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
259        )?;
260        assert_eq!(
261            (format.sample_rate, format.channels, format.valid_bits),
262            (48_000, 2, 16)
263        );
264        let negotiated = out_of_band("snapshot")?;
265        no_44k(&negotiated)?;
266        out_of_band("reset")?;
267        let decision = dac.resolve_playback(
268            &StreamRequest::pcm(44_100, 2, 16),
269            &PlaybackPolicy::default(),
270        )?;
271        assert_eq!(decision.format.sample_rate, 48_000);
272        assert_eq!(decision.candidates[0], StreamRequest::pcm(44_100, 2, 16));
273        assert!(
274            matches!(decision.exact_refusal, Some(Error::Unsupported { .. })),
275            "the skipped exact source must report a typed refusal: {:?}",
276            decision.exact_refusal
277        );
278        let resolved = out_of_band("snapshot")?;
279        no_44k(&resolved)?;
280        println!(
281            "NEGOTIATE_CASE mode=full-uac3-nearest requested=44100 actual=48000 resolve=48000 attempted={} negotiate={negotiated} resolve_snapshot={resolved}",
282            decision.attempted_candidates
283        );
284        assert_eq!(alt(fd)?, 0);
285        dac.close()?;
286        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
287        assert_eq!(alt(fd)?, 0);
288        for interface in [1, 0] {
289            claim(fd, interface, false)?;
290        }
291        println!("USBIP_LIFECYCLE_PASS mode=full-uac3-nearest retired=true");
292        Ok(())
293    }
294
295    fn vendor(fd: i32, value: u16) -> Result<(), Box<dyn std::error::Error>> {
296        assert_eq!(control(fd, 0x40, 0x5a, value, 0, &mut [])?, 0);
297        Ok(())
298    }
299    fn vendor_status(fd: i32) -> Result<u8, Box<dyn std::error::Error>> {
300        let mut status = [0u8];
301        assert_eq!(control(fd, 0xc0, 0x5a, 0, 0, &mut status)?, 1);
302        Ok(status[0])
303    }
304    fn out_of_band(action: &str) -> Result<String, Box<dyn std::error::Error>> {
305        let port = std::env::var("USBDAC_USBIP_PORT")?;
306        let _: u16 = port.parse()?;
307        let output = std::process::Command::new("/fixture/usbip_uac")
308            .args(["--control", action, "--port", &port])
309            .output()?;
310        if !output.status.success() {
311            return Err(format!(
312                "fixture control {action} failed: {}",
313                String::from_utf8_lossy(&output.stderr)
314            )
315            .into());
316        }
317        Ok(String::from_utf8(output.stdout)?.trim().to_string())
318    }
319    fn wait_status(fd: i32, mask: u8) -> Result<u8, Box<dyn std::error::Error>> {
320        let start = Instant::now();
321        loop {
322            let status = vendor_status(fd)?;
323            if status & mask == mask {
324                return Ok(status);
325            }
326            if start.elapsed() >= Duration::from_secs(5) {
327                return Err(
328                    format!("fixture status {status:#04x} did not reach {mask:#04x}").into(),
329                );
330            }
331            thread::sleep(Duration::from_millis(10));
332        }
333    }
334    fn test_pcm() -> Vec<u8> {
335        let mut pcm = Vec::with_capacity(4800 * 4);
336        for i in 0..4800i32 {
337            let v = (((i % 96) - 48) * 20) as i16;
338            pcm.extend_from_slice(&v.to_le_bytes());
339            pcm.extend_from_slice(&(-v).to_le_bytes());
340        }
341        pcm
342    }
343    fn feed(stream: &usbdac_core::DacStream, pcm: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
344        let n = stream.writable_bytes().min(pcm.len());
345        if n >= 4 {
346            stream.write(&pcm[..n - n % 4])?;
347        }
348        Ok(())
349    }
350    fn duplex(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
351        use usbdac_core::{CaptureRequest, CaptureState};
352        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
353        let request = CaptureRequest {
354            sample_rate: 48_000,
355            channels: 2,
356            valid_bits: 16,
357            channel_map: None,
358        };
359        let (playback, capture) = dac.open_duplex(
360            &format,
361            &request,
362            48_000,
363            Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")),
364        )?;
365        assert_eq!(
366            (capture.interface_number(), capture.endpoint_address()),
367            (3, 0x82)
368        );
369        let pcm = test_pcm();
370        for _ in 0..3 {
371            playback.write(&pcm)?;
372        }
373        playback.play()?;
374        let start = Instant::now();
375        let mut received = [0u8; 4096];
376        let mut marker_frames = 0;
377        while start.elapsed() < Duration::from_secs(5) && marker_frames == 0 {
378            feed(&playback, &pcm)?;
379            let frames = capture.read(&mut received)?;
380            if frames > 0 {
381                assert!(
382                    received[..frames * 4]
383                        .chunks_exact(4)
384                        .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
385                    "unexpected capture payload"
386                );
387                marker_frames = frames;
388            }
389            thread::sleep(Duration::from_millis(5));
390        }
391        assert!(marker_frames > 0, "no actual capture marker");
392        println!("DUPLEX_CAPTURE_MARKER frames={marker_frames}");
393        out_of_band("mixed")?;
394        let mixed_start = Instant::now();
395        while mixed_start.elapsed() < Duration::from_secs(5) {
396            feed(&playback, &pcm)?;
397            let frames = capture.read(&mut received)?;
398            assert!(
399                received[..frames * 4]
400                    .chunks_exact(4)
401                    .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
402                "invalid packet leaked into capture"
403            );
404            let stats = capture.stats();
405            if stats.short_packets > 0 && stats.failed_packets > 0 && stats.malformed_packets > 0 {
406                break;
407            }
408            thread::sleep(Duration::from_millis(5));
409        }
410        let mixed_stats = capture.stats();
411        assert!(
412            mixed_stats.short_packets > 0
413                && mixed_stats.failed_packets > 0
414                && mixed_stats.malformed_packets > 0,
415            "mixed packet statuses not observed: {mixed_stats:?}"
416        );
417        println!("DUPLEX_MIXED_PACKETS {mixed_stats:?}");
418        vendor(fd, 1)?;
419        let start = Instant::now();
420        while start.elapsed() < Duration::from_secs(5) && capture.state() == CaptureState::Active {
421            feed(&playback, &pcm)?;
422            thread::sleep(Duration::from_millis(5));
423        }
424        assert_eq!(capture.state(), CaptureState::Failed);
425        assert!(
426            capture.last_error().is_some(),
427            "capture failure must preserve an error"
428        );
429        assert_ne!(
430            vendor_status(fd)? & 8,
431            0,
432            "fixture did not deliver capture fault"
433        );
434        let before = playback.played_frames();
435        let start = Instant::now();
436        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() <= before {
437            feed(&playback, &pcm)?;
438            thread::sleep(Duration::from_millis(5));
439        }
440        let after = playback.played_frames();
441        assert!(
442            after > before,
443            "playback stopped after independent capture failure"
444        );
445        println!(
446            "DUPLEX_ISOLATION_PASS before={before} after={after} error={:?}",
447            capture.last_error()
448        );
449        capture.close()?;
450        playback.close()?;
451        let retirement = dac.retirement();
452        dac.close()?;
453        assert!(retirement.wait(Duration::from_secs(3)));
454        assert_eq!(alt(fd)?, 0);
455        for interface in [3, 2, 1, 0] {
456            claim(fd, interface, false)?;
457        }
458        println!("USBIP_LIFECYCLE_PASS mode=duplex retired=true");
459        Ok(())
460    }
461    fn retire(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
462        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
463        let playback =
464            dac.open_stream(&format, Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")))?;
465        let pcm = test_pcm();
466        for _ in 0..3 {
467            playback.write(&pcm)?;
468        }
469        playback.play()?;
470        let start = Instant::now();
471        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() == 0 {
472            feed(&playback, &pcm)?;
473            thread::sleep(Duration::from_millis(5));
474        }
475        assert!(playback.played_frames() > 0, "playback never completed");
476        let token = dac.retirement();
477        vendor(fd, 1)?;
478        let status = wait_status(fd, 2)?;
479        println!("RETIRE_HELD status={status:#04x}");
480        let start = Instant::now();
481        let result = dac.close();
482        let elapsed = start.elapsed();
483        println!(
484            "RETIRE_CLOSE result={result:?} elapsed_ms={}",
485            elapsed.as_millis()
486        );
487        assert!(
488            matches!(result, Err(Error::Transfer(_))),
489            "close must report timeout: {result:?}"
490        );
491        assert!(
492            elapsed >= Duration::from_millis(2500),
493            "close returned before its actual timeout: {elapsed:?}"
494        );
495        assert!(
496            !token.wait(Duration::ZERO),
497            "owner retired while URB unlink was held"
498        );
499        let status: u8 = out_of_band("status")?.parse()?;
500        assert_eq!(
501            status & 0x14,
502            0x14,
503            "unlink must be held and AS1 active: {status:#04x}"
504        );
505        println!("RETIRE_PENDING elapsed_ms={}", elapsed.as_millis());
506        out_of_band("release")?;
507        assert!(
508            token.wait(Duration::from_secs(10)),
509            "owner did not retire after unlink release"
510        );
511        assert_eq!(alt(fd)?, 0, "retired owner did not restore alt zero");
512        drop(playback);
513        for interface in [1, 0] {
514            claim(fd, interface, false)?;
515        }
516        println!("USBIP_LIFECYCLE_PASS mode=retire retired=true alt=0");
517        Ok(())
518    }
519
520    fn reconfigure(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
521        use usbdac_core::StreamState;
522        let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
523        let initial = dac.negotiate(&StreamRequest::pcm(96_000, 2, 16))?;
524        assert_eq!(
525            (
526                initial.sample_rate,
527                initial.interface_number,
528                initial.alt_setting
529            ),
530            (96_000, 1, 1)
531        );
532        let previous = dac.open_stream(&initial, listener.clone())?;
533        let pcm = test_pcm();
534        for _ in 0..3 {
535            previous.write(&pcm)?;
536        }
537        previous.play()?;
538        let start = Instant::now();
539        while start.elapsed() < Duration::from_secs(5) && previous.played_frames() == 0 {
540            feed(&previous, &pcm)?;
541            thread::sleep(Duration::from_millis(5));
542        }
543        assert!(
544            previous.played_frames() > 0,
545            "original playback never completed"
546        );
547        out_of_band("reset")?;
548        println!("RECONFIGURE_PHASE_BEGIN from=96000 to=48000");
549        let request = StreamRequest::pcm(48_000, 2, 16);
550        let replacement = dac.reconfigure_stream_candidates(
551            &previous,
552            &[request],
553            listener,
554            Duration::from_secs(3),
555        )?;
556        println!("RECONFIGURE_PHASE_END from=96000 to=48000");
557        assert!(
558            replacement.rollback_cause.is_none(),
559            "unexpected rollback: {:?}",
560            replacement.rollback_cause
561        );
562        assert_eq!(previous.state(), StreamState::Closed);
563        assert_eq!(replacement.stream.state(), StreamState::Paused);
564        assert_eq!(replacement.stream.format().sample_rate, 48_000);
565        assert_eq!(replacement.stream.played_frames(), 0);
566        assert_eq!(alt(fd)?, 1);
567        let transitions = out_of_band("snapshot")?;
568        let alt_history = transitions
569            .split("alts=[")
570            .nth(1)
571            .ok_or("missing alternate history")?
572            .split(']')
573            .next()
574            .ok_or("missing alternate terminator")?;
575        let unlink_count: u64 = transitions
576            .split("unlinks=")
577            .nth(1)
578            .ok_or("missing unlink count")?
579            .parse()?;
580        assert!(
581            unlink_count <= 16,
582            "more than one bounded transfer set cancelled: {transitions}"
583        );
584        let mut alts: Vec<_> = alt_history.split(", ").collect();
585        alts.dedup();
586        assert_eq!(
587            alts,
588            ["0", "1"],
589            "unexpected alternate transitions: {transitions}"
590        );
591        // USB-level count of the live 96 -> 48 kHz replacement on interface 1 and
592        // clock 16. ALSA's UAC2 prepare deselects the alternate first, writes the
593        // rate, and enables the alternate last (sound/usb/endpoint.c
594        // snd_usb_endpoint_prepare:1498-1530, endpoint_set_interface:917-951).
595        // ALSA elides a SET_INTERFACE to the alternate it already holds
596        // (endpoint.c:926-927); usbdac re-asserts alt 0 at stop, before and after
597        // the read-only negotiation and before activation, which is idempotent.
598        let sequence = out_of_band("sequence")?;
599        let writes: Vec<_> = sequence
600            .strip_prefix("seq=[")
601            .and_then(|rest| rest.strip_suffix(']'))
602            .ok_or("missing write sequence")?
603            .split(", ")
604            .collect();
605        let count = |w: &str| writes.iter().filter(|x| **x == w).count();
606        assert_eq!(
607            (
608                count("alt0"),
609                count("alt1"),
610                count("rate48000"),
611                writes.len()
612            ),
613            (4, 1, 2, 7),
614            "unexpected replacement write counts: {sequence}"
615        );
616        assert_eq!(
617            writes.first(),
618            Some(&"alt0"),
619            "old alternate not deselected first: {sequence}"
620        );
621        assert_eq!(
622            writes.last(),
623            Some(&"alt1"),
624            "alternate not enabled last: {sequence}"
625        );
626        assert!(
627            !writes
628                .iter()
629                .any(|w| w.starts_with("rate") && *w != "rate48000"),
630            "a rate other than 48 kHz was written: {sequence}"
631        );
632        // Fresh post-replacement evidence: the DAC's clock reads back 48 kHz at alt 1.
633        let mut current = [0u8; 4];
634        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
635        assert_eq!(u32::from_le_bytes(current), 48_000);
636        println!(
637            "RECONFIGURE_USB_WRITES {sequence} clock_readback=48000 alt={}",
638            alt(fd)?
639        );
640        let stream = replacement.stream;
641        for _ in 0..3 {
642            stream.write(&pcm)?;
643        }
644        stream.play()?;
645        let start = Instant::now();
646        while start.elapsed() < Duration::from_secs(5)
647            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
648        {
649            feed(&stream, &pcm)?;
650            thread::sleep(Duration::from_millis(5));
651        }
652        assert!(
653            stream.played_frames() > 0 && stream.stats().completed_transfers > 0,
654            "replacement playback never completed"
655        );
656        let stats = stream.stats();
657        assert!(stats.played_frames <= stats.frames_written);
658        assert!(stats.queued_frames <= stats.frames_written);
659        assert!(
660            stats.underruns <= 50,
661            "USB/IP replacement exceeded 50 underruns: {stats:?}"
662        );
663        let mut current = [0u8; 4];
664        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
665        assert_eq!(
666            u32::from_le_bytes(current),
667            48_000,
668            "clock drifted during replacement playback"
669        );
670        let fixture_stats = out_of_band("snapshot")?;
671        assert!(
672            !fixture_stats.contains("out_completions=0"),
673            "replacement has no completed OUT URB: {fixture_stats}"
674        );
675        println!(
676            "RECONFIGURE_PLAYBACK_PASS stats={stats:?} underrun_limit=50 fixture={fixture_stats}"
677        );
678        stream.close()?;
679        let retirement = dac.retirement();
680        dac.close()?;
681        assert!(retirement.wait(Duration::from_secs(3)));
682        assert_eq!(alt(fd)?, 0);
683        for interface in [1, 0] {
684            claim(fd, interface, false)?;
685        }
686        println!("USBIP_LIFECYCLE_PASS mode=reconfigure retired=true alt=0");
687        Ok(())
688    }
689
690    /// DoP resolution through the production resolve_playback, transport and
691    /// PlaybackStream. DoP v1.1 carries 16 DSD bits per channel per carrier frame,
692    /// so a DoP carrier of another depth or channel count is a repack (H1), and an
693    /// exact DoP shape absent from the descriptors is never attempted (H2).
694    fn dop_resolution(dac: Dac, fd: i32, mode: &str) -> Result<(), Box<dyn std::error::Error>> {
695        use usbdac_core::playback::{PlaybackFidelity, PlaybackPolicy, PlaybackTransform};
696        use usbdac_core::Encoding;
697        let confirmed = PlaybackPolicy {
698            dop_confirmed: true,
699            ..PlaybackPolicy::default()
700        };
701        let caps = dac.capabilities()?;
702        assert!(
703            caps.exclusion_snapshot_complete,
704            "the fixture descriptor snapshot must be complete"
705        );
706        let source = StreamRequest::dop(2_822_400, if mode == "dop-stereo24" { 1 } else { 2 });
707        if mode == "dop-carrier32" {
708            // H2: 24-bit DoP on a 32-bit-only DAC reaches the 32-bit carrier.
709            let widened = dac.resolve_playback(&source, &confirmed)?;
710            println!(
711                "DOP_DECISION mode={mode} case=widen transform={:?} fidelity={:?} bits={} preflight={:?}",
712                widened.transform, widened.fidelity, widened.format.valid_bits, widened.source_preflight_refusal
713            );
714            assert!(widened.source_preflight_refusal.is_some());
715            assert_eq!(widened.format.encoding, Encoding::DoP);
716            assert_eq!(widened.format.valid_bits, 32);
717            assert_eq!(
718                widened.transform,
719                PlaybackTransform::DopRepack { target_channels: 2 }
720            );
721        }
722        let policy = if mode == "dop-carrier32" {
723            // H1: the review's smallest case.
724            PlaybackPolicy {
725                allowed_pcm_depths: Some(vec![32]),
726                ..confirmed.clone()
727            }
728        } else {
729            confirmed.clone()
730        };
731        out_of_band("reset")?;
732        let decision = dac.resolve_playback(&source, &policy)?;
733        println!(
734            "DOP_DECISION mode={mode} transform={:?} fidelity={:?} format={:?}/{}ch/{}bit preflight={:?} attempted={}",
735            decision.transform,
736            decision.fidelity,
737            decision.format.encoding,
738            decision.format.channels,
739            decision.format.valid_bits,
740            decision.source_preflight_refusal,
741            decision.attempted_candidates
742        );
743        if mode == "dop-no-carrier" {
744            // H2: confirmed DoP on a DAC that cannot carry it falls back like unconfirmed.
745            assert!(decision.source_preflight_refusal.is_some());
746            assert_eq!(decision.format.encoding, Encoding::Pcm);
747            assert!(matches!(
748                decision.transform,
749                PlaybackTransform::DsdToPcm {
750                    dop_input: true,
751                    ..
752                }
753            ));
754            let unconfirmed = dac.resolve_playback(&source, &PlaybackPolicy::default())?;
755            assert_eq!(unconfirmed.format, decision.format);
756        } else {
757            assert_eq!(decision.format.encoding, Encoding::DoP);
758            assert_eq!(decision.format.channels, 2);
759            assert_eq!(
760                decision.transform,
761                PlaybackTransform::DopRepack { target_channels: 2 }
762            );
763            assert_eq!(
764                decision.fidelity,
765                if source.channels == 2 {
766                    PlaybackFidelity::BitExact
767                } else {
768                    PlaybackFidelity::Lossless
769                }
770            );
771            assert_eq!(decision.attempted_candidates, 1);
772        }
773        let mut stream = dac.open_playback(&decision, Arc::new(|_| {}))?;
774        let channels = usize::from(source.channels);
775        let frame = decision.source_frame_bytes;
776        let mut next = 0usize;
777        let mut chunk = Vec::new();
778        let start = Instant::now();
779        let mut started = false;
780        while start.elapsed() < Duration::from_secs(3)
781            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
782        {
783            let frames = stream.writable_bytes() / frame;
784            if frames > 0 {
785                chunk.clear();
786                for i in next..next + frames {
787                    let marker = if i % 2 == 0 { 0x05 } else { 0xfa };
788                    for _ in 0..channels {
789                        chunk.extend_from_slice(&[0x69, 0x69, marker]);
790                    }
791                }
792                next += stream.write(&chunk)? / frame;
793            }
794            if !started && next > 0 {
795                stream.play()?;
796                started = true;
797            }
798            thread::sleep(Duration::from_millis(2));
799        }
800        let stats = stream.target_stats();
801        let snapshot = out_of_band("snapshot")?;
802        println!("DOP_STATS mode={mode} source_frames={next} {stats:?} {snapshot}");
803        assert!(
804            stats.played_frames > 0 && stats.completed_transfers > 0,
805            "no DoP-resolved completions"
806        );
807        let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
808        let carrier_set = rates
809            .split(|c: char| !c.is_ascii_digit())
810            .any(|v| v == "176400");
811        // The carrier DACs clock 176.4 kHz; the exact carrier is never set on a DAC without one.
812        assert_eq!(carrier_set, mode != "dop-no-carrier", "{snapshot}");
813        if mode != "dop-no-carrier" {
814            assert!(stats.payload_verified, "the DoP payload must audit clean");
815        }
816        stream.close()?;
817        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
818        let retirement = dac.retirement();
819        dac.close()?;
820        assert!(retirement.wait(Duration::from_secs(3)));
821        assert_eq!(alt(fd)?, 0);
822        for interface in [1, 0] {
823            claim(fd, interface, false)?;
824        }
825        println!("USBIP_LIFECYCLE_PASS mode={mode} alt=0 retired=true");
826        Ok(())
827    }
828
829    pub fn run() -> Result<(), Box<dyn std::error::Error>> {
830        let args: Vec<_> = std::env::args().collect();
831        if args.len() != 3
832            || !matches!(
833                args[2].as_str(),
834                "normal"
835                    | "bad-cur"
836                    | "stale-cur"
837                    | "badd"
838                    | "full-uac3"
839                    | "full-uac3-volatile"
840                    | "full-uac3-clock"
841                    | "full-uac3-clock-bad"
842                    | "full-uac3-clock-stale"
843                    | "duplex"
844                    | "retire"
845                    | "reconfigure"
846                    | "selector"
847                    | "refuse-set"
848                    | "zero-res"
849                    | "full-uac3-nearest"
850                    | "dop-carrier32"
851                    | "dop-stereo24"
852                    | "dop-no-carrier"
853            )
854        {
855            return Err(
856                "usage: usbip_lifecycle /dev/bus/usb/BBB/DDD normal|bad-cur|stale-cur|badd|full-uac3|full-uac3-clock|duplex|retire|reconfigure".into(),
857            );
858        }
859        let path = &args[1];
860        if !path.starts_with("/dev/bus/usb/") {
861            return Err("expected a usbfs device path".into());
862        }
863        let file = OpenOptions::new().read(true).write(true).open(path)?;
864        let fd = file.as_raw_fd();
865        // Read and validate the actual descriptor before claiming or invoking the driver.
866        let mut descriptor = [0u8; 18];
867        assert_eq!(control(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?, 18);
868        assert_eq!((descriptor[0], descriptor[1]), (18, 1));
869        assert_eq!(
870            (
871                u16::from_le_bytes([descriptor[8], descriptor[9]]),
872                u16::from_le_bytes([descriptor[10], descriptor[11]])
873            ),
874            (VID, PID),
875            "refusing a device other than the fixture"
876        );
877        // Select the explicitly advertised fixture configuration before interface claims.
878        let configuration = match args[2].as_str() {
879            "badd" => 2u32,
880            "full-uac3"
881            | "full-uac3-volatile"
882            | "full-uac3-clock"
883            | "full-uac3-clock-bad"
884            | "full-uac3-clock-stale"
885            | "full-uac3-nearest" => 3,
886            _ => 1,
887        };
888        if configuration != 1 {
889            let mut config_descriptor = [0u8; 9];
890            assert_eq!(
891                control(
892                    fd,
893                    0x80,
894                    6,
895                    0x0200 | (configuration as u16 - 1),
896                    0,
897                    &mut config_descriptor
898                )?,
899                9
900            );
901            assert_eq!(
902                (
903                    config_descriptor[0],
904                    config_descriptor[1],
905                    config_descriptor[5]
906                ),
907                (9, 2, configuration as u8)
908            );
909            if unsafe { libc::ioctl(fd, 0x80045505u32 as _, &configuration) } != 0 {
910                return Err(std::io::Error::last_os_error().into());
911            }
912        }
913        let claims = if args[2] == "duplex" {
914            vec![0u8, 1, 2, 3]
915        } else {
916            vec![0u8, 1]
917        };
918        for &interface in &claims {
919            claim(fd, u32::from(interface), true)?;
920        }
921        assert_eq!(alt(fd)?, 0);
922        if matches!(
923            args[2].as_str(),
924            "badd" | "full-uac3" | "full-uac3-volatile"
925        ) {
926            assert_eq!(power(fd)?, 0, "power domain must initially be D0");
927            let mut state = [2u8];
928            assert_eq!(control(fd, 0x21, 1, 0x0200, 0x0a00, &mut state)?, 1);
929            assert_eq!(power(fd)?, 2, "failed to seed D2 baseline");
930        }
931        let mut info = DeviceInfo::new(VID, PID, "USB/IP audio fixture")
932            .with_claimed_interfaces(claims)
933            .with_device_name(path);
934        info.configuration_id = Some(configuration as u8);
935        let config = DacConfig {
936            require_hardware_volume: false,
937            require_verified_rate: true,
938            ..DacConfig::default()
939        };
940        let dac = if args[2] == "duplex" {
941            Dac::open_duplex_device(fd, info, config)?
942        } else {
943            Dac::open(fd, info, config)?
944        };
945        if args[2] == "duplex" {
946            return duplex(dac, fd);
947        }
948        if args[2] == "retire" {
949            return retire(dac, fd);
950        }
951        if args[2] == "reconfigure" {
952            return reconfigure(dac, fd);
953        }
954        if args[2].starts_with("dop-") {
955            return dop_resolution(dac, fd, &args[2]);
956        }
957        let caps = dac.capabilities()?;
958        if args[2] == "refuse-set" {
959            out_of_band("reset")?;
960            let requests = [
961                StreamRequest::pcm(96_000, 2, 16),
962                StreamRequest::pcm(48_000, 2, 16),
963            ];
964            let failure = dac.negotiate_candidates(&requests);
965            assert!(
966                matches!(
967                    failure,
968                    Err(Error::ClockUnverified {
969                        requested_hz: 96_000,
970                        ..
971                    })
972                ),
973                "refused SET must be terminal: {failure:?}"
974            );
975            let snapshot = out_of_band("snapshot")?;
976            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
977            assert!(rates.contains("96000"));
978            assert!(
979                !rates.contains("48000"),
980                "second candidate was tried after uncertain SET: {snapshot}"
981            );
982            let retirement = dac.retirement();
983            dac.close()?;
984            assert!(retirement.wait(Duration::from_secs(3)));
985            assert_eq!(alt(fd)?, 0);
986            for interface in [1, 0] {
987                claim(fd, interface, false)?;
988            }
989            println!("USBIP_LIFECYCLE_PASS mode=refuse-set snapshot={snapshot}");
990            return Ok(());
991        }
992        if matches!(args[2].as_str(), "selector" | "zero-res") {
993            let (requested, expected) = if args[2] == "selector" {
994                (192_000, 96_000)
995            } else {
996                (96_000, 44_100)
997            };
998            out_of_band("reset")?;
999            let request =
1000                StreamRequest::pcm(requested, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1001            let format = dac.negotiate(&request)?;
1002            assert_eq!(format.sample_rate, expected);
1003            let stream = dac.open_stream(&format, Arc::new(|_| {}))?;
1004            let snapshot = out_of_band("snapshot")?;
1005            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
1006            let rejected = requested.to_string();
1007            assert!(
1008                !rates
1009                    .split(|c: char| !c.is_ascii_digit())
1010                    .any(|v| v == rejected),
1011                "requested unsupported rate was sent: {snapshot}"
1012            );
1013            println!(
1014                "NEGOTIATE_CASE mode={} requested={requested} actual={expected} {snapshot}",
1015                args[2]
1016            );
1017            stream.close()?;
1018            let retirement = dac.retirement();
1019            dac.close()?;
1020            assert!(retirement.wait(Duration::from_secs(3)));
1021            assert_eq!(alt(fd)?, 0);
1022            for interface in [1, 0] {
1023                claim(fd, interface, false)?;
1024            }
1025            println!("USBIP_LIFECYCLE_PASS mode={} retired=true", args[2]);
1026            return Ok(());
1027        }
1028        if args[2] == "badd" {
1029            badd(&dac, fd, &caps)?;
1030            assert_eq!(alt(fd)?, 0);
1031            dac.close()?;
1032            assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
1033            assert_eq!(alt(fd)?, 0);
1034            assert_eq!(power(fd)?, 2, "BADD must restore D2");
1035            let power_log = out_of_band("snapshot")?;
1036            let powers = power_log
1037                .split("power=[")
1038                .nth(1)
1039                .ok_or("missing power history")?
1040                .split(']')
1041                .next()
1042                .ok_or("missing power terminator")?;
1043            assert!(
1044                powers
1045                    .split(", ")
1046                    .collect::<Vec<_>>()
1047                    .windows(2)
1048                    .any(|pair| pair == ["0", "2"]),
1049                "expected D0 to D2 transition: {power_log}"
1050            );
1051            for interface in [1, 0] {
1052                claim(fd, interface, false)?;
1053            }
1054            println!("USBIP_LIFECYCLE_PASS mode=badd alt=0 retired=true");
1055            return Ok(());
1056        }
1057        if args[2] == "full-uac3-nearest" {
1058            return full_uac3_nearest(dac, fd, &caps);
1059        }
1060        if matches!(args[2].as_str(), "full-uac3" | "full-uac3-volatile") {
1061            return full_uac3(dac, fd, &caps, args[2] == "full-uac3-volatile");
1062        }
1063        assert_eq!(
1064            caps.uac_version,
1065            if args[2].starts_with("full-uac3-clock") {
1066                UacVersion::V3
1067            } else {
1068                UacVersion::V2
1069            }
1070        );
1071        assert_eq!(caps.link_speed, LinkSpeed::High);
1072        let mut rates = caps.pcm_sample_rates.clone();
1073        rates.sort_unstable();
1074        rates.dedup();
1075        assert_eq!(rates, [48_000, 96_000], "unexpected fixture rates");
1076        assert!(
1077            matches!(
1078                dac.negotiate(&StreamRequest::pcm(192_000, 2, 16)),
1079                Err(Error::Unsupported { .. })
1080            ),
1081            "exact 192 kHz must be refused"
1082        );
1083        let request =
1084            StreamRequest::pcm(192_000, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1085        let format = dac.negotiate(&request)?;
1086        assert_eq!(
1087            (
1088                format.sample_rate,
1089                format.channels,
1090                format.valid_bits,
1091                format.subslot_bytes,
1092                format.interface_number,
1093                format.alt_setting
1094            ),
1095            (96_000, 2, 16, 2, 1, 1)
1096        );
1097        assert_eq!(format.sync_type, SyncKind::Synchronous);
1098        assert_eq!(format.endpoint_address, 0x01);
1099        assert_eq!(format.link_speed, LinkSpeed::High);
1100        assert_eq!(format.bytes_per_frame(), 4);
1101        if args[2].starts_with("full-uac3-clock") {
1102            assert_eq!(format.service_interval_us, 125);
1103            assert!(!format.explicit_feedback);
1104        }
1105        let clock = format
1106            .clock
1107            .as_ref()
1108            .ok_or("fixture clock missing")?
1109            .clone();
1110        assert_eq!(
1111            (clock.control_interface, clock.source_id),
1112            (
1113                0,
1114                if args[2].starts_with("full-uac3-clock") {
1115                    9
1116                } else {
1117                    0x10
1118                }
1119            )
1120        );
1121        println!("NEGOTIATED exact192=unsupported nearest192=96000 format={format:?}");
1122        let listener = Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}"));
1123        match args[2].as_str() {
1124            "normal" | "full-uac3-clock" => {
1125                let stream = dac.open_stream(&format, listener)?;
1126                assert_eq!(alt(fd)?, 1);
1127                let mut current = [0u8; 4];
1128                assert_eq!(
1129                    control(
1130                        fd,
1131                        0xa1,
1132                        1,
1133                        0x0100,
1134                        (u16::from(clock.source_id) << 8) | u16::from(clock.control_interface),
1135                        &mut current
1136                    )?,
1137                    4
1138                );
1139                assert_eq!(
1140                    u32::from_le_bytes(current),
1141                    96_000,
1142                    "post-alt clock readback"
1143                );
1144                let mut pcm = Vec::with_capacity(9600 * 4);
1145                for i in 0..9600i32 {
1146                    let v = (((i % 96) - 48) * 20) as i16;
1147                    pcm.extend_from_slice(&v.to_le_bytes());
1148                    pcm.extend_from_slice(&(-v).to_le_bytes());
1149                }
1150                for _ in 0..3 {
1151                    stream.write(&pcm)?;
1152                }
1153                stream.play()?;
1154                let start = Instant::now();
1155                while start.elapsed() < Duration::from_secs(3)
1156                    && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
1157                {
1158                    let n = stream.writable_bytes().min(pcm.len());
1159                    if n >= 4 {
1160                        stream.write(&pcm[..n - n % 4])?;
1161                    }
1162                    thread::sleep(Duration::from_millis(2));
1163                }
1164                let stats = stream.stats();
1165                println!("PCM_STATS {stats:?}");
1166                assert!(
1167                    stats.played_frames > 0 && stats.completed_transfers > 0,
1168                    "no actual PCM completions"
1169                );
1170                stream.close()?;
1171            }
1172            mode => match dac.open_stream(&format, listener) {
1173                Err(error @ Error::ClockUnverified { .. }) => {
1174                    let expected_reported = if mode == "bad-cur" || mode == "full-uac3-clock-bad" {
1175                        None
1176                    } else {
1177                        Some(48_000)
1178                    };
1179                    assert!(
1180                        matches!(error, Error::ClockUnverified { requested_hz: 96_000, reported_hz } if reported_hz == expected_reported)
1181                    );
1182                    println!(
1183                        "EXPECTED_FAILURE mode={mode} code={} error={error:?}",
1184                        error.code()
1185                    );
1186                }
1187                Err(error) => {
1188                    return Err(format!("unexpected failure for {mode}: {error:?}").into())
1189                }
1190                Ok(stream) => {
1191                    stream.close()?;
1192                    return Err(format!("{mode} incorrectly admitted the stream").into());
1193                }
1194            },
1195        }
1196        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
1197        dac.close()?;
1198        assert!(
1199            Dac::await_usb_retirement(Duration::from_secs(3)),
1200            "USB retirement timed out"
1201        );
1202        assert_eq!(alt(fd)?, 0);
1203        for interface in [1, 0] {
1204            claim(fd, interface, false)?;
1205        }
1206        println!("USBIP_LIFECYCLE_PASS mode={} alt=0 retired=true", args[2]);
1207        Ok(())
1208    }
examples/qemu_smoke.rs (line 128)
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 write_i32(&self, samples: &[i32]) -> Result<usize>

Like write for the ring’s native i32 samples. Counts and returns samples (a whole number of wire frames: multiples of channels, or of subslot_bytes * channels for native DSD).

Examples found in repository?
examples/guide_player.rs (line 83)
82    fn write_i32(&self, samples: &[i32]) -> Result<usize> {
83        DacStream::write_i32(self, samples)
84    }
Source

pub fn writable_bytes(&self) -> usize

How many bytes the host should write now to bring the ring to its target depth (DacConfig::buffer_target_ms, or the shallower processing_buffer_target_ms while software gain is on). A whole number of wire frames. write still accepts more, up to the ring’s capacity.

Examples found in repository?
examples/guide_player.rs (line 80)
79    fn writable_bytes(&self) -> usize {
80        DacStream::writable_bytes(self)
81    }
More examples
Hide additional examples
examples/two_dac_smoke.rs (line 104)
89    fn feed(streams: &[&DacStream], duration: Duration) -> Result<(), Error> {
90        let mut audio = Vec::new();
91        for sample in 0..4800i16 {
92            let value = (sample % 96 - 48) * 20;
93            audio.extend_from_slice(&value.to_le_bytes());
94            audio.extend_from_slice(&(-value).to_le_bytes());
95        }
96        for stream in streams {
97            for _ in 0..3 {
98                stream.write(&audio)?;
99            }
100        }
101        let start = Instant::now();
102        while start.elapsed() < duration {
103            for stream in streams {
104                let bytes = stream.writable_bytes().min(audio.len()) / 4 * 4;
105                if bytes > 0 {
106                    stream.write(&audio[..bytes])?;
107                }
108            }
109            std::thread::sleep(Duration::from_millis(2));
110        }
111        Ok(())
112    }
examples/pull_adapter.rs (line 138)
123fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
124    let frame = stream.format().bytes_per_frame();
125    // About 10 ms per render call.
126    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
127    let mut scratch = vec![0u8; chunk_frames * frame];
128    while !stop.load(Ordering::Acquire) {
129        let mut state = lock(state);
130        if state.ended {
131            drop(state);
132            thread::sleep(Duration::from_millis(10));
133            continue;
134        }
135        // Render only when the ring wants more, so the decoder is never ahead of
136        // the configured buffer depth (and a seek never has much to throw away).
137        if state.taken == state.chunk.len() {
138            if stream.writable_bytes() < scratch.len() {
139                drop(state);
140                thread::sleep(Duration::from_millis(2));
141                continue;
142            }
143            let rendered = state.source.render(&mut scratch);
144            if rendered == 0 {
145                // No more audio: let the ring play out, even a short tail.
146                if stream.drain().is_ok() {
147                    state.ended = true;
148                }
149                continue;
150            }
151            state.chunk.clear();
152            state.chunk.extend_from_slice(&scratch[..rendered]);
153            state.taken = 0;
154        }
155        match stream.write(&state.chunk[state.taken..]) {
156            Ok(0) => {
157                drop(state);
158                thread::sleep(Duration::from_millis(2));
159            }
160            Ok(taken) => state.taken += taken,
161            Err(error) => {
162                // The stream closed or failed; the listener has the details.
163                eprintln!("writer stopping: {error}");
164                return;
165            }
166        }
167    }
168}
examples/usbip_lifecycle.rs (line 132)
79    fn badd(
80        dac: &Dac,
81        fd: i32,
82        caps: &usbdac_core::Capabilities,
83    ) -> Result<(), Box<dyn std::error::Error>> {
84        assert_eq!(caps.uac_version, UacVersion::V3);
85        assert_eq!(caps.link_speed, LinkSpeed::High);
86        assert_eq!(caps.pcm_sample_rates, [48_000]);
87        assert!(matches!(
88            dac.negotiate(&StreamRequest::pcm(96_000, 2, 16)),
89            Err(Error::Unsupported { .. })
90        ));
91        let format = dac.negotiate(
92            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
93        )?;
94        assert_eq!(
95            (
96                format.sample_rate,
97                format.channels,
98                format.valid_bits,
99                format.subslot_bytes,
100                format.interface_number,
101                format.alt_setting,
102                format.endpoint_address
103            ),
104            (48_000, 2, 16, 2, 1, 1, 1)
105        );
106        assert!(
107            format.explicit_feedback,
108            "BADD profile must expose feedback"
109        );
110        println!("BADD_FORMAT {format:?}");
111        let stream = dac.open_stream(
112            &format,
113            Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}")),
114        )?;
115        assert_eq!(alt(fd)?, 1);
116        let mut pcm = Vec::with_capacity(4800 * 4);
117        for i in 0..4800i32 {
118            let v = (((i % 96) - 48) * 20) as i16;
119            pcm.extend_from_slice(&v.to_le_bytes());
120            pcm.extend_from_slice(&(-v).to_le_bytes());
121        }
122        for _ in 0..3 {
123            stream.write(&pcm)?;
124        }
125        stream.play()?;
126        let start = Instant::now();
127        while start.elapsed() < Duration::from_secs(3)
128            && (stream.played_frames() == 0
129                || stream.stats().completed_transfers == 0
130                || stream.stats().feedback_reports == 0)
131        {
132            let n = stream.writable_bytes().min(pcm.len());
133            if n >= 4 {
134                stream.write(&pcm[..n - n % 4])?;
135            }
136            thread::sleep(Duration::from_millis(2));
137        }
138        let stats = stream.stats();
139        println!("BADD_PCM_STATS {stats:?}");
140        assert!(
141            stats.played_frames > 0 && stats.completed_transfers > 0 && stats.feedback_reports > 0,
142            "BADD playback or feedback has no real completions"
143        );
144        stream.close()?;
145        Ok(())
146    }
147
148    fn full_uac3(
149        dac: Dac,
150        fd: i32,
151        caps: &usbdac_core::Capabilities,
152        volatile: bool,
153    ) -> Result<(), Box<dyn std::error::Error>> {
154        use usbdac_core::routing::{
155            ControlKey, Entity, RouteEdit, RouteValue, RoutingHandBackOutcome,
156        };
157        assert_eq!(caps.uac_version, UacVersion::V3);
158        assert_eq!(caps.link_speed, LinkSpeed::High);
159        let key = ControlKey::Selector(Entity {
160            interface: 0,
161            id: 8,
162        });
163        assert_eq!(power(fd)?, 2, "initial power must be D2");
164        let snapshot = dac.routing_discover_powered()?;
165        println!("UAC3_ROUTING snapshot={snapshot:?}");
166        assert_eq!(snapshot.configuration(), 3);
167        assert_eq!(power(fd)?, 2, "discovery must restore D2");
168        assert_eq!(
169            dac.routing_read_powered(&snapshot, key)?,
170            RouteValue::SelectorPin(1)
171        );
172        assert_eq!(power(fd)?, 2, "read must restore D2");
173        let report = dac.routing_apply_powered(
174            &snapshot,
175            &[RouteEdit {
176                key,
177                expected: RouteValue::SelectorPin(1),
178                value: RouteValue::SelectorPin(2),
179            }],
180        )?;
181        assert_eq!(report.changed, vec![key]);
182        let applied = out_of_band("snapshot")?;
183        assert!(
184            applied.contains("selector=[2]"),
185            "fixture selector was not written: {applied}"
186        );
187        assert!(
188            applied.contains(if volatile {
189                "selector_state=1"
190            } else {
191                "selector_state=2"
192            }),
193            "unexpected fixture selector after D2: {applied}"
194        );
195        assert_eq!(power(fd)?, 2, "apply must restore D2");
196        let updated = dac.routing_discover_powered()?;
197        assert_eq!(
198            dac.routing_read_powered(&updated, key)?,
199            RouteValue::SelectorPin(if volatile { 1 } else { 2 }),
200            "selector readback must reflect the fixture's D2 behavior"
201        );
202        assert_eq!(power(fd)?, 2);
203        dac.close()?;
204        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
205        let hand_back = snapshot
206            .hand_back_report()
207            .ok_or("missing routing hand-back report")?;
208        println!("UAC3_HAND_BACK {hand_back:?}");
209        if !volatile {
210            assert!(
211                hand_back
212                    .controls
213                    .contains(&(key, RoutingHandBackOutcome::Restored)),
214                "selector hand-back was not verified"
215            );
216        }
217        assert_eq!(power(fd)?, 2, "final power must be D2");
218        assert!(
219            out_of_band("snapshot")?.contains("selector_state=1"),
220            "fixture selector was not restored"
221        );
222        assert_eq!(alt(fd)?, 0);
223        for interface in [1, 0] {
224            claim(fd, interface, false)?;
225        }
226        println!("USBIP_LIFECYCLE_PASS mode=full-uac3 selector=restored power=D2 retired=true");
227        Ok(())
228    }
229
230    // Full UAC3 whose clock RANGE lists only 48 kHz behind a powered route that
231    // cannot certify a live refusal. The cached model excludes 44.1 kHz, so the
232    // ranked loop and the playback candidates must skip it without any USB request,
233    // as ALSA never offers a rate absent from its format table (pcm.c hw_rule_rate).
234    fn full_uac3_nearest(
235        dac: Dac,
236        fd: i32,
237        caps: &usbdac_core::Capabilities,
238    ) -> Result<(), Box<dyn std::error::Error>> {
239        use usbdac_core::playback::PlaybackPolicy;
240        assert_eq!(caps.uac_version, UacVersion::V3);
241        assert_eq!(caps.link_speed, LinkSpeed::High);
242        let mut rates = caps.pcm_sample_rates.clone();
243        rates.sort_unstable();
244        rates.dedup();
245        assert_eq!(rates, [48_000], "unexpected full-UAC3 fixture rates");
246        let no_44k = |snapshot: &str| -> Result<(), Box<dyn std::error::Error>> {
247            let sets = snapshot.split(';').next().ok_or("missing rate snapshot")?;
248            if sets
249                .split(|c: char| !c.is_ascii_digit())
250                .any(|v| v == "44100")
251            {
252                return Err(format!("model-excluded 44100 Hz was programmed: {snapshot}").into());
253            }
254            Ok(())
255        };
256        out_of_band("reset")?;
257        let format = dac.negotiate(
258            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
259        )?;
260        assert_eq!(
261            (format.sample_rate, format.channels, format.valid_bits),
262            (48_000, 2, 16)
263        );
264        let negotiated = out_of_band("snapshot")?;
265        no_44k(&negotiated)?;
266        out_of_band("reset")?;
267        let decision = dac.resolve_playback(
268            &StreamRequest::pcm(44_100, 2, 16),
269            &PlaybackPolicy::default(),
270        )?;
271        assert_eq!(decision.format.sample_rate, 48_000);
272        assert_eq!(decision.candidates[0], StreamRequest::pcm(44_100, 2, 16));
273        assert!(
274            matches!(decision.exact_refusal, Some(Error::Unsupported { .. })),
275            "the skipped exact source must report a typed refusal: {:?}",
276            decision.exact_refusal
277        );
278        let resolved = out_of_band("snapshot")?;
279        no_44k(&resolved)?;
280        println!(
281            "NEGOTIATE_CASE mode=full-uac3-nearest requested=44100 actual=48000 resolve=48000 attempted={} negotiate={negotiated} resolve_snapshot={resolved}",
282            decision.attempted_candidates
283        );
284        assert_eq!(alt(fd)?, 0);
285        dac.close()?;
286        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
287        assert_eq!(alt(fd)?, 0);
288        for interface in [1, 0] {
289            claim(fd, interface, false)?;
290        }
291        println!("USBIP_LIFECYCLE_PASS mode=full-uac3-nearest retired=true");
292        Ok(())
293    }
294
295    fn vendor(fd: i32, value: u16) -> Result<(), Box<dyn std::error::Error>> {
296        assert_eq!(control(fd, 0x40, 0x5a, value, 0, &mut [])?, 0);
297        Ok(())
298    }
299    fn vendor_status(fd: i32) -> Result<u8, Box<dyn std::error::Error>> {
300        let mut status = [0u8];
301        assert_eq!(control(fd, 0xc0, 0x5a, 0, 0, &mut status)?, 1);
302        Ok(status[0])
303    }
304    fn out_of_band(action: &str) -> Result<String, Box<dyn std::error::Error>> {
305        let port = std::env::var("USBDAC_USBIP_PORT")?;
306        let _: u16 = port.parse()?;
307        let output = std::process::Command::new("/fixture/usbip_uac")
308            .args(["--control", action, "--port", &port])
309            .output()?;
310        if !output.status.success() {
311            return Err(format!(
312                "fixture control {action} failed: {}",
313                String::from_utf8_lossy(&output.stderr)
314            )
315            .into());
316        }
317        Ok(String::from_utf8(output.stdout)?.trim().to_string())
318    }
319    fn wait_status(fd: i32, mask: u8) -> Result<u8, Box<dyn std::error::Error>> {
320        let start = Instant::now();
321        loop {
322            let status = vendor_status(fd)?;
323            if status & mask == mask {
324                return Ok(status);
325            }
326            if start.elapsed() >= Duration::from_secs(5) {
327                return Err(
328                    format!("fixture status {status:#04x} did not reach {mask:#04x}").into(),
329                );
330            }
331            thread::sleep(Duration::from_millis(10));
332        }
333    }
334    fn test_pcm() -> Vec<u8> {
335        let mut pcm = Vec::with_capacity(4800 * 4);
336        for i in 0..4800i32 {
337            let v = (((i % 96) - 48) * 20) as i16;
338            pcm.extend_from_slice(&v.to_le_bytes());
339            pcm.extend_from_slice(&(-v).to_le_bytes());
340        }
341        pcm
342    }
343    fn feed(stream: &usbdac_core::DacStream, pcm: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
344        let n = stream.writable_bytes().min(pcm.len());
345        if n >= 4 {
346            stream.write(&pcm[..n - n % 4])?;
347        }
348        Ok(())
349    }
350    fn duplex(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
351        use usbdac_core::{CaptureRequest, CaptureState};
352        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
353        let request = CaptureRequest {
354            sample_rate: 48_000,
355            channels: 2,
356            valid_bits: 16,
357            channel_map: None,
358        };
359        let (playback, capture) = dac.open_duplex(
360            &format,
361            &request,
362            48_000,
363            Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")),
364        )?;
365        assert_eq!(
366            (capture.interface_number(), capture.endpoint_address()),
367            (3, 0x82)
368        );
369        let pcm = test_pcm();
370        for _ in 0..3 {
371            playback.write(&pcm)?;
372        }
373        playback.play()?;
374        let start = Instant::now();
375        let mut received = [0u8; 4096];
376        let mut marker_frames = 0;
377        while start.elapsed() < Duration::from_secs(5) && marker_frames == 0 {
378            feed(&playback, &pcm)?;
379            let frames = capture.read(&mut received)?;
380            if frames > 0 {
381                assert!(
382                    received[..frames * 4]
383                        .chunks_exact(4)
384                        .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
385                    "unexpected capture payload"
386                );
387                marker_frames = frames;
388            }
389            thread::sleep(Duration::from_millis(5));
390        }
391        assert!(marker_frames > 0, "no actual capture marker");
392        println!("DUPLEX_CAPTURE_MARKER frames={marker_frames}");
393        out_of_band("mixed")?;
394        let mixed_start = Instant::now();
395        while mixed_start.elapsed() < Duration::from_secs(5) {
396            feed(&playback, &pcm)?;
397            let frames = capture.read(&mut received)?;
398            assert!(
399                received[..frames * 4]
400                    .chunks_exact(4)
401                    .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
402                "invalid packet leaked into capture"
403            );
404            let stats = capture.stats();
405            if stats.short_packets > 0 && stats.failed_packets > 0 && stats.malformed_packets > 0 {
406                break;
407            }
408            thread::sleep(Duration::from_millis(5));
409        }
410        let mixed_stats = capture.stats();
411        assert!(
412            mixed_stats.short_packets > 0
413                && mixed_stats.failed_packets > 0
414                && mixed_stats.malformed_packets > 0,
415            "mixed packet statuses not observed: {mixed_stats:?}"
416        );
417        println!("DUPLEX_MIXED_PACKETS {mixed_stats:?}");
418        vendor(fd, 1)?;
419        let start = Instant::now();
420        while start.elapsed() < Duration::from_secs(5) && capture.state() == CaptureState::Active {
421            feed(&playback, &pcm)?;
422            thread::sleep(Duration::from_millis(5));
423        }
424        assert_eq!(capture.state(), CaptureState::Failed);
425        assert!(
426            capture.last_error().is_some(),
427            "capture failure must preserve an error"
428        );
429        assert_ne!(
430            vendor_status(fd)? & 8,
431            0,
432            "fixture did not deliver capture fault"
433        );
434        let before = playback.played_frames();
435        let start = Instant::now();
436        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() <= before {
437            feed(&playback, &pcm)?;
438            thread::sleep(Duration::from_millis(5));
439        }
440        let after = playback.played_frames();
441        assert!(
442            after > before,
443            "playback stopped after independent capture failure"
444        );
445        println!(
446            "DUPLEX_ISOLATION_PASS before={before} after={after} error={:?}",
447            capture.last_error()
448        );
449        capture.close()?;
450        playback.close()?;
451        let retirement = dac.retirement();
452        dac.close()?;
453        assert!(retirement.wait(Duration::from_secs(3)));
454        assert_eq!(alt(fd)?, 0);
455        for interface in [3, 2, 1, 0] {
456            claim(fd, interface, false)?;
457        }
458        println!("USBIP_LIFECYCLE_PASS mode=duplex retired=true");
459        Ok(())
460    }
461    fn retire(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
462        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
463        let playback =
464            dac.open_stream(&format, Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")))?;
465        let pcm = test_pcm();
466        for _ in 0..3 {
467            playback.write(&pcm)?;
468        }
469        playback.play()?;
470        let start = Instant::now();
471        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() == 0 {
472            feed(&playback, &pcm)?;
473            thread::sleep(Duration::from_millis(5));
474        }
475        assert!(playback.played_frames() > 0, "playback never completed");
476        let token = dac.retirement();
477        vendor(fd, 1)?;
478        let status = wait_status(fd, 2)?;
479        println!("RETIRE_HELD status={status:#04x}");
480        let start = Instant::now();
481        let result = dac.close();
482        let elapsed = start.elapsed();
483        println!(
484            "RETIRE_CLOSE result={result:?} elapsed_ms={}",
485            elapsed.as_millis()
486        );
487        assert!(
488            matches!(result, Err(Error::Transfer(_))),
489            "close must report timeout: {result:?}"
490        );
491        assert!(
492            elapsed >= Duration::from_millis(2500),
493            "close returned before its actual timeout: {elapsed:?}"
494        );
495        assert!(
496            !token.wait(Duration::ZERO),
497            "owner retired while URB unlink was held"
498        );
499        let status: u8 = out_of_band("status")?.parse()?;
500        assert_eq!(
501            status & 0x14,
502            0x14,
503            "unlink must be held and AS1 active: {status:#04x}"
504        );
505        println!("RETIRE_PENDING elapsed_ms={}", elapsed.as_millis());
506        out_of_band("release")?;
507        assert!(
508            token.wait(Duration::from_secs(10)),
509            "owner did not retire after unlink release"
510        );
511        assert_eq!(alt(fd)?, 0, "retired owner did not restore alt zero");
512        drop(playback);
513        for interface in [1, 0] {
514            claim(fd, interface, false)?;
515        }
516        println!("USBIP_LIFECYCLE_PASS mode=retire retired=true alt=0");
517        Ok(())
518    }
519
520    fn reconfigure(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
521        use usbdac_core::StreamState;
522        let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
523        let initial = dac.negotiate(&StreamRequest::pcm(96_000, 2, 16))?;
524        assert_eq!(
525            (
526                initial.sample_rate,
527                initial.interface_number,
528                initial.alt_setting
529            ),
530            (96_000, 1, 1)
531        );
532        let previous = dac.open_stream(&initial, listener.clone())?;
533        let pcm = test_pcm();
534        for _ in 0..3 {
535            previous.write(&pcm)?;
536        }
537        previous.play()?;
538        let start = Instant::now();
539        while start.elapsed() < Duration::from_secs(5) && previous.played_frames() == 0 {
540            feed(&previous, &pcm)?;
541            thread::sleep(Duration::from_millis(5));
542        }
543        assert!(
544            previous.played_frames() > 0,
545            "original playback never completed"
546        );
547        out_of_band("reset")?;
548        println!("RECONFIGURE_PHASE_BEGIN from=96000 to=48000");
549        let request = StreamRequest::pcm(48_000, 2, 16);
550        let replacement = dac.reconfigure_stream_candidates(
551            &previous,
552            &[request],
553            listener,
554            Duration::from_secs(3),
555        )?;
556        println!("RECONFIGURE_PHASE_END from=96000 to=48000");
557        assert!(
558            replacement.rollback_cause.is_none(),
559            "unexpected rollback: {:?}",
560            replacement.rollback_cause
561        );
562        assert_eq!(previous.state(), StreamState::Closed);
563        assert_eq!(replacement.stream.state(), StreamState::Paused);
564        assert_eq!(replacement.stream.format().sample_rate, 48_000);
565        assert_eq!(replacement.stream.played_frames(), 0);
566        assert_eq!(alt(fd)?, 1);
567        let transitions = out_of_band("snapshot")?;
568        let alt_history = transitions
569            .split("alts=[")
570            .nth(1)
571            .ok_or("missing alternate history")?
572            .split(']')
573            .next()
574            .ok_or("missing alternate terminator")?;
575        let unlink_count: u64 = transitions
576            .split("unlinks=")
577            .nth(1)
578            .ok_or("missing unlink count")?
579            .parse()?;
580        assert!(
581            unlink_count <= 16,
582            "more than one bounded transfer set cancelled: {transitions}"
583        );
584        let mut alts: Vec<_> = alt_history.split(", ").collect();
585        alts.dedup();
586        assert_eq!(
587            alts,
588            ["0", "1"],
589            "unexpected alternate transitions: {transitions}"
590        );
591        // USB-level count of the live 96 -> 48 kHz replacement on interface 1 and
592        // clock 16. ALSA's UAC2 prepare deselects the alternate first, writes the
593        // rate, and enables the alternate last (sound/usb/endpoint.c
594        // snd_usb_endpoint_prepare:1498-1530, endpoint_set_interface:917-951).
595        // ALSA elides a SET_INTERFACE to the alternate it already holds
596        // (endpoint.c:926-927); usbdac re-asserts alt 0 at stop, before and after
597        // the read-only negotiation and before activation, which is idempotent.
598        let sequence = out_of_band("sequence")?;
599        let writes: Vec<_> = sequence
600            .strip_prefix("seq=[")
601            .and_then(|rest| rest.strip_suffix(']'))
602            .ok_or("missing write sequence")?
603            .split(", ")
604            .collect();
605        let count = |w: &str| writes.iter().filter(|x| **x == w).count();
606        assert_eq!(
607            (
608                count("alt0"),
609                count("alt1"),
610                count("rate48000"),
611                writes.len()
612            ),
613            (4, 1, 2, 7),
614            "unexpected replacement write counts: {sequence}"
615        );
616        assert_eq!(
617            writes.first(),
618            Some(&"alt0"),
619            "old alternate not deselected first: {sequence}"
620        );
621        assert_eq!(
622            writes.last(),
623            Some(&"alt1"),
624            "alternate not enabled last: {sequence}"
625        );
626        assert!(
627            !writes
628                .iter()
629                .any(|w| w.starts_with("rate") && *w != "rate48000"),
630            "a rate other than 48 kHz was written: {sequence}"
631        );
632        // Fresh post-replacement evidence: the DAC's clock reads back 48 kHz at alt 1.
633        let mut current = [0u8; 4];
634        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
635        assert_eq!(u32::from_le_bytes(current), 48_000);
636        println!(
637            "RECONFIGURE_USB_WRITES {sequence} clock_readback=48000 alt={}",
638            alt(fd)?
639        );
640        let stream = replacement.stream;
641        for _ in 0..3 {
642            stream.write(&pcm)?;
643        }
644        stream.play()?;
645        let start = Instant::now();
646        while start.elapsed() < Duration::from_secs(5)
647            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
648        {
649            feed(&stream, &pcm)?;
650            thread::sleep(Duration::from_millis(5));
651        }
652        assert!(
653            stream.played_frames() > 0 && stream.stats().completed_transfers > 0,
654            "replacement playback never completed"
655        );
656        let stats = stream.stats();
657        assert!(stats.played_frames <= stats.frames_written);
658        assert!(stats.queued_frames <= stats.frames_written);
659        assert!(
660            stats.underruns <= 50,
661            "USB/IP replacement exceeded 50 underruns: {stats:?}"
662        );
663        let mut current = [0u8; 4];
664        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
665        assert_eq!(
666            u32::from_le_bytes(current),
667            48_000,
668            "clock drifted during replacement playback"
669        );
670        let fixture_stats = out_of_band("snapshot")?;
671        assert!(
672            !fixture_stats.contains("out_completions=0"),
673            "replacement has no completed OUT URB: {fixture_stats}"
674        );
675        println!(
676            "RECONFIGURE_PLAYBACK_PASS stats={stats:?} underrun_limit=50 fixture={fixture_stats}"
677        );
678        stream.close()?;
679        let retirement = dac.retirement();
680        dac.close()?;
681        assert!(retirement.wait(Duration::from_secs(3)));
682        assert_eq!(alt(fd)?, 0);
683        for interface in [1, 0] {
684            claim(fd, interface, false)?;
685        }
686        println!("USBIP_LIFECYCLE_PASS mode=reconfigure retired=true alt=0");
687        Ok(())
688    }
689
690    /// DoP resolution through the production resolve_playback, transport and
691    /// PlaybackStream. DoP v1.1 carries 16 DSD bits per channel per carrier frame,
692    /// so a DoP carrier of another depth or channel count is a repack (H1), and an
693    /// exact DoP shape absent from the descriptors is never attempted (H2).
694    fn dop_resolution(dac: Dac, fd: i32, mode: &str) -> Result<(), Box<dyn std::error::Error>> {
695        use usbdac_core::playback::{PlaybackFidelity, PlaybackPolicy, PlaybackTransform};
696        use usbdac_core::Encoding;
697        let confirmed = PlaybackPolicy {
698            dop_confirmed: true,
699            ..PlaybackPolicy::default()
700        };
701        let caps = dac.capabilities()?;
702        assert!(
703            caps.exclusion_snapshot_complete,
704            "the fixture descriptor snapshot must be complete"
705        );
706        let source = StreamRequest::dop(2_822_400, if mode == "dop-stereo24" { 1 } else { 2 });
707        if mode == "dop-carrier32" {
708            // H2: 24-bit DoP on a 32-bit-only DAC reaches the 32-bit carrier.
709            let widened = dac.resolve_playback(&source, &confirmed)?;
710            println!(
711                "DOP_DECISION mode={mode} case=widen transform={:?} fidelity={:?} bits={} preflight={:?}",
712                widened.transform, widened.fidelity, widened.format.valid_bits, widened.source_preflight_refusal
713            );
714            assert!(widened.source_preflight_refusal.is_some());
715            assert_eq!(widened.format.encoding, Encoding::DoP);
716            assert_eq!(widened.format.valid_bits, 32);
717            assert_eq!(
718                widened.transform,
719                PlaybackTransform::DopRepack { target_channels: 2 }
720            );
721        }
722        let policy = if mode == "dop-carrier32" {
723            // H1: the review's smallest case.
724            PlaybackPolicy {
725                allowed_pcm_depths: Some(vec![32]),
726                ..confirmed.clone()
727            }
728        } else {
729            confirmed.clone()
730        };
731        out_of_band("reset")?;
732        let decision = dac.resolve_playback(&source, &policy)?;
733        println!(
734            "DOP_DECISION mode={mode} transform={:?} fidelity={:?} format={:?}/{}ch/{}bit preflight={:?} attempted={}",
735            decision.transform,
736            decision.fidelity,
737            decision.format.encoding,
738            decision.format.channels,
739            decision.format.valid_bits,
740            decision.source_preflight_refusal,
741            decision.attempted_candidates
742        );
743        if mode == "dop-no-carrier" {
744            // H2: confirmed DoP on a DAC that cannot carry it falls back like unconfirmed.
745            assert!(decision.source_preflight_refusal.is_some());
746            assert_eq!(decision.format.encoding, Encoding::Pcm);
747            assert!(matches!(
748                decision.transform,
749                PlaybackTransform::DsdToPcm {
750                    dop_input: true,
751                    ..
752                }
753            ));
754            let unconfirmed = dac.resolve_playback(&source, &PlaybackPolicy::default())?;
755            assert_eq!(unconfirmed.format, decision.format);
756        } else {
757            assert_eq!(decision.format.encoding, Encoding::DoP);
758            assert_eq!(decision.format.channels, 2);
759            assert_eq!(
760                decision.transform,
761                PlaybackTransform::DopRepack { target_channels: 2 }
762            );
763            assert_eq!(
764                decision.fidelity,
765                if source.channels == 2 {
766                    PlaybackFidelity::BitExact
767                } else {
768                    PlaybackFidelity::Lossless
769                }
770            );
771            assert_eq!(decision.attempted_candidates, 1);
772        }
773        let mut stream = dac.open_playback(&decision, Arc::new(|_| {}))?;
774        let channels = usize::from(source.channels);
775        let frame = decision.source_frame_bytes;
776        let mut next = 0usize;
777        let mut chunk = Vec::new();
778        let start = Instant::now();
779        let mut started = false;
780        while start.elapsed() < Duration::from_secs(3)
781            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
782        {
783            let frames = stream.writable_bytes() / frame;
784            if frames > 0 {
785                chunk.clear();
786                for i in next..next + frames {
787                    let marker = if i % 2 == 0 { 0x05 } else { 0xfa };
788                    for _ in 0..channels {
789                        chunk.extend_from_slice(&[0x69, 0x69, marker]);
790                    }
791                }
792                next += stream.write(&chunk)? / frame;
793            }
794            if !started && next > 0 {
795                stream.play()?;
796                started = true;
797            }
798            thread::sleep(Duration::from_millis(2));
799        }
800        let stats = stream.target_stats();
801        let snapshot = out_of_band("snapshot")?;
802        println!("DOP_STATS mode={mode} source_frames={next} {stats:?} {snapshot}");
803        assert!(
804            stats.played_frames > 0 && stats.completed_transfers > 0,
805            "no DoP-resolved completions"
806        );
807        let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
808        let carrier_set = rates
809            .split(|c: char| !c.is_ascii_digit())
810            .any(|v| v == "176400");
811        // The carrier DACs clock 176.4 kHz; the exact carrier is never set on a DAC without one.
812        assert_eq!(carrier_set, mode != "dop-no-carrier", "{snapshot}");
813        if mode != "dop-no-carrier" {
814            assert!(stats.payload_verified, "the DoP payload must audit clean");
815        }
816        stream.close()?;
817        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
818        let retirement = dac.retirement();
819        dac.close()?;
820        assert!(retirement.wait(Duration::from_secs(3)));
821        assert_eq!(alt(fd)?, 0);
822        for interface in [1, 0] {
823            claim(fd, interface, false)?;
824        }
825        println!("USBIP_LIFECYCLE_PASS mode={mode} alt=0 retired=true");
826        Ok(())
827    }
828
829    pub fn run() -> Result<(), Box<dyn std::error::Error>> {
830        let args: Vec<_> = std::env::args().collect();
831        if args.len() != 3
832            || !matches!(
833                args[2].as_str(),
834                "normal"
835                    | "bad-cur"
836                    | "stale-cur"
837                    | "badd"
838                    | "full-uac3"
839                    | "full-uac3-volatile"
840                    | "full-uac3-clock"
841                    | "full-uac3-clock-bad"
842                    | "full-uac3-clock-stale"
843                    | "duplex"
844                    | "retire"
845                    | "reconfigure"
846                    | "selector"
847                    | "refuse-set"
848                    | "zero-res"
849                    | "full-uac3-nearest"
850                    | "dop-carrier32"
851                    | "dop-stereo24"
852                    | "dop-no-carrier"
853            )
854        {
855            return Err(
856                "usage: usbip_lifecycle /dev/bus/usb/BBB/DDD normal|bad-cur|stale-cur|badd|full-uac3|full-uac3-clock|duplex|retire|reconfigure".into(),
857            );
858        }
859        let path = &args[1];
860        if !path.starts_with("/dev/bus/usb/") {
861            return Err("expected a usbfs device path".into());
862        }
863        let file = OpenOptions::new().read(true).write(true).open(path)?;
864        let fd = file.as_raw_fd();
865        // Read and validate the actual descriptor before claiming or invoking the driver.
866        let mut descriptor = [0u8; 18];
867        assert_eq!(control(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?, 18);
868        assert_eq!((descriptor[0], descriptor[1]), (18, 1));
869        assert_eq!(
870            (
871                u16::from_le_bytes([descriptor[8], descriptor[9]]),
872                u16::from_le_bytes([descriptor[10], descriptor[11]])
873            ),
874            (VID, PID),
875            "refusing a device other than the fixture"
876        );
877        // Select the explicitly advertised fixture configuration before interface claims.
878        let configuration = match args[2].as_str() {
879            "badd" => 2u32,
880            "full-uac3"
881            | "full-uac3-volatile"
882            | "full-uac3-clock"
883            | "full-uac3-clock-bad"
884            | "full-uac3-clock-stale"
885            | "full-uac3-nearest" => 3,
886            _ => 1,
887        };
888        if configuration != 1 {
889            let mut config_descriptor = [0u8; 9];
890            assert_eq!(
891                control(
892                    fd,
893                    0x80,
894                    6,
895                    0x0200 | (configuration as u16 - 1),
896                    0,
897                    &mut config_descriptor
898                )?,
899                9
900            );
901            assert_eq!(
902                (
903                    config_descriptor[0],
904                    config_descriptor[1],
905                    config_descriptor[5]
906                ),
907                (9, 2, configuration as u8)
908            );
909            if unsafe { libc::ioctl(fd, 0x80045505u32 as _, &configuration) } != 0 {
910                return Err(std::io::Error::last_os_error().into());
911            }
912        }
913        let claims = if args[2] == "duplex" {
914            vec![0u8, 1, 2, 3]
915        } else {
916            vec![0u8, 1]
917        };
918        for &interface in &claims {
919            claim(fd, u32::from(interface), true)?;
920        }
921        assert_eq!(alt(fd)?, 0);
922        if matches!(
923            args[2].as_str(),
924            "badd" | "full-uac3" | "full-uac3-volatile"
925        ) {
926            assert_eq!(power(fd)?, 0, "power domain must initially be D0");
927            let mut state = [2u8];
928            assert_eq!(control(fd, 0x21, 1, 0x0200, 0x0a00, &mut state)?, 1);
929            assert_eq!(power(fd)?, 2, "failed to seed D2 baseline");
930        }
931        let mut info = DeviceInfo::new(VID, PID, "USB/IP audio fixture")
932            .with_claimed_interfaces(claims)
933            .with_device_name(path);
934        info.configuration_id = Some(configuration as u8);
935        let config = DacConfig {
936            require_hardware_volume: false,
937            require_verified_rate: true,
938            ..DacConfig::default()
939        };
940        let dac = if args[2] == "duplex" {
941            Dac::open_duplex_device(fd, info, config)?
942        } else {
943            Dac::open(fd, info, config)?
944        };
945        if args[2] == "duplex" {
946            return duplex(dac, fd);
947        }
948        if args[2] == "retire" {
949            return retire(dac, fd);
950        }
951        if args[2] == "reconfigure" {
952            return reconfigure(dac, fd);
953        }
954        if args[2].starts_with("dop-") {
955            return dop_resolution(dac, fd, &args[2]);
956        }
957        let caps = dac.capabilities()?;
958        if args[2] == "refuse-set" {
959            out_of_band("reset")?;
960            let requests = [
961                StreamRequest::pcm(96_000, 2, 16),
962                StreamRequest::pcm(48_000, 2, 16),
963            ];
964            let failure = dac.negotiate_candidates(&requests);
965            assert!(
966                matches!(
967                    failure,
968                    Err(Error::ClockUnverified {
969                        requested_hz: 96_000,
970                        ..
971                    })
972                ),
973                "refused SET must be terminal: {failure:?}"
974            );
975            let snapshot = out_of_band("snapshot")?;
976            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
977            assert!(rates.contains("96000"));
978            assert!(
979                !rates.contains("48000"),
980                "second candidate was tried after uncertain SET: {snapshot}"
981            );
982            let retirement = dac.retirement();
983            dac.close()?;
984            assert!(retirement.wait(Duration::from_secs(3)));
985            assert_eq!(alt(fd)?, 0);
986            for interface in [1, 0] {
987                claim(fd, interface, false)?;
988            }
989            println!("USBIP_LIFECYCLE_PASS mode=refuse-set snapshot={snapshot}");
990            return Ok(());
991        }
992        if matches!(args[2].as_str(), "selector" | "zero-res") {
993            let (requested, expected) = if args[2] == "selector" {
994                (192_000, 96_000)
995            } else {
996                (96_000, 44_100)
997            };
998            out_of_band("reset")?;
999            let request =
1000                StreamRequest::pcm(requested, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1001            let format = dac.negotiate(&request)?;
1002            assert_eq!(format.sample_rate, expected);
1003            let stream = dac.open_stream(&format, Arc::new(|_| {}))?;
1004            let snapshot = out_of_band("snapshot")?;
1005            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
1006            let rejected = requested.to_string();
1007            assert!(
1008                !rates
1009                    .split(|c: char| !c.is_ascii_digit())
1010                    .any(|v| v == rejected),
1011                "requested unsupported rate was sent: {snapshot}"
1012            );
1013            println!(
1014                "NEGOTIATE_CASE mode={} requested={requested} actual={expected} {snapshot}",
1015                args[2]
1016            );
1017            stream.close()?;
1018            let retirement = dac.retirement();
1019            dac.close()?;
1020            assert!(retirement.wait(Duration::from_secs(3)));
1021            assert_eq!(alt(fd)?, 0);
1022            for interface in [1, 0] {
1023                claim(fd, interface, false)?;
1024            }
1025            println!("USBIP_LIFECYCLE_PASS mode={} retired=true", args[2]);
1026            return Ok(());
1027        }
1028        if args[2] == "badd" {
1029            badd(&dac, fd, &caps)?;
1030            assert_eq!(alt(fd)?, 0);
1031            dac.close()?;
1032            assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
1033            assert_eq!(alt(fd)?, 0);
1034            assert_eq!(power(fd)?, 2, "BADD must restore D2");
1035            let power_log = out_of_band("snapshot")?;
1036            let powers = power_log
1037                .split("power=[")
1038                .nth(1)
1039                .ok_or("missing power history")?
1040                .split(']')
1041                .next()
1042                .ok_or("missing power terminator")?;
1043            assert!(
1044                powers
1045                    .split(", ")
1046                    .collect::<Vec<_>>()
1047                    .windows(2)
1048                    .any(|pair| pair == ["0", "2"]),
1049                "expected D0 to D2 transition: {power_log}"
1050            );
1051            for interface in [1, 0] {
1052                claim(fd, interface, false)?;
1053            }
1054            println!("USBIP_LIFECYCLE_PASS mode=badd alt=0 retired=true");
1055            return Ok(());
1056        }
1057        if args[2] == "full-uac3-nearest" {
1058            return full_uac3_nearest(dac, fd, &caps);
1059        }
1060        if matches!(args[2].as_str(), "full-uac3" | "full-uac3-volatile") {
1061            return full_uac3(dac, fd, &caps, args[2] == "full-uac3-volatile");
1062        }
1063        assert_eq!(
1064            caps.uac_version,
1065            if args[2].starts_with("full-uac3-clock") {
1066                UacVersion::V3
1067            } else {
1068                UacVersion::V2
1069            }
1070        );
1071        assert_eq!(caps.link_speed, LinkSpeed::High);
1072        let mut rates = caps.pcm_sample_rates.clone();
1073        rates.sort_unstable();
1074        rates.dedup();
1075        assert_eq!(rates, [48_000, 96_000], "unexpected fixture rates");
1076        assert!(
1077            matches!(
1078                dac.negotiate(&StreamRequest::pcm(192_000, 2, 16)),
1079                Err(Error::Unsupported { .. })
1080            ),
1081            "exact 192 kHz must be refused"
1082        );
1083        let request =
1084            StreamRequest::pcm(192_000, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1085        let format = dac.negotiate(&request)?;
1086        assert_eq!(
1087            (
1088                format.sample_rate,
1089                format.channels,
1090                format.valid_bits,
1091                format.subslot_bytes,
1092                format.interface_number,
1093                format.alt_setting
1094            ),
1095            (96_000, 2, 16, 2, 1, 1)
1096        );
1097        assert_eq!(format.sync_type, SyncKind::Synchronous);
1098        assert_eq!(format.endpoint_address, 0x01);
1099        assert_eq!(format.link_speed, LinkSpeed::High);
1100        assert_eq!(format.bytes_per_frame(), 4);
1101        if args[2].starts_with("full-uac3-clock") {
1102            assert_eq!(format.service_interval_us, 125);
1103            assert!(!format.explicit_feedback);
1104        }
1105        let clock = format
1106            .clock
1107            .as_ref()
1108            .ok_or("fixture clock missing")?
1109            .clone();
1110        assert_eq!(
1111            (clock.control_interface, clock.source_id),
1112            (
1113                0,
1114                if args[2].starts_with("full-uac3-clock") {
1115                    9
1116                } else {
1117                    0x10
1118                }
1119            )
1120        );
1121        println!("NEGOTIATED exact192=unsupported nearest192=96000 format={format:?}");
1122        let listener = Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}"));
1123        match args[2].as_str() {
1124            "normal" | "full-uac3-clock" => {
1125                let stream = dac.open_stream(&format, listener)?;
1126                assert_eq!(alt(fd)?, 1);
1127                let mut current = [0u8; 4];
1128                assert_eq!(
1129                    control(
1130                        fd,
1131                        0xa1,
1132                        1,
1133                        0x0100,
1134                        (u16::from(clock.source_id) << 8) | u16::from(clock.control_interface),
1135                        &mut current
1136                    )?,
1137                    4
1138                );
1139                assert_eq!(
1140                    u32::from_le_bytes(current),
1141                    96_000,
1142                    "post-alt clock readback"
1143                );
1144                let mut pcm = Vec::with_capacity(9600 * 4);
1145                for i in 0..9600i32 {
1146                    let v = (((i % 96) - 48) * 20) as i16;
1147                    pcm.extend_from_slice(&v.to_le_bytes());
1148                    pcm.extend_from_slice(&(-v).to_le_bytes());
1149                }
1150                for _ in 0..3 {
1151                    stream.write(&pcm)?;
1152                }
1153                stream.play()?;
1154                let start = Instant::now();
1155                while start.elapsed() < Duration::from_secs(3)
1156                    && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
1157                {
1158                    let n = stream.writable_bytes().min(pcm.len());
1159                    if n >= 4 {
1160                        stream.write(&pcm[..n - n % 4])?;
1161                    }
1162                    thread::sleep(Duration::from_millis(2));
1163                }
1164                let stats = stream.stats();
1165                println!("PCM_STATS {stats:?}");
1166                assert!(
1167                    stats.played_frames > 0 && stats.completed_transfers > 0,
1168                    "no actual PCM completions"
1169                );
1170                stream.close()?;
1171            }
1172            mode => match dac.open_stream(&format, listener) {
1173                Err(error @ Error::ClockUnverified { .. }) => {
1174                    let expected_reported = if mode == "bad-cur" || mode == "full-uac3-clock-bad" {
1175                        None
1176                    } else {
1177                        Some(48_000)
1178                    };
1179                    assert!(
1180                        matches!(error, Error::ClockUnverified { requested_hz: 96_000, reported_hz } if reported_hz == expected_reported)
1181                    );
1182                    println!(
1183                        "EXPECTED_FAILURE mode={mode} code={} error={error:?}",
1184                        error.code()
1185                    );
1186                }
1187                Err(error) => {
1188                    return Err(format!("unexpected failure for {mode}: {error:?}").into())
1189                }
1190                Ok(stream) => {
1191                    stream.close()?;
1192                    return Err(format!("{mode} incorrectly admitted the stream").into());
1193                }
1194            },
1195        }
1196        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
1197        dac.close()?;
1198        assert!(
1199            Dac::await_usb_retirement(Duration::from_secs(3)),
1200            "USB retirement timed out"
1201        );
1202        assert_eq!(alt(fd)?, 0);
1203        for interface in [1, 0] {
1204            claim(fd, interface, false)?;
1205        }
1206        println!("USBIP_LIFECYCLE_PASS mode={} alt=0 retired=true", args[2]);
1207        Ok(())
1208    }
examples/qemu_smoke.rs (line 133)
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 play(&self) -> Result<()>

Resumes after pause. A new stream plays by itself once the ring holds the start threshold; this is only needed after a pause.

Examples found in repository?
examples/pull_adapter.rs (line 83)
82    fn resume(&self) -> Result<()> {
83        self.stream.play()
84    }
More examples
Hide additional examples
examples/guide_player.rs (line 86)
85    fn play(&self) -> Result<()> {
86        DacStream::play(self)
87    }
examples/usbip_lifecycle.rs (line 125)
79    fn badd(
80        dac: &Dac,
81        fd: i32,
82        caps: &usbdac_core::Capabilities,
83    ) -> Result<(), Box<dyn std::error::Error>> {
84        assert_eq!(caps.uac_version, UacVersion::V3);
85        assert_eq!(caps.link_speed, LinkSpeed::High);
86        assert_eq!(caps.pcm_sample_rates, [48_000]);
87        assert!(matches!(
88            dac.negotiate(&StreamRequest::pcm(96_000, 2, 16)),
89            Err(Error::Unsupported { .. })
90        ));
91        let format = dac.negotiate(
92            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
93        )?;
94        assert_eq!(
95            (
96                format.sample_rate,
97                format.channels,
98                format.valid_bits,
99                format.subslot_bytes,
100                format.interface_number,
101                format.alt_setting,
102                format.endpoint_address
103            ),
104            (48_000, 2, 16, 2, 1, 1, 1)
105        );
106        assert!(
107            format.explicit_feedback,
108            "BADD profile must expose feedback"
109        );
110        println!("BADD_FORMAT {format:?}");
111        let stream = dac.open_stream(
112            &format,
113            Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}")),
114        )?;
115        assert_eq!(alt(fd)?, 1);
116        let mut pcm = Vec::with_capacity(4800 * 4);
117        for i in 0..4800i32 {
118            let v = (((i % 96) - 48) * 20) as i16;
119            pcm.extend_from_slice(&v.to_le_bytes());
120            pcm.extend_from_slice(&(-v).to_le_bytes());
121        }
122        for _ in 0..3 {
123            stream.write(&pcm)?;
124        }
125        stream.play()?;
126        let start = Instant::now();
127        while start.elapsed() < Duration::from_secs(3)
128            && (stream.played_frames() == 0
129                || stream.stats().completed_transfers == 0
130                || stream.stats().feedback_reports == 0)
131        {
132            let n = stream.writable_bytes().min(pcm.len());
133            if n >= 4 {
134                stream.write(&pcm[..n - n % 4])?;
135            }
136            thread::sleep(Duration::from_millis(2));
137        }
138        let stats = stream.stats();
139        println!("BADD_PCM_STATS {stats:?}");
140        assert!(
141            stats.played_frames > 0 && stats.completed_transfers > 0 && stats.feedback_reports > 0,
142            "BADD playback or feedback has no real completions"
143        );
144        stream.close()?;
145        Ok(())
146    }
147
148    fn full_uac3(
149        dac: Dac,
150        fd: i32,
151        caps: &usbdac_core::Capabilities,
152        volatile: bool,
153    ) -> Result<(), Box<dyn std::error::Error>> {
154        use usbdac_core::routing::{
155            ControlKey, Entity, RouteEdit, RouteValue, RoutingHandBackOutcome,
156        };
157        assert_eq!(caps.uac_version, UacVersion::V3);
158        assert_eq!(caps.link_speed, LinkSpeed::High);
159        let key = ControlKey::Selector(Entity {
160            interface: 0,
161            id: 8,
162        });
163        assert_eq!(power(fd)?, 2, "initial power must be D2");
164        let snapshot = dac.routing_discover_powered()?;
165        println!("UAC3_ROUTING snapshot={snapshot:?}");
166        assert_eq!(snapshot.configuration(), 3);
167        assert_eq!(power(fd)?, 2, "discovery must restore D2");
168        assert_eq!(
169            dac.routing_read_powered(&snapshot, key)?,
170            RouteValue::SelectorPin(1)
171        );
172        assert_eq!(power(fd)?, 2, "read must restore D2");
173        let report = dac.routing_apply_powered(
174            &snapshot,
175            &[RouteEdit {
176                key,
177                expected: RouteValue::SelectorPin(1),
178                value: RouteValue::SelectorPin(2),
179            }],
180        )?;
181        assert_eq!(report.changed, vec![key]);
182        let applied = out_of_band("snapshot")?;
183        assert!(
184            applied.contains("selector=[2]"),
185            "fixture selector was not written: {applied}"
186        );
187        assert!(
188            applied.contains(if volatile {
189                "selector_state=1"
190            } else {
191                "selector_state=2"
192            }),
193            "unexpected fixture selector after D2: {applied}"
194        );
195        assert_eq!(power(fd)?, 2, "apply must restore D2");
196        let updated = dac.routing_discover_powered()?;
197        assert_eq!(
198            dac.routing_read_powered(&updated, key)?,
199            RouteValue::SelectorPin(if volatile { 1 } else { 2 }),
200            "selector readback must reflect the fixture's D2 behavior"
201        );
202        assert_eq!(power(fd)?, 2);
203        dac.close()?;
204        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
205        let hand_back = snapshot
206            .hand_back_report()
207            .ok_or("missing routing hand-back report")?;
208        println!("UAC3_HAND_BACK {hand_back:?}");
209        if !volatile {
210            assert!(
211                hand_back
212                    .controls
213                    .contains(&(key, RoutingHandBackOutcome::Restored)),
214                "selector hand-back was not verified"
215            );
216        }
217        assert_eq!(power(fd)?, 2, "final power must be D2");
218        assert!(
219            out_of_band("snapshot")?.contains("selector_state=1"),
220            "fixture selector was not restored"
221        );
222        assert_eq!(alt(fd)?, 0);
223        for interface in [1, 0] {
224            claim(fd, interface, false)?;
225        }
226        println!("USBIP_LIFECYCLE_PASS mode=full-uac3 selector=restored power=D2 retired=true");
227        Ok(())
228    }
229
230    // Full UAC3 whose clock RANGE lists only 48 kHz behind a powered route that
231    // cannot certify a live refusal. The cached model excludes 44.1 kHz, so the
232    // ranked loop and the playback candidates must skip it without any USB request,
233    // as ALSA never offers a rate absent from its format table (pcm.c hw_rule_rate).
234    fn full_uac3_nearest(
235        dac: Dac,
236        fd: i32,
237        caps: &usbdac_core::Capabilities,
238    ) -> Result<(), Box<dyn std::error::Error>> {
239        use usbdac_core::playback::PlaybackPolicy;
240        assert_eq!(caps.uac_version, UacVersion::V3);
241        assert_eq!(caps.link_speed, LinkSpeed::High);
242        let mut rates = caps.pcm_sample_rates.clone();
243        rates.sort_unstable();
244        rates.dedup();
245        assert_eq!(rates, [48_000], "unexpected full-UAC3 fixture rates");
246        let no_44k = |snapshot: &str| -> Result<(), Box<dyn std::error::Error>> {
247            let sets = snapshot.split(';').next().ok_or("missing rate snapshot")?;
248            if sets
249                .split(|c: char| !c.is_ascii_digit())
250                .any(|v| v == "44100")
251            {
252                return Err(format!("model-excluded 44100 Hz was programmed: {snapshot}").into());
253            }
254            Ok(())
255        };
256        out_of_band("reset")?;
257        let format = dac.negotiate(
258            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
259        )?;
260        assert_eq!(
261            (format.sample_rate, format.channels, format.valid_bits),
262            (48_000, 2, 16)
263        );
264        let negotiated = out_of_band("snapshot")?;
265        no_44k(&negotiated)?;
266        out_of_band("reset")?;
267        let decision = dac.resolve_playback(
268            &StreamRequest::pcm(44_100, 2, 16),
269            &PlaybackPolicy::default(),
270        )?;
271        assert_eq!(decision.format.sample_rate, 48_000);
272        assert_eq!(decision.candidates[0], StreamRequest::pcm(44_100, 2, 16));
273        assert!(
274            matches!(decision.exact_refusal, Some(Error::Unsupported { .. })),
275            "the skipped exact source must report a typed refusal: {:?}",
276            decision.exact_refusal
277        );
278        let resolved = out_of_band("snapshot")?;
279        no_44k(&resolved)?;
280        println!(
281            "NEGOTIATE_CASE mode=full-uac3-nearest requested=44100 actual=48000 resolve=48000 attempted={} negotiate={negotiated} resolve_snapshot={resolved}",
282            decision.attempted_candidates
283        );
284        assert_eq!(alt(fd)?, 0);
285        dac.close()?;
286        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
287        assert_eq!(alt(fd)?, 0);
288        for interface in [1, 0] {
289            claim(fd, interface, false)?;
290        }
291        println!("USBIP_LIFECYCLE_PASS mode=full-uac3-nearest retired=true");
292        Ok(())
293    }
294
295    fn vendor(fd: i32, value: u16) -> Result<(), Box<dyn std::error::Error>> {
296        assert_eq!(control(fd, 0x40, 0x5a, value, 0, &mut [])?, 0);
297        Ok(())
298    }
299    fn vendor_status(fd: i32) -> Result<u8, Box<dyn std::error::Error>> {
300        let mut status = [0u8];
301        assert_eq!(control(fd, 0xc0, 0x5a, 0, 0, &mut status)?, 1);
302        Ok(status[0])
303    }
304    fn out_of_band(action: &str) -> Result<String, Box<dyn std::error::Error>> {
305        let port = std::env::var("USBDAC_USBIP_PORT")?;
306        let _: u16 = port.parse()?;
307        let output = std::process::Command::new("/fixture/usbip_uac")
308            .args(["--control", action, "--port", &port])
309            .output()?;
310        if !output.status.success() {
311            return Err(format!(
312                "fixture control {action} failed: {}",
313                String::from_utf8_lossy(&output.stderr)
314            )
315            .into());
316        }
317        Ok(String::from_utf8(output.stdout)?.trim().to_string())
318    }
319    fn wait_status(fd: i32, mask: u8) -> Result<u8, Box<dyn std::error::Error>> {
320        let start = Instant::now();
321        loop {
322            let status = vendor_status(fd)?;
323            if status & mask == mask {
324                return Ok(status);
325            }
326            if start.elapsed() >= Duration::from_secs(5) {
327                return Err(
328                    format!("fixture status {status:#04x} did not reach {mask:#04x}").into(),
329                );
330            }
331            thread::sleep(Duration::from_millis(10));
332        }
333    }
334    fn test_pcm() -> Vec<u8> {
335        let mut pcm = Vec::with_capacity(4800 * 4);
336        for i in 0..4800i32 {
337            let v = (((i % 96) - 48) * 20) as i16;
338            pcm.extend_from_slice(&v.to_le_bytes());
339            pcm.extend_from_slice(&(-v).to_le_bytes());
340        }
341        pcm
342    }
343    fn feed(stream: &usbdac_core::DacStream, pcm: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
344        let n = stream.writable_bytes().min(pcm.len());
345        if n >= 4 {
346            stream.write(&pcm[..n - n % 4])?;
347        }
348        Ok(())
349    }
350    fn duplex(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
351        use usbdac_core::{CaptureRequest, CaptureState};
352        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
353        let request = CaptureRequest {
354            sample_rate: 48_000,
355            channels: 2,
356            valid_bits: 16,
357            channel_map: None,
358        };
359        let (playback, capture) = dac.open_duplex(
360            &format,
361            &request,
362            48_000,
363            Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")),
364        )?;
365        assert_eq!(
366            (capture.interface_number(), capture.endpoint_address()),
367            (3, 0x82)
368        );
369        let pcm = test_pcm();
370        for _ in 0..3 {
371            playback.write(&pcm)?;
372        }
373        playback.play()?;
374        let start = Instant::now();
375        let mut received = [0u8; 4096];
376        let mut marker_frames = 0;
377        while start.elapsed() < Duration::from_secs(5) && marker_frames == 0 {
378            feed(&playback, &pcm)?;
379            let frames = capture.read(&mut received)?;
380            if frames > 0 {
381                assert!(
382                    received[..frames * 4]
383                        .chunks_exact(4)
384                        .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
385                    "unexpected capture payload"
386                );
387                marker_frames = frames;
388            }
389            thread::sleep(Duration::from_millis(5));
390        }
391        assert!(marker_frames > 0, "no actual capture marker");
392        println!("DUPLEX_CAPTURE_MARKER frames={marker_frames}");
393        out_of_band("mixed")?;
394        let mixed_start = Instant::now();
395        while mixed_start.elapsed() < Duration::from_secs(5) {
396            feed(&playback, &pcm)?;
397            let frames = capture.read(&mut received)?;
398            assert!(
399                received[..frames * 4]
400                    .chunks_exact(4)
401                    .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
402                "invalid packet leaked into capture"
403            );
404            let stats = capture.stats();
405            if stats.short_packets > 0 && stats.failed_packets > 0 && stats.malformed_packets > 0 {
406                break;
407            }
408            thread::sleep(Duration::from_millis(5));
409        }
410        let mixed_stats = capture.stats();
411        assert!(
412            mixed_stats.short_packets > 0
413                && mixed_stats.failed_packets > 0
414                && mixed_stats.malformed_packets > 0,
415            "mixed packet statuses not observed: {mixed_stats:?}"
416        );
417        println!("DUPLEX_MIXED_PACKETS {mixed_stats:?}");
418        vendor(fd, 1)?;
419        let start = Instant::now();
420        while start.elapsed() < Duration::from_secs(5) && capture.state() == CaptureState::Active {
421            feed(&playback, &pcm)?;
422            thread::sleep(Duration::from_millis(5));
423        }
424        assert_eq!(capture.state(), CaptureState::Failed);
425        assert!(
426            capture.last_error().is_some(),
427            "capture failure must preserve an error"
428        );
429        assert_ne!(
430            vendor_status(fd)? & 8,
431            0,
432            "fixture did not deliver capture fault"
433        );
434        let before = playback.played_frames();
435        let start = Instant::now();
436        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() <= before {
437            feed(&playback, &pcm)?;
438            thread::sleep(Duration::from_millis(5));
439        }
440        let after = playback.played_frames();
441        assert!(
442            after > before,
443            "playback stopped after independent capture failure"
444        );
445        println!(
446            "DUPLEX_ISOLATION_PASS before={before} after={after} error={:?}",
447            capture.last_error()
448        );
449        capture.close()?;
450        playback.close()?;
451        let retirement = dac.retirement();
452        dac.close()?;
453        assert!(retirement.wait(Duration::from_secs(3)));
454        assert_eq!(alt(fd)?, 0);
455        for interface in [3, 2, 1, 0] {
456            claim(fd, interface, false)?;
457        }
458        println!("USBIP_LIFECYCLE_PASS mode=duplex retired=true");
459        Ok(())
460    }
461    fn retire(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
462        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
463        let playback =
464            dac.open_stream(&format, Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")))?;
465        let pcm = test_pcm();
466        for _ in 0..3 {
467            playback.write(&pcm)?;
468        }
469        playback.play()?;
470        let start = Instant::now();
471        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() == 0 {
472            feed(&playback, &pcm)?;
473            thread::sleep(Duration::from_millis(5));
474        }
475        assert!(playback.played_frames() > 0, "playback never completed");
476        let token = dac.retirement();
477        vendor(fd, 1)?;
478        let status = wait_status(fd, 2)?;
479        println!("RETIRE_HELD status={status:#04x}");
480        let start = Instant::now();
481        let result = dac.close();
482        let elapsed = start.elapsed();
483        println!(
484            "RETIRE_CLOSE result={result:?} elapsed_ms={}",
485            elapsed.as_millis()
486        );
487        assert!(
488            matches!(result, Err(Error::Transfer(_))),
489            "close must report timeout: {result:?}"
490        );
491        assert!(
492            elapsed >= Duration::from_millis(2500),
493            "close returned before its actual timeout: {elapsed:?}"
494        );
495        assert!(
496            !token.wait(Duration::ZERO),
497            "owner retired while URB unlink was held"
498        );
499        let status: u8 = out_of_band("status")?.parse()?;
500        assert_eq!(
501            status & 0x14,
502            0x14,
503            "unlink must be held and AS1 active: {status:#04x}"
504        );
505        println!("RETIRE_PENDING elapsed_ms={}", elapsed.as_millis());
506        out_of_band("release")?;
507        assert!(
508            token.wait(Duration::from_secs(10)),
509            "owner did not retire after unlink release"
510        );
511        assert_eq!(alt(fd)?, 0, "retired owner did not restore alt zero");
512        drop(playback);
513        for interface in [1, 0] {
514            claim(fd, interface, false)?;
515        }
516        println!("USBIP_LIFECYCLE_PASS mode=retire retired=true alt=0");
517        Ok(())
518    }
519
520    fn reconfigure(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
521        use usbdac_core::StreamState;
522        let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
523        let initial = dac.negotiate(&StreamRequest::pcm(96_000, 2, 16))?;
524        assert_eq!(
525            (
526                initial.sample_rate,
527                initial.interface_number,
528                initial.alt_setting
529            ),
530            (96_000, 1, 1)
531        );
532        let previous = dac.open_stream(&initial, listener.clone())?;
533        let pcm = test_pcm();
534        for _ in 0..3 {
535            previous.write(&pcm)?;
536        }
537        previous.play()?;
538        let start = Instant::now();
539        while start.elapsed() < Duration::from_secs(5) && previous.played_frames() == 0 {
540            feed(&previous, &pcm)?;
541            thread::sleep(Duration::from_millis(5));
542        }
543        assert!(
544            previous.played_frames() > 0,
545            "original playback never completed"
546        );
547        out_of_band("reset")?;
548        println!("RECONFIGURE_PHASE_BEGIN from=96000 to=48000");
549        let request = StreamRequest::pcm(48_000, 2, 16);
550        let replacement = dac.reconfigure_stream_candidates(
551            &previous,
552            &[request],
553            listener,
554            Duration::from_secs(3),
555        )?;
556        println!("RECONFIGURE_PHASE_END from=96000 to=48000");
557        assert!(
558            replacement.rollback_cause.is_none(),
559            "unexpected rollback: {:?}",
560            replacement.rollback_cause
561        );
562        assert_eq!(previous.state(), StreamState::Closed);
563        assert_eq!(replacement.stream.state(), StreamState::Paused);
564        assert_eq!(replacement.stream.format().sample_rate, 48_000);
565        assert_eq!(replacement.stream.played_frames(), 0);
566        assert_eq!(alt(fd)?, 1);
567        let transitions = out_of_band("snapshot")?;
568        let alt_history = transitions
569            .split("alts=[")
570            .nth(1)
571            .ok_or("missing alternate history")?
572            .split(']')
573            .next()
574            .ok_or("missing alternate terminator")?;
575        let unlink_count: u64 = transitions
576            .split("unlinks=")
577            .nth(1)
578            .ok_or("missing unlink count")?
579            .parse()?;
580        assert!(
581            unlink_count <= 16,
582            "more than one bounded transfer set cancelled: {transitions}"
583        );
584        let mut alts: Vec<_> = alt_history.split(", ").collect();
585        alts.dedup();
586        assert_eq!(
587            alts,
588            ["0", "1"],
589            "unexpected alternate transitions: {transitions}"
590        );
591        // USB-level count of the live 96 -> 48 kHz replacement on interface 1 and
592        // clock 16. ALSA's UAC2 prepare deselects the alternate first, writes the
593        // rate, and enables the alternate last (sound/usb/endpoint.c
594        // snd_usb_endpoint_prepare:1498-1530, endpoint_set_interface:917-951).
595        // ALSA elides a SET_INTERFACE to the alternate it already holds
596        // (endpoint.c:926-927); usbdac re-asserts alt 0 at stop, before and after
597        // the read-only negotiation and before activation, which is idempotent.
598        let sequence = out_of_band("sequence")?;
599        let writes: Vec<_> = sequence
600            .strip_prefix("seq=[")
601            .and_then(|rest| rest.strip_suffix(']'))
602            .ok_or("missing write sequence")?
603            .split(", ")
604            .collect();
605        let count = |w: &str| writes.iter().filter(|x| **x == w).count();
606        assert_eq!(
607            (
608                count("alt0"),
609                count("alt1"),
610                count("rate48000"),
611                writes.len()
612            ),
613            (4, 1, 2, 7),
614            "unexpected replacement write counts: {sequence}"
615        );
616        assert_eq!(
617            writes.first(),
618            Some(&"alt0"),
619            "old alternate not deselected first: {sequence}"
620        );
621        assert_eq!(
622            writes.last(),
623            Some(&"alt1"),
624            "alternate not enabled last: {sequence}"
625        );
626        assert!(
627            !writes
628                .iter()
629                .any(|w| w.starts_with("rate") && *w != "rate48000"),
630            "a rate other than 48 kHz was written: {sequence}"
631        );
632        // Fresh post-replacement evidence: the DAC's clock reads back 48 kHz at alt 1.
633        let mut current = [0u8; 4];
634        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
635        assert_eq!(u32::from_le_bytes(current), 48_000);
636        println!(
637            "RECONFIGURE_USB_WRITES {sequence} clock_readback=48000 alt={}",
638            alt(fd)?
639        );
640        let stream = replacement.stream;
641        for _ in 0..3 {
642            stream.write(&pcm)?;
643        }
644        stream.play()?;
645        let start = Instant::now();
646        while start.elapsed() < Duration::from_secs(5)
647            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
648        {
649            feed(&stream, &pcm)?;
650            thread::sleep(Duration::from_millis(5));
651        }
652        assert!(
653            stream.played_frames() > 0 && stream.stats().completed_transfers > 0,
654            "replacement playback never completed"
655        );
656        let stats = stream.stats();
657        assert!(stats.played_frames <= stats.frames_written);
658        assert!(stats.queued_frames <= stats.frames_written);
659        assert!(
660            stats.underruns <= 50,
661            "USB/IP replacement exceeded 50 underruns: {stats:?}"
662        );
663        let mut current = [0u8; 4];
664        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
665        assert_eq!(
666            u32::from_le_bytes(current),
667            48_000,
668            "clock drifted during replacement playback"
669        );
670        let fixture_stats = out_of_band("snapshot")?;
671        assert!(
672            !fixture_stats.contains("out_completions=0"),
673            "replacement has no completed OUT URB: {fixture_stats}"
674        );
675        println!(
676            "RECONFIGURE_PLAYBACK_PASS stats={stats:?} underrun_limit=50 fixture={fixture_stats}"
677        );
678        stream.close()?;
679        let retirement = dac.retirement();
680        dac.close()?;
681        assert!(retirement.wait(Duration::from_secs(3)));
682        assert_eq!(alt(fd)?, 0);
683        for interface in [1, 0] {
684            claim(fd, interface, false)?;
685        }
686        println!("USBIP_LIFECYCLE_PASS mode=reconfigure retired=true alt=0");
687        Ok(())
688    }
689
690    /// DoP resolution through the production resolve_playback, transport and
691    /// PlaybackStream. DoP v1.1 carries 16 DSD bits per channel per carrier frame,
692    /// so a DoP carrier of another depth or channel count is a repack (H1), and an
693    /// exact DoP shape absent from the descriptors is never attempted (H2).
694    fn dop_resolution(dac: Dac, fd: i32, mode: &str) -> Result<(), Box<dyn std::error::Error>> {
695        use usbdac_core::playback::{PlaybackFidelity, PlaybackPolicy, PlaybackTransform};
696        use usbdac_core::Encoding;
697        let confirmed = PlaybackPolicy {
698            dop_confirmed: true,
699            ..PlaybackPolicy::default()
700        };
701        let caps = dac.capabilities()?;
702        assert!(
703            caps.exclusion_snapshot_complete,
704            "the fixture descriptor snapshot must be complete"
705        );
706        let source = StreamRequest::dop(2_822_400, if mode == "dop-stereo24" { 1 } else { 2 });
707        if mode == "dop-carrier32" {
708            // H2: 24-bit DoP on a 32-bit-only DAC reaches the 32-bit carrier.
709            let widened = dac.resolve_playback(&source, &confirmed)?;
710            println!(
711                "DOP_DECISION mode={mode} case=widen transform={:?} fidelity={:?} bits={} preflight={:?}",
712                widened.transform, widened.fidelity, widened.format.valid_bits, widened.source_preflight_refusal
713            );
714            assert!(widened.source_preflight_refusal.is_some());
715            assert_eq!(widened.format.encoding, Encoding::DoP);
716            assert_eq!(widened.format.valid_bits, 32);
717            assert_eq!(
718                widened.transform,
719                PlaybackTransform::DopRepack { target_channels: 2 }
720            );
721        }
722        let policy = if mode == "dop-carrier32" {
723            // H1: the review's smallest case.
724            PlaybackPolicy {
725                allowed_pcm_depths: Some(vec![32]),
726                ..confirmed.clone()
727            }
728        } else {
729            confirmed.clone()
730        };
731        out_of_band("reset")?;
732        let decision = dac.resolve_playback(&source, &policy)?;
733        println!(
734            "DOP_DECISION mode={mode} transform={:?} fidelity={:?} format={:?}/{}ch/{}bit preflight={:?} attempted={}",
735            decision.transform,
736            decision.fidelity,
737            decision.format.encoding,
738            decision.format.channels,
739            decision.format.valid_bits,
740            decision.source_preflight_refusal,
741            decision.attempted_candidates
742        );
743        if mode == "dop-no-carrier" {
744            // H2: confirmed DoP on a DAC that cannot carry it falls back like unconfirmed.
745            assert!(decision.source_preflight_refusal.is_some());
746            assert_eq!(decision.format.encoding, Encoding::Pcm);
747            assert!(matches!(
748                decision.transform,
749                PlaybackTransform::DsdToPcm {
750                    dop_input: true,
751                    ..
752                }
753            ));
754            let unconfirmed = dac.resolve_playback(&source, &PlaybackPolicy::default())?;
755            assert_eq!(unconfirmed.format, decision.format);
756        } else {
757            assert_eq!(decision.format.encoding, Encoding::DoP);
758            assert_eq!(decision.format.channels, 2);
759            assert_eq!(
760                decision.transform,
761                PlaybackTransform::DopRepack { target_channels: 2 }
762            );
763            assert_eq!(
764                decision.fidelity,
765                if source.channels == 2 {
766                    PlaybackFidelity::BitExact
767                } else {
768                    PlaybackFidelity::Lossless
769                }
770            );
771            assert_eq!(decision.attempted_candidates, 1);
772        }
773        let mut stream = dac.open_playback(&decision, Arc::new(|_| {}))?;
774        let channels = usize::from(source.channels);
775        let frame = decision.source_frame_bytes;
776        let mut next = 0usize;
777        let mut chunk = Vec::new();
778        let start = Instant::now();
779        let mut started = false;
780        while start.elapsed() < Duration::from_secs(3)
781            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
782        {
783            let frames = stream.writable_bytes() / frame;
784            if frames > 0 {
785                chunk.clear();
786                for i in next..next + frames {
787                    let marker = if i % 2 == 0 { 0x05 } else { 0xfa };
788                    for _ in 0..channels {
789                        chunk.extend_from_slice(&[0x69, 0x69, marker]);
790                    }
791                }
792                next += stream.write(&chunk)? / frame;
793            }
794            if !started && next > 0 {
795                stream.play()?;
796                started = true;
797            }
798            thread::sleep(Duration::from_millis(2));
799        }
800        let stats = stream.target_stats();
801        let snapshot = out_of_band("snapshot")?;
802        println!("DOP_STATS mode={mode} source_frames={next} {stats:?} {snapshot}");
803        assert!(
804            stats.played_frames > 0 && stats.completed_transfers > 0,
805            "no DoP-resolved completions"
806        );
807        let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
808        let carrier_set = rates
809            .split(|c: char| !c.is_ascii_digit())
810            .any(|v| v == "176400");
811        // The carrier DACs clock 176.4 kHz; the exact carrier is never set on a DAC without one.
812        assert_eq!(carrier_set, mode != "dop-no-carrier", "{snapshot}");
813        if mode != "dop-no-carrier" {
814            assert!(stats.payload_verified, "the DoP payload must audit clean");
815        }
816        stream.close()?;
817        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
818        let retirement = dac.retirement();
819        dac.close()?;
820        assert!(retirement.wait(Duration::from_secs(3)));
821        assert_eq!(alt(fd)?, 0);
822        for interface in [1, 0] {
823            claim(fd, interface, false)?;
824        }
825        println!("USBIP_LIFECYCLE_PASS mode={mode} alt=0 retired=true");
826        Ok(())
827    }
828
829    pub fn run() -> Result<(), Box<dyn std::error::Error>> {
830        let args: Vec<_> = std::env::args().collect();
831        if args.len() != 3
832            || !matches!(
833                args[2].as_str(),
834                "normal"
835                    | "bad-cur"
836                    | "stale-cur"
837                    | "badd"
838                    | "full-uac3"
839                    | "full-uac3-volatile"
840                    | "full-uac3-clock"
841                    | "full-uac3-clock-bad"
842                    | "full-uac3-clock-stale"
843                    | "duplex"
844                    | "retire"
845                    | "reconfigure"
846                    | "selector"
847                    | "refuse-set"
848                    | "zero-res"
849                    | "full-uac3-nearest"
850                    | "dop-carrier32"
851                    | "dop-stereo24"
852                    | "dop-no-carrier"
853            )
854        {
855            return Err(
856                "usage: usbip_lifecycle /dev/bus/usb/BBB/DDD normal|bad-cur|stale-cur|badd|full-uac3|full-uac3-clock|duplex|retire|reconfigure".into(),
857            );
858        }
859        let path = &args[1];
860        if !path.starts_with("/dev/bus/usb/") {
861            return Err("expected a usbfs device path".into());
862        }
863        let file = OpenOptions::new().read(true).write(true).open(path)?;
864        let fd = file.as_raw_fd();
865        // Read and validate the actual descriptor before claiming or invoking the driver.
866        let mut descriptor = [0u8; 18];
867        assert_eq!(control(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?, 18);
868        assert_eq!((descriptor[0], descriptor[1]), (18, 1));
869        assert_eq!(
870            (
871                u16::from_le_bytes([descriptor[8], descriptor[9]]),
872                u16::from_le_bytes([descriptor[10], descriptor[11]])
873            ),
874            (VID, PID),
875            "refusing a device other than the fixture"
876        );
877        // Select the explicitly advertised fixture configuration before interface claims.
878        let configuration = match args[2].as_str() {
879            "badd" => 2u32,
880            "full-uac3"
881            | "full-uac3-volatile"
882            | "full-uac3-clock"
883            | "full-uac3-clock-bad"
884            | "full-uac3-clock-stale"
885            | "full-uac3-nearest" => 3,
886            _ => 1,
887        };
888        if configuration != 1 {
889            let mut config_descriptor = [0u8; 9];
890            assert_eq!(
891                control(
892                    fd,
893                    0x80,
894                    6,
895                    0x0200 | (configuration as u16 - 1),
896                    0,
897                    &mut config_descriptor
898                )?,
899                9
900            );
901            assert_eq!(
902                (
903                    config_descriptor[0],
904                    config_descriptor[1],
905                    config_descriptor[5]
906                ),
907                (9, 2, configuration as u8)
908            );
909            if unsafe { libc::ioctl(fd, 0x80045505u32 as _, &configuration) } != 0 {
910                return Err(std::io::Error::last_os_error().into());
911            }
912        }
913        let claims = if args[2] == "duplex" {
914            vec![0u8, 1, 2, 3]
915        } else {
916            vec![0u8, 1]
917        };
918        for &interface in &claims {
919            claim(fd, u32::from(interface), true)?;
920        }
921        assert_eq!(alt(fd)?, 0);
922        if matches!(
923            args[2].as_str(),
924            "badd" | "full-uac3" | "full-uac3-volatile"
925        ) {
926            assert_eq!(power(fd)?, 0, "power domain must initially be D0");
927            let mut state = [2u8];
928            assert_eq!(control(fd, 0x21, 1, 0x0200, 0x0a00, &mut state)?, 1);
929            assert_eq!(power(fd)?, 2, "failed to seed D2 baseline");
930        }
931        let mut info = DeviceInfo::new(VID, PID, "USB/IP audio fixture")
932            .with_claimed_interfaces(claims)
933            .with_device_name(path);
934        info.configuration_id = Some(configuration as u8);
935        let config = DacConfig {
936            require_hardware_volume: false,
937            require_verified_rate: true,
938            ..DacConfig::default()
939        };
940        let dac = if args[2] == "duplex" {
941            Dac::open_duplex_device(fd, info, config)?
942        } else {
943            Dac::open(fd, info, config)?
944        };
945        if args[2] == "duplex" {
946            return duplex(dac, fd);
947        }
948        if args[2] == "retire" {
949            return retire(dac, fd);
950        }
951        if args[2] == "reconfigure" {
952            return reconfigure(dac, fd);
953        }
954        if args[2].starts_with("dop-") {
955            return dop_resolution(dac, fd, &args[2]);
956        }
957        let caps = dac.capabilities()?;
958        if args[2] == "refuse-set" {
959            out_of_band("reset")?;
960            let requests = [
961                StreamRequest::pcm(96_000, 2, 16),
962                StreamRequest::pcm(48_000, 2, 16),
963            ];
964            let failure = dac.negotiate_candidates(&requests);
965            assert!(
966                matches!(
967                    failure,
968                    Err(Error::ClockUnverified {
969                        requested_hz: 96_000,
970                        ..
971                    })
972                ),
973                "refused SET must be terminal: {failure:?}"
974            );
975            let snapshot = out_of_band("snapshot")?;
976            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
977            assert!(rates.contains("96000"));
978            assert!(
979                !rates.contains("48000"),
980                "second candidate was tried after uncertain SET: {snapshot}"
981            );
982            let retirement = dac.retirement();
983            dac.close()?;
984            assert!(retirement.wait(Duration::from_secs(3)));
985            assert_eq!(alt(fd)?, 0);
986            for interface in [1, 0] {
987                claim(fd, interface, false)?;
988            }
989            println!("USBIP_LIFECYCLE_PASS mode=refuse-set snapshot={snapshot}");
990            return Ok(());
991        }
992        if matches!(args[2].as_str(), "selector" | "zero-res") {
993            let (requested, expected) = if args[2] == "selector" {
994                (192_000, 96_000)
995            } else {
996                (96_000, 44_100)
997            };
998            out_of_band("reset")?;
999            let request =
1000                StreamRequest::pcm(requested, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1001            let format = dac.negotiate(&request)?;
1002            assert_eq!(format.sample_rate, expected);
1003            let stream = dac.open_stream(&format, Arc::new(|_| {}))?;
1004            let snapshot = out_of_band("snapshot")?;
1005            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
1006            let rejected = requested.to_string();
1007            assert!(
1008                !rates
1009                    .split(|c: char| !c.is_ascii_digit())
1010                    .any(|v| v == rejected),
1011                "requested unsupported rate was sent: {snapshot}"
1012            );
1013            println!(
1014                "NEGOTIATE_CASE mode={} requested={requested} actual={expected} {snapshot}",
1015                args[2]
1016            );
1017            stream.close()?;
1018            let retirement = dac.retirement();
1019            dac.close()?;
1020            assert!(retirement.wait(Duration::from_secs(3)));
1021            assert_eq!(alt(fd)?, 0);
1022            for interface in [1, 0] {
1023                claim(fd, interface, false)?;
1024            }
1025            println!("USBIP_LIFECYCLE_PASS mode={} retired=true", args[2]);
1026            return Ok(());
1027        }
1028        if args[2] == "badd" {
1029            badd(&dac, fd, &caps)?;
1030            assert_eq!(alt(fd)?, 0);
1031            dac.close()?;
1032            assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
1033            assert_eq!(alt(fd)?, 0);
1034            assert_eq!(power(fd)?, 2, "BADD must restore D2");
1035            let power_log = out_of_band("snapshot")?;
1036            let powers = power_log
1037                .split("power=[")
1038                .nth(1)
1039                .ok_or("missing power history")?
1040                .split(']')
1041                .next()
1042                .ok_or("missing power terminator")?;
1043            assert!(
1044                powers
1045                    .split(", ")
1046                    .collect::<Vec<_>>()
1047                    .windows(2)
1048                    .any(|pair| pair == ["0", "2"]),
1049                "expected D0 to D2 transition: {power_log}"
1050            );
1051            for interface in [1, 0] {
1052                claim(fd, interface, false)?;
1053            }
1054            println!("USBIP_LIFECYCLE_PASS mode=badd alt=0 retired=true");
1055            return Ok(());
1056        }
1057        if args[2] == "full-uac3-nearest" {
1058            return full_uac3_nearest(dac, fd, &caps);
1059        }
1060        if matches!(args[2].as_str(), "full-uac3" | "full-uac3-volatile") {
1061            return full_uac3(dac, fd, &caps, args[2] == "full-uac3-volatile");
1062        }
1063        assert_eq!(
1064            caps.uac_version,
1065            if args[2].starts_with("full-uac3-clock") {
1066                UacVersion::V3
1067            } else {
1068                UacVersion::V2
1069            }
1070        );
1071        assert_eq!(caps.link_speed, LinkSpeed::High);
1072        let mut rates = caps.pcm_sample_rates.clone();
1073        rates.sort_unstable();
1074        rates.dedup();
1075        assert_eq!(rates, [48_000, 96_000], "unexpected fixture rates");
1076        assert!(
1077            matches!(
1078                dac.negotiate(&StreamRequest::pcm(192_000, 2, 16)),
1079                Err(Error::Unsupported { .. })
1080            ),
1081            "exact 192 kHz must be refused"
1082        );
1083        let request =
1084            StreamRequest::pcm(192_000, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1085        let format = dac.negotiate(&request)?;
1086        assert_eq!(
1087            (
1088                format.sample_rate,
1089                format.channels,
1090                format.valid_bits,
1091                format.subslot_bytes,
1092                format.interface_number,
1093                format.alt_setting
1094            ),
1095            (96_000, 2, 16, 2, 1, 1)
1096        );
1097        assert_eq!(format.sync_type, SyncKind::Synchronous);
1098        assert_eq!(format.endpoint_address, 0x01);
1099        assert_eq!(format.link_speed, LinkSpeed::High);
1100        assert_eq!(format.bytes_per_frame(), 4);
1101        if args[2].starts_with("full-uac3-clock") {
1102            assert_eq!(format.service_interval_us, 125);
1103            assert!(!format.explicit_feedback);
1104        }
1105        let clock = format
1106            .clock
1107            .as_ref()
1108            .ok_or("fixture clock missing")?
1109            .clone();
1110        assert_eq!(
1111            (clock.control_interface, clock.source_id),
1112            (
1113                0,
1114                if args[2].starts_with("full-uac3-clock") {
1115                    9
1116                } else {
1117                    0x10
1118                }
1119            )
1120        );
1121        println!("NEGOTIATED exact192=unsupported nearest192=96000 format={format:?}");
1122        let listener = Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}"));
1123        match args[2].as_str() {
1124            "normal" | "full-uac3-clock" => {
1125                let stream = dac.open_stream(&format, listener)?;
1126                assert_eq!(alt(fd)?, 1);
1127                let mut current = [0u8; 4];
1128                assert_eq!(
1129                    control(
1130                        fd,
1131                        0xa1,
1132                        1,
1133                        0x0100,
1134                        (u16::from(clock.source_id) << 8) | u16::from(clock.control_interface),
1135                        &mut current
1136                    )?,
1137                    4
1138                );
1139                assert_eq!(
1140                    u32::from_le_bytes(current),
1141                    96_000,
1142                    "post-alt clock readback"
1143                );
1144                let mut pcm = Vec::with_capacity(9600 * 4);
1145                for i in 0..9600i32 {
1146                    let v = (((i % 96) - 48) * 20) as i16;
1147                    pcm.extend_from_slice(&v.to_le_bytes());
1148                    pcm.extend_from_slice(&(-v).to_le_bytes());
1149                }
1150                for _ in 0..3 {
1151                    stream.write(&pcm)?;
1152                }
1153                stream.play()?;
1154                let start = Instant::now();
1155                while start.elapsed() < Duration::from_secs(3)
1156                    && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
1157                {
1158                    let n = stream.writable_bytes().min(pcm.len());
1159                    if n >= 4 {
1160                        stream.write(&pcm[..n - n % 4])?;
1161                    }
1162                    thread::sleep(Duration::from_millis(2));
1163                }
1164                let stats = stream.stats();
1165                println!("PCM_STATS {stats:?}");
1166                assert!(
1167                    stats.played_frames > 0 && stats.completed_transfers > 0,
1168                    "no actual PCM completions"
1169                );
1170                stream.close()?;
1171            }
1172            mode => match dac.open_stream(&format, listener) {
1173                Err(error @ Error::ClockUnverified { .. }) => {
1174                    let expected_reported = if mode == "bad-cur" || mode == "full-uac3-clock-bad" {
1175                        None
1176                    } else {
1177                        Some(48_000)
1178                    };
1179                    assert!(
1180                        matches!(error, Error::ClockUnverified { requested_hz: 96_000, reported_hz } if reported_hz == expected_reported)
1181                    );
1182                    println!(
1183                        "EXPECTED_FAILURE mode={mode} code={} error={error:?}",
1184                        error.code()
1185                    );
1186                }
1187                Err(error) => {
1188                    return Err(format!("unexpected failure for {mode}: {error:?}").into())
1189                }
1190                Ok(stream) => {
1191                    stream.close()?;
1192                    return Err(format!("{mode} incorrectly admitted the stream").into());
1193                }
1194            },
1195        }
1196        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
1197        dac.close()?;
1198        assert!(
1199            Dac::await_usb_retirement(Duration::from_secs(3)),
1200            "USB retirement timed out"
1201        );
1202        assert_eq!(alt(fd)?, 0);
1203        for interface in [1, 0] {
1204            claim(fd, interface, false)?;
1205        }
1206        println!("USBIP_LIFECYCLE_PASS mode={} alt=0 retired=true", args[2]);
1207        Ok(())
1208    }
examples/qemu_smoke.rs (line 130)
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 pause(&self) -> Result<()>

Holds the stream: wire-correct silence goes out (zero for PCM, the idle pattern for DSD, DoP markers keep alternating) so the DAC stays locked, and the ring is not consumed. Audio already submitted to the bus (about DacConfig::bus_queue_ms, 16 ms by default, at every service interval) still plays out first; the ring resumes exactly where it was.

Examples found in repository?
examples/pull_adapter.rs (line 79)
78    fn pause(&self) -> Result<()> {
79        self.stream.pause()
80    }
More examples
Hide additional examples
examples/guide_player.rs (line 89)
88    fn pause(&self) -> Result<()> {
89        DacStream::pause(self)
90    }
examples/qemu_smoke.rs (line 148)
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 flush(&self) -> Result<()>

Drops everything queued in the ring and resets played_frames to 0. The stream holds wire silence until the ring holds the start threshold again. Also clears drain, so the stream can be reused.

Returns at once. With DacConfig::cancel_in_flight_on_flush (the default) the output thread then cancels the transfers already on the bus, within about one transfer (2 ms), waits for every one to be handed back and refills the slots with silence; those transfers are not lost audio, not underruns and not counted as played. Off, or when only silence is queued (a flush while paused), the queue plays out (DacConfig::bus_queue_ms, 16 ms by default) and is not counted as played.

Examples found in repository?
examples/guide_player.rs (line 92)
91    fn flush(&self) -> Result<()> {
92        DacStream::flush(self)
93    }
More examples
Hide additional examples
examples/pull_adapter.rs (line 97)
90    fn seek(&self, seconds: f64) -> Result<()> {
91        let mut state = lock(&self.state);
92        state.source.seek(seconds);
93        state.chunk.clear();
94        state.taken = 0;
95        state.ended = false;
96        state.base_seconds = seconds;
97        self.stream.flush()
98    }
Source

pub fn drain(&self) -> Result<()>

Declares that no more audio will be written: the ring plays out, even a tail shorter than the start threshold, and the stream then reports is_drained and the Drained state. The padded tail is not an underrun. Further writes fail until flush.

Examples found in repository?
examples/guide_player.rs (line 95)
94    fn drain(&self) -> Result<()> {
95        DacStream::drain(self)
96    }
More examples
Hide additional examples
examples/pull_adapter.rs (line 146)
123fn write_loop(stream: &DacStream, state: &Mutex<State>, stop: &AtomicBool) {
124    let frame = stream.format().bytes_per_frame();
125    // About 10 ms per render call.
126    let chunk_frames = (stream.format().sample_rate as usize / 100).max(1);
127    let mut scratch = vec![0u8; chunk_frames * frame];
128    while !stop.load(Ordering::Acquire) {
129        let mut state = lock(state);
130        if state.ended {
131            drop(state);
132            thread::sleep(Duration::from_millis(10));
133            continue;
134        }
135        // Render only when the ring wants more, so the decoder is never ahead of
136        // the configured buffer depth (and a seek never has much to throw away).
137        if state.taken == state.chunk.len() {
138            if stream.writable_bytes() < scratch.len() {
139                drop(state);
140                thread::sleep(Duration::from_millis(2));
141                continue;
142            }
143            let rendered = state.source.render(&mut scratch);
144            if rendered == 0 {
145                // No more audio: let the ring play out, even a short tail.
146                if stream.drain().is_ok() {
147                    state.ended = true;
148                }
149                continue;
150            }
151            state.chunk.clear();
152            state.chunk.extend_from_slice(&scratch[..rendered]);
153            state.taken = 0;
154        }
155        match stream.write(&state.chunk[state.taken..]) {
156            Ok(0) => {
157                drop(state);
158                thread::sleep(Duration::from_millis(2));
159            }
160            Ok(taken) => state.taken += taken,
161            Err(error) => {
162                // The stream closed or failed; the listener has the details.
163                eprintln!("writer stopping: {error}");
164                return;
165            }
166        }
167    }
168}
Source

pub fn is_drained(&self) -> bool

drain() was called and everything written has been played.

Examples found in repository?
examples/guide_player.rs (line 98)
97    fn is_drained(&self) -> bool {
98        DacStream::is_drained(self)
99    }
More examples
Hide additional examples
examples/pull_adapter.rs (line 110)
109    fn finished(&self) -> bool {
110        lock(&self.state).ended && self.stream.is_drained()
111    }
Source

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

Closes the stream and waits for the output thread. The DAC stays open.

Examples found in repository?
examples/guide_player.rs (line 384)
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 135)
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/usbip_lifecycle.rs (line 144)
79    fn badd(
80        dac: &Dac,
81        fd: i32,
82        caps: &usbdac_core::Capabilities,
83    ) -> Result<(), Box<dyn std::error::Error>> {
84        assert_eq!(caps.uac_version, UacVersion::V3);
85        assert_eq!(caps.link_speed, LinkSpeed::High);
86        assert_eq!(caps.pcm_sample_rates, [48_000]);
87        assert!(matches!(
88            dac.negotiate(&StreamRequest::pcm(96_000, 2, 16)),
89            Err(Error::Unsupported { .. })
90        ));
91        let format = dac.negotiate(
92            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
93        )?;
94        assert_eq!(
95            (
96                format.sample_rate,
97                format.channels,
98                format.valid_bits,
99                format.subslot_bytes,
100                format.interface_number,
101                format.alt_setting,
102                format.endpoint_address
103            ),
104            (48_000, 2, 16, 2, 1, 1, 1)
105        );
106        assert!(
107            format.explicit_feedback,
108            "BADD profile must expose feedback"
109        );
110        println!("BADD_FORMAT {format:?}");
111        let stream = dac.open_stream(
112            &format,
113            Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}")),
114        )?;
115        assert_eq!(alt(fd)?, 1);
116        let mut pcm = Vec::with_capacity(4800 * 4);
117        for i in 0..4800i32 {
118            let v = (((i % 96) - 48) * 20) as i16;
119            pcm.extend_from_slice(&v.to_le_bytes());
120            pcm.extend_from_slice(&(-v).to_le_bytes());
121        }
122        for _ in 0..3 {
123            stream.write(&pcm)?;
124        }
125        stream.play()?;
126        let start = Instant::now();
127        while start.elapsed() < Duration::from_secs(3)
128            && (stream.played_frames() == 0
129                || stream.stats().completed_transfers == 0
130                || stream.stats().feedback_reports == 0)
131        {
132            let n = stream.writable_bytes().min(pcm.len());
133            if n >= 4 {
134                stream.write(&pcm[..n - n % 4])?;
135            }
136            thread::sleep(Duration::from_millis(2));
137        }
138        let stats = stream.stats();
139        println!("BADD_PCM_STATS {stats:?}");
140        assert!(
141            stats.played_frames > 0 && stats.completed_transfers > 0 && stats.feedback_reports > 0,
142            "BADD playback or feedback has no real completions"
143        );
144        stream.close()?;
145        Ok(())
146    }
147
148    fn full_uac3(
149        dac: Dac,
150        fd: i32,
151        caps: &usbdac_core::Capabilities,
152        volatile: bool,
153    ) -> Result<(), Box<dyn std::error::Error>> {
154        use usbdac_core::routing::{
155            ControlKey, Entity, RouteEdit, RouteValue, RoutingHandBackOutcome,
156        };
157        assert_eq!(caps.uac_version, UacVersion::V3);
158        assert_eq!(caps.link_speed, LinkSpeed::High);
159        let key = ControlKey::Selector(Entity {
160            interface: 0,
161            id: 8,
162        });
163        assert_eq!(power(fd)?, 2, "initial power must be D2");
164        let snapshot = dac.routing_discover_powered()?;
165        println!("UAC3_ROUTING snapshot={snapshot:?}");
166        assert_eq!(snapshot.configuration(), 3);
167        assert_eq!(power(fd)?, 2, "discovery must restore D2");
168        assert_eq!(
169            dac.routing_read_powered(&snapshot, key)?,
170            RouteValue::SelectorPin(1)
171        );
172        assert_eq!(power(fd)?, 2, "read must restore D2");
173        let report = dac.routing_apply_powered(
174            &snapshot,
175            &[RouteEdit {
176                key,
177                expected: RouteValue::SelectorPin(1),
178                value: RouteValue::SelectorPin(2),
179            }],
180        )?;
181        assert_eq!(report.changed, vec![key]);
182        let applied = out_of_band("snapshot")?;
183        assert!(
184            applied.contains("selector=[2]"),
185            "fixture selector was not written: {applied}"
186        );
187        assert!(
188            applied.contains(if volatile {
189                "selector_state=1"
190            } else {
191                "selector_state=2"
192            }),
193            "unexpected fixture selector after D2: {applied}"
194        );
195        assert_eq!(power(fd)?, 2, "apply must restore D2");
196        let updated = dac.routing_discover_powered()?;
197        assert_eq!(
198            dac.routing_read_powered(&updated, key)?,
199            RouteValue::SelectorPin(if volatile { 1 } else { 2 }),
200            "selector readback must reflect the fixture's D2 behavior"
201        );
202        assert_eq!(power(fd)?, 2);
203        dac.close()?;
204        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
205        let hand_back = snapshot
206            .hand_back_report()
207            .ok_or("missing routing hand-back report")?;
208        println!("UAC3_HAND_BACK {hand_back:?}");
209        if !volatile {
210            assert!(
211                hand_back
212                    .controls
213                    .contains(&(key, RoutingHandBackOutcome::Restored)),
214                "selector hand-back was not verified"
215            );
216        }
217        assert_eq!(power(fd)?, 2, "final power must be D2");
218        assert!(
219            out_of_band("snapshot")?.contains("selector_state=1"),
220            "fixture selector was not restored"
221        );
222        assert_eq!(alt(fd)?, 0);
223        for interface in [1, 0] {
224            claim(fd, interface, false)?;
225        }
226        println!("USBIP_LIFECYCLE_PASS mode=full-uac3 selector=restored power=D2 retired=true");
227        Ok(())
228    }
229
230    // Full UAC3 whose clock RANGE lists only 48 kHz behind a powered route that
231    // cannot certify a live refusal. The cached model excludes 44.1 kHz, so the
232    // ranked loop and the playback candidates must skip it without any USB request,
233    // as ALSA never offers a rate absent from its format table (pcm.c hw_rule_rate).
234    fn full_uac3_nearest(
235        dac: Dac,
236        fd: i32,
237        caps: &usbdac_core::Capabilities,
238    ) -> Result<(), Box<dyn std::error::Error>> {
239        use usbdac_core::playback::PlaybackPolicy;
240        assert_eq!(caps.uac_version, UacVersion::V3);
241        assert_eq!(caps.link_speed, LinkSpeed::High);
242        let mut rates = caps.pcm_sample_rates.clone();
243        rates.sort_unstable();
244        rates.dedup();
245        assert_eq!(rates, [48_000], "unexpected full-UAC3 fixture rates");
246        let no_44k = |snapshot: &str| -> Result<(), Box<dyn std::error::Error>> {
247            let sets = snapshot.split(';').next().ok_or("missing rate snapshot")?;
248            if sets
249                .split(|c: char| !c.is_ascii_digit())
250                .any(|v| v == "44100")
251            {
252                return Err(format!("model-excluded 44100 Hz was programmed: {snapshot}").into());
253            }
254            Ok(())
255        };
256        out_of_band("reset")?;
257        let format = dac.negotiate(
258            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
259        )?;
260        assert_eq!(
261            (format.sample_rate, format.channels, format.valid_bits),
262            (48_000, 2, 16)
263        );
264        let negotiated = out_of_band("snapshot")?;
265        no_44k(&negotiated)?;
266        out_of_band("reset")?;
267        let decision = dac.resolve_playback(
268            &StreamRequest::pcm(44_100, 2, 16),
269            &PlaybackPolicy::default(),
270        )?;
271        assert_eq!(decision.format.sample_rate, 48_000);
272        assert_eq!(decision.candidates[0], StreamRequest::pcm(44_100, 2, 16));
273        assert!(
274            matches!(decision.exact_refusal, Some(Error::Unsupported { .. })),
275            "the skipped exact source must report a typed refusal: {:?}",
276            decision.exact_refusal
277        );
278        let resolved = out_of_band("snapshot")?;
279        no_44k(&resolved)?;
280        println!(
281            "NEGOTIATE_CASE mode=full-uac3-nearest requested=44100 actual=48000 resolve=48000 attempted={} negotiate={negotiated} resolve_snapshot={resolved}",
282            decision.attempted_candidates
283        );
284        assert_eq!(alt(fd)?, 0);
285        dac.close()?;
286        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
287        assert_eq!(alt(fd)?, 0);
288        for interface in [1, 0] {
289            claim(fd, interface, false)?;
290        }
291        println!("USBIP_LIFECYCLE_PASS mode=full-uac3-nearest retired=true");
292        Ok(())
293    }
294
295    fn vendor(fd: i32, value: u16) -> Result<(), Box<dyn std::error::Error>> {
296        assert_eq!(control(fd, 0x40, 0x5a, value, 0, &mut [])?, 0);
297        Ok(())
298    }
299    fn vendor_status(fd: i32) -> Result<u8, Box<dyn std::error::Error>> {
300        let mut status = [0u8];
301        assert_eq!(control(fd, 0xc0, 0x5a, 0, 0, &mut status)?, 1);
302        Ok(status[0])
303    }
304    fn out_of_band(action: &str) -> Result<String, Box<dyn std::error::Error>> {
305        let port = std::env::var("USBDAC_USBIP_PORT")?;
306        let _: u16 = port.parse()?;
307        let output = std::process::Command::new("/fixture/usbip_uac")
308            .args(["--control", action, "--port", &port])
309            .output()?;
310        if !output.status.success() {
311            return Err(format!(
312                "fixture control {action} failed: {}",
313                String::from_utf8_lossy(&output.stderr)
314            )
315            .into());
316        }
317        Ok(String::from_utf8(output.stdout)?.trim().to_string())
318    }
319    fn wait_status(fd: i32, mask: u8) -> Result<u8, Box<dyn std::error::Error>> {
320        let start = Instant::now();
321        loop {
322            let status = vendor_status(fd)?;
323            if status & mask == mask {
324                return Ok(status);
325            }
326            if start.elapsed() >= Duration::from_secs(5) {
327                return Err(
328                    format!("fixture status {status:#04x} did not reach {mask:#04x}").into(),
329                );
330            }
331            thread::sleep(Duration::from_millis(10));
332        }
333    }
334    fn test_pcm() -> Vec<u8> {
335        let mut pcm = Vec::with_capacity(4800 * 4);
336        for i in 0..4800i32 {
337            let v = (((i % 96) - 48) * 20) as i16;
338            pcm.extend_from_slice(&v.to_le_bytes());
339            pcm.extend_from_slice(&(-v).to_le_bytes());
340        }
341        pcm
342    }
343    fn feed(stream: &usbdac_core::DacStream, pcm: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
344        let n = stream.writable_bytes().min(pcm.len());
345        if n >= 4 {
346            stream.write(&pcm[..n - n % 4])?;
347        }
348        Ok(())
349    }
350    fn duplex(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
351        use usbdac_core::{CaptureRequest, CaptureState};
352        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
353        let request = CaptureRequest {
354            sample_rate: 48_000,
355            channels: 2,
356            valid_bits: 16,
357            channel_map: None,
358        };
359        let (playback, capture) = dac.open_duplex(
360            &format,
361            &request,
362            48_000,
363            Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")),
364        )?;
365        assert_eq!(
366            (capture.interface_number(), capture.endpoint_address()),
367            (3, 0x82)
368        );
369        let pcm = test_pcm();
370        for _ in 0..3 {
371            playback.write(&pcm)?;
372        }
373        playback.play()?;
374        let start = Instant::now();
375        let mut received = [0u8; 4096];
376        let mut marker_frames = 0;
377        while start.elapsed() < Duration::from_secs(5) && marker_frames == 0 {
378            feed(&playback, &pcm)?;
379            let frames = capture.read(&mut received)?;
380            if frames > 0 {
381                assert!(
382                    received[..frames * 4]
383                        .chunks_exact(4)
384                        .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
385                    "unexpected capture payload"
386                );
387                marker_frames = frames;
388            }
389            thread::sleep(Duration::from_millis(5));
390        }
391        assert!(marker_frames > 0, "no actual capture marker");
392        println!("DUPLEX_CAPTURE_MARKER frames={marker_frames}");
393        out_of_band("mixed")?;
394        let mixed_start = Instant::now();
395        while mixed_start.elapsed() < Duration::from_secs(5) {
396            feed(&playback, &pcm)?;
397            let frames = capture.read(&mut received)?;
398            assert!(
399                received[..frames * 4]
400                    .chunks_exact(4)
401                    .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
402                "invalid packet leaked into capture"
403            );
404            let stats = capture.stats();
405            if stats.short_packets > 0 && stats.failed_packets > 0 && stats.malformed_packets > 0 {
406                break;
407            }
408            thread::sleep(Duration::from_millis(5));
409        }
410        let mixed_stats = capture.stats();
411        assert!(
412            mixed_stats.short_packets > 0
413                && mixed_stats.failed_packets > 0
414                && mixed_stats.malformed_packets > 0,
415            "mixed packet statuses not observed: {mixed_stats:?}"
416        );
417        println!("DUPLEX_MIXED_PACKETS {mixed_stats:?}");
418        vendor(fd, 1)?;
419        let start = Instant::now();
420        while start.elapsed() < Duration::from_secs(5) && capture.state() == CaptureState::Active {
421            feed(&playback, &pcm)?;
422            thread::sleep(Duration::from_millis(5));
423        }
424        assert_eq!(capture.state(), CaptureState::Failed);
425        assert!(
426            capture.last_error().is_some(),
427            "capture failure must preserve an error"
428        );
429        assert_ne!(
430            vendor_status(fd)? & 8,
431            0,
432            "fixture did not deliver capture fault"
433        );
434        let before = playback.played_frames();
435        let start = Instant::now();
436        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() <= before {
437            feed(&playback, &pcm)?;
438            thread::sleep(Duration::from_millis(5));
439        }
440        let after = playback.played_frames();
441        assert!(
442            after > before,
443            "playback stopped after independent capture failure"
444        );
445        println!(
446            "DUPLEX_ISOLATION_PASS before={before} after={after} error={:?}",
447            capture.last_error()
448        );
449        capture.close()?;
450        playback.close()?;
451        let retirement = dac.retirement();
452        dac.close()?;
453        assert!(retirement.wait(Duration::from_secs(3)));
454        assert_eq!(alt(fd)?, 0);
455        for interface in [3, 2, 1, 0] {
456            claim(fd, interface, false)?;
457        }
458        println!("USBIP_LIFECYCLE_PASS mode=duplex retired=true");
459        Ok(())
460    }
461    fn retire(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
462        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
463        let playback =
464            dac.open_stream(&format, Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")))?;
465        let pcm = test_pcm();
466        for _ in 0..3 {
467            playback.write(&pcm)?;
468        }
469        playback.play()?;
470        let start = Instant::now();
471        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() == 0 {
472            feed(&playback, &pcm)?;
473            thread::sleep(Duration::from_millis(5));
474        }
475        assert!(playback.played_frames() > 0, "playback never completed");
476        let token = dac.retirement();
477        vendor(fd, 1)?;
478        let status = wait_status(fd, 2)?;
479        println!("RETIRE_HELD status={status:#04x}");
480        let start = Instant::now();
481        let result = dac.close();
482        let elapsed = start.elapsed();
483        println!(
484            "RETIRE_CLOSE result={result:?} elapsed_ms={}",
485            elapsed.as_millis()
486        );
487        assert!(
488            matches!(result, Err(Error::Transfer(_))),
489            "close must report timeout: {result:?}"
490        );
491        assert!(
492            elapsed >= Duration::from_millis(2500),
493            "close returned before its actual timeout: {elapsed:?}"
494        );
495        assert!(
496            !token.wait(Duration::ZERO),
497            "owner retired while URB unlink was held"
498        );
499        let status: u8 = out_of_band("status")?.parse()?;
500        assert_eq!(
501            status & 0x14,
502            0x14,
503            "unlink must be held and AS1 active: {status:#04x}"
504        );
505        println!("RETIRE_PENDING elapsed_ms={}", elapsed.as_millis());
506        out_of_band("release")?;
507        assert!(
508            token.wait(Duration::from_secs(10)),
509            "owner did not retire after unlink release"
510        );
511        assert_eq!(alt(fd)?, 0, "retired owner did not restore alt zero");
512        drop(playback);
513        for interface in [1, 0] {
514            claim(fd, interface, false)?;
515        }
516        println!("USBIP_LIFECYCLE_PASS mode=retire retired=true alt=0");
517        Ok(())
518    }
519
520    fn reconfigure(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
521        use usbdac_core::StreamState;
522        let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
523        let initial = dac.negotiate(&StreamRequest::pcm(96_000, 2, 16))?;
524        assert_eq!(
525            (
526                initial.sample_rate,
527                initial.interface_number,
528                initial.alt_setting
529            ),
530            (96_000, 1, 1)
531        );
532        let previous = dac.open_stream(&initial, listener.clone())?;
533        let pcm = test_pcm();
534        for _ in 0..3 {
535            previous.write(&pcm)?;
536        }
537        previous.play()?;
538        let start = Instant::now();
539        while start.elapsed() < Duration::from_secs(5) && previous.played_frames() == 0 {
540            feed(&previous, &pcm)?;
541            thread::sleep(Duration::from_millis(5));
542        }
543        assert!(
544            previous.played_frames() > 0,
545            "original playback never completed"
546        );
547        out_of_band("reset")?;
548        println!("RECONFIGURE_PHASE_BEGIN from=96000 to=48000");
549        let request = StreamRequest::pcm(48_000, 2, 16);
550        let replacement = dac.reconfigure_stream_candidates(
551            &previous,
552            &[request],
553            listener,
554            Duration::from_secs(3),
555        )?;
556        println!("RECONFIGURE_PHASE_END from=96000 to=48000");
557        assert!(
558            replacement.rollback_cause.is_none(),
559            "unexpected rollback: {:?}",
560            replacement.rollback_cause
561        );
562        assert_eq!(previous.state(), StreamState::Closed);
563        assert_eq!(replacement.stream.state(), StreamState::Paused);
564        assert_eq!(replacement.stream.format().sample_rate, 48_000);
565        assert_eq!(replacement.stream.played_frames(), 0);
566        assert_eq!(alt(fd)?, 1);
567        let transitions = out_of_band("snapshot")?;
568        let alt_history = transitions
569            .split("alts=[")
570            .nth(1)
571            .ok_or("missing alternate history")?
572            .split(']')
573            .next()
574            .ok_or("missing alternate terminator")?;
575        let unlink_count: u64 = transitions
576            .split("unlinks=")
577            .nth(1)
578            .ok_or("missing unlink count")?
579            .parse()?;
580        assert!(
581            unlink_count <= 16,
582            "more than one bounded transfer set cancelled: {transitions}"
583        );
584        let mut alts: Vec<_> = alt_history.split(", ").collect();
585        alts.dedup();
586        assert_eq!(
587            alts,
588            ["0", "1"],
589            "unexpected alternate transitions: {transitions}"
590        );
591        // USB-level count of the live 96 -> 48 kHz replacement on interface 1 and
592        // clock 16. ALSA's UAC2 prepare deselects the alternate first, writes the
593        // rate, and enables the alternate last (sound/usb/endpoint.c
594        // snd_usb_endpoint_prepare:1498-1530, endpoint_set_interface:917-951).
595        // ALSA elides a SET_INTERFACE to the alternate it already holds
596        // (endpoint.c:926-927); usbdac re-asserts alt 0 at stop, before and after
597        // the read-only negotiation and before activation, which is idempotent.
598        let sequence = out_of_band("sequence")?;
599        let writes: Vec<_> = sequence
600            .strip_prefix("seq=[")
601            .and_then(|rest| rest.strip_suffix(']'))
602            .ok_or("missing write sequence")?
603            .split(", ")
604            .collect();
605        let count = |w: &str| writes.iter().filter(|x| **x == w).count();
606        assert_eq!(
607            (
608                count("alt0"),
609                count("alt1"),
610                count("rate48000"),
611                writes.len()
612            ),
613            (4, 1, 2, 7),
614            "unexpected replacement write counts: {sequence}"
615        );
616        assert_eq!(
617            writes.first(),
618            Some(&"alt0"),
619            "old alternate not deselected first: {sequence}"
620        );
621        assert_eq!(
622            writes.last(),
623            Some(&"alt1"),
624            "alternate not enabled last: {sequence}"
625        );
626        assert!(
627            !writes
628                .iter()
629                .any(|w| w.starts_with("rate") && *w != "rate48000"),
630            "a rate other than 48 kHz was written: {sequence}"
631        );
632        // Fresh post-replacement evidence: the DAC's clock reads back 48 kHz at alt 1.
633        let mut current = [0u8; 4];
634        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
635        assert_eq!(u32::from_le_bytes(current), 48_000);
636        println!(
637            "RECONFIGURE_USB_WRITES {sequence} clock_readback=48000 alt={}",
638            alt(fd)?
639        );
640        let stream = replacement.stream;
641        for _ in 0..3 {
642            stream.write(&pcm)?;
643        }
644        stream.play()?;
645        let start = Instant::now();
646        while start.elapsed() < Duration::from_secs(5)
647            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
648        {
649            feed(&stream, &pcm)?;
650            thread::sleep(Duration::from_millis(5));
651        }
652        assert!(
653            stream.played_frames() > 0 && stream.stats().completed_transfers > 0,
654            "replacement playback never completed"
655        );
656        let stats = stream.stats();
657        assert!(stats.played_frames <= stats.frames_written);
658        assert!(stats.queued_frames <= stats.frames_written);
659        assert!(
660            stats.underruns <= 50,
661            "USB/IP replacement exceeded 50 underruns: {stats:?}"
662        );
663        let mut current = [0u8; 4];
664        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
665        assert_eq!(
666            u32::from_le_bytes(current),
667            48_000,
668            "clock drifted during replacement playback"
669        );
670        let fixture_stats = out_of_band("snapshot")?;
671        assert!(
672            !fixture_stats.contains("out_completions=0"),
673            "replacement has no completed OUT URB: {fixture_stats}"
674        );
675        println!(
676            "RECONFIGURE_PLAYBACK_PASS stats={stats:?} underrun_limit=50 fixture={fixture_stats}"
677        );
678        stream.close()?;
679        let retirement = dac.retirement();
680        dac.close()?;
681        assert!(retirement.wait(Duration::from_secs(3)));
682        assert_eq!(alt(fd)?, 0);
683        for interface in [1, 0] {
684            claim(fd, interface, false)?;
685        }
686        println!("USBIP_LIFECYCLE_PASS mode=reconfigure retired=true alt=0");
687        Ok(())
688    }
689
690    /// DoP resolution through the production resolve_playback, transport and
691    /// PlaybackStream. DoP v1.1 carries 16 DSD bits per channel per carrier frame,
692    /// so a DoP carrier of another depth or channel count is a repack (H1), and an
693    /// exact DoP shape absent from the descriptors is never attempted (H2).
694    fn dop_resolution(dac: Dac, fd: i32, mode: &str) -> Result<(), Box<dyn std::error::Error>> {
695        use usbdac_core::playback::{PlaybackFidelity, PlaybackPolicy, PlaybackTransform};
696        use usbdac_core::Encoding;
697        let confirmed = PlaybackPolicy {
698            dop_confirmed: true,
699            ..PlaybackPolicy::default()
700        };
701        let caps = dac.capabilities()?;
702        assert!(
703            caps.exclusion_snapshot_complete,
704            "the fixture descriptor snapshot must be complete"
705        );
706        let source = StreamRequest::dop(2_822_400, if mode == "dop-stereo24" { 1 } else { 2 });
707        if mode == "dop-carrier32" {
708            // H2: 24-bit DoP on a 32-bit-only DAC reaches the 32-bit carrier.
709            let widened = dac.resolve_playback(&source, &confirmed)?;
710            println!(
711                "DOP_DECISION mode={mode} case=widen transform={:?} fidelity={:?} bits={} preflight={:?}",
712                widened.transform, widened.fidelity, widened.format.valid_bits, widened.source_preflight_refusal
713            );
714            assert!(widened.source_preflight_refusal.is_some());
715            assert_eq!(widened.format.encoding, Encoding::DoP);
716            assert_eq!(widened.format.valid_bits, 32);
717            assert_eq!(
718                widened.transform,
719                PlaybackTransform::DopRepack { target_channels: 2 }
720            );
721        }
722        let policy = if mode == "dop-carrier32" {
723            // H1: the review's smallest case.
724            PlaybackPolicy {
725                allowed_pcm_depths: Some(vec![32]),
726                ..confirmed.clone()
727            }
728        } else {
729            confirmed.clone()
730        };
731        out_of_band("reset")?;
732        let decision = dac.resolve_playback(&source, &policy)?;
733        println!(
734            "DOP_DECISION mode={mode} transform={:?} fidelity={:?} format={:?}/{}ch/{}bit preflight={:?} attempted={}",
735            decision.transform,
736            decision.fidelity,
737            decision.format.encoding,
738            decision.format.channels,
739            decision.format.valid_bits,
740            decision.source_preflight_refusal,
741            decision.attempted_candidates
742        );
743        if mode == "dop-no-carrier" {
744            // H2: confirmed DoP on a DAC that cannot carry it falls back like unconfirmed.
745            assert!(decision.source_preflight_refusal.is_some());
746            assert_eq!(decision.format.encoding, Encoding::Pcm);
747            assert!(matches!(
748                decision.transform,
749                PlaybackTransform::DsdToPcm {
750                    dop_input: true,
751                    ..
752                }
753            ));
754            let unconfirmed = dac.resolve_playback(&source, &PlaybackPolicy::default())?;
755            assert_eq!(unconfirmed.format, decision.format);
756        } else {
757            assert_eq!(decision.format.encoding, Encoding::DoP);
758            assert_eq!(decision.format.channels, 2);
759            assert_eq!(
760                decision.transform,
761                PlaybackTransform::DopRepack { target_channels: 2 }
762            );
763            assert_eq!(
764                decision.fidelity,
765                if source.channels == 2 {
766                    PlaybackFidelity::BitExact
767                } else {
768                    PlaybackFidelity::Lossless
769                }
770            );
771            assert_eq!(decision.attempted_candidates, 1);
772        }
773        let mut stream = dac.open_playback(&decision, Arc::new(|_| {}))?;
774        let channels = usize::from(source.channels);
775        let frame = decision.source_frame_bytes;
776        let mut next = 0usize;
777        let mut chunk = Vec::new();
778        let start = Instant::now();
779        let mut started = false;
780        while start.elapsed() < Duration::from_secs(3)
781            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
782        {
783            let frames = stream.writable_bytes() / frame;
784            if frames > 0 {
785                chunk.clear();
786                for i in next..next + frames {
787                    let marker = if i % 2 == 0 { 0x05 } else { 0xfa };
788                    for _ in 0..channels {
789                        chunk.extend_from_slice(&[0x69, 0x69, marker]);
790                    }
791                }
792                next += stream.write(&chunk)? / frame;
793            }
794            if !started && next > 0 {
795                stream.play()?;
796                started = true;
797            }
798            thread::sleep(Duration::from_millis(2));
799        }
800        let stats = stream.target_stats();
801        let snapshot = out_of_band("snapshot")?;
802        println!("DOP_STATS mode={mode} source_frames={next} {stats:?} {snapshot}");
803        assert!(
804            stats.played_frames > 0 && stats.completed_transfers > 0,
805            "no DoP-resolved completions"
806        );
807        let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
808        let carrier_set = rates
809            .split(|c: char| !c.is_ascii_digit())
810            .any(|v| v == "176400");
811        // The carrier DACs clock 176.4 kHz; the exact carrier is never set on a DAC without one.
812        assert_eq!(carrier_set, mode != "dop-no-carrier", "{snapshot}");
813        if mode != "dop-no-carrier" {
814            assert!(stats.payload_verified, "the DoP payload must audit clean");
815        }
816        stream.close()?;
817        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
818        let retirement = dac.retirement();
819        dac.close()?;
820        assert!(retirement.wait(Duration::from_secs(3)));
821        assert_eq!(alt(fd)?, 0);
822        for interface in [1, 0] {
823            claim(fd, interface, false)?;
824        }
825        println!("USBIP_LIFECYCLE_PASS mode={mode} alt=0 retired=true");
826        Ok(())
827    }
828
829    pub fn run() -> Result<(), Box<dyn std::error::Error>> {
830        let args: Vec<_> = std::env::args().collect();
831        if args.len() != 3
832            || !matches!(
833                args[2].as_str(),
834                "normal"
835                    | "bad-cur"
836                    | "stale-cur"
837                    | "badd"
838                    | "full-uac3"
839                    | "full-uac3-volatile"
840                    | "full-uac3-clock"
841                    | "full-uac3-clock-bad"
842                    | "full-uac3-clock-stale"
843                    | "duplex"
844                    | "retire"
845                    | "reconfigure"
846                    | "selector"
847                    | "refuse-set"
848                    | "zero-res"
849                    | "full-uac3-nearest"
850                    | "dop-carrier32"
851                    | "dop-stereo24"
852                    | "dop-no-carrier"
853            )
854        {
855            return Err(
856                "usage: usbip_lifecycle /dev/bus/usb/BBB/DDD normal|bad-cur|stale-cur|badd|full-uac3|full-uac3-clock|duplex|retire|reconfigure".into(),
857            );
858        }
859        let path = &args[1];
860        if !path.starts_with("/dev/bus/usb/") {
861            return Err("expected a usbfs device path".into());
862        }
863        let file = OpenOptions::new().read(true).write(true).open(path)?;
864        let fd = file.as_raw_fd();
865        // Read and validate the actual descriptor before claiming or invoking the driver.
866        let mut descriptor = [0u8; 18];
867        assert_eq!(control(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?, 18);
868        assert_eq!((descriptor[0], descriptor[1]), (18, 1));
869        assert_eq!(
870            (
871                u16::from_le_bytes([descriptor[8], descriptor[9]]),
872                u16::from_le_bytes([descriptor[10], descriptor[11]])
873            ),
874            (VID, PID),
875            "refusing a device other than the fixture"
876        );
877        // Select the explicitly advertised fixture configuration before interface claims.
878        let configuration = match args[2].as_str() {
879            "badd" => 2u32,
880            "full-uac3"
881            | "full-uac3-volatile"
882            | "full-uac3-clock"
883            | "full-uac3-clock-bad"
884            | "full-uac3-clock-stale"
885            | "full-uac3-nearest" => 3,
886            _ => 1,
887        };
888        if configuration != 1 {
889            let mut config_descriptor = [0u8; 9];
890            assert_eq!(
891                control(
892                    fd,
893                    0x80,
894                    6,
895                    0x0200 | (configuration as u16 - 1),
896                    0,
897                    &mut config_descriptor
898                )?,
899                9
900            );
901            assert_eq!(
902                (
903                    config_descriptor[0],
904                    config_descriptor[1],
905                    config_descriptor[5]
906                ),
907                (9, 2, configuration as u8)
908            );
909            if unsafe { libc::ioctl(fd, 0x80045505u32 as _, &configuration) } != 0 {
910                return Err(std::io::Error::last_os_error().into());
911            }
912        }
913        let claims = if args[2] == "duplex" {
914            vec![0u8, 1, 2, 3]
915        } else {
916            vec![0u8, 1]
917        };
918        for &interface in &claims {
919            claim(fd, u32::from(interface), true)?;
920        }
921        assert_eq!(alt(fd)?, 0);
922        if matches!(
923            args[2].as_str(),
924            "badd" | "full-uac3" | "full-uac3-volatile"
925        ) {
926            assert_eq!(power(fd)?, 0, "power domain must initially be D0");
927            let mut state = [2u8];
928            assert_eq!(control(fd, 0x21, 1, 0x0200, 0x0a00, &mut state)?, 1);
929            assert_eq!(power(fd)?, 2, "failed to seed D2 baseline");
930        }
931        let mut info = DeviceInfo::new(VID, PID, "USB/IP audio fixture")
932            .with_claimed_interfaces(claims)
933            .with_device_name(path);
934        info.configuration_id = Some(configuration as u8);
935        let config = DacConfig {
936            require_hardware_volume: false,
937            require_verified_rate: true,
938            ..DacConfig::default()
939        };
940        let dac = if args[2] == "duplex" {
941            Dac::open_duplex_device(fd, info, config)?
942        } else {
943            Dac::open(fd, info, config)?
944        };
945        if args[2] == "duplex" {
946            return duplex(dac, fd);
947        }
948        if args[2] == "retire" {
949            return retire(dac, fd);
950        }
951        if args[2] == "reconfigure" {
952            return reconfigure(dac, fd);
953        }
954        if args[2].starts_with("dop-") {
955            return dop_resolution(dac, fd, &args[2]);
956        }
957        let caps = dac.capabilities()?;
958        if args[2] == "refuse-set" {
959            out_of_band("reset")?;
960            let requests = [
961                StreamRequest::pcm(96_000, 2, 16),
962                StreamRequest::pcm(48_000, 2, 16),
963            ];
964            let failure = dac.negotiate_candidates(&requests);
965            assert!(
966                matches!(
967                    failure,
968                    Err(Error::ClockUnverified {
969                        requested_hz: 96_000,
970                        ..
971                    })
972                ),
973                "refused SET must be terminal: {failure:?}"
974            );
975            let snapshot = out_of_band("snapshot")?;
976            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
977            assert!(rates.contains("96000"));
978            assert!(
979                !rates.contains("48000"),
980                "second candidate was tried after uncertain SET: {snapshot}"
981            );
982            let retirement = dac.retirement();
983            dac.close()?;
984            assert!(retirement.wait(Duration::from_secs(3)));
985            assert_eq!(alt(fd)?, 0);
986            for interface in [1, 0] {
987                claim(fd, interface, false)?;
988            }
989            println!("USBIP_LIFECYCLE_PASS mode=refuse-set snapshot={snapshot}");
990            return Ok(());
991        }
992        if matches!(args[2].as_str(), "selector" | "zero-res") {
993            let (requested, expected) = if args[2] == "selector" {
994                (192_000, 96_000)
995            } else {
996                (96_000, 44_100)
997            };
998            out_of_band("reset")?;
999            let request =
1000                StreamRequest::pcm(requested, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1001            let format = dac.negotiate(&request)?;
1002            assert_eq!(format.sample_rate, expected);
1003            let stream = dac.open_stream(&format, Arc::new(|_| {}))?;
1004            let snapshot = out_of_band("snapshot")?;
1005            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
1006            let rejected = requested.to_string();
1007            assert!(
1008                !rates
1009                    .split(|c: char| !c.is_ascii_digit())
1010                    .any(|v| v == rejected),
1011                "requested unsupported rate was sent: {snapshot}"
1012            );
1013            println!(
1014                "NEGOTIATE_CASE mode={} requested={requested} actual={expected} {snapshot}",
1015                args[2]
1016            );
1017            stream.close()?;
1018            let retirement = dac.retirement();
1019            dac.close()?;
1020            assert!(retirement.wait(Duration::from_secs(3)));
1021            assert_eq!(alt(fd)?, 0);
1022            for interface in [1, 0] {
1023                claim(fd, interface, false)?;
1024            }
1025            println!("USBIP_LIFECYCLE_PASS mode={} retired=true", args[2]);
1026            return Ok(());
1027        }
1028        if args[2] == "badd" {
1029            badd(&dac, fd, &caps)?;
1030            assert_eq!(alt(fd)?, 0);
1031            dac.close()?;
1032            assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
1033            assert_eq!(alt(fd)?, 0);
1034            assert_eq!(power(fd)?, 2, "BADD must restore D2");
1035            let power_log = out_of_band("snapshot")?;
1036            let powers = power_log
1037                .split("power=[")
1038                .nth(1)
1039                .ok_or("missing power history")?
1040                .split(']')
1041                .next()
1042                .ok_or("missing power terminator")?;
1043            assert!(
1044                powers
1045                    .split(", ")
1046                    .collect::<Vec<_>>()
1047                    .windows(2)
1048                    .any(|pair| pair == ["0", "2"]),
1049                "expected D0 to D2 transition: {power_log}"
1050            );
1051            for interface in [1, 0] {
1052                claim(fd, interface, false)?;
1053            }
1054            println!("USBIP_LIFECYCLE_PASS mode=badd alt=0 retired=true");
1055            return Ok(());
1056        }
1057        if args[2] == "full-uac3-nearest" {
1058            return full_uac3_nearest(dac, fd, &caps);
1059        }
1060        if matches!(args[2].as_str(), "full-uac3" | "full-uac3-volatile") {
1061            return full_uac3(dac, fd, &caps, args[2] == "full-uac3-volatile");
1062        }
1063        assert_eq!(
1064            caps.uac_version,
1065            if args[2].starts_with("full-uac3-clock") {
1066                UacVersion::V3
1067            } else {
1068                UacVersion::V2
1069            }
1070        );
1071        assert_eq!(caps.link_speed, LinkSpeed::High);
1072        let mut rates = caps.pcm_sample_rates.clone();
1073        rates.sort_unstable();
1074        rates.dedup();
1075        assert_eq!(rates, [48_000, 96_000], "unexpected fixture rates");
1076        assert!(
1077            matches!(
1078                dac.negotiate(&StreamRequest::pcm(192_000, 2, 16)),
1079                Err(Error::Unsupported { .. })
1080            ),
1081            "exact 192 kHz must be refused"
1082        );
1083        let request =
1084            StreamRequest::pcm(192_000, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1085        let format = dac.negotiate(&request)?;
1086        assert_eq!(
1087            (
1088                format.sample_rate,
1089                format.channels,
1090                format.valid_bits,
1091                format.subslot_bytes,
1092                format.interface_number,
1093                format.alt_setting
1094            ),
1095            (96_000, 2, 16, 2, 1, 1)
1096        );
1097        assert_eq!(format.sync_type, SyncKind::Synchronous);
1098        assert_eq!(format.endpoint_address, 0x01);
1099        assert_eq!(format.link_speed, LinkSpeed::High);
1100        assert_eq!(format.bytes_per_frame(), 4);
1101        if args[2].starts_with("full-uac3-clock") {
1102            assert_eq!(format.service_interval_us, 125);
1103            assert!(!format.explicit_feedback);
1104        }
1105        let clock = format
1106            .clock
1107            .as_ref()
1108            .ok_or("fixture clock missing")?
1109            .clone();
1110        assert_eq!(
1111            (clock.control_interface, clock.source_id),
1112            (
1113                0,
1114                if args[2].starts_with("full-uac3-clock") {
1115                    9
1116                } else {
1117                    0x10
1118                }
1119            )
1120        );
1121        println!("NEGOTIATED exact192=unsupported nearest192=96000 format={format:?}");
1122        let listener = Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}"));
1123        match args[2].as_str() {
1124            "normal" | "full-uac3-clock" => {
1125                let stream = dac.open_stream(&format, listener)?;
1126                assert_eq!(alt(fd)?, 1);
1127                let mut current = [0u8; 4];
1128                assert_eq!(
1129                    control(
1130                        fd,
1131                        0xa1,
1132                        1,
1133                        0x0100,
1134                        (u16::from(clock.source_id) << 8) | u16::from(clock.control_interface),
1135                        &mut current
1136                    )?,
1137                    4
1138                );
1139                assert_eq!(
1140                    u32::from_le_bytes(current),
1141                    96_000,
1142                    "post-alt clock readback"
1143                );
1144                let mut pcm = Vec::with_capacity(9600 * 4);
1145                for i in 0..9600i32 {
1146                    let v = (((i % 96) - 48) * 20) as i16;
1147                    pcm.extend_from_slice(&v.to_le_bytes());
1148                    pcm.extend_from_slice(&(-v).to_le_bytes());
1149                }
1150                for _ in 0..3 {
1151                    stream.write(&pcm)?;
1152                }
1153                stream.play()?;
1154                let start = Instant::now();
1155                while start.elapsed() < Duration::from_secs(3)
1156                    && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
1157                {
1158                    let n = stream.writable_bytes().min(pcm.len());
1159                    if n >= 4 {
1160                        stream.write(&pcm[..n - n % 4])?;
1161                    }
1162                    thread::sleep(Duration::from_millis(2));
1163                }
1164                let stats = stream.stats();
1165                println!("PCM_STATS {stats:?}");
1166                assert!(
1167                    stats.played_frames > 0 && stats.completed_transfers > 0,
1168                    "no actual PCM completions"
1169                );
1170                stream.close()?;
1171            }
1172            mode => match dac.open_stream(&format, listener) {
1173                Err(error @ Error::ClockUnverified { .. }) => {
1174                    let expected_reported = if mode == "bad-cur" || mode == "full-uac3-clock-bad" {
1175                        None
1176                    } else {
1177                        Some(48_000)
1178                    };
1179                    assert!(
1180                        matches!(error, Error::ClockUnverified { requested_hz: 96_000, reported_hz } if reported_hz == expected_reported)
1181                    );
1182                    println!(
1183                        "EXPECTED_FAILURE mode={mode} code={} error={error:?}",
1184                        error.code()
1185                    );
1186                }
1187                Err(error) => {
1188                    return Err(format!("unexpected failure for {mode}: {error:?}").into())
1189                }
1190                Ok(stream) => {
1191                    stream.close()?;
1192                    return Err(format!("{mode} incorrectly admitted the stream").into());
1193                }
1194            },
1195        }
1196        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
1197        dac.close()?;
1198        assert!(
1199            Dac::await_usb_retirement(Duration::from_secs(3)),
1200            "USB retirement timed out"
1201        );
1202        assert_eq!(alt(fd)?, 0);
1203        for interface in [1, 0] {
1204            claim(fd, interface, false)?;
1205        }
1206        println!("USBIP_LIFECYCLE_PASS mode={} alt=0 retired=true", args[2]);
1207        Ok(())
1208    }
examples/qemu_smoke.rs (line 198)
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 state(&self) -> StreamState

Examples found in repository?
examples/qemu_smoke.rs (line 157)
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}
More examples
Hide additional examples
examples/usbip_lifecycle.rs (line 562)
520    fn reconfigure(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
521        use usbdac_core::StreamState;
522        let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
523        let initial = dac.negotiate(&StreamRequest::pcm(96_000, 2, 16))?;
524        assert_eq!(
525            (
526                initial.sample_rate,
527                initial.interface_number,
528                initial.alt_setting
529            ),
530            (96_000, 1, 1)
531        );
532        let previous = dac.open_stream(&initial, listener.clone())?;
533        let pcm = test_pcm();
534        for _ in 0..3 {
535            previous.write(&pcm)?;
536        }
537        previous.play()?;
538        let start = Instant::now();
539        while start.elapsed() < Duration::from_secs(5) && previous.played_frames() == 0 {
540            feed(&previous, &pcm)?;
541            thread::sleep(Duration::from_millis(5));
542        }
543        assert!(
544            previous.played_frames() > 0,
545            "original playback never completed"
546        );
547        out_of_band("reset")?;
548        println!("RECONFIGURE_PHASE_BEGIN from=96000 to=48000");
549        let request = StreamRequest::pcm(48_000, 2, 16);
550        let replacement = dac.reconfigure_stream_candidates(
551            &previous,
552            &[request],
553            listener,
554            Duration::from_secs(3),
555        )?;
556        println!("RECONFIGURE_PHASE_END from=96000 to=48000");
557        assert!(
558            replacement.rollback_cause.is_none(),
559            "unexpected rollback: {:?}",
560            replacement.rollback_cause
561        );
562        assert_eq!(previous.state(), StreamState::Closed);
563        assert_eq!(replacement.stream.state(), StreamState::Paused);
564        assert_eq!(replacement.stream.format().sample_rate, 48_000);
565        assert_eq!(replacement.stream.played_frames(), 0);
566        assert_eq!(alt(fd)?, 1);
567        let transitions = out_of_band("snapshot")?;
568        let alt_history = transitions
569            .split("alts=[")
570            .nth(1)
571            .ok_or("missing alternate history")?
572            .split(']')
573            .next()
574            .ok_or("missing alternate terminator")?;
575        let unlink_count: u64 = transitions
576            .split("unlinks=")
577            .nth(1)
578            .ok_or("missing unlink count")?
579            .parse()?;
580        assert!(
581            unlink_count <= 16,
582            "more than one bounded transfer set cancelled: {transitions}"
583        );
584        let mut alts: Vec<_> = alt_history.split(", ").collect();
585        alts.dedup();
586        assert_eq!(
587            alts,
588            ["0", "1"],
589            "unexpected alternate transitions: {transitions}"
590        );
591        // USB-level count of the live 96 -> 48 kHz replacement on interface 1 and
592        // clock 16. ALSA's UAC2 prepare deselects the alternate first, writes the
593        // rate, and enables the alternate last (sound/usb/endpoint.c
594        // snd_usb_endpoint_prepare:1498-1530, endpoint_set_interface:917-951).
595        // ALSA elides a SET_INTERFACE to the alternate it already holds
596        // (endpoint.c:926-927); usbdac re-asserts alt 0 at stop, before and after
597        // the read-only negotiation and before activation, which is idempotent.
598        let sequence = out_of_band("sequence")?;
599        let writes: Vec<_> = sequence
600            .strip_prefix("seq=[")
601            .and_then(|rest| rest.strip_suffix(']'))
602            .ok_or("missing write sequence")?
603            .split(", ")
604            .collect();
605        let count = |w: &str| writes.iter().filter(|x| **x == w).count();
606        assert_eq!(
607            (
608                count("alt0"),
609                count("alt1"),
610                count("rate48000"),
611                writes.len()
612            ),
613            (4, 1, 2, 7),
614            "unexpected replacement write counts: {sequence}"
615        );
616        assert_eq!(
617            writes.first(),
618            Some(&"alt0"),
619            "old alternate not deselected first: {sequence}"
620        );
621        assert_eq!(
622            writes.last(),
623            Some(&"alt1"),
624            "alternate not enabled last: {sequence}"
625        );
626        assert!(
627            !writes
628                .iter()
629                .any(|w| w.starts_with("rate") && *w != "rate48000"),
630            "a rate other than 48 kHz was written: {sequence}"
631        );
632        // Fresh post-replacement evidence: the DAC's clock reads back 48 kHz at alt 1.
633        let mut current = [0u8; 4];
634        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
635        assert_eq!(u32::from_le_bytes(current), 48_000);
636        println!(
637            "RECONFIGURE_USB_WRITES {sequence} clock_readback=48000 alt={}",
638            alt(fd)?
639        );
640        let stream = replacement.stream;
641        for _ in 0..3 {
642            stream.write(&pcm)?;
643        }
644        stream.play()?;
645        let start = Instant::now();
646        while start.elapsed() < Duration::from_secs(5)
647            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
648        {
649            feed(&stream, &pcm)?;
650            thread::sleep(Duration::from_millis(5));
651        }
652        assert!(
653            stream.played_frames() > 0 && stream.stats().completed_transfers > 0,
654            "replacement playback never completed"
655        );
656        let stats = stream.stats();
657        assert!(stats.played_frames <= stats.frames_written);
658        assert!(stats.queued_frames <= stats.frames_written);
659        assert!(
660            stats.underruns <= 50,
661            "USB/IP replacement exceeded 50 underruns: {stats:?}"
662        );
663        let mut current = [0u8; 4];
664        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
665        assert_eq!(
666            u32::from_le_bytes(current),
667            48_000,
668            "clock drifted during replacement playback"
669        );
670        let fixture_stats = out_of_band("snapshot")?;
671        assert!(
672            !fixture_stats.contains("out_completions=0"),
673            "replacement has no completed OUT URB: {fixture_stats}"
674        );
675        println!(
676            "RECONFIGURE_PLAYBACK_PASS stats={stats:?} underrun_limit=50 fixture={fixture_stats}"
677        );
678        stream.close()?;
679        let retirement = dac.retirement();
680        dac.close()?;
681        assert!(retirement.wait(Duration::from_secs(3)));
682        assert_eq!(alt(fd)?, 0);
683        for interface in [1, 0] {
684            claim(fd, interface, false)?;
685        }
686        println!("USBIP_LIFECYCLE_PASS mode=reconfigure retired=true alt=0");
687        Ok(())
688    }
Source

pub fn played_frames(&self) -> u64

Music frames the DAC has completed on the bus since the stream started or the last flush. Padding, held silence and lost frames are not counted. The unit is format().counter_rate_hz().

Examples found in repository?
examples/guide_player.rs (line 101)
100    fn played_frames(&self) -> u64 {
101        DacStream::played_frames(self)
102    }
More examples
Hide additional examples
examples/pull_adapter.rs (line 104)
102    fn position_seconds(&self) -> f64 {
103        let base = lock(&self.state).base_seconds;
104        base + self.stream.played_frames() as f64
105            / f64::from(self.stream.format().counter_rate_hz())
106    }
examples/usbip_lifecycle.rs (line 128)
79    fn badd(
80        dac: &Dac,
81        fd: i32,
82        caps: &usbdac_core::Capabilities,
83    ) -> Result<(), Box<dyn std::error::Error>> {
84        assert_eq!(caps.uac_version, UacVersion::V3);
85        assert_eq!(caps.link_speed, LinkSpeed::High);
86        assert_eq!(caps.pcm_sample_rates, [48_000]);
87        assert!(matches!(
88            dac.negotiate(&StreamRequest::pcm(96_000, 2, 16)),
89            Err(Error::Unsupported { .. })
90        ));
91        let format = dac.negotiate(
92            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
93        )?;
94        assert_eq!(
95            (
96                format.sample_rate,
97                format.channels,
98                format.valid_bits,
99                format.subslot_bytes,
100                format.interface_number,
101                format.alt_setting,
102                format.endpoint_address
103            ),
104            (48_000, 2, 16, 2, 1, 1, 1)
105        );
106        assert!(
107            format.explicit_feedback,
108            "BADD profile must expose feedback"
109        );
110        println!("BADD_FORMAT {format:?}");
111        let stream = dac.open_stream(
112            &format,
113            Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}")),
114        )?;
115        assert_eq!(alt(fd)?, 1);
116        let mut pcm = Vec::with_capacity(4800 * 4);
117        for i in 0..4800i32 {
118            let v = (((i % 96) - 48) * 20) as i16;
119            pcm.extend_from_slice(&v.to_le_bytes());
120            pcm.extend_from_slice(&(-v).to_le_bytes());
121        }
122        for _ in 0..3 {
123            stream.write(&pcm)?;
124        }
125        stream.play()?;
126        let start = Instant::now();
127        while start.elapsed() < Duration::from_secs(3)
128            && (stream.played_frames() == 0
129                || stream.stats().completed_transfers == 0
130                || stream.stats().feedback_reports == 0)
131        {
132            let n = stream.writable_bytes().min(pcm.len());
133            if n >= 4 {
134                stream.write(&pcm[..n - n % 4])?;
135            }
136            thread::sleep(Duration::from_millis(2));
137        }
138        let stats = stream.stats();
139        println!("BADD_PCM_STATS {stats:?}");
140        assert!(
141            stats.played_frames > 0 && stats.completed_transfers > 0 && stats.feedback_reports > 0,
142            "BADD playback or feedback has no real completions"
143        );
144        stream.close()?;
145        Ok(())
146    }
147
148    fn full_uac3(
149        dac: Dac,
150        fd: i32,
151        caps: &usbdac_core::Capabilities,
152        volatile: bool,
153    ) -> Result<(), Box<dyn std::error::Error>> {
154        use usbdac_core::routing::{
155            ControlKey, Entity, RouteEdit, RouteValue, RoutingHandBackOutcome,
156        };
157        assert_eq!(caps.uac_version, UacVersion::V3);
158        assert_eq!(caps.link_speed, LinkSpeed::High);
159        let key = ControlKey::Selector(Entity {
160            interface: 0,
161            id: 8,
162        });
163        assert_eq!(power(fd)?, 2, "initial power must be D2");
164        let snapshot = dac.routing_discover_powered()?;
165        println!("UAC3_ROUTING snapshot={snapshot:?}");
166        assert_eq!(snapshot.configuration(), 3);
167        assert_eq!(power(fd)?, 2, "discovery must restore D2");
168        assert_eq!(
169            dac.routing_read_powered(&snapshot, key)?,
170            RouteValue::SelectorPin(1)
171        );
172        assert_eq!(power(fd)?, 2, "read must restore D2");
173        let report = dac.routing_apply_powered(
174            &snapshot,
175            &[RouteEdit {
176                key,
177                expected: RouteValue::SelectorPin(1),
178                value: RouteValue::SelectorPin(2),
179            }],
180        )?;
181        assert_eq!(report.changed, vec![key]);
182        let applied = out_of_band("snapshot")?;
183        assert!(
184            applied.contains("selector=[2]"),
185            "fixture selector was not written: {applied}"
186        );
187        assert!(
188            applied.contains(if volatile {
189                "selector_state=1"
190            } else {
191                "selector_state=2"
192            }),
193            "unexpected fixture selector after D2: {applied}"
194        );
195        assert_eq!(power(fd)?, 2, "apply must restore D2");
196        let updated = dac.routing_discover_powered()?;
197        assert_eq!(
198            dac.routing_read_powered(&updated, key)?,
199            RouteValue::SelectorPin(if volatile { 1 } else { 2 }),
200            "selector readback must reflect the fixture's D2 behavior"
201        );
202        assert_eq!(power(fd)?, 2);
203        dac.close()?;
204        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
205        let hand_back = snapshot
206            .hand_back_report()
207            .ok_or("missing routing hand-back report")?;
208        println!("UAC3_HAND_BACK {hand_back:?}");
209        if !volatile {
210            assert!(
211                hand_back
212                    .controls
213                    .contains(&(key, RoutingHandBackOutcome::Restored)),
214                "selector hand-back was not verified"
215            );
216        }
217        assert_eq!(power(fd)?, 2, "final power must be D2");
218        assert!(
219            out_of_band("snapshot")?.contains("selector_state=1"),
220            "fixture selector was not restored"
221        );
222        assert_eq!(alt(fd)?, 0);
223        for interface in [1, 0] {
224            claim(fd, interface, false)?;
225        }
226        println!("USBIP_LIFECYCLE_PASS mode=full-uac3 selector=restored power=D2 retired=true");
227        Ok(())
228    }
229
230    // Full UAC3 whose clock RANGE lists only 48 kHz behind a powered route that
231    // cannot certify a live refusal. The cached model excludes 44.1 kHz, so the
232    // ranked loop and the playback candidates must skip it without any USB request,
233    // as ALSA never offers a rate absent from its format table (pcm.c hw_rule_rate).
234    fn full_uac3_nearest(
235        dac: Dac,
236        fd: i32,
237        caps: &usbdac_core::Capabilities,
238    ) -> Result<(), Box<dyn std::error::Error>> {
239        use usbdac_core::playback::PlaybackPolicy;
240        assert_eq!(caps.uac_version, UacVersion::V3);
241        assert_eq!(caps.link_speed, LinkSpeed::High);
242        let mut rates = caps.pcm_sample_rates.clone();
243        rates.sort_unstable();
244        rates.dedup();
245        assert_eq!(rates, [48_000], "unexpected full-UAC3 fixture rates");
246        let no_44k = |snapshot: &str| -> Result<(), Box<dyn std::error::Error>> {
247            let sets = snapshot.split(';').next().ok_or("missing rate snapshot")?;
248            if sets
249                .split(|c: char| !c.is_ascii_digit())
250                .any(|v| v == "44100")
251            {
252                return Err(format!("model-excluded 44100 Hz was programmed: {snapshot}").into());
253            }
254            Ok(())
255        };
256        out_of_band("reset")?;
257        let format = dac.negotiate(
258            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
259        )?;
260        assert_eq!(
261            (format.sample_rate, format.channels, format.valid_bits),
262            (48_000, 2, 16)
263        );
264        let negotiated = out_of_band("snapshot")?;
265        no_44k(&negotiated)?;
266        out_of_band("reset")?;
267        let decision = dac.resolve_playback(
268            &StreamRequest::pcm(44_100, 2, 16),
269            &PlaybackPolicy::default(),
270        )?;
271        assert_eq!(decision.format.sample_rate, 48_000);
272        assert_eq!(decision.candidates[0], StreamRequest::pcm(44_100, 2, 16));
273        assert!(
274            matches!(decision.exact_refusal, Some(Error::Unsupported { .. })),
275            "the skipped exact source must report a typed refusal: {:?}",
276            decision.exact_refusal
277        );
278        let resolved = out_of_band("snapshot")?;
279        no_44k(&resolved)?;
280        println!(
281            "NEGOTIATE_CASE mode=full-uac3-nearest requested=44100 actual=48000 resolve=48000 attempted={} negotiate={negotiated} resolve_snapshot={resolved}",
282            decision.attempted_candidates
283        );
284        assert_eq!(alt(fd)?, 0);
285        dac.close()?;
286        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
287        assert_eq!(alt(fd)?, 0);
288        for interface in [1, 0] {
289            claim(fd, interface, false)?;
290        }
291        println!("USBIP_LIFECYCLE_PASS mode=full-uac3-nearest retired=true");
292        Ok(())
293    }
294
295    fn vendor(fd: i32, value: u16) -> Result<(), Box<dyn std::error::Error>> {
296        assert_eq!(control(fd, 0x40, 0x5a, value, 0, &mut [])?, 0);
297        Ok(())
298    }
299    fn vendor_status(fd: i32) -> Result<u8, Box<dyn std::error::Error>> {
300        let mut status = [0u8];
301        assert_eq!(control(fd, 0xc0, 0x5a, 0, 0, &mut status)?, 1);
302        Ok(status[0])
303    }
304    fn out_of_band(action: &str) -> Result<String, Box<dyn std::error::Error>> {
305        let port = std::env::var("USBDAC_USBIP_PORT")?;
306        let _: u16 = port.parse()?;
307        let output = std::process::Command::new("/fixture/usbip_uac")
308            .args(["--control", action, "--port", &port])
309            .output()?;
310        if !output.status.success() {
311            return Err(format!(
312                "fixture control {action} failed: {}",
313                String::from_utf8_lossy(&output.stderr)
314            )
315            .into());
316        }
317        Ok(String::from_utf8(output.stdout)?.trim().to_string())
318    }
319    fn wait_status(fd: i32, mask: u8) -> Result<u8, Box<dyn std::error::Error>> {
320        let start = Instant::now();
321        loop {
322            let status = vendor_status(fd)?;
323            if status & mask == mask {
324                return Ok(status);
325            }
326            if start.elapsed() >= Duration::from_secs(5) {
327                return Err(
328                    format!("fixture status {status:#04x} did not reach {mask:#04x}").into(),
329                );
330            }
331            thread::sleep(Duration::from_millis(10));
332        }
333    }
334    fn test_pcm() -> Vec<u8> {
335        let mut pcm = Vec::with_capacity(4800 * 4);
336        for i in 0..4800i32 {
337            let v = (((i % 96) - 48) * 20) as i16;
338            pcm.extend_from_slice(&v.to_le_bytes());
339            pcm.extend_from_slice(&(-v).to_le_bytes());
340        }
341        pcm
342    }
343    fn feed(stream: &usbdac_core::DacStream, pcm: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
344        let n = stream.writable_bytes().min(pcm.len());
345        if n >= 4 {
346            stream.write(&pcm[..n - n % 4])?;
347        }
348        Ok(())
349    }
350    fn duplex(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
351        use usbdac_core::{CaptureRequest, CaptureState};
352        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
353        let request = CaptureRequest {
354            sample_rate: 48_000,
355            channels: 2,
356            valid_bits: 16,
357            channel_map: None,
358        };
359        let (playback, capture) = dac.open_duplex(
360            &format,
361            &request,
362            48_000,
363            Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")),
364        )?;
365        assert_eq!(
366            (capture.interface_number(), capture.endpoint_address()),
367            (3, 0x82)
368        );
369        let pcm = test_pcm();
370        for _ in 0..3 {
371            playback.write(&pcm)?;
372        }
373        playback.play()?;
374        let start = Instant::now();
375        let mut received = [0u8; 4096];
376        let mut marker_frames = 0;
377        while start.elapsed() < Duration::from_secs(5) && marker_frames == 0 {
378            feed(&playback, &pcm)?;
379            let frames = capture.read(&mut received)?;
380            if frames > 0 {
381                assert!(
382                    received[..frames * 4]
383                        .chunks_exact(4)
384                        .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
385                    "unexpected capture payload"
386                );
387                marker_frames = frames;
388            }
389            thread::sleep(Duration::from_millis(5));
390        }
391        assert!(marker_frames > 0, "no actual capture marker");
392        println!("DUPLEX_CAPTURE_MARKER frames={marker_frames}");
393        out_of_band("mixed")?;
394        let mixed_start = Instant::now();
395        while mixed_start.elapsed() < Duration::from_secs(5) {
396            feed(&playback, &pcm)?;
397            let frames = capture.read(&mut received)?;
398            assert!(
399                received[..frames * 4]
400                    .chunks_exact(4)
401                    .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
402                "invalid packet leaked into capture"
403            );
404            let stats = capture.stats();
405            if stats.short_packets > 0 && stats.failed_packets > 0 && stats.malformed_packets > 0 {
406                break;
407            }
408            thread::sleep(Duration::from_millis(5));
409        }
410        let mixed_stats = capture.stats();
411        assert!(
412            mixed_stats.short_packets > 0
413                && mixed_stats.failed_packets > 0
414                && mixed_stats.malformed_packets > 0,
415            "mixed packet statuses not observed: {mixed_stats:?}"
416        );
417        println!("DUPLEX_MIXED_PACKETS {mixed_stats:?}");
418        vendor(fd, 1)?;
419        let start = Instant::now();
420        while start.elapsed() < Duration::from_secs(5) && capture.state() == CaptureState::Active {
421            feed(&playback, &pcm)?;
422            thread::sleep(Duration::from_millis(5));
423        }
424        assert_eq!(capture.state(), CaptureState::Failed);
425        assert!(
426            capture.last_error().is_some(),
427            "capture failure must preserve an error"
428        );
429        assert_ne!(
430            vendor_status(fd)? & 8,
431            0,
432            "fixture did not deliver capture fault"
433        );
434        let before = playback.played_frames();
435        let start = Instant::now();
436        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() <= before {
437            feed(&playback, &pcm)?;
438            thread::sleep(Duration::from_millis(5));
439        }
440        let after = playback.played_frames();
441        assert!(
442            after > before,
443            "playback stopped after independent capture failure"
444        );
445        println!(
446            "DUPLEX_ISOLATION_PASS before={before} after={after} error={:?}",
447            capture.last_error()
448        );
449        capture.close()?;
450        playback.close()?;
451        let retirement = dac.retirement();
452        dac.close()?;
453        assert!(retirement.wait(Duration::from_secs(3)));
454        assert_eq!(alt(fd)?, 0);
455        for interface in [3, 2, 1, 0] {
456            claim(fd, interface, false)?;
457        }
458        println!("USBIP_LIFECYCLE_PASS mode=duplex retired=true");
459        Ok(())
460    }
461    fn retire(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
462        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
463        let playback =
464            dac.open_stream(&format, Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")))?;
465        let pcm = test_pcm();
466        for _ in 0..3 {
467            playback.write(&pcm)?;
468        }
469        playback.play()?;
470        let start = Instant::now();
471        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() == 0 {
472            feed(&playback, &pcm)?;
473            thread::sleep(Duration::from_millis(5));
474        }
475        assert!(playback.played_frames() > 0, "playback never completed");
476        let token = dac.retirement();
477        vendor(fd, 1)?;
478        let status = wait_status(fd, 2)?;
479        println!("RETIRE_HELD status={status:#04x}");
480        let start = Instant::now();
481        let result = dac.close();
482        let elapsed = start.elapsed();
483        println!(
484            "RETIRE_CLOSE result={result:?} elapsed_ms={}",
485            elapsed.as_millis()
486        );
487        assert!(
488            matches!(result, Err(Error::Transfer(_))),
489            "close must report timeout: {result:?}"
490        );
491        assert!(
492            elapsed >= Duration::from_millis(2500),
493            "close returned before its actual timeout: {elapsed:?}"
494        );
495        assert!(
496            !token.wait(Duration::ZERO),
497            "owner retired while URB unlink was held"
498        );
499        let status: u8 = out_of_band("status")?.parse()?;
500        assert_eq!(
501            status & 0x14,
502            0x14,
503            "unlink must be held and AS1 active: {status:#04x}"
504        );
505        println!("RETIRE_PENDING elapsed_ms={}", elapsed.as_millis());
506        out_of_band("release")?;
507        assert!(
508            token.wait(Duration::from_secs(10)),
509            "owner did not retire after unlink release"
510        );
511        assert_eq!(alt(fd)?, 0, "retired owner did not restore alt zero");
512        drop(playback);
513        for interface in [1, 0] {
514            claim(fd, interface, false)?;
515        }
516        println!("USBIP_LIFECYCLE_PASS mode=retire retired=true alt=0");
517        Ok(())
518    }
519
520    fn reconfigure(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
521        use usbdac_core::StreamState;
522        let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
523        let initial = dac.negotiate(&StreamRequest::pcm(96_000, 2, 16))?;
524        assert_eq!(
525            (
526                initial.sample_rate,
527                initial.interface_number,
528                initial.alt_setting
529            ),
530            (96_000, 1, 1)
531        );
532        let previous = dac.open_stream(&initial, listener.clone())?;
533        let pcm = test_pcm();
534        for _ in 0..3 {
535            previous.write(&pcm)?;
536        }
537        previous.play()?;
538        let start = Instant::now();
539        while start.elapsed() < Duration::from_secs(5) && previous.played_frames() == 0 {
540            feed(&previous, &pcm)?;
541            thread::sleep(Duration::from_millis(5));
542        }
543        assert!(
544            previous.played_frames() > 0,
545            "original playback never completed"
546        );
547        out_of_band("reset")?;
548        println!("RECONFIGURE_PHASE_BEGIN from=96000 to=48000");
549        let request = StreamRequest::pcm(48_000, 2, 16);
550        let replacement = dac.reconfigure_stream_candidates(
551            &previous,
552            &[request],
553            listener,
554            Duration::from_secs(3),
555        )?;
556        println!("RECONFIGURE_PHASE_END from=96000 to=48000");
557        assert!(
558            replacement.rollback_cause.is_none(),
559            "unexpected rollback: {:?}",
560            replacement.rollback_cause
561        );
562        assert_eq!(previous.state(), StreamState::Closed);
563        assert_eq!(replacement.stream.state(), StreamState::Paused);
564        assert_eq!(replacement.stream.format().sample_rate, 48_000);
565        assert_eq!(replacement.stream.played_frames(), 0);
566        assert_eq!(alt(fd)?, 1);
567        let transitions = out_of_band("snapshot")?;
568        let alt_history = transitions
569            .split("alts=[")
570            .nth(1)
571            .ok_or("missing alternate history")?
572            .split(']')
573            .next()
574            .ok_or("missing alternate terminator")?;
575        let unlink_count: u64 = transitions
576            .split("unlinks=")
577            .nth(1)
578            .ok_or("missing unlink count")?
579            .parse()?;
580        assert!(
581            unlink_count <= 16,
582            "more than one bounded transfer set cancelled: {transitions}"
583        );
584        let mut alts: Vec<_> = alt_history.split(", ").collect();
585        alts.dedup();
586        assert_eq!(
587            alts,
588            ["0", "1"],
589            "unexpected alternate transitions: {transitions}"
590        );
591        // USB-level count of the live 96 -> 48 kHz replacement on interface 1 and
592        // clock 16. ALSA's UAC2 prepare deselects the alternate first, writes the
593        // rate, and enables the alternate last (sound/usb/endpoint.c
594        // snd_usb_endpoint_prepare:1498-1530, endpoint_set_interface:917-951).
595        // ALSA elides a SET_INTERFACE to the alternate it already holds
596        // (endpoint.c:926-927); usbdac re-asserts alt 0 at stop, before and after
597        // the read-only negotiation and before activation, which is idempotent.
598        let sequence = out_of_band("sequence")?;
599        let writes: Vec<_> = sequence
600            .strip_prefix("seq=[")
601            .and_then(|rest| rest.strip_suffix(']'))
602            .ok_or("missing write sequence")?
603            .split(", ")
604            .collect();
605        let count = |w: &str| writes.iter().filter(|x| **x == w).count();
606        assert_eq!(
607            (
608                count("alt0"),
609                count("alt1"),
610                count("rate48000"),
611                writes.len()
612            ),
613            (4, 1, 2, 7),
614            "unexpected replacement write counts: {sequence}"
615        );
616        assert_eq!(
617            writes.first(),
618            Some(&"alt0"),
619            "old alternate not deselected first: {sequence}"
620        );
621        assert_eq!(
622            writes.last(),
623            Some(&"alt1"),
624            "alternate not enabled last: {sequence}"
625        );
626        assert!(
627            !writes
628                .iter()
629                .any(|w| w.starts_with("rate") && *w != "rate48000"),
630            "a rate other than 48 kHz was written: {sequence}"
631        );
632        // Fresh post-replacement evidence: the DAC's clock reads back 48 kHz at alt 1.
633        let mut current = [0u8; 4];
634        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
635        assert_eq!(u32::from_le_bytes(current), 48_000);
636        println!(
637            "RECONFIGURE_USB_WRITES {sequence} clock_readback=48000 alt={}",
638            alt(fd)?
639        );
640        let stream = replacement.stream;
641        for _ in 0..3 {
642            stream.write(&pcm)?;
643        }
644        stream.play()?;
645        let start = Instant::now();
646        while start.elapsed() < Duration::from_secs(5)
647            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
648        {
649            feed(&stream, &pcm)?;
650            thread::sleep(Duration::from_millis(5));
651        }
652        assert!(
653            stream.played_frames() > 0 && stream.stats().completed_transfers > 0,
654            "replacement playback never completed"
655        );
656        let stats = stream.stats();
657        assert!(stats.played_frames <= stats.frames_written);
658        assert!(stats.queued_frames <= stats.frames_written);
659        assert!(
660            stats.underruns <= 50,
661            "USB/IP replacement exceeded 50 underruns: {stats:?}"
662        );
663        let mut current = [0u8; 4];
664        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
665        assert_eq!(
666            u32::from_le_bytes(current),
667            48_000,
668            "clock drifted during replacement playback"
669        );
670        let fixture_stats = out_of_band("snapshot")?;
671        assert!(
672            !fixture_stats.contains("out_completions=0"),
673            "replacement has no completed OUT URB: {fixture_stats}"
674        );
675        println!(
676            "RECONFIGURE_PLAYBACK_PASS stats={stats:?} underrun_limit=50 fixture={fixture_stats}"
677        );
678        stream.close()?;
679        let retirement = dac.retirement();
680        dac.close()?;
681        assert!(retirement.wait(Duration::from_secs(3)));
682        assert_eq!(alt(fd)?, 0);
683        for interface in [1, 0] {
684            claim(fd, interface, false)?;
685        }
686        println!("USBIP_LIFECYCLE_PASS mode=reconfigure retired=true alt=0");
687        Ok(())
688    }
689
690    /// DoP resolution through the production resolve_playback, transport and
691    /// PlaybackStream. DoP v1.1 carries 16 DSD bits per channel per carrier frame,
692    /// so a DoP carrier of another depth or channel count is a repack (H1), and an
693    /// exact DoP shape absent from the descriptors is never attempted (H2).
694    fn dop_resolution(dac: Dac, fd: i32, mode: &str) -> Result<(), Box<dyn std::error::Error>> {
695        use usbdac_core::playback::{PlaybackFidelity, PlaybackPolicy, PlaybackTransform};
696        use usbdac_core::Encoding;
697        let confirmed = PlaybackPolicy {
698            dop_confirmed: true,
699            ..PlaybackPolicy::default()
700        };
701        let caps = dac.capabilities()?;
702        assert!(
703            caps.exclusion_snapshot_complete,
704            "the fixture descriptor snapshot must be complete"
705        );
706        let source = StreamRequest::dop(2_822_400, if mode == "dop-stereo24" { 1 } else { 2 });
707        if mode == "dop-carrier32" {
708            // H2: 24-bit DoP on a 32-bit-only DAC reaches the 32-bit carrier.
709            let widened = dac.resolve_playback(&source, &confirmed)?;
710            println!(
711                "DOP_DECISION mode={mode} case=widen transform={:?} fidelity={:?} bits={} preflight={:?}",
712                widened.transform, widened.fidelity, widened.format.valid_bits, widened.source_preflight_refusal
713            );
714            assert!(widened.source_preflight_refusal.is_some());
715            assert_eq!(widened.format.encoding, Encoding::DoP);
716            assert_eq!(widened.format.valid_bits, 32);
717            assert_eq!(
718                widened.transform,
719                PlaybackTransform::DopRepack { target_channels: 2 }
720            );
721        }
722        let policy = if mode == "dop-carrier32" {
723            // H1: the review's smallest case.
724            PlaybackPolicy {
725                allowed_pcm_depths: Some(vec![32]),
726                ..confirmed.clone()
727            }
728        } else {
729            confirmed.clone()
730        };
731        out_of_band("reset")?;
732        let decision = dac.resolve_playback(&source, &policy)?;
733        println!(
734            "DOP_DECISION mode={mode} transform={:?} fidelity={:?} format={:?}/{}ch/{}bit preflight={:?} attempted={}",
735            decision.transform,
736            decision.fidelity,
737            decision.format.encoding,
738            decision.format.channels,
739            decision.format.valid_bits,
740            decision.source_preflight_refusal,
741            decision.attempted_candidates
742        );
743        if mode == "dop-no-carrier" {
744            // H2: confirmed DoP on a DAC that cannot carry it falls back like unconfirmed.
745            assert!(decision.source_preflight_refusal.is_some());
746            assert_eq!(decision.format.encoding, Encoding::Pcm);
747            assert!(matches!(
748                decision.transform,
749                PlaybackTransform::DsdToPcm {
750                    dop_input: true,
751                    ..
752                }
753            ));
754            let unconfirmed = dac.resolve_playback(&source, &PlaybackPolicy::default())?;
755            assert_eq!(unconfirmed.format, decision.format);
756        } else {
757            assert_eq!(decision.format.encoding, Encoding::DoP);
758            assert_eq!(decision.format.channels, 2);
759            assert_eq!(
760                decision.transform,
761                PlaybackTransform::DopRepack { target_channels: 2 }
762            );
763            assert_eq!(
764                decision.fidelity,
765                if source.channels == 2 {
766                    PlaybackFidelity::BitExact
767                } else {
768                    PlaybackFidelity::Lossless
769                }
770            );
771            assert_eq!(decision.attempted_candidates, 1);
772        }
773        let mut stream = dac.open_playback(&decision, Arc::new(|_| {}))?;
774        let channels = usize::from(source.channels);
775        let frame = decision.source_frame_bytes;
776        let mut next = 0usize;
777        let mut chunk = Vec::new();
778        let start = Instant::now();
779        let mut started = false;
780        while start.elapsed() < Duration::from_secs(3)
781            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
782        {
783            let frames = stream.writable_bytes() / frame;
784            if frames > 0 {
785                chunk.clear();
786                for i in next..next + frames {
787                    let marker = if i % 2 == 0 { 0x05 } else { 0xfa };
788                    for _ in 0..channels {
789                        chunk.extend_from_slice(&[0x69, 0x69, marker]);
790                    }
791                }
792                next += stream.write(&chunk)? / frame;
793            }
794            if !started && next > 0 {
795                stream.play()?;
796                started = true;
797            }
798            thread::sleep(Duration::from_millis(2));
799        }
800        let stats = stream.target_stats();
801        let snapshot = out_of_band("snapshot")?;
802        println!("DOP_STATS mode={mode} source_frames={next} {stats:?} {snapshot}");
803        assert!(
804            stats.played_frames > 0 && stats.completed_transfers > 0,
805            "no DoP-resolved completions"
806        );
807        let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
808        let carrier_set = rates
809            .split(|c: char| !c.is_ascii_digit())
810            .any(|v| v == "176400");
811        // The carrier DACs clock 176.4 kHz; the exact carrier is never set on a DAC without one.
812        assert_eq!(carrier_set, mode != "dop-no-carrier", "{snapshot}");
813        if mode != "dop-no-carrier" {
814            assert!(stats.payload_verified, "the DoP payload must audit clean");
815        }
816        stream.close()?;
817        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
818        let retirement = dac.retirement();
819        dac.close()?;
820        assert!(retirement.wait(Duration::from_secs(3)));
821        assert_eq!(alt(fd)?, 0);
822        for interface in [1, 0] {
823            claim(fd, interface, false)?;
824        }
825        println!("USBIP_LIFECYCLE_PASS mode={mode} alt=0 retired=true");
826        Ok(())
827    }
828
829    pub fn run() -> Result<(), Box<dyn std::error::Error>> {
830        let args: Vec<_> = std::env::args().collect();
831        if args.len() != 3
832            || !matches!(
833                args[2].as_str(),
834                "normal"
835                    | "bad-cur"
836                    | "stale-cur"
837                    | "badd"
838                    | "full-uac3"
839                    | "full-uac3-volatile"
840                    | "full-uac3-clock"
841                    | "full-uac3-clock-bad"
842                    | "full-uac3-clock-stale"
843                    | "duplex"
844                    | "retire"
845                    | "reconfigure"
846                    | "selector"
847                    | "refuse-set"
848                    | "zero-res"
849                    | "full-uac3-nearest"
850                    | "dop-carrier32"
851                    | "dop-stereo24"
852                    | "dop-no-carrier"
853            )
854        {
855            return Err(
856                "usage: usbip_lifecycle /dev/bus/usb/BBB/DDD normal|bad-cur|stale-cur|badd|full-uac3|full-uac3-clock|duplex|retire|reconfigure".into(),
857            );
858        }
859        let path = &args[1];
860        if !path.starts_with("/dev/bus/usb/") {
861            return Err("expected a usbfs device path".into());
862        }
863        let file = OpenOptions::new().read(true).write(true).open(path)?;
864        let fd = file.as_raw_fd();
865        // Read and validate the actual descriptor before claiming or invoking the driver.
866        let mut descriptor = [0u8; 18];
867        assert_eq!(control(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?, 18);
868        assert_eq!((descriptor[0], descriptor[1]), (18, 1));
869        assert_eq!(
870            (
871                u16::from_le_bytes([descriptor[8], descriptor[9]]),
872                u16::from_le_bytes([descriptor[10], descriptor[11]])
873            ),
874            (VID, PID),
875            "refusing a device other than the fixture"
876        );
877        // Select the explicitly advertised fixture configuration before interface claims.
878        let configuration = match args[2].as_str() {
879            "badd" => 2u32,
880            "full-uac3"
881            | "full-uac3-volatile"
882            | "full-uac3-clock"
883            | "full-uac3-clock-bad"
884            | "full-uac3-clock-stale"
885            | "full-uac3-nearest" => 3,
886            _ => 1,
887        };
888        if configuration != 1 {
889            let mut config_descriptor = [0u8; 9];
890            assert_eq!(
891                control(
892                    fd,
893                    0x80,
894                    6,
895                    0x0200 | (configuration as u16 - 1),
896                    0,
897                    &mut config_descriptor
898                )?,
899                9
900            );
901            assert_eq!(
902                (
903                    config_descriptor[0],
904                    config_descriptor[1],
905                    config_descriptor[5]
906                ),
907                (9, 2, configuration as u8)
908            );
909            if unsafe { libc::ioctl(fd, 0x80045505u32 as _, &configuration) } != 0 {
910                return Err(std::io::Error::last_os_error().into());
911            }
912        }
913        let claims = if args[2] == "duplex" {
914            vec![0u8, 1, 2, 3]
915        } else {
916            vec![0u8, 1]
917        };
918        for &interface in &claims {
919            claim(fd, u32::from(interface), true)?;
920        }
921        assert_eq!(alt(fd)?, 0);
922        if matches!(
923            args[2].as_str(),
924            "badd" | "full-uac3" | "full-uac3-volatile"
925        ) {
926            assert_eq!(power(fd)?, 0, "power domain must initially be D0");
927            let mut state = [2u8];
928            assert_eq!(control(fd, 0x21, 1, 0x0200, 0x0a00, &mut state)?, 1);
929            assert_eq!(power(fd)?, 2, "failed to seed D2 baseline");
930        }
931        let mut info = DeviceInfo::new(VID, PID, "USB/IP audio fixture")
932            .with_claimed_interfaces(claims)
933            .with_device_name(path);
934        info.configuration_id = Some(configuration as u8);
935        let config = DacConfig {
936            require_hardware_volume: false,
937            require_verified_rate: true,
938            ..DacConfig::default()
939        };
940        let dac = if args[2] == "duplex" {
941            Dac::open_duplex_device(fd, info, config)?
942        } else {
943            Dac::open(fd, info, config)?
944        };
945        if args[2] == "duplex" {
946            return duplex(dac, fd);
947        }
948        if args[2] == "retire" {
949            return retire(dac, fd);
950        }
951        if args[2] == "reconfigure" {
952            return reconfigure(dac, fd);
953        }
954        if args[2].starts_with("dop-") {
955            return dop_resolution(dac, fd, &args[2]);
956        }
957        let caps = dac.capabilities()?;
958        if args[2] == "refuse-set" {
959            out_of_band("reset")?;
960            let requests = [
961                StreamRequest::pcm(96_000, 2, 16),
962                StreamRequest::pcm(48_000, 2, 16),
963            ];
964            let failure = dac.negotiate_candidates(&requests);
965            assert!(
966                matches!(
967                    failure,
968                    Err(Error::ClockUnverified {
969                        requested_hz: 96_000,
970                        ..
971                    })
972                ),
973                "refused SET must be terminal: {failure:?}"
974            );
975            let snapshot = out_of_band("snapshot")?;
976            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
977            assert!(rates.contains("96000"));
978            assert!(
979                !rates.contains("48000"),
980                "second candidate was tried after uncertain SET: {snapshot}"
981            );
982            let retirement = dac.retirement();
983            dac.close()?;
984            assert!(retirement.wait(Duration::from_secs(3)));
985            assert_eq!(alt(fd)?, 0);
986            for interface in [1, 0] {
987                claim(fd, interface, false)?;
988            }
989            println!("USBIP_LIFECYCLE_PASS mode=refuse-set snapshot={snapshot}");
990            return Ok(());
991        }
992        if matches!(args[2].as_str(), "selector" | "zero-res") {
993            let (requested, expected) = if args[2] == "selector" {
994                (192_000, 96_000)
995            } else {
996                (96_000, 44_100)
997            };
998            out_of_band("reset")?;
999            let request =
1000                StreamRequest::pcm(requested, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1001            let format = dac.negotiate(&request)?;
1002            assert_eq!(format.sample_rate, expected);
1003            let stream = dac.open_stream(&format, Arc::new(|_| {}))?;
1004            let snapshot = out_of_band("snapshot")?;
1005            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
1006            let rejected = requested.to_string();
1007            assert!(
1008                !rates
1009                    .split(|c: char| !c.is_ascii_digit())
1010                    .any(|v| v == rejected),
1011                "requested unsupported rate was sent: {snapshot}"
1012            );
1013            println!(
1014                "NEGOTIATE_CASE mode={} requested={requested} actual={expected} {snapshot}",
1015                args[2]
1016            );
1017            stream.close()?;
1018            let retirement = dac.retirement();
1019            dac.close()?;
1020            assert!(retirement.wait(Duration::from_secs(3)));
1021            assert_eq!(alt(fd)?, 0);
1022            for interface in [1, 0] {
1023                claim(fd, interface, false)?;
1024            }
1025            println!("USBIP_LIFECYCLE_PASS mode={} retired=true", args[2]);
1026            return Ok(());
1027        }
1028        if args[2] == "badd" {
1029            badd(&dac, fd, &caps)?;
1030            assert_eq!(alt(fd)?, 0);
1031            dac.close()?;
1032            assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
1033            assert_eq!(alt(fd)?, 0);
1034            assert_eq!(power(fd)?, 2, "BADD must restore D2");
1035            let power_log = out_of_band("snapshot")?;
1036            let powers = power_log
1037                .split("power=[")
1038                .nth(1)
1039                .ok_or("missing power history")?
1040                .split(']')
1041                .next()
1042                .ok_or("missing power terminator")?;
1043            assert!(
1044                powers
1045                    .split(", ")
1046                    .collect::<Vec<_>>()
1047                    .windows(2)
1048                    .any(|pair| pair == ["0", "2"]),
1049                "expected D0 to D2 transition: {power_log}"
1050            );
1051            for interface in [1, 0] {
1052                claim(fd, interface, false)?;
1053            }
1054            println!("USBIP_LIFECYCLE_PASS mode=badd alt=0 retired=true");
1055            return Ok(());
1056        }
1057        if args[2] == "full-uac3-nearest" {
1058            return full_uac3_nearest(dac, fd, &caps);
1059        }
1060        if matches!(args[2].as_str(), "full-uac3" | "full-uac3-volatile") {
1061            return full_uac3(dac, fd, &caps, args[2] == "full-uac3-volatile");
1062        }
1063        assert_eq!(
1064            caps.uac_version,
1065            if args[2].starts_with("full-uac3-clock") {
1066                UacVersion::V3
1067            } else {
1068                UacVersion::V2
1069            }
1070        );
1071        assert_eq!(caps.link_speed, LinkSpeed::High);
1072        let mut rates = caps.pcm_sample_rates.clone();
1073        rates.sort_unstable();
1074        rates.dedup();
1075        assert_eq!(rates, [48_000, 96_000], "unexpected fixture rates");
1076        assert!(
1077            matches!(
1078                dac.negotiate(&StreamRequest::pcm(192_000, 2, 16)),
1079                Err(Error::Unsupported { .. })
1080            ),
1081            "exact 192 kHz must be refused"
1082        );
1083        let request =
1084            StreamRequest::pcm(192_000, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1085        let format = dac.negotiate(&request)?;
1086        assert_eq!(
1087            (
1088                format.sample_rate,
1089                format.channels,
1090                format.valid_bits,
1091                format.subslot_bytes,
1092                format.interface_number,
1093                format.alt_setting
1094            ),
1095            (96_000, 2, 16, 2, 1, 1)
1096        );
1097        assert_eq!(format.sync_type, SyncKind::Synchronous);
1098        assert_eq!(format.endpoint_address, 0x01);
1099        assert_eq!(format.link_speed, LinkSpeed::High);
1100        assert_eq!(format.bytes_per_frame(), 4);
1101        if args[2].starts_with("full-uac3-clock") {
1102            assert_eq!(format.service_interval_us, 125);
1103            assert!(!format.explicit_feedback);
1104        }
1105        let clock = format
1106            .clock
1107            .as_ref()
1108            .ok_or("fixture clock missing")?
1109            .clone();
1110        assert_eq!(
1111            (clock.control_interface, clock.source_id),
1112            (
1113                0,
1114                if args[2].starts_with("full-uac3-clock") {
1115                    9
1116                } else {
1117                    0x10
1118                }
1119            )
1120        );
1121        println!("NEGOTIATED exact192=unsupported nearest192=96000 format={format:?}");
1122        let listener = Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}"));
1123        match args[2].as_str() {
1124            "normal" | "full-uac3-clock" => {
1125                let stream = dac.open_stream(&format, listener)?;
1126                assert_eq!(alt(fd)?, 1);
1127                let mut current = [0u8; 4];
1128                assert_eq!(
1129                    control(
1130                        fd,
1131                        0xa1,
1132                        1,
1133                        0x0100,
1134                        (u16::from(clock.source_id) << 8) | u16::from(clock.control_interface),
1135                        &mut current
1136                    )?,
1137                    4
1138                );
1139                assert_eq!(
1140                    u32::from_le_bytes(current),
1141                    96_000,
1142                    "post-alt clock readback"
1143                );
1144                let mut pcm = Vec::with_capacity(9600 * 4);
1145                for i in 0..9600i32 {
1146                    let v = (((i % 96) - 48) * 20) as i16;
1147                    pcm.extend_from_slice(&v.to_le_bytes());
1148                    pcm.extend_from_slice(&(-v).to_le_bytes());
1149                }
1150                for _ in 0..3 {
1151                    stream.write(&pcm)?;
1152                }
1153                stream.play()?;
1154                let start = Instant::now();
1155                while start.elapsed() < Duration::from_secs(3)
1156                    && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
1157                {
1158                    let n = stream.writable_bytes().min(pcm.len());
1159                    if n >= 4 {
1160                        stream.write(&pcm[..n - n % 4])?;
1161                    }
1162                    thread::sleep(Duration::from_millis(2));
1163                }
1164                let stats = stream.stats();
1165                println!("PCM_STATS {stats:?}");
1166                assert!(
1167                    stats.played_frames > 0 && stats.completed_transfers > 0,
1168                    "no actual PCM completions"
1169                );
1170                stream.close()?;
1171            }
1172            mode => match dac.open_stream(&format, listener) {
1173                Err(error @ Error::ClockUnverified { .. }) => {
1174                    let expected_reported = if mode == "bad-cur" || mode == "full-uac3-clock-bad" {
1175                        None
1176                    } else {
1177                        Some(48_000)
1178                    };
1179                    assert!(
1180                        matches!(error, Error::ClockUnverified { requested_hz: 96_000, reported_hz } if reported_hz == expected_reported)
1181                    );
1182                    println!(
1183                        "EXPECTED_FAILURE mode={mode} code={} error={error:?}",
1184                        error.code()
1185                    );
1186                }
1187                Err(error) => {
1188                    return Err(format!("unexpected failure for {mode}: {error:?}").into())
1189                }
1190                Ok(stream) => {
1191                    stream.close()?;
1192                    return Err(format!("{mode} incorrectly admitted the stream").into());
1193                }
1194            },
1195        }
1196        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
1197        dac.close()?;
1198        assert!(
1199            Dac::await_usb_retirement(Duration::from_secs(3)),
1200            "USB retirement timed out"
1201        );
1202        assert_eq!(alt(fd)?, 0);
1203        for interface in [1, 0] {
1204            claim(fd, interface, false)?;
1205        }
1206        println!("USBIP_LIFECYCLE_PASS mode={} alt=0 retired=true", args[2]);
1207        Ok(())
1208    }
examples/qemu_smoke.rs (line 159)
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 latency_frames(&self) -> u64

Music frames between the host and the DAC: in the ring plus on the bus. What the audible position lags the written position by.

Source

pub fn queued_frames(&self) -> u64

Frames waiting in the ring, in the unit of StreamFormat::counter_rate_hz. Cheaper than stats (StreamStats::queued_frames), for a host that wants to know how full the ring is on every cycle of its writer loop.

Source

pub fn is_bit_perfect(&self) -> bool

Bit-perfect means: no software gain, a verified clock at the requested rate, no frame lost on the bus, and the wire payload is real audio. False as soon as any of that stops being true, and for good after a lost frame.

Source

pub fn bit_perfect_blocker(&self) -> Option<BitPerfectBlocker>

Why is_bit_perfect is false: None when it is true, otherwise the first condition that fails.

Examples found in repository?
examples/guide_player.rs (line 350)
346pub fn status_line(stream: &DacStream, engine_untouched: bool, lossy_source: bool) -> String {
347    if !engine_untouched {
348        return "Not bit-perfect: the player is processing the audio".to_string();
349    }
350    match stream.bit_perfect_blocker() {
351        None if lossy_source => "Direct USB, decoded from a lossy file".to_string(),
352        None => "Bit-perfect".to_string(),
353        Some(blocker) => format!("Not bit-perfect: {}", blocker_text(blocker)),
354    }
355}
Source

pub fn set_software_gain(&self, gain: f32) -> Result<()>

Scales PCM samples by gain (0.0 to 16.0) as each transfer is prepared, so it takes effect within the bus latency rather than the ring depth. Rounds to nearest and saturates; no dither. Any value other than 1.0 ends bit-perfect output. Refused for DoP and native DSD (it would corrupt the bitstream).

Source

pub fn software_gain(&self) -> f32

Source

pub fn set_host_processing(&self, processing: bool)

Tells the stream that the host processes the audio (EQ, DSP, crossfade, pitch) before it writes it. A change the host makes is then heard after the ring’s fill, so writable_bytes asks for the shallow processing_buffer_target_ms instead of the deep target, as it does for software gain. Nothing is flushed when the depth changes (see writable_bytes).

It is only a hint about buffering. It does not change a sample, and the library cannot see what the host did to the audio, so it does not touch is_bit_perfect: a host that processes audio is responsible for not claiming bit-perfect output. It has no effect for DoP and native DSD, which are never processed.

Source

pub fn host_processing(&self) -> bool

Whether set_host_processing is on.

Source

pub fn explicit_feedback_diagnostics( &self, ) -> Option<ExplicitFeedbackDiagnostics>

A bounded snapshot of the explicit USB feedback path for this stream.

Available after the worker has selected the endpoint, including after a feedback failure. Other pacing modes return None.

Source

pub fn stats(&self) -> StreamStats

Examples found in repository?
examples/two_dac_smoke.rs (line 125)
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    }
More examples
Hide additional examples
examples/usbip_lifecycle.rs (line 129)
79    fn badd(
80        dac: &Dac,
81        fd: i32,
82        caps: &usbdac_core::Capabilities,
83    ) -> Result<(), Box<dyn std::error::Error>> {
84        assert_eq!(caps.uac_version, UacVersion::V3);
85        assert_eq!(caps.link_speed, LinkSpeed::High);
86        assert_eq!(caps.pcm_sample_rates, [48_000]);
87        assert!(matches!(
88            dac.negotiate(&StreamRequest::pcm(96_000, 2, 16)),
89            Err(Error::Unsupported { .. })
90        ));
91        let format = dac.negotiate(
92            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
93        )?;
94        assert_eq!(
95            (
96                format.sample_rate,
97                format.channels,
98                format.valid_bits,
99                format.subslot_bytes,
100                format.interface_number,
101                format.alt_setting,
102                format.endpoint_address
103            ),
104            (48_000, 2, 16, 2, 1, 1, 1)
105        );
106        assert!(
107            format.explicit_feedback,
108            "BADD profile must expose feedback"
109        );
110        println!("BADD_FORMAT {format:?}");
111        let stream = dac.open_stream(
112            &format,
113            Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}")),
114        )?;
115        assert_eq!(alt(fd)?, 1);
116        let mut pcm = Vec::with_capacity(4800 * 4);
117        for i in 0..4800i32 {
118            let v = (((i % 96) - 48) * 20) as i16;
119            pcm.extend_from_slice(&v.to_le_bytes());
120            pcm.extend_from_slice(&(-v).to_le_bytes());
121        }
122        for _ in 0..3 {
123            stream.write(&pcm)?;
124        }
125        stream.play()?;
126        let start = Instant::now();
127        while start.elapsed() < Duration::from_secs(3)
128            && (stream.played_frames() == 0
129                || stream.stats().completed_transfers == 0
130                || stream.stats().feedback_reports == 0)
131        {
132            let n = stream.writable_bytes().min(pcm.len());
133            if n >= 4 {
134                stream.write(&pcm[..n - n % 4])?;
135            }
136            thread::sleep(Duration::from_millis(2));
137        }
138        let stats = stream.stats();
139        println!("BADD_PCM_STATS {stats:?}");
140        assert!(
141            stats.played_frames > 0 && stats.completed_transfers > 0 && stats.feedback_reports > 0,
142            "BADD playback or feedback has no real completions"
143        );
144        stream.close()?;
145        Ok(())
146    }
147
148    fn full_uac3(
149        dac: Dac,
150        fd: i32,
151        caps: &usbdac_core::Capabilities,
152        volatile: bool,
153    ) -> Result<(), Box<dyn std::error::Error>> {
154        use usbdac_core::routing::{
155            ControlKey, Entity, RouteEdit, RouteValue, RoutingHandBackOutcome,
156        };
157        assert_eq!(caps.uac_version, UacVersion::V3);
158        assert_eq!(caps.link_speed, LinkSpeed::High);
159        let key = ControlKey::Selector(Entity {
160            interface: 0,
161            id: 8,
162        });
163        assert_eq!(power(fd)?, 2, "initial power must be D2");
164        let snapshot = dac.routing_discover_powered()?;
165        println!("UAC3_ROUTING snapshot={snapshot:?}");
166        assert_eq!(snapshot.configuration(), 3);
167        assert_eq!(power(fd)?, 2, "discovery must restore D2");
168        assert_eq!(
169            dac.routing_read_powered(&snapshot, key)?,
170            RouteValue::SelectorPin(1)
171        );
172        assert_eq!(power(fd)?, 2, "read must restore D2");
173        let report = dac.routing_apply_powered(
174            &snapshot,
175            &[RouteEdit {
176                key,
177                expected: RouteValue::SelectorPin(1),
178                value: RouteValue::SelectorPin(2),
179            }],
180        )?;
181        assert_eq!(report.changed, vec![key]);
182        let applied = out_of_band("snapshot")?;
183        assert!(
184            applied.contains("selector=[2]"),
185            "fixture selector was not written: {applied}"
186        );
187        assert!(
188            applied.contains(if volatile {
189                "selector_state=1"
190            } else {
191                "selector_state=2"
192            }),
193            "unexpected fixture selector after D2: {applied}"
194        );
195        assert_eq!(power(fd)?, 2, "apply must restore D2");
196        let updated = dac.routing_discover_powered()?;
197        assert_eq!(
198            dac.routing_read_powered(&updated, key)?,
199            RouteValue::SelectorPin(if volatile { 1 } else { 2 }),
200            "selector readback must reflect the fixture's D2 behavior"
201        );
202        assert_eq!(power(fd)?, 2);
203        dac.close()?;
204        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
205        let hand_back = snapshot
206            .hand_back_report()
207            .ok_or("missing routing hand-back report")?;
208        println!("UAC3_HAND_BACK {hand_back:?}");
209        if !volatile {
210            assert!(
211                hand_back
212                    .controls
213                    .contains(&(key, RoutingHandBackOutcome::Restored)),
214                "selector hand-back was not verified"
215            );
216        }
217        assert_eq!(power(fd)?, 2, "final power must be D2");
218        assert!(
219            out_of_band("snapshot")?.contains("selector_state=1"),
220            "fixture selector was not restored"
221        );
222        assert_eq!(alt(fd)?, 0);
223        for interface in [1, 0] {
224            claim(fd, interface, false)?;
225        }
226        println!("USBIP_LIFECYCLE_PASS mode=full-uac3 selector=restored power=D2 retired=true");
227        Ok(())
228    }
229
230    // Full UAC3 whose clock RANGE lists only 48 kHz behind a powered route that
231    // cannot certify a live refusal. The cached model excludes 44.1 kHz, so the
232    // ranked loop and the playback candidates must skip it without any USB request,
233    // as ALSA never offers a rate absent from its format table (pcm.c hw_rule_rate).
234    fn full_uac3_nearest(
235        dac: Dac,
236        fd: i32,
237        caps: &usbdac_core::Capabilities,
238    ) -> Result<(), Box<dyn std::error::Error>> {
239        use usbdac_core::playback::PlaybackPolicy;
240        assert_eq!(caps.uac_version, UacVersion::V3);
241        assert_eq!(caps.link_speed, LinkSpeed::High);
242        let mut rates = caps.pcm_sample_rates.clone();
243        rates.sort_unstable();
244        rates.dedup();
245        assert_eq!(rates, [48_000], "unexpected full-UAC3 fixture rates");
246        let no_44k = |snapshot: &str| -> Result<(), Box<dyn std::error::Error>> {
247            let sets = snapshot.split(';').next().ok_or("missing rate snapshot")?;
248            if sets
249                .split(|c: char| !c.is_ascii_digit())
250                .any(|v| v == "44100")
251            {
252                return Err(format!("model-excluded 44100 Hz was programmed: {snapshot}").into());
253            }
254            Ok(())
255        };
256        out_of_band("reset")?;
257        let format = dac.negotiate(
258            &StreamRequest::pcm(44_100, 2, 16).with_rate_policy(RatePolicy::NearestSupported),
259        )?;
260        assert_eq!(
261            (format.sample_rate, format.channels, format.valid_bits),
262            (48_000, 2, 16)
263        );
264        let negotiated = out_of_band("snapshot")?;
265        no_44k(&negotiated)?;
266        out_of_band("reset")?;
267        let decision = dac.resolve_playback(
268            &StreamRequest::pcm(44_100, 2, 16),
269            &PlaybackPolicy::default(),
270        )?;
271        assert_eq!(decision.format.sample_rate, 48_000);
272        assert_eq!(decision.candidates[0], StreamRequest::pcm(44_100, 2, 16));
273        assert!(
274            matches!(decision.exact_refusal, Some(Error::Unsupported { .. })),
275            "the skipped exact source must report a typed refusal: {:?}",
276            decision.exact_refusal
277        );
278        let resolved = out_of_band("snapshot")?;
279        no_44k(&resolved)?;
280        println!(
281            "NEGOTIATE_CASE mode=full-uac3-nearest requested=44100 actual=48000 resolve=48000 attempted={} negotiate={negotiated} resolve_snapshot={resolved}",
282            decision.attempted_candidates
283        );
284        assert_eq!(alt(fd)?, 0);
285        dac.close()?;
286        assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
287        assert_eq!(alt(fd)?, 0);
288        for interface in [1, 0] {
289            claim(fd, interface, false)?;
290        }
291        println!("USBIP_LIFECYCLE_PASS mode=full-uac3-nearest retired=true");
292        Ok(())
293    }
294
295    fn vendor(fd: i32, value: u16) -> Result<(), Box<dyn std::error::Error>> {
296        assert_eq!(control(fd, 0x40, 0x5a, value, 0, &mut [])?, 0);
297        Ok(())
298    }
299    fn vendor_status(fd: i32) -> Result<u8, Box<dyn std::error::Error>> {
300        let mut status = [0u8];
301        assert_eq!(control(fd, 0xc0, 0x5a, 0, 0, &mut status)?, 1);
302        Ok(status[0])
303    }
304    fn out_of_band(action: &str) -> Result<String, Box<dyn std::error::Error>> {
305        let port = std::env::var("USBDAC_USBIP_PORT")?;
306        let _: u16 = port.parse()?;
307        let output = std::process::Command::new("/fixture/usbip_uac")
308            .args(["--control", action, "--port", &port])
309            .output()?;
310        if !output.status.success() {
311            return Err(format!(
312                "fixture control {action} failed: {}",
313                String::from_utf8_lossy(&output.stderr)
314            )
315            .into());
316        }
317        Ok(String::from_utf8(output.stdout)?.trim().to_string())
318    }
319    fn wait_status(fd: i32, mask: u8) -> Result<u8, Box<dyn std::error::Error>> {
320        let start = Instant::now();
321        loop {
322            let status = vendor_status(fd)?;
323            if status & mask == mask {
324                return Ok(status);
325            }
326            if start.elapsed() >= Duration::from_secs(5) {
327                return Err(
328                    format!("fixture status {status:#04x} did not reach {mask:#04x}").into(),
329                );
330            }
331            thread::sleep(Duration::from_millis(10));
332        }
333    }
334    fn test_pcm() -> Vec<u8> {
335        let mut pcm = Vec::with_capacity(4800 * 4);
336        for i in 0..4800i32 {
337            let v = (((i % 96) - 48) * 20) as i16;
338            pcm.extend_from_slice(&v.to_le_bytes());
339            pcm.extend_from_slice(&(-v).to_le_bytes());
340        }
341        pcm
342    }
343    fn feed(stream: &usbdac_core::DacStream, pcm: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
344        let n = stream.writable_bytes().min(pcm.len());
345        if n >= 4 {
346            stream.write(&pcm[..n - n % 4])?;
347        }
348        Ok(())
349    }
350    fn duplex(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
351        use usbdac_core::{CaptureRequest, CaptureState};
352        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
353        let request = CaptureRequest {
354            sample_rate: 48_000,
355            channels: 2,
356            valid_bits: 16,
357            channel_map: None,
358        };
359        let (playback, capture) = dac.open_duplex(
360            &format,
361            &request,
362            48_000,
363            Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")),
364        )?;
365        assert_eq!(
366            (capture.interface_number(), capture.endpoint_address()),
367            (3, 0x82)
368        );
369        let pcm = test_pcm();
370        for _ in 0..3 {
371            playback.write(&pcm)?;
372        }
373        playback.play()?;
374        let start = Instant::now();
375        let mut received = [0u8; 4096];
376        let mut marker_frames = 0;
377        while start.elapsed() < Duration::from_secs(5) && marker_frames == 0 {
378            feed(&playback, &pcm)?;
379            let frames = capture.read(&mut received)?;
380            if frames > 0 {
381                assert!(
382                    received[..frames * 4]
383                        .chunks_exact(4)
384                        .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
385                    "unexpected capture payload"
386                );
387                marker_frames = frames;
388            }
389            thread::sleep(Duration::from_millis(5));
390        }
391        assert!(marker_frames > 0, "no actual capture marker");
392        println!("DUPLEX_CAPTURE_MARKER frames={marker_frames}");
393        out_of_band("mixed")?;
394        let mixed_start = Instant::now();
395        while mixed_start.elapsed() < Duration::from_secs(5) {
396            feed(&playback, &pcm)?;
397            let frames = capture.read(&mut received)?;
398            assert!(
399                received[..frames * 4]
400                    .chunks_exact(4)
401                    .all(|frame| frame == [0x34, 0x12, 0xcc, 0xed]),
402                "invalid packet leaked into capture"
403            );
404            let stats = capture.stats();
405            if stats.short_packets > 0 && stats.failed_packets > 0 && stats.malformed_packets > 0 {
406                break;
407            }
408            thread::sleep(Duration::from_millis(5));
409        }
410        let mixed_stats = capture.stats();
411        assert!(
412            mixed_stats.short_packets > 0
413                && mixed_stats.failed_packets > 0
414                && mixed_stats.malformed_packets > 0,
415            "mixed packet statuses not observed: {mixed_stats:?}"
416        );
417        println!("DUPLEX_MIXED_PACKETS {mixed_stats:?}");
418        vendor(fd, 1)?;
419        let start = Instant::now();
420        while start.elapsed() < Duration::from_secs(5) && capture.state() == CaptureState::Active {
421            feed(&playback, &pcm)?;
422            thread::sleep(Duration::from_millis(5));
423        }
424        assert_eq!(capture.state(), CaptureState::Failed);
425        assert!(
426            capture.last_error().is_some(),
427            "capture failure must preserve an error"
428        );
429        assert_ne!(
430            vendor_status(fd)? & 8,
431            0,
432            "fixture did not deliver capture fault"
433        );
434        let before = playback.played_frames();
435        let start = Instant::now();
436        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() <= before {
437            feed(&playback, &pcm)?;
438            thread::sleep(Duration::from_millis(5));
439        }
440        let after = playback.played_frames();
441        assert!(
442            after > before,
443            "playback stopped after independent capture failure"
444        );
445        println!(
446            "DUPLEX_ISOLATION_PASS before={before} after={after} error={:?}",
447            capture.last_error()
448        );
449        capture.close()?;
450        playback.close()?;
451        let retirement = dac.retirement();
452        dac.close()?;
453        assert!(retirement.wait(Duration::from_secs(3)));
454        assert_eq!(alt(fd)?, 0);
455        for interface in [3, 2, 1, 0] {
456            claim(fd, interface, false)?;
457        }
458        println!("USBIP_LIFECYCLE_PASS mode=duplex retired=true");
459        Ok(())
460    }
461    fn retire(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
462        let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
463        let playback =
464            dac.open_stream(&format, Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}")))?;
465        let pcm = test_pcm();
466        for _ in 0..3 {
467            playback.write(&pcm)?;
468        }
469        playback.play()?;
470        let start = Instant::now();
471        while start.elapsed() < Duration::from_secs(5) && playback.played_frames() == 0 {
472            feed(&playback, &pcm)?;
473            thread::sleep(Duration::from_millis(5));
474        }
475        assert!(playback.played_frames() > 0, "playback never completed");
476        let token = dac.retirement();
477        vendor(fd, 1)?;
478        let status = wait_status(fd, 2)?;
479        println!("RETIRE_HELD status={status:#04x}");
480        let start = Instant::now();
481        let result = dac.close();
482        let elapsed = start.elapsed();
483        println!(
484            "RETIRE_CLOSE result={result:?} elapsed_ms={}",
485            elapsed.as_millis()
486        );
487        assert!(
488            matches!(result, Err(Error::Transfer(_))),
489            "close must report timeout: {result:?}"
490        );
491        assert!(
492            elapsed >= Duration::from_millis(2500),
493            "close returned before its actual timeout: {elapsed:?}"
494        );
495        assert!(
496            !token.wait(Duration::ZERO),
497            "owner retired while URB unlink was held"
498        );
499        let status: u8 = out_of_band("status")?.parse()?;
500        assert_eq!(
501            status & 0x14,
502            0x14,
503            "unlink must be held and AS1 active: {status:#04x}"
504        );
505        println!("RETIRE_PENDING elapsed_ms={}", elapsed.as_millis());
506        out_of_band("release")?;
507        assert!(
508            token.wait(Duration::from_secs(10)),
509            "owner did not retire after unlink release"
510        );
511        assert_eq!(alt(fd)?, 0, "retired owner did not restore alt zero");
512        drop(playback);
513        for interface in [1, 0] {
514            claim(fd, interface, false)?;
515        }
516        println!("USBIP_LIFECYCLE_PASS mode=retire retired=true alt=0");
517        Ok(())
518    }
519
520    fn reconfigure(dac: Dac, fd: i32) -> Result<(), Box<dyn std::error::Error>> {
521        use usbdac_core::StreamState;
522        let listener = Arc::new(|e: DacEvent| eprintln!("EVENT {e:?}"));
523        let initial = dac.negotiate(&StreamRequest::pcm(96_000, 2, 16))?;
524        assert_eq!(
525            (
526                initial.sample_rate,
527                initial.interface_number,
528                initial.alt_setting
529            ),
530            (96_000, 1, 1)
531        );
532        let previous = dac.open_stream(&initial, listener.clone())?;
533        let pcm = test_pcm();
534        for _ in 0..3 {
535            previous.write(&pcm)?;
536        }
537        previous.play()?;
538        let start = Instant::now();
539        while start.elapsed() < Duration::from_secs(5) && previous.played_frames() == 0 {
540            feed(&previous, &pcm)?;
541            thread::sleep(Duration::from_millis(5));
542        }
543        assert!(
544            previous.played_frames() > 0,
545            "original playback never completed"
546        );
547        out_of_band("reset")?;
548        println!("RECONFIGURE_PHASE_BEGIN from=96000 to=48000");
549        let request = StreamRequest::pcm(48_000, 2, 16);
550        let replacement = dac.reconfigure_stream_candidates(
551            &previous,
552            &[request],
553            listener,
554            Duration::from_secs(3),
555        )?;
556        println!("RECONFIGURE_PHASE_END from=96000 to=48000");
557        assert!(
558            replacement.rollback_cause.is_none(),
559            "unexpected rollback: {:?}",
560            replacement.rollback_cause
561        );
562        assert_eq!(previous.state(), StreamState::Closed);
563        assert_eq!(replacement.stream.state(), StreamState::Paused);
564        assert_eq!(replacement.stream.format().sample_rate, 48_000);
565        assert_eq!(replacement.stream.played_frames(), 0);
566        assert_eq!(alt(fd)?, 1);
567        let transitions = out_of_band("snapshot")?;
568        let alt_history = transitions
569            .split("alts=[")
570            .nth(1)
571            .ok_or("missing alternate history")?
572            .split(']')
573            .next()
574            .ok_or("missing alternate terminator")?;
575        let unlink_count: u64 = transitions
576            .split("unlinks=")
577            .nth(1)
578            .ok_or("missing unlink count")?
579            .parse()?;
580        assert!(
581            unlink_count <= 16,
582            "more than one bounded transfer set cancelled: {transitions}"
583        );
584        let mut alts: Vec<_> = alt_history.split(", ").collect();
585        alts.dedup();
586        assert_eq!(
587            alts,
588            ["0", "1"],
589            "unexpected alternate transitions: {transitions}"
590        );
591        // USB-level count of the live 96 -> 48 kHz replacement on interface 1 and
592        // clock 16. ALSA's UAC2 prepare deselects the alternate first, writes the
593        // rate, and enables the alternate last (sound/usb/endpoint.c
594        // snd_usb_endpoint_prepare:1498-1530, endpoint_set_interface:917-951).
595        // ALSA elides a SET_INTERFACE to the alternate it already holds
596        // (endpoint.c:926-927); usbdac re-asserts alt 0 at stop, before and after
597        // the read-only negotiation and before activation, which is idempotent.
598        let sequence = out_of_band("sequence")?;
599        let writes: Vec<_> = sequence
600            .strip_prefix("seq=[")
601            .and_then(|rest| rest.strip_suffix(']'))
602            .ok_or("missing write sequence")?
603            .split(", ")
604            .collect();
605        let count = |w: &str| writes.iter().filter(|x| **x == w).count();
606        assert_eq!(
607            (
608                count("alt0"),
609                count("alt1"),
610                count("rate48000"),
611                writes.len()
612            ),
613            (4, 1, 2, 7),
614            "unexpected replacement write counts: {sequence}"
615        );
616        assert_eq!(
617            writes.first(),
618            Some(&"alt0"),
619            "old alternate not deselected first: {sequence}"
620        );
621        assert_eq!(
622            writes.last(),
623            Some(&"alt1"),
624            "alternate not enabled last: {sequence}"
625        );
626        assert!(
627            !writes
628                .iter()
629                .any(|w| w.starts_with("rate") && *w != "rate48000"),
630            "a rate other than 48 kHz was written: {sequence}"
631        );
632        // Fresh post-replacement evidence: the DAC's clock reads back 48 kHz at alt 1.
633        let mut current = [0u8; 4];
634        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
635        assert_eq!(u32::from_le_bytes(current), 48_000);
636        println!(
637            "RECONFIGURE_USB_WRITES {sequence} clock_readback=48000 alt={}",
638            alt(fd)?
639        );
640        let stream = replacement.stream;
641        for _ in 0..3 {
642            stream.write(&pcm)?;
643        }
644        stream.play()?;
645        let start = Instant::now();
646        while start.elapsed() < Duration::from_secs(5)
647            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
648        {
649            feed(&stream, &pcm)?;
650            thread::sleep(Duration::from_millis(5));
651        }
652        assert!(
653            stream.played_frames() > 0 && stream.stats().completed_transfers > 0,
654            "replacement playback never completed"
655        );
656        let stats = stream.stats();
657        assert!(stats.played_frames <= stats.frames_written);
658        assert!(stats.queued_frames <= stats.frames_written);
659        assert!(
660            stats.underruns <= 50,
661            "USB/IP replacement exceeded 50 underruns: {stats:?}"
662        );
663        let mut current = [0u8; 4];
664        assert_eq!(control(fd, 0xa1, 1, 0x0100, 0x1000, &mut current)?, 4);
665        assert_eq!(
666            u32::from_le_bytes(current),
667            48_000,
668            "clock drifted during replacement playback"
669        );
670        let fixture_stats = out_of_band("snapshot")?;
671        assert!(
672            !fixture_stats.contains("out_completions=0"),
673            "replacement has no completed OUT URB: {fixture_stats}"
674        );
675        println!(
676            "RECONFIGURE_PLAYBACK_PASS stats={stats:?} underrun_limit=50 fixture={fixture_stats}"
677        );
678        stream.close()?;
679        let retirement = dac.retirement();
680        dac.close()?;
681        assert!(retirement.wait(Duration::from_secs(3)));
682        assert_eq!(alt(fd)?, 0);
683        for interface in [1, 0] {
684            claim(fd, interface, false)?;
685        }
686        println!("USBIP_LIFECYCLE_PASS mode=reconfigure retired=true alt=0");
687        Ok(())
688    }
689
690    /// DoP resolution through the production resolve_playback, transport and
691    /// PlaybackStream. DoP v1.1 carries 16 DSD bits per channel per carrier frame,
692    /// so a DoP carrier of another depth or channel count is a repack (H1), and an
693    /// exact DoP shape absent from the descriptors is never attempted (H2).
694    fn dop_resolution(dac: Dac, fd: i32, mode: &str) -> Result<(), Box<dyn std::error::Error>> {
695        use usbdac_core::playback::{PlaybackFidelity, PlaybackPolicy, PlaybackTransform};
696        use usbdac_core::Encoding;
697        let confirmed = PlaybackPolicy {
698            dop_confirmed: true,
699            ..PlaybackPolicy::default()
700        };
701        let caps = dac.capabilities()?;
702        assert!(
703            caps.exclusion_snapshot_complete,
704            "the fixture descriptor snapshot must be complete"
705        );
706        let source = StreamRequest::dop(2_822_400, if mode == "dop-stereo24" { 1 } else { 2 });
707        if mode == "dop-carrier32" {
708            // H2: 24-bit DoP on a 32-bit-only DAC reaches the 32-bit carrier.
709            let widened = dac.resolve_playback(&source, &confirmed)?;
710            println!(
711                "DOP_DECISION mode={mode} case=widen transform={:?} fidelity={:?} bits={} preflight={:?}",
712                widened.transform, widened.fidelity, widened.format.valid_bits, widened.source_preflight_refusal
713            );
714            assert!(widened.source_preflight_refusal.is_some());
715            assert_eq!(widened.format.encoding, Encoding::DoP);
716            assert_eq!(widened.format.valid_bits, 32);
717            assert_eq!(
718                widened.transform,
719                PlaybackTransform::DopRepack { target_channels: 2 }
720            );
721        }
722        let policy = if mode == "dop-carrier32" {
723            // H1: the review's smallest case.
724            PlaybackPolicy {
725                allowed_pcm_depths: Some(vec![32]),
726                ..confirmed.clone()
727            }
728        } else {
729            confirmed.clone()
730        };
731        out_of_band("reset")?;
732        let decision = dac.resolve_playback(&source, &policy)?;
733        println!(
734            "DOP_DECISION mode={mode} transform={:?} fidelity={:?} format={:?}/{}ch/{}bit preflight={:?} attempted={}",
735            decision.transform,
736            decision.fidelity,
737            decision.format.encoding,
738            decision.format.channels,
739            decision.format.valid_bits,
740            decision.source_preflight_refusal,
741            decision.attempted_candidates
742        );
743        if mode == "dop-no-carrier" {
744            // H2: confirmed DoP on a DAC that cannot carry it falls back like unconfirmed.
745            assert!(decision.source_preflight_refusal.is_some());
746            assert_eq!(decision.format.encoding, Encoding::Pcm);
747            assert!(matches!(
748                decision.transform,
749                PlaybackTransform::DsdToPcm {
750                    dop_input: true,
751                    ..
752                }
753            ));
754            let unconfirmed = dac.resolve_playback(&source, &PlaybackPolicy::default())?;
755            assert_eq!(unconfirmed.format, decision.format);
756        } else {
757            assert_eq!(decision.format.encoding, Encoding::DoP);
758            assert_eq!(decision.format.channels, 2);
759            assert_eq!(
760                decision.transform,
761                PlaybackTransform::DopRepack { target_channels: 2 }
762            );
763            assert_eq!(
764                decision.fidelity,
765                if source.channels == 2 {
766                    PlaybackFidelity::BitExact
767                } else {
768                    PlaybackFidelity::Lossless
769                }
770            );
771            assert_eq!(decision.attempted_candidates, 1);
772        }
773        let mut stream = dac.open_playback(&decision, Arc::new(|_| {}))?;
774        let channels = usize::from(source.channels);
775        let frame = decision.source_frame_bytes;
776        let mut next = 0usize;
777        let mut chunk = Vec::new();
778        let start = Instant::now();
779        let mut started = false;
780        while start.elapsed() < Duration::from_secs(3)
781            && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
782        {
783            let frames = stream.writable_bytes() / frame;
784            if frames > 0 {
785                chunk.clear();
786                for i in next..next + frames {
787                    let marker = if i % 2 == 0 { 0x05 } else { 0xfa };
788                    for _ in 0..channels {
789                        chunk.extend_from_slice(&[0x69, 0x69, marker]);
790                    }
791                }
792                next += stream.write(&chunk)? / frame;
793            }
794            if !started && next > 0 {
795                stream.play()?;
796                started = true;
797            }
798            thread::sleep(Duration::from_millis(2));
799        }
800        let stats = stream.target_stats();
801        let snapshot = out_of_band("snapshot")?;
802        println!("DOP_STATS mode={mode} source_frames={next} {stats:?} {snapshot}");
803        assert!(
804            stats.played_frames > 0 && stats.completed_transfers > 0,
805            "no DoP-resolved completions"
806        );
807        let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
808        let carrier_set = rates
809            .split(|c: char| !c.is_ascii_digit())
810            .any(|v| v == "176400");
811        // The carrier DACs clock 176.4 kHz; the exact carrier is never set on a DAC without one.
812        assert_eq!(carrier_set, mode != "dop-no-carrier", "{snapshot}");
813        if mode != "dop-no-carrier" {
814            assert!(stats.payload_verified, "the DoP payload must audit clean");
815        }
816        stream.close()?;
817        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
818        let retirement = dac.retirement();
819        dac.close()?;
820        assert!(retirement.wait(Duration::from_secs(3)));
821        assert_eq!(alt(fd)?, 0);
822        for interface in [1, 0] {
823            claim(fd, interface, false)?;
824        }
825        println!("USBIP_LIFECYCLE_PASS mode={mode} alt=0 retired=true");
826        Ok(())
827    }
828
829    pub fn run() -> Result<(), Box<dyn std::error::Error>> {
830        let args: Vec<_> = std::env::args().collect();
831        if args.len() != 3
832            || !matches!(
833                args[2].as_str(),
834                "normal"
835                    | "bad-cur"
836                    | "stale-cur"
837                    | "badd"
838                    | "full-uac3"
839                    | "full-uac3-volatile"
840                    | "full-uac3-clock"
841                    | "full-uac3-clock-bad"
842                    | "full-uac3-clock-stale"
843                    | "duplex"
844                    | "retire"
845                    | "reconfigure"
846                    | "selector"
847                    | "refuse-set"
848                    | "zero-res"
849                    | "full-uac3-nearest"
850                    | "dop-carrier32"
851                    | "dop-stereo24"
852                    | "dop-no-carrier"
853            )
854        {
855            return Err(
856                "usage: usbip_lifecycle /dev/bus/usb/BBB/DDD normal|bad-cur|stale-cur|badd|full-uac3|full-uac3-clock|duplex|retire|reconfigure".into(),
857            );
858        }
859        let path = &args[1];
860        if !path.starts_with("/dev/bus/usb/") {
861            return Err("expected a usbfs device path".into());
862        }
863        let file = OpenOptions::new().read(true).write(true).open(path)?;
864        let fd = file.as_raw_fd();
865        // Read and validate the actual descriptor before claiming or invoking the driver.
866        let mut descriptor = [0u8; 18];
867        assert_eq!(control(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?, 18);
868        assert_eq!((descriptor[0], descriptor[1]), (18, 1));
869        assert_eq!(
870            (
871                u16::from_le_bytes([descriptor[8], descriptor[9]]),
872                u16::from_le_bytes([descriptor[10], descriptor[11]])
873            ),
874            (VID, PID),
875            "refusing a device other than the fixture"
876        );
877        // Select the explicitly advertised fixture configuration before interface claims.
878        let configuration = match args[2].as_str() {
879            "badd" => 2u32,
880            "full-uac3"
881            | "full-uac3-volatile"
882            | "full-uac3-clock"
883            | "full-uac3-clock-bad"
884            | "full-uac3-clock-stale"
885            | "full-uac3-nearest" => 3,
886            _ => 1,
887        };
888        if configuration != 1 {
889            let mut config_descriptor = [0u8; 9];
890            assert_eq!(
891                control(
892                    fd,
893                    0x80,
894                    6,
895                    0x0200 | (configuration as u16 - 1),
896                    0,
897                    &mut config_descriptor
898                )?,
899                9
900            );
901            assert_eq!(
902                (
903                    config_descriptor[0],
904                    config_descriptor[1],
905                    config_descriptor[5]
906                ),
907                (9, 2, configuration as u8)
908            );
909            if unsafe { libc::ioctl(fd, 0x80045505u32 as _, &configuration) } != 0 {
910                return Err(std::io::Error::last_os_error().into());
911            }
912        }
913        let claims = if args[2] == "duplex" {
914            vec![0u8, 1, 2, 3]
915        } else {
916            vec![0u8, 1]
917        };
918        for &interface in &claims {
919            claim(fd, u32::from(interface), true)?;
920        }
921        assert_eq!(alt(fd)?, 0);
922        if matches!(
923            args[2].as_str(),
924            "badd" | "full-uac3" | "full-uac3-volatile"
925        ) {
926            assert_eq!(power(fd)?, 0, "power domain must initially be D0");
927            let mut state = [2u8];
928            assert_eq!(control(fd, 0x21, 1, 0x0200, 0x0a00, &mut state)?, 1);
929            assert_eq!(power(fd)?, 2, "failed to seed D2 baseline");
930        }
931        let mut info = DeviceInfo::new(VID, PID, "USB/IP audio fixture")
932            .with_claimed_interfaces(claims)
933            .with_device_name(path);
934        info.configuration_id = Some(configuration as u8);
935        let config = DacConfig {
936            require_hardware_volume: false,
937            require_verified_rate: true,
938            ..DacConfig::default()
939        };
940        let dac = if args[2] == "duplex" {
941            Dac::open_duplex_device(fd, info, config)?
942        } else {
943            Dac::open(fd, info, config)?
944        };
945        if args[2] == "duplex" {
946            return duplex(dac, fd);
947        }
948        if args[2] == "retire" {
949            return retire(dac, fd);
950        }
951        if args[2] == "reconfigure" {
952            return reconfigure(dac, fd);
953        }
954        if args[2].starts_with("dop-") {
955            return dop_resolution(dac, fd, &args[2]);
956        }
957        let caps = dac.capabilities()?;
958        if args[2] == "refuse-set" {
959            out_of_band("reset")?;
960            let requests = [
961                StreamRequest::pcm(96_000, 2, 16),
962                StreamRequest::pcm(48_000, 2, 16),
963            ];
964            let failure = dac.negotiate_candidates(&requests);
965            assert!(
966                matches!(
967                    failure,
968                    Err(Error::ClockUnverified {
969                        requested_hz: 96_000,
970                        ..
971                    })
972                ),
973                "refused SET must be terminal: {failure:?}"
974            );
975            let snapshot = out_of_band("snapshot")?;
976            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
977            assert!(rates.contains("96000"));
978            assert!(
979                !rates.contains("48000"),
980                "second candidate was tried after uncertain SET: {snapshot}"
981            );
982            let retirement = dac.retirement();
983            dac.close()?;
984            assert!(retirement.wait(Duration::from_secs(3)));
985            assert_eq!(alt(fd)?, 0);
986            for interface in [1, 0] {
987                claim(fd, interface, false)?;
988            }
989            println!("USBIP_LIFECYCLE_PASS mode=refuse-set snapshot={snapshot}");
990            return Ok(());
991        }
992        if matches!(args[2].as_str(), "selector" | "zero-res") {
993            let (requested, expected) = if args[2] == "selector" {
994                (192_000, 96_000)
995            } else {
996                (96_000, 44_100)
997            };
998            out_of_band("reset")?;
999            let request =
1000                StreamRequest::pcm(requested, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1001            let format = dac.negotiate(&request)?;
1002            assert_eq!(format.sample_rate, expected);
1003            let stream = dac.open_stream(&format, Arc::new(|_| {}))?;
1004            let snapshot = out_of_band("snapshot")?;
1005            let rates = snapshot.split(';').next().ok_or("missing rate snapshot")?;
1006            let rejected = requested.to_string();
1007            assert!(
1008                !rates
1009                    .split(|c: char| !c.is_ascii_digit())
1010                    .any(|v| v == rejected),
1011                "requested unsupported rate was sent: {snapshot}"
1012            );
1013            println!(
1014                "NEGOTIATE_CASE mode={} requested={requested} actual={expected} {snapshot}",
1015                args[2]
1016            );
1017            stream.close()?;
1018            let retirement = dac.retirement();
1019            dac.close()?;
1020            assert!(retirement.wait(Duration::from_secs(3)));
1021            assert_eq!(alt(fd)?, 0);
1022            for interface in [1, 0] {
1023                claim(fd, interface, false)?;
1024            }
1025            println!("USBIP_LIFECYCLE_PASS mode={} retired=true", args[2]);
1026            return Ok(());
1027        }
1028        if args[2] == "badd" {
1029            badd(&dac, fd, &caps)?;
1030            assert_eq!(alt(fd)?, 0);
1031            dac.close()?;
1032            assert!(Dac::await_usb_retirement(Duration::from_secs(3)));
1033            assert_eq!(alt(fd)?, 0);
1034            assert_eq!(power(fd)?, 2, "BADD must restore D2");
1035            let power_log = out_of_band("snapshot")?;
1036            let powers = power_log
1037                .split("power=[")
1038                .nth(1)
1039                .ok_or("missing power history")?
1040                .split(']')
1041                .next()
1042                .ok_or("missing power terminator")?;
1043            assert!(
1044                powers
1045                    .split(", ")
1046                    .collect::<Vec<_>>()
1047                    .windows(2)
1048                    .any(|pair| pair == ["0", "2"]),
1049                "expected D0 to D2 transition: {power_log}"
1050            );
1051            for interface in [1, 0] {
1052                claim(fd, interface, false)?;
1053            }
1054            println!("USBIP_LIFECYCLE_PASS mode=badd alt=0 retired=true");
1055            return Ok(());
1056        }
1057        if args[2] == "full-uac3-nearest" {
1058            return full_uac3_nearest(dac, fd, &caps);
1059        }
1060        if matches!(args[2].as_str(), "full-uac3" | "full-uac3-volatile") {
1061            return full_uac3(dac, fd, &caps, args[2] == "full-uac3-volatile");
1062        }
1063        assert_eq!(
1064            caps.uac_version,
1065            if args[2].starts_with("full-uac3-clock") {
1066                UacVersion::V3
1067            } else {
1068                UacVersion::V2
1069            }
1070        );
1071        assert_eq!(caps.link_speed, LinkSpeed::High);
1072        let mut rates = caps.pcm_sample_rates.clone();
1073        rates.sort_unstable();
1074        rates.dedup();
1075        assert_eq!(rates, [48_000, 96_000], "unexpected fixture rates");
1076        assert!(
1077            matches!(
1078                dac.negotiate(&StreamRequest::pcm(192_000, 2, 16)),
1079                Err(Error::Unsupported { .. })
1080            ),
1081            "exact 192 kHz must be refused"
1082        );
1083        let request =
1084            StreamRequest::pcm(192_000, 2, 16).with_rate_policy(RatePolicy::NearestSupported);
1085        let format = dac.negotiate(&request)?;
1086        assert_eq!(
1087            (
1088                format.sample_rate,
1089                format.channels,
1090                format.valid_bits,
1091                format.subslot_bytes,
1092                format.interface_number,
1093                format.alt_setting
1094            ),
1095            (96_000, 2, 16, 2, 1, 1)
1096        );
1097        assert_eq!(format.sync_type, SyncKind::Synchronous);
1098        assert_eq!(format.endpoint_address, 0x01);
1099        assert_eq!(format.link_speed, LinkSpeed::High);
1100        assert_eq!(format.bytes_per_frame(), 4);
1101        if args[2].starts_with("full-uac3-clock") {
1102            assert_eq!(format.service_interval_us, 125);
1103            assert!(!format.explicit_feedback);
1104        }
1105        let clock = format
1106            .clock
1107            .as_ref()
1108            .ok_or("fixture clock missing")?
1109            .clone();
1110        assert_eq!(
1111            (clock.control_interface, clock.source_id),
1112            (
1113                0,
1114                if args[2].starts_with("full-uac3-clock") {
1115                    9
1116                } else {
1117                    0x10
1118                }
1119            )
1120        );
1121        println!("NEGOTIATED exact192=unsupported nearest192=96000 format={format:?}");
1122        let listener = Arc::new(|event: DacEvent| eprintln!("EVENT {event:?}"));
1123        match args[2].as_str() {
1124            "normal" | "full-uac3-clock" => {
1125                let stream = dac.open_stream(&format, listener)?;
1126                assert_eq!(alt(fd)?, 1);
1127                let mut current = [0u8; 4];
1128                assert_eq!(
1129                    control(
1130                        fd,
1131                        0xa1,
1132                        1,
1133                        0x0100,
1134                        (u16::from(clock.source_id) << 8) | u16::from(clock.control_interface),
1135                        &mut current
1136                    )?,
1137                    4
1138                );
1139                assert_eq!(
1140                    u32::from_le_bytes(current),
1141                    96_000,
1142                    "post-alt clock readback"
1143                );
1144                let mut pcm = Vec::with_capacity(9600 * 4);
1145                for i in 0..9600i32 {
1146                    let v = (((i % 96) - 48) * 20) as i16;
1147                    pcm.extend_from_slice(&v.to_le_bytes());
1148                    pcm.extend_from_slice(&(-v).to_le_bytes());
1149                }
1150                for _ in 0..3 {
1151                    stream.write(&pcm)?;
1152                }
1153                stream.play()?;
1154                let start = Instant::now();
1155                while start.elapsed() < Duration::from_secs(3)
1156                    && (stream.played_frames() == 0 || stream.stats().completed_transfers == 0)
1157                {
1158                    let n = stream.writable_bytes().min(pcm.len());
1159                    if n >= 4 {
1160                        stream.write(&pcm[..n - n % 4])?;
1161                    }
1162                    thread::sleep(Duration::from_millis(2));
1163                }
1164                let stats = stream.stats();
1165                println!("PCM_STATS {stats:?}");
1166                assert!(
1167                    stats.played_frames > 0 && stats.completed_transfers > 0,
1168                    "no actual PCM completions"
1169                );
1170                stream.close()?;
1171            }
1172            mode => match dac.open_stream(&format, listener) {
1173                Err(error @ Error::ClockUnverified { .. }) => {
1174                    let expected_reported = if mode == "bad-cur" || mode == "full-uac3-clock-bad" {
1175                        None
1176                    } else {
1177                        Some(48_000)
1178                    };
1179                    assert!(
1180                        matches!(error, Error::ClockUnverified { requested_hz: 96_000, reported_hz } if reported_hz == expected_reported)
1181                    );
1182                    println!(
1183                        "EXPECTED_FAILURE mode={mode} code={} error={error:?}",
1184                        error.code()
1185                    );
1186                }
1187                Err(error) => {
1188                    return Err(format!("unexpected failure for {mode}: {error:?}").into())
1189                }
1190                Ok(stream) => {
1191                    stream.close()?;
1192                    return Err(format!("{mode} incorrectly admitted the stream").into());
1193                }
1194            },
1195        }
1196        assert_eq!(alt(fd)?, 0, "stream teardown must restore alternate zero");
1197        dac.close()?;
1198        assert!(
1199            Dac::await_usb_retirement(Duration::from_secs(3)),
1200            "USB retirement timed out"
1201        );
1202        assert_eq!(alt(fd)?, 0);
1203        for interface in [1, 0] {
1204            claim(fd, interface, false)?;
1205        }
1206        println!("USBIP_LIFECYCLE_PASS mode={} alt=0 retired=true", args[2]);
1207        Ok(())
1208    }
examples/qemu_smoke.rs (line 139)
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}

Trait Implementations§

Source§

impl Debug for DacStream

Source§

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

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

impl Drop for DacStream

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 PlaybackStream for DacStream

Source§

fn write(&self, data: &[u8]) -> Result<usize>

Source§

fn writable_bytes(&self) -> usize

Source§

fn played_frames(&self) -> u64

Source§

fn latency_frames(&self) -> u64

Source§

fn play(&self) -> Result<()>

Source§

fn pause(&self) -> Result<()>

Source§

fn flush(&self) -> Result<()>

Source§

fn drain(&self) -> Result<()>

Auto Trait Implementations§

§

impl !RefUnwindSafe for DacStream

§

impl !UnwindSafe for DacStream

§

impl Forget for DacStream

§

impl Freeze for DacStream
where *const ArcInner<StreamInner> is !null: Freeze, PhantomData<ArcInner<StreamInner>>: Freeze,

§

impl Move for DacStream

§

impl Send for DacStream
where Arc<StreamInner>: Send,

§

impl Sync for DacStream
where Arc<StreamInner>: Sync,

§

impl Unpin for DacStream
where Arc<StreamInner>: Unpin,

§

impl UnsafeUnpin for DacStream
where *const ArcInner<StreamInner> is !null: UnsafeUnpin, PhantomData<ArcInner<StreamInner>>: UnsafeUnpin,

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.