Skip to main content

usbip_lifecycle/
usbip_lifecycle.rs

1//! Focused Linux usbfs lifecycle probe for the synthetic USB/IP audio fixture.
2//! Usage: usbip_lifecycle /dev/bus/usb/BBB/DDD normal|bad-cur|stale-cur|badd|full-uac3|duplex|retire
3#![cfg_attr(not(target_os = "linux"), allow(unused))]
4
5#[cfg(target_os = "linux")]
6mod linux {
7    use std::{
8        fs::OpenOptions,
9        os::fd::AsRawFd,
10        sync::Arc,
11        thread,
12        time::{Duration, Instant},
13    };
14    use usbdac_core::{
15        Dac, DacConfig, DacEvent, DeviceInfo, Error, LinkSpeed, RatePolicy, StreamRequest,
16        SyncKind, UacVersion,
17    };
18
19    const VID: u16 = 0x1209;
20    const PID: u16 = 0xdaca;
21    #[repr(C)]
22    struct Control {
23        kind: u8,
24        request: u8,
25        value: u16,
26        index: u16,
27        length: u16,
28        timeout: u32,
29        data: *mut u8,
30    }
31
32    fn control(
33        fd: i32,
34        kind: u8,
35        request: u8,
36        value: u16,
37        index: u16,
38        data: &mut [u8],
39    ) -> std::io::Result<usize> {
40        let mut c = Control {
41            kind,
42            request,
43            value,
44            index,
45            length: data.len() as u16,
46            timeout: 1000,
47            data: data.as_mut_ptr(),
48        };
49        let result = unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut c) };
50        if result < 0 {
51            Err(std::io::Error::last_os_error())
52        } else {
53            Ok(result as usize)
54        }
55    }
56    fn alt(fd: i32) -> Result<u8, Box<dyn std::error::Error>> {
57        let mut value = [0xff];
58        assert_eq!(control(fd, 0x81, 10, 0, 1, &mut value)?, 1);
59        Ok(value[0])
60    }
61    fn claim(fd: i32, interface: u32, acquire: bool) -> std::io::Result<()> {
62        let command = if acquire {
63            0x8004550fu32
64        } else {
65            0x80045510u32
66        };
67        if unsafe { libc::ioctl(fd, command as _, &interface) } != 0 {
68            Err(std::io::Error::last_os_error())
69        } else {
70            Ok(())
71        }
72    }
73    fn power(fd: i32) -> Result<u8, Box<dyn std::error::Error>> {
74        let mut state = [0xff];
75        assert_eq!(control(fd, 0xa1, 1, 0x0200, 0x0a00, &mut state)?, 1);
76        Ok(state[0])
77    }
78
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    }
1209}
1210#[cfg(target_os = "linux")]
1211fn main() -> Result<(), Box<dyn std::error::Error>> {
1212    linux::run()
1213}
1214#[cfg(not(target_os = "linux"))]
1215fn main() {
1216    eprintln!("usbip_lifecycle requires Linux usbfs");
1217}