pub struct Dac { /* private fields */ }Expand description
An open USB DAC.
Distinct USB attachments have independent owners. Opening the same physical
attachment twice returns Error::Busy until its owner retires. The host keeps its
UsbDeviceConnection open until then.
Implementations§
Source§impl Dac
impl Dac
Sourcepub fn resolve_playback(
&self,
source: &StreamRequest,
policy: &PlaybackPolicy,
) -> Result<PlaybackDecision>
pub fn resolve_playback( &self, source: &StreamRequest, policy: &PlaybackPolicy, ) -> Result<PlaybackDecision>
Examples found in repository?
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 }Source§impl Dac
impl Dac
Sourcepub fn open_playback(
&self,
decision: &PlaybackDecision,
listener: Arc<dyn DacListener>,
) -> Result<PlaybackStream>
pub fn open_playback( &self, decision: &PlaybackDecision, listener: Arc<dyn DacListener>, ) -> Result<PlaybackStream>
Examples found in repository?
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 }Source§impl Dac
Unavailable in this release; retained for source compatibility.
impl Dac
Unavailable in this release; retained for source compatibility.
Sourcepub fn djm_routing_discover(
&self,
) -> Result<DjmRoutingProfile, RoutingSessionError>
pub fn djm_routing_discover( &self, ) -> Result<DjmRoutingProfile, RoutingSessionError>
Discover source-backed DJM choices on an exact, idle vendor PCM session. Discovery leaves the mixer’s routing intact.
Sourcepub fn djm_routing_apply(
&self,
model: DjmModel,
configuration: u8,
key: DjmControlKey,
option: u8,
) -> Result<(), RoutingSessionError>
pub fn djm_routing_apply( &self, model: DjmModel, configuration: u8, key: DjmControlKey, option: u8, ) -> Result<(), RoutingSessionError>
Unavailable in this release; retained for source compatibility.
Send one explicitly selected DJM option after fresh model, configuration,
claim and idle-alternate proof. option is a listed zero-based option ID.
Success confirms USB acknowledgement. The mixer’s current routing
remains unknown through this protocol.
Sourcepub fn scarlett_gen1_read(&self) -> Result<Gen1Readback, RoutingSessionError>
pub fn scarlett_gen1_read(&self) -> Result<Gen1Readback, RoutingSessionError>
Unavailable in this release; retained for source compatibility.
Read source-backed first-generation Focusrite controls using the already claimed AudioControl interface while idle. No vendor claim or probe write. Hardware behavior remains physically unvalidated.
Sourcepub fn scarlett_gen1_apply(
&self,
expected: &Gen1Readback,
edits: &[Gen1Edit],
) -> Result<Gen1Report, RoutingSessionError>
pub fn scarlett_gen1_apply( &self, expected: &Gen1Readback, edits: &[Gen1Edit], ) -> Result<Gen1Report, RoutingSessionError>
Unavailable in this release; retained for source compatibility.
Apply bounded typed Gen1 controls against a fresh readback on the live DAC. Verify each write and restore attempted controls on failure. Configured hand-back preserves external edits; no clock, preamp or persistent writes.
Sourcepub fn scarlett_routing_capability(
&self,
) -> Result<Option<ReadCapability>, RoutingSessionError>
pub fn scarlett_routing_capability( &self, ) -> Result<Option<ReadCapability>, RoutingSessionError>
Unavailable in this release; retained for source compatibility.
Inspect the exact Scarlett read candidate and required vendor claim, without initializing its protocol or reading proprietary state.
Sourcepub fn scarlett_routing_read(
&self,
) -> Result<RoutingReadback, RoutingSessionError>
pub fn scarlett_routing_read( &self, ) -> Result<RoutingReadback, RoutingSessionError>
Unavailable in this release; retained for source compatibility.
Initialize and read source-backed Scarlett routing while idle. Requires the host’s explicit vendor-interface claim. Exact-model firmware and live geometry guards apply before mux/mix controls become available. No route, volume or persistent setting writes are sent. Hardware behavior remains unvalidated.
Sourcepub fn fcp_routing_read(&self) -> Result<FcpReadback, RoutingSessionError>
pub fn fcp_routing_read(&self) -> Result<FcpReadback, RoutingSessionError>
Unavailable in this release; retained for source compatibility.
Read firmware-defined modern Focusrite FCP pins, mux banks and mix rows. Requires idle ownership and an explicit exact-model vendor-interface claim. Does not send persistent configuration commands.
Sourcepub fn fcp_routing_apply(
&self,
expected: &FcpReadback,
routes: &[FcpRouteEdit],
mixes: &[FcpMixEdit],
) -> Result<FcpWriteReport, RoutingSessionError>
pub fn fcp_routing_apply( &self, expected: &FcpReadback, routes: &[FcpRouteEdit], mixes: &[FcpMixEdit], ) -> Result<FcpWriteReport, RoutingSessionError>
Unavailable in this release; retained for source compatibility.
Apply typed firmware pin routes and mixer coefficients against a fresh readback. Requires idle ownership and explicit vendor claim. Verify every affected target, restore attempted targets on failure, and preserve external edits at hand-back. No persistent configuration commands are sent. Physically unvalidated.
Sourcepub fn scarlett_mix_apply(
&self,
edit: &MixRowEdit,
) -> Result<MixWriteReport, RoutingSessionError>
pub fn scarlett_mix_apply( &self, edit: &MixRowEdit, ) -> Result<MixWriteReport, RoutingSessionError>
Unavailable in this release; retained for source compatibility.
Apply bounded half-dB replacements to one complete Scarlett mixer row. Requires fresh expected raw coefficients, idle ownership and the explicit vendor claim. Verifies the whole row and attempts verified restoration after any attempted-write failure. Configured hand-back restores only rows still matching the last verified write. Source-backed, physically unverified; no mux bank or persistent configuration is written.
Sourcepub fn scarlett_mux_read(&self) -> Result<MuxSnapshot, RoutingSessionError>
pub fn scarlett_mux_read(&self) -> Result<MuxSnapshot, RoutingSessionError>
Unavailable in this release; retained for source compatibility.
Probe optional per-bank support and read every raw bank including padding. An unsupported response never enables writes; legacy reads remain usable.
Sourcepub fn scarlett_mux_apply(
&self,
edit: &MuxEdit,
) -> Result<MuxWriteReport, RoutingSessionError>
pub fn scarlett_mux_apply( &self, edit: &MuxEdit, ) -> Result<MuxWriteReport, RoutingSessionError>
Unavailable in this release; retained for source compatibility.
Apply explicit bank edits only after a fresh complete capability/geometry read equals the expected snapshot. Restore each attempted raw bank after any uncertain write. Configured hand-back preserves external edits. Source-backed; physical routing has not been validated.
Sourcepub fn routing_discover(&self) -> Result<RoutingSnapshot, RoutingSessionError>
pub fn routing_discover(&self) -> Result<RoutingSnapshot, RoutingSessionError>
Discover standard UAC2 selectors and mixer crosspoints on claimed AudioControl interfaces in the active configuration. No vendor protocol is inferred. Requires an idle DAC, including no open capture stream.
Sourcepub fn routing_discover_powered(
&self,
) -> Result<RoutingSnapshot, RoutingSessionError>
pub fn routing_discover_powered( &self, ) -> Result<RoutingSnapshot, RoutingSessionError>
Explicitly wake affected full ADC3 routing domains on entirely claimed idle functions. Restore checked original power after discovery, including failures. The snapshot does not retain a power lease.
Examples found in repository?
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 }Sourcepub fn routing_read_powered(
&self,
snapshot: &RoutingSnapshot,
key: ControlKey,
) -> Result<RouteValue, RoutingSessionError>
pub fn routing_read_powered( &self, snapshot: &RoutingSnapshot, key: ControlKey, ) -> Result<RouteValue, RoutingSessionError>
Revalidate the snapshot and acquire a fresh scoped ADC3 routing lease. Preserve external power drift instead of overwriting it on hand-back.
Examples found in repository?
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 }Sourcepub fn routing_apply_powered(
&self,
snapshot: &RoutingSnapshot,
edits: &[RouteEdit],
) -> Result<RouteReport, RoutingSessionError>
pub fn routing_apply_powered( &self, snapshot: &RoutingSnapshot, edits: &[RouteEdit], ) -> Result<RouteReport, RoutingSessionError>
Apply the ordinary verified routing transaction with explicit scoped ADC3 wake. Restore original power after success or failure. Configured route hand-back reacquires power only for these opted-in edits.
Examples found in repository?
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 }Sourcepub fn routing_apply_powered_detailed(
&self,
snapshot: &RoutingSnapshot,
edits: &[RouteEdit],
) -> Result<RouteReport, RoutingApplyError>
pub fn routing_apply_powered_detailed( &self, snapshot: &RoutingSnapshot, edits: &[RouteEdit], ) -> Result<RouteReport, RoutingApplyError>
Apply with the committed report retained if power restoration fails.
Sourcepub fn routing_read(
&self,
snapshot: &RoutingSnapshot,
key: ControlKey,
) -> Result<RouteValue, RoutingSessionError>
pub fn routing_read( &self, snapshot: &RoutingSnapshot, key: ControlKey, ) -> Result<RouteValue, RoutingSessionError>
Read a descriptor-backed control after checking the attachment, configuration, descriptors and discovered selector pins for drift.
Sourcepub fn routing_apply(
&self,
snapshot: &RoutingSnapshot,
edits: &[RouteEdit],
) -> Result<RouteReport, RoutingSessionError>
pub fn routing_apply( &self, snapshot: &RoutingSnapshot, edits: &[RouteEdit], ) -> Result<RouteReport, RoutingSessionError>
Apply bounded, verified routing edits only while idle. Each edit includes
the expected current value from routing_read; stale values fail before
writing. Rediscover after changing a selector. The configured HandBack
policy controls route restoration on close; close_with overrides volume
handling only. Feature Unit volume and mute settings are not changed.
Source§impl Dac
impl Dac
Sourcepub fn vendor_pcm_preflight(
fd: RawFd,
info: &DeviceInfo,
) -> Result<Option<(u8, u8)>>
pub fn vendor_pcm_preflight( fd: RawFd, info: &DeviceInfo, ) -> Result<Option<(u8, u8)>>
Read-only proof of a fixed-rate vendor PCM profile. Returns the actual active configuration and the sole interface the host may claim.
Sourcepub fn vendor_pcm_claims_preflight(
fd: RawFd,
info: &DeviceInfo,
) -> Result<Option<(u8, Vec<u8>)>>
pub fn vendor_pcm_claims_preflight( fd: RawFd, info: &DeviceInfo, ) -> Result<Option<(u8, Vec<u8>)>>
Read-only descriptor proof of the exact active configuration and complete interface claim set for a fixed-rate vendor PCM profile.
Sourcepub fn scarlett_routing_preflight(
fd: RawFd,
info: &DeviceInfo,
) -> Result<Option<ReadCapability>>
pub fn scarlett_routing_preflight( fd: RawFd, info: &DeviceInfo, ) -> Result<Option<ReadCapability>>
Prove the exact optional Scarlett vendor claim from actual USB descriptors. Requires the host-selected configuration; sends no proprietary requests.
Sourcepub fn capture_preflight(
fd: RawFd,
info: &DeviceInfo,
) -> Result<(u8, Vec<u8>, Vec<u8>)>
pub fn capture_preflight( fd: RawFd, info: &DeviceInfo, ) -> Result<(u8, Vec<u8>, Vec<u8>)>
Read the active configuration’s explicit PCM IN claim plan before the
host claims its AudioControl and input streaming interfaces. Returns
(configuration, control_interfaces, input_interfaces) without audio.
Examples found in repository?
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5 use std::{
6 fs::OpenOptions,
7 io::{Seek, SeekFrom, Write},
8 os::fd::AsRawFd,
9 time::{Duration, Instant},
10 };
11 use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12 let args: Vec<String> = std::env::args().collect();
13 if args.len() != 5 {
14 return Err(
15 "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16 .into(),
17 );
18 }
19 let rate: u32 = args[3].parse()?;
20 let seconds: u64 = args[4].parse()?;
21 if rate == 0 || !(1..=120).contains(&seconds) {
22 return Err("invalid capture duration/rate".into());
23 }
24 let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25 let fd = file.as_raw_fd();
26 // GET_DESCRIPTOR device: identity comes from the actual USB device.
27 #[repr(C)]
28 struct Control {
29 kind: u8,
30 request: u8,
31 value: u16,
32 index: u16,
33 length: u16,
34 timeout: u32,
35 data: *mut u8,
36 }
37 let mut descriptor = [0u8; 18];
38 let mut control = Control {
39 kind: 0x80,
40 request: 6,
41 value: 0x0100,
42 index: 0,
43 length: 18,
44 timeout: 1000,
45 data: descriptor.as_mut_ptr(),
46 };
47 if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48 return Err(std::io::Error::last_os_error().into());
49 }
50 let mut info = DeviceInfo::new(
51 u16::from_le_bytes([descriptor[8], descriptor[9]]),
52 u16::from_le_bytes([descriptor[10], descriptor[11]]),
53 "Independent loopback input",
54 )
55 .with_device_name(&args[1]);
56 let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57 let mut claims = control_interfaces;
58 claims.extend(input_interfaces);
59 claims.sort_unstable();
60 claims.dedup();
61 for &interface in &claims {
62 let interface = u32::from(interface);
63 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64 return Err(std::io::Error::last_os_error().into());
65 }
66 }
67 info.configuration_id = Some(configuration);
68 info.claimed_interfaces = claims.clone();
69 let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70 let capture = dac.open_capture(
71 &CaptureRequest {
72 sample_rate: rate,
73 channels: 2,
74 valid_bits: 16,
75 channel_map: None,
76 },
77 rate as usize,
78 )?;
79 if capture.format().subslot_bytes() != 2 {
80 return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81 }
82 let mut output = OpenOptions::new()
83 .create_new(true)
84 .write(true)
85 .open(&args[2])?;
86 output.write_all(&[0u8; 44])?;
87 let mut buffer = [0u8; 8192];
88 let mut bytes = 0u32;
89 let started = Instant::now();
90 while started.elapsed() < Duration::from_secs(seconds) {
91 let frames = capture.read(&mut buffer)?;
92 let count = frames * capture.format().bytes_per_frame();
93 output.write_all(&buffer[..count])?;
94 bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95 std::thread::sleep(Duration::from_millis(2));
96 }
97 let stats = capture.stats();
98 capture.close()?;
99 dac.close()?;
100 if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101 return Err("capture did not retire; retain host claims".into());
102 }
103 for &interface in claims.iter().rev() {
104 let interface = u32::from(interface);
105 if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106 return Err(std::io::Error::last_os_error().into());
107 }
108 }
109 let mut header = Vec::with_capacity(44);
110 header.extend_from_slice(b"RIFF");
111 header.extend_from_slice(&(36 + bytes).to_le_bytes());
112 header.extend_from_slice(b"WAVEfmt ");
113 header.extend_from_slice(&16u32.to_le_bytes());
114 header.extend_from_slice(&1u16.to_le_bytes());
115 header.extend_from_slice(&2u16.to_le_bytes());
116 header.extend_from_slice(&rate.to_le_bytes());
117 header.extend_from_slice(&(rate * 4).to_le_bytes());
118 header.extend_from_slice(&4u16.to_le_bytes());
119 header.extend_from_slice(&16u16.to_le_bytes());
120 header.extend_from_slice(b"data");
121 header.extend_from_slice(&bytes.to_le_bytes());
122 output.seek(SeekFrom::Start(0))?;
123 output.write_all(&header)?;
124 output.flush()?;
125 let valid = bytes > 0
126 && stats.failed_transfers == 0
127 && stats.failed_packets == 0
128 && stats.missing_frames == 0
129 && stats.overrun_frames == 0
130 && stats.contention_frames == 0;
131 let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132 std::fs::write(
133 format!("{}.json", args[2]),
134 serde_json::to_vec_pretty(&metadata)?,
135 )?;
136 if !valid {
137 return Err(
138 "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139 .into(),
140 );
141 }
142 println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143 Ok(())
144}Sourcepub fn open_capture_device(
fd: RawFd,
info: DeviceInfo,
config: DacConfig,
) -> Result<Dac>
pub fn open_capture_device( fd: RawFd, info: DeviceInfo, config: DacConfig, ) -> Result<Dac>
Register an explicitly claimed capture device, including an input-only device. Claim its IN AudioStreaming interfaces and their owning AudioControl interfaces before calling; no playback claim is needed. This entry point performs no output-volume setup. Android/JNI capture permission and claim orchestration is a separate integration step.
Examples found in repository?
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5 use std::{
6 fs::OpenOptions,
7 io::{Seek, SeekFrom, Write},
8 os::fd::AsRawFd,
9 time::{Duration, Instant},
10 };
11 use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12 let args: Vec<String> = std::env::args().collect();
13 if args.len() != 5 {
14 return Err(
15 "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16 .into(),
17 );
18 }
19 let rate: u32 = args[3].parse()?;
20 let seconds: u64 = args[4].parse()?;
21 if rate == 0 || !(1..=120).contains(&seconds) {
22 return Err("invalid capture duration/rate".into());
23 }
24 let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25 let fd = file.as_raw_fd();
26 // GET_DESCRIPTOR device: identity comes from the actual USB device.
27 #[repr(C)]
28 struct Control {
29 kind: u8,
30 request: u8,
31 value: u16,
32 index: u16,
33 length: u16,
34 timeout: u32,
35 data: *mut u8,
36 }
37 let mut descriptor = [0u8; 18];
38 let mut control = Control {
39 kind: 0x80,
40 request: 6,
41 value: 0x0100,
42 index: 0,
43 length: 18,
44 timeout: 1000,
45 data: descriptor.as_mut_ptr(),
46 };
47 if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48 return Err(std::io::Error::last_os_error().into());
49 }
50 let mut info = DeviceInfo::new(
51 u16::from_le_bytes([descriptor[8], descriptor[9]]),
52 u16::from_le_bytes([descriptor[10], descriptor[11]]),
53 "Independent loopback input",
54 )
55 .with_device_name(&args[1]);
56 let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57 let mut claims = control_interfaces;
58 claims.extend(input_interfaces);
59 claims.sort_unstable();
60 claims.dedup();
61 for &interface in &claims {
62 let interface = u32::from(interface);
63 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64 return Err(std::io::Error::last_os_error().into());
65 }
66 }
67 info.configuration_id = Some(configuration);
68 info.claimed_interfaces = claims.clone();
69 let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70 let capture = dac.open_capture(
71 &CaptureRequest {
72 sample_rate: rate,
73 channels: 2,
74 valid_bits: 16,
75 channel_map: None,
76 },
77 rate as usize,
78 )?;
79 if capture.format().subslot_bytes() != 2 {
80 return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81 }
82 let mut output = OpenOptions::new()
83 .create_new(true)
84 .write(true)
85 .open(&args[2])?;
86 output.write_all(&[0u8; 44])?;
87 let mut buffer = [0u8; 8192];
88 let mut bytes = 0u32;
89 let started = Instant::now();
90 while started.elapsed() < Duration::from_secs(seconds) {
91 let frames = capture.read(&mut buffer)?;
92 let count = frames * capture.format().bytes_per_frame();
93 output.write_all(&buffer[..count])?;
94 bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95 std::thread::sleep(Duration::from_millis(2));
96 }
97 let stats = capture.stats();
98 capture.close()?;
99 dac.close()?;
100 if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101 return Err("capture did not retire; retain host claims".into());
102 }
103 for &interface in claims.iter().rev() {
104 let interface = u32::from(interface);
105 if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106 return Err(std::io::Error::last_os_error().into());
107 }
108 }
109 let mut header = Vec::with_capacity(44);
110 header.extend_from_slice(b"RIFF");
111 header.extend_from_slice(&(36 + bytes).to_le_bytes());
112 header.extend_from_slice(b"WAVEfmt ");
113 header.extend_from_slice(&16u32.to_le_bytes());
114 header.extend_from_slice(&1u16.to_le_bytes());
115 header.extend_from_slice(&2u16.to_le_bytes());
116 header.extend_from_slice(&rate.to_le_bytes());
117 header.extend_from_slice(&(rate * 4).to_le_bytes());
118 header.extend_from_slice(&4u16.to_le_bytes());
119 header.extend_from_slice(&16u16.to_le_bytes());
120 header.extend_from_slice(b"data");
121 header.extend_from_slice(&bytes.to_le_bytes());
122 output.seek(SeekFrom::Start(0))?;
123 output.write_all(&header)?;
124 output.flush()?;
125 let valid = bytes > 0
126 && stats.failed_transfers == 0
127 && stats.failed_packets == 0
128 && stats.missing_frames == 0
129 && stats.overrun_frames == 0
130 && stats.contention_frames == 0;
131 let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132 std::fs::write(
133 format!("{}.json", args[2]),
134 serde_json::to_vec_pretty(&metadata)?,
135 )?;
136 if !valid {
137 return Err(
138 "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139 .into(),
140 );
141 }
142 println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143 Ok(())
144}Sourcepub fn open_capture(
&self,
request: &CaptureRequest,
capacity_frames: usize,
) -> Result<DacCaptureStream>
pub fn open_capture( &self, request: &CaptureRequest, capacity_frames: usize, ) -> Result<DacCaptureStream>
Start standalone, exact-format PCM capture on a claimed IN interface. The capture worker exclusively owns USB until all transfers retire; concurrent playback, duplex and routing changes are refused.
Examples found in repository?
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5 use std::{
6 fs::OpenOptions,
7 io::{Seek, SeekFrom, Write},
8 os::fd::AsRawFd,
9 time::{Duration, Instant},
10 };
11 use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12 let args: Vec<String> = std::env::args().collect();
13 if args.len() != 5 {
14 return Err(
15 "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16 .into(),
17 );
18 }
19 let rate: u32 = args[3].parse()?;
20 let seconds: u64 = args[4].parse()?;
21 if rate == 0 || !(1..=120).contains(&seconds) {
22 return Err("invalid capture duration/rate".into());
23 }
24 let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25 let fd = file.as_raw_fd();
26 // GET_DESCRIPTOR device: identity comes from the actual USB device.
27 #[repr(C)]
28 struct Control {
29 kind: u8,
30 request: u8,
31 value: u16,
32 index: u16,
33 length: u16,
34 timeout: u32,
35 data: *mut u8,
36 }
37 let mut descriptor = [0u8; 18];
38 let mut control = Control {
39 kind: 0x80,
40 request: 6,
41 value: 0x0100,
42 index: 0,
43 length: 18,
44 timeout: 1000,
45 data: descriptor.as_mut_ptr(),
46 };
47 if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48 return Err(std::io::Error::last_os_error().into());
49 }
50 let mut info = DeviceInfo::new(
51 u16::from_le_bytes([descriptor[8], descriptor[9]]),
52 u16::from_le_bytes([descriptor[10], descriptor[11]]),
53 "Independent loopback input",
54 )
55 .with_device_name(&args[1]);
56 let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57 let mut claims = control_interfaces;
58 claims.extend(input_interfaces);
59 claims.sort_unstable();
60 claims.dedup();
61 for &interface in &claims {
62 let interface = u32::from(interface);
63 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64 return Err(std::io::Error::last_os_error().into());
65 }
66 }
67 info.configuration_id = Some(configuration);
68 info.claimed_interfaces = claims.clone();
69 let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70 let capture = dac.open_capture(
71 &CaptureRequest {
72 sample_rate: rate,
73 channels: 2,
74 valid_bits: 16,
75 channel_map: None,
76 },
77 rate as usize,
78 )?;
79 if capture.format().subslot_bytes() != 2 {
80 return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81 }
82 let mut output = OpenOptions::new()
83 .create_new(true)
84 .write(true)
85 .open(&args[2])?;
86 output.write_all(&[0u8; 44])?;
87 let mut buffer = [0u8; 8192];
88 let mut bytes = 0u32;
89 let started = Instant::now();
90 while started.elapsed() < Duration::from_secs(seconds) {
91 let frames = capture.read(&mut buffer)?;
92 let count = frames * capture.format().bytes_per_frame();
93 output.write_all(&buffer[..count])?;
94 bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95 std::thread::sleep(Duration::from_millis(2));
96 }
97 let stats = capture.stats();
98 capture.close()?;
99 dac.close()?;
100 if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101 return Err("capture did not retire; retain host claims".into());
102 }
103 for &interface in claims.iter().rev() {
104 let interface = u32::from(interface);
105 if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106 return Err(std::io::Error::last_os_error().into());
107 }
108 }
109 let mut header = Vec::with_capacity(44);
110 header.extend_from_slice(b"RIFF");
111 header.extend_from_slice(&(36 + bytes).to_le_bytes());
112 header.extend_from_slice(b"WAVEfmt ");
113 header.extend_from_slice(&16u32.to_le_bytes());
114 header.extend_from_slice(&1u16.to_le_bytes());
115 header.extend_from_slice(&2u16.to_le_bytes());
116 header.extend_from_slice(&rate.to_le_bytes());
117 header.extend_from_slice(&(rate * 4).to_le_bytes());
118 header.extend_from_slice(&4u16.to_le_bytes());
119 header.extend_from_slice(&16u16.to_le_bytes());
120 header.extend_from_slice(b"data");
121 header.extend_from_slice(&bytes.to_le_bytes());
122 output.seek(SeekFrom::Start(0))?;
123 output.write_all(&header)?;
124 output.flush()?;
125 let valid = bytes > 0
126 && stats.failed_transfers == 0
127 && stats.failed_packets == 0
128 && stats.missing_frames == 0
129 && stats.overrun_frames == 0
130 && stats.contention_frames == 0;
131 let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132 std::fs::write(
133 format!("{}.json", args[2]),
134 serde_json::to_vec_pretty(&metadata)?,
135 )?;
136 if !valid {
137 return Err(
138 "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139 .into(),
140 );
141 }
142 println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143 Ok(())
144}Sourcepub fn retirement(&self) -> UsbRetirement
pub fn retirement(&self) -> UsbRetirement
Capture owner-specific retirement evidence before consuming close.
Retain this token with this device’s claims/FD after a close timeout;
another open device does not affect its result.
Examples found in repository?
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
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 }Sourcepub fn await_connection_retirement(fd: RawFd, timeout: Duration) -> Result<bool>
pub fn await_connection_retirement(fd: RawFd, timeout: Duration) -> Result<bool>
Wait until all process USB owners retire. For a particular connection,
use Dac::retirement so another active DAC does not block hand-back.
After Dac::close returns a transfer timeout, retain all host ownership
and call this until it returns true. This does not require a live Dac handle.
Check retirement using the actual host connection FD after a failed open.
The host must keep this FD valid; caller-supplied USB names are not identity.
Sourcepub fn await_usb_retirement(timeout: Duration) -> bool
pub fn await_usb_retirement(timeout: Duration) -> bool
Examples found in repository?
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
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 }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}4fn main() -> Result<(), Box<dyn std::error::Error>> {
5 use std::{
6 fs::OpenOptions,
7 io::{Seek, SeekFrom, Write},
8 os::fd::AsRawFd,
9 time::{Duration, Instant},
10 };
11 use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12 let args: Vec<String> = std::env::args().collect();
13 if args.len() != 5 {
14 return Err(
15 "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16 .into(),
17 );
18 }
19 let rate: u32 = args[3].parse()?;
20 let seconds: u64 = args[4].parse()?;
21 if rate == 0 || !(1..=120).contains(&seconds) {
22 return Err("invalid capture duration/rate".into());
23 }
24 let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25 let fd = file.as_raw_fd();
26 // GET_DESCRIPTOR device: identity comes from the actual USB device.
27 #[repr(C)]
28 struct Control {
29 kind: u8,
30 request: u8,
31 value: u16,
32 index: u16,
33 length: u16,
34 timeout: u32,
35 data: *mut u8,
36 }
37 let mut descriptor = [0u8; 18];
38 let mut control = Control {
39 kind: 0x80,
40 request: 6,
41 value: 0x0100,
42 index: 0,
43 length: 18,
44 timeout: 1000,
45 data: descriptor.as_mut_ptr(),
46 };
47 if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48 return Err(std::io::Error::last_os_error().into());
49 }
50 let mut info = DeviceInfo::new(
51 u16::from_le_bytes([descriptor[8], descriptor[9]]),
52 u16::from_le_bytes([descriptor[10], descriptor[11]]),
53 "Independent loopback input",
54 )
55 .with_device_name(&args[1]);
56 let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57 let mut claims = control_interfaces;
58 claims.extend(input_interfaces);
59 claims.sort_unstable();
60 claims.dedup();
61 for &interface in &claims {
62 let interface = u32::from(interface);
63 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64 return Err(std::io::Error::last_os_error().into());
65 }
66 }
67 info.configuration_id = Some(configuration);
68 info.claimed_interfaces = claims.clone();
69 let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70 let capture = dac.open_capture(
71 &CaptureRequest {
72 sample_rate: rate,
73 channels: 2,
74 valid_bits: 16,
75 channel_map: None,
76 },
77 rate as usize,
78 )?;
79 if capture.format().subslot_bytes() != 2 {
80 return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81 }
82 let mut output = OpenOptions::new()
83 .create_new(true)
84 .write(true)
85 .open(&args[2])?;
86 output.write_all(&[0u8; 44])?;
87 let mut buffer = [0u8; 8192];
88 let mut bytes = 0u32;
89 let started = Instant::now();
90 while started.elapsed() < Duration::from_secs(seconds) {
91 let frames = capture.read(&mut buffer)?;
92 let count = frames * capture.format().bytes_per_frame();
93 output.write_all(&buffer[..count])?;
94 bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95 std::thread::sleep(Duration::from_millis(2));
96 }
97 let stats = capture.stats();
98 capture.close()?;
99 dac.close()?;
100 if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101 return Err("capture did not retire; retain host claims".into());
102 }
103 for &interface in claims.iter().rev() {
104 let interface = u32::from(interface);
105 if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106 return Err(std::io::Error::last_os_error().into());
107 }
108 }
109 let mut header = Vec::with_capacity(44);
110 header.extend_from_slice(b"RIFF");
111 header.extend_from_slice(&(36 + bytes).to_le_bytes());
112 header.extend_from_slice(b"WAVEfmt ");
113 header.extend_from_slice(&16u32.to_le_bytes());
114 header.extend_from_slice(&1u16.to_le_bytes());
115 header.extend_from_slice(&2u16.to_le_bytes());
116 header.extend_from_slice(&rate.to_le_bytes());
117 header.extend_from_slice(&(rate * 4).to_le_bytes());
118 header.extend_from_slice(&4u16.to_le_bytes());
119 header.extend_from_slice(&16u16.to_le_bytes());
120 header.extend_from_slice(b"data");
121 header.extend_from_slice(&bytes.to_le_bytes());
122 output.seek(SeekFrom::Start(0))?;
123 output.write_all(&header)?;
124 output.flush()?;
125 let valid = bytes > 0
126 && stats.failed_transfers == 0
127 && stats.failed_packets == 0
128 && stats.missing_frames == 0
129 && stats.overrun_frames == 0
130 && stats.contention_frames == 0;
131 let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132 std::fs::write(
133 format!("{}.json", args[2]),
134 serde_json::to_vec_pretty(&metadata)?,
135 )?;
136 if !valid {
137 return Err(
138 "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139 .into(),
140 );
141 }
142 println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143 Ok(())
144}Sourcepub fn feedback_preflight(fd: RawFd, info: &DeviceInfo) -> Result<(u8, Vec<u8>)>
pub fn feedback_preflight(fd: RawFd, info: &DeviceInfo) -> Result<(u8, Vec<u8>)>
Identify optional capture interfaces after the host claims the base audio interfaces. Returns the active configuration ID and source interface numbers without starting audio.
Examples found in repository?
35pub fn open_dac(host: &mut dyn UsbHost, identity: DeviceInfo, config: DacConfig) -> Result<Dac> {
36 let mut info = identity.with_claimed_interfaces(host.claim_audio_interfaces()?);
37 if !config.disable_feedback {
38 // Read-only: it names the active configuration and the IN interfaces a DAC may pace itself with.
39 let (configuration, candidates) = Dac::feedback_preflight(host.fd(), &info)?;
40 let got = host.claim_optional(&candidates);
41 info.configuration_id = Some(configuration);
42 info.unavailable_feedback_interfaces = candidates
43 .iter()
44 .copied()
45 .filter(|n| !got.contains(n))
46 .collect();
47 info.claimed_interfaces.extend(got);
48 }
49 // Lowers the DAC to at most -40 dB, verifies it, and touches neither the clock nor the audio.
50 Dac::open(host.fd(), info, config)
51}Sourcepub fn open(fd: RawFd, info: DeviceInfo, config: DacConfig) -> Result<Dac>
pub fn open(fd: RawFd, info: DeviceInfo, config: DacConfig) -> Result<Dac>
Opens the DAC behind fd.
fd is the usbfs file descriptor of the device (on Android
UsbDeviceConnection.getFileDescriptor()); the library duplicates it, so
the host keeps ownership of its own. info.claimed_interfaces must be
the AudioControl and playback AudioStreaming interfaces plus any
optional capture sources identified by Dac::feedback_preflight.
Opening scans the descriptors, finds the hardware volume control, records
the DAC’s current level and, with the default
StartupVolume::Attenuate, lowers every
channel to at most -40 dB and verifies it, so that no stream can start
at the DAC’s own (often full-scale) level. It does not touch the clock or
start any audio. VolumeControl::startup
says what it did.
Examples found in repository?
35pub fn open_dac(host: &mut dyn UsbHost, identity: DeviceInfo, config: DacConfig) -> Result<Dac> {
36 let mut info = identity.with_claimed_interfaces(host.claim_audio_interfaces()?);
37 if !config.disable_feedback {
38 // Read-only: it names the active configuration and the IN interfaces a DAC may pace itself with.
39 let (configuration, candidates) = Dac::feedback_preflight(host.fd(), &info)?;
40 let got = host.claim_optional(&candidates);
41 info.configuration_id = Some(configuration);
42 info.unavailable_feedback_interfaces = candidates
43 .iter()
44 .copied()
45 .filter(|n| !got.contains(n))
46 .collect();
47 info.claimed_interfaces.extend(got);
48 }
49 // Lowers the DAC to at most -40 dB, verifies it, and touches neither the clock nor the audio.
50 Dac::open(host.fd(), info, config)
51}More examples
61 fn open(path: &str) -> Result<OpenedDac, Box<dyn std::error::Error>> {
62 let file = OpenOptions::new().read(true).write(true).open(path)?;
63 let fd = file.as_raw_fd();
64 let mut descriptor = [0; 18];
65 read(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?;
66 assert_eq!(
67 &descriptor[8..12],
68 &[0xf4, 0x46, 0x02, 0x00],
69 "probe is restricted to QEMU USB Audio"
70 );
71 for interface in [0u32, 1] {
72 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
73 return Err(std::io::Error::last_os_error().into());
74 }
75 }
76 let before = volume(fd)?;
77 let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
78 .with_device_name(path)
79 .with_claimed_interfaces(vec![0u8, 1]);
80 let dac = Dac::open(fd, info.clone(), DacConfig::default())?;
81 assert!(
82 matches!(Dac::open(fd, info, DacConfig::default()), Err(Error::Busy)),
83 "duplicate attachment was admitted"
84 );
85 let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
86 let stream = dac.open_stream(&format, Arc::new(|event| eprintln!("{event:?}")))?;
87 Ok((file, dac, stream, before))
88 }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}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 }Sourcepub fn open_duplex_device(
fd: RawFd,
info: DeviceInfo,
config: DacConfig,
) -> Result<Dac>
pub fn open_duplex_device( fd: RawFd, info: DeviceInfo, config: DacConfig, ) -> Result<Dac>
Explicit duplex registration. Claim the base playback interfaces and all IN/control interfaces returned by capture_preflight for the same configuration. Ordinary playback registration retains its narrower optional-IN policy.
Examples found in repository?
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 }Sourcepub fn info(&self) -> &DeviceInfo
pub fn info(&self) -> &DeviceInfo
The identity the host gave at open.
Sourcepub fn feedback_trace(&self) -> Option<FeedbackTrace>
pub fn feedback_trace(&self) -> Option<FeedbackTrace>
Export the last stream’s opt-in support capture, even after the stream has closed. A new successfully opened stream replaces it.
Sourcepub fn capabilities(&self) -> Result<Capabilities>
pub fn capabilities(&self) -> Result<Capabilities>
What the DAC offers, from the descriptors scanned at open.
Examples found in repository?
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
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 }Sourcepub fn negotiate(&self, request: &StreamRequest) -> Result<StreamFormat>
pub fn negotiate(&self, request: &StreamRequest) -> Result<StreamFormat>
Settles the wire format for request.
This programs the DAC’s sampling frequency and reads it back (it is the
step that can fail with Error::ClockUnverified later), so it takes
100 ms or more. It fails with Error::InvalidState while a stream is
open. Nothing is resampled: with RatePolicy::Exact a rate the DAC
cannot run is Error::Unsupported; with NearestSupported the
returned format carries the rate the DAC will run.
Examples found in repository?
91pub fn negotiate(dac: &Dac, track: TrackFormat, allow_nearest: bool) -> Result<Negotiated> {
92 let policy = if allow_nearest {
93 RatePolicy::NearestSupported
94 } else {
95 RatePolicy::Exact
96 };
97 let request =
98 StreamRequest::pcm(track.sample_rate, track.channels, track.bits).with_rate_policy(policy);
99 let format = dac.negotiate(&request)?;
100 let resample_to = format
101 .rate_differs_from_request()
102 .then_some(format.sample_rate);
103 Ok(Negotiated {
104 format,
105 resample_to,
106 })
107}More examples
61 fn open(path: &str) -> Result<OpenedDac, Box<dyn std::error::Error>> {
62 let file = OpenOptions::new().read(true).write(true).open(path)?;
63 let fd = file.as_raw_fd();
64 let mut descriptor = [0; 18];
65 read(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?;
66 assert_eq!(
67 &descriptor[8..12],
68 &[0xf4, 0x46, 0x02, 0x00],
69 "probe is restricted to QEMU USB Audio"
70 );
71 for interface in [0u32, 1] {
72 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
73 return Err(std::io::Error::last_os_error().into());
74 }
75 }
76 let before = volume(fd)?;
77 let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
78 .with_device_name(path)
79 .with_claimed_interfaces(vec![0u8, 1]);
80 let dac = Dac::open(fd, info.clone(), DacConfig::default())?;
81 assert!(
82 matches!(Dac::open(fd, info, DacConfig::default()), Err(Error::Busy)),
83 "duplicate attachment was admitted"
84 );
85 let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
86 let stream = dac.open_stream(&format, Arc::new(|event| eprintln!("{event:?}")))?;
87 Ok((file, dac, stream, before))
88 }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 }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}Sourcepub fn negotiate_candidates(
&self,
requests: &[StreamRequest],
) -> Result<StreamFormat>
pub fn negotiate_candidates( &self, requests: &[StreamRequest], ) -> Result<StreamFormat>
Negotiate a bounded, ordered list of exact PCM formats on one retained owner. A later candidate is considered only after a certified clean refusal.
Examples found in repository?
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 }Sourcepub fn open_stream(
&self,
format: &StreamFormat,
listener: Arc<dyn DacListener>,
) -> Result<DacStream>
pub fn open_stream( &self, format: &StreamFormat, listener: Arc<dyn DacListener>, ) -> Result<DacStream>
Opens the output stream for a negotiated format and starts the output
thread. The stream plays as soon as the ring holds the start threshold
(DacConfig::start_threshold_ms) of audio. Only one stream can be open
at a time.
Fails with Error::VolumeUnavailable when the stream’s own route has
no usable hardware volume control and
DacConfig::require_hardware_volume is on; nothing is programmed and
no output thread starts.
listener receives the stream’s events; see DacListener.
Examples found in repository?
404pub fn play_one(dac: Dac, format: &StreamFormat, source: Box<dyn Source>) -> Result<()> {
405 let (listener, events) = event_channel();
406 let stream = dac.open_stream(format, listener)?;
407 let shape = Shape::from(stream.format());
408 let player = Player::start(Arc::new(stream), shape, source);
409 let mut device_lost = false;
410 while !player.finished() {
411 match events.recv_timeout(Duration::from_millis(100)).map(react) {
412 Ok(Reaction::Pause(reason)) => {
413 log::warn!("{reason}");
414 device_lost = true;
415 break;
416 }
417 Ok(Reaction::Failed(error)) => {
418 device_lost = error == Error::DeviceLost;
419 log::warn!("the stream failed: {error}");
420 break;
421 }
422 _ => {}
423 }
424 }
425 log::info!("{}", status_line(player.ring(), true, false));
426 shutdown(player, dac, device_lost)
427}More examples
61 fn open(path: &str) -> Result<OpenedDac, Box<dyn std::error::Error>> {
62 let file = OpenOptions::new().read(true).write(true).open(path)?;
63 let fd = file.as_raw_fd();
64 let mut descriptor = [0; 18];
65 read(fd, 0x80, 6, 0x0100, 0, &mut descriptor)?;
66 assert_eq!(
67 &descriptor[8..12],
68 &[0xf4, 0x46, 0x02, 0x00],
69 "probe is restricted to QEMU USB Audio"
70 );
71 for interface in [0u32, 1] {
72 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
73 return Err(std::io::Error::last_os_error().into());
74 }
75 }
76 let before = volume(fd)?;
77 let info = DeviceInfo::new(0x46f4, 0x0002, "QEMU USB Audio")
78 .with_device_name(path)
79 .with_claimed_interfaces(vec![0u8, 1]);
80 let dac = Dac::open(fd, info.clone(), DacConfig::default())?;
81 assert!(
82 matches!(Dac::open(fd, info, DacConfig::default()), Err(Error::Busy)),
83 "duplicate attachment was admitted"
84 );
85 let format = dac.negotiate(&StreamRequest::pcm(48_000, 2, 16))?;
86 let stream = dac.open_stream(&format, Arc::new(|event| eprintln!("{event:?}")))?;
87 Ok((file, dac, stream, before))
88 }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 }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}Sourcepub fn reconfigure_stream(
&self,
current: &DacStream,
request: &StreamRequest,
listener: Arc<dyn DacListener>,
drain_timeout: Duration,
) -> Result<StreamReconfiguration>
pub fn reconfigure_stream( &self, current: &DacStream, request: &StreamRequest, listener: Arc<dyn DacListener>, drain_timeout: Duration, ) -> Result<StreamReconfiguration>
Drain and replace a playback-only stream without reopening the physical USB handle or host claims.
Stop the writer before calling. The stream must belong to this DAC. Drain temporarily plays a paused stream so queued audio can complete. A drain timeout retains the original open stream in draining state; the caller still owns it and may wait, flush or close it.
After retirement, normal lock-requested cleanup retains the exact libusb owner in IDLE_LOCK.
Every negotiation/open must reuse that identity; losing it is an unusable-state error, never
an implicit physical reopen. No volume initialization/hand-back occurs. Success or rollback
returns a paused replacement with zero-based counters; supply/reseek PCM and explicitly play.
A rollback failure returns ReconfigureUnusable and requires closing the DAC.
While draining, routing and negotiation return Busy; volume remains available.
Examples found in repository?
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}Sourcepub fn reconfigure_stream_candidates(
&self,
current: &DacStream,
requests: &[StreamRequest],
listener: Arc<dyn DacListener>,
drain_timeout: Duration,
) -> Result<StreamReconfiguration>
pub fn reconfigure_stream_candidates( &self, current: &DacStream, requests: &[StreamRequest], listener: Arc<dyn DacListener>, drain_timeout: Duration, ) -> Result<StreamReconfiguration>
Replace once using a bounded list of equivalent-rate lossless widening candidates. Continue only after a certified clean refusal. A terminal failure requires explicit close; exhaustion restores the previous request once.
Examples found in repository?
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 }Sourcepub fn open_duplex(
&self,
format: &StreamFormat,
capture: &CaptureRequest,
capacity_frames: usize,
listener: Arc<dyn DacListener>,
) -> Result<(DacStream, DacCaptureStream)>
pub fn open_duplex( &self, format: &StreamFormat, capture: &CaptureRequest, capacity_frames: usize, listener: Arc<dyn DacListener>, ) -> Result<(DacStream, DacCaptureStream)>
Open playback and PCM capture atomically on one USB worker.
The output must have a current negotiated format. Shared source clocks require equal wire rates; distinct proven clock sources retain their own rates and position counters. Capture never supplies playback timing unless it exactly matches playback’s already selected implicit feedback source. Closing either stream stops both endpoints and retires their transfers.
Examples found in repository?
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 }Sourcepub fn volume(&self) -> Option<VolumeControl>
pub fn volume(&self) -> Option<VolumeControl>
The hardware volume control, if the DAC has a writable one.
Sourcepub fn set_listener(&self, listener: Option<Arc<dyn DacListener>>)
pub fn set_listener(&self, listener: Option<Arc<dyn DacListener>>)
Sets the listener for events about the device itself (volume changes, device loss) while no stream is open. While a stream is open its listener gets those events too.
Sourcepub fn set_routing_hand_back(&self, hand_back: HandBack) -> Result<()>
pub fn set_routing_hand_back(&self, hand_back: HandBack) -> Result<()>
Select the routing hand-back policy independently of volume hand-back. The policy remains attached to this owner if USB retirement is delayed.
Sourcepub fn close(self) -> Result<()>
pub fn close(self) -> Result<()>
Closes the DAC: stops the stream if one is open, hands the volume back
as DacConfig::hand_back says, and releases the session so another
Dac::open can succeed. The host may then release its interfaces and
close its connection after success. If closing times out, keep all host
claims and the connection until Dac::await_usb_retirement returns
true. Dropping the Dac initiates the same cleanup, but cannot report
a timeout; hosts must still wait for retirement before releasing claims.
Examples found in repository?
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
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 }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 }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}4fn main() -> Result<(), Box<dyn std::error::Error>> {
5 use std::{
6 fs::OpenOptions,
7 io::{Seek, SeekFrom, Write},
8 os::fd::AsRawFd,
9 time::{Duration, Instant},
10 };
11 use usbdac_core::{CaptureRequest, Dac, DacConfig, DeviceInfo};
12 let args: Vec<String> = std::env::args().collect();
13 if args.len() != 5 {
14 return Err(
15 "usage: loopback_capture /dev/bus/usb/BBB/DDD output.wav sample_rate seconds (1..120)"
16 .into(),
17 );
18 }
19 let rate: u32 = args[3].parse()?;
20 let seconds: u64 = args[4].parse()?;
21 if rate == 0 || !(1..=120).contains(&seconds) {
22 return Err("invalid capture duration/rate".into());
23 }
24 let file = OpenOptions::new().read(true).write(true).open(&args[1])?;
25 let fd = file.as_raw_fd();
26 // GET_DESCRIPTOR device: identity comes from the actual USB device.
27 #[repr(C)]
28 struct Control {
29 kind: u8,
30 request: u8,
31 value: u16,
32 index: u16,
33 length: u16,
34 timeout: u32,
35 data: *mut u8,
36 }
37 let mut descriptor = [0u8; 18];
38 let mut control = Control {
39 kind: 0x80,
40 request: 6,
41 value: 0x0100,
42 index: 0,
43 length: 18,
44 timeout: 1000,
45 data: descriptor.as_mut_ptr(),
46 };
47 if unsafe { libc::ioctl(fd, 0xc0185500u32 as _, &mut control) } != 18 {
48 return Err(std::io::Error::last_os_error().into());
49 }
50 let mut info = DeviceInfo::new(
51 u16::from_le_bytes([descriptor[8], descriptor[9]]),
52 u16::from_le_bytes([descriptor[10], descriptor[11]]),
53 "Independent loopback input",
54 )
55 .with_device_name(&args[1]);
56 let (configuration, control_interfaces, input_interfaces) = Dac::capture_preflight(fd, &info)?;
57 let mut claims = control_interfaces;
58 claims.extend(input_interfaces);
59 claims.sort_unstable();
60 claims.dedup();
61 for &interface in &claims {
62 let interface = u32::from(interface);
63 if unsafe { libc::ioctl(fd, 0x8004550fu32 as _, &interface) } != 0 {
64 return Err(std::io::Error::last_os_error().into());
65 }
66 }
67 info.configuration_id = Some(configuration);
68 info.claimed_interfaces = claims.clone();
69 let dac = Dac::open_capture_device(fd, info, DacConfig::default())?;
70 let capture = dac.open_capture(
71 &CaptureRequest {
72 sample_rate: rate,
73 channels: 2,
74 valid_bits: 16,
75 channel_map: None,
76 },
77 rate as usize,
78 )?;
79 if capture.format().subslot_bytes() != 2 {
80 return Err("probe requires packed 16-bit stereo input for WAV analysis".into());
81 }
82 let mut output = OpenOptions::new()
83 .create_new(true)
84 .write(true)
85 .open(&args[2])?;
86 output.write_all(&[0u8; 44])?;
87 let mut buffer = [0u8; 8192];
88 let mut bytes = 0u32;
89 let started = Instant::now();
90 while started.elapsed() < Duration::from_secs(seconds) {
91 let frames = capture.read(&mut buffer)?;
92 let count = frames * capture.format().bytes_per_frame();
93 output.write_all(&buffer[..count])?;
94 bytes = bytes.checked_add(count as u32).ok_or("WAV too large")?;
95 std::thread::sleep(Duration::from_millis(2));
96 }
97 let stats = capture.stats();
98 capture.close()?;
99 dac.close()?;
100 if !Dac::await_usb_retirement(Duration::from_secs(3)) {
101 return Err("capture did not retire; retain host claims".into());
102 }
103 for &interface in claims.iter().rev() {
104 let interface = u32::from(interface);
105 if unsafe { libc::ioctl(fd, 0x80045510u32 as _, &interface) } != 0 {
106 return Err(std::io::Error::last_os_error().into());
107 }
108 }
109 let mut header = Vec::with_capacity(44);
110 header.extend_from_slice(b"RIFF");
111 header.extend_from_slice(&(36 + bytes).to_le_bytes());
112 header.extend_from_slice(b"WAVEfmt ");
113 header.extend_from_slice(&16u32.to_le_bytes());
114 header.extend_from_slice(&1u16.to_le_bytes());
115 header.extend_from_slice(&2u16.to_le_bytes());
116 header.extend_from_slice(&rate.to_le_bytes());
117 header.extend_from_slice(&(rate * 4).to_le_bytes());
118 header.extend_from_slice(&4u16.to_le_bytes());
119 header.extend_from_slice(&16u16.to_le_bytes());
120 header.extend_from_slice(b"data");
121 header.extend_from_slice(&bytes.to_le_bytes());
122 output.seek(SeekFrom::Start(0))?;
123 output.write_all(&header)?;
124 output.flush()?;
125 let valid = bytes > 0
126 && stats.failed_transfers == 0
127 && stats.failed_packets == 0
128 && stats.missing_frames == 0
129 && stats.overrun_frames == 0
130 && stats.contention_frames == 0;
131 let metadata = serde_json::json!({"sample_rate":rate,"channels":2,"valid_bits":16,"subslot_bytes":2,"bytes":bytes,"capture_complete":valid,"stats":format!("{stats:?}"),"clock_alignment":"unmeasured","gain_calibration":"unmeasured"});
132 std::fs::write(
133 format!("{}.json", args[2]),
134 serde_json::to_vec_pretty(&metadata)?,
135 )?;
136 if !valid {
137 return Err(
138 "capture has missing/failed/backlogged frames; metrics cannot establish discontinuity"
139 .into(),
140 );
141 }
142 println!("CAPTURE_COMPLETE {} frames; annotate playback events against the capture clock before analysis", bytes / 4);
143 Ok(())
144}Sourcepub fn close_with(self, volume: CloseVolume) -> Result<()>
pub fn close_with(self, volume: CloseVolume) -> Result<()>
Like close, but the host says what becomes of the level
the DAC had before the library first changed it, instead of
DacConfig::hand_back deciding at open: write it back (another driver
gets the DAC), keep the record (the host holds on to the DAC or takes it
straight back) or forget it (the DAC was unplugged).
A DAC the library saw disappear is always forgotten: nothing can be written to it and a later attachment must start fresh.
Examples found in repository?
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}Sourcepub fn set_dsd_overrides(
&self,
big_endian: Option<bool>,
subslot: Option<u8>,
) -> Result<()>
pub fn set_dsd_overrides( &self, big_endian: Option<bool>, subslot: Option<u8>, ) -> Result<()>
Changes the native DSD overrides of the open DAC (DacConfig::dsd_big_endian
and DacConfig::dsd_subslot), for a host whose user can change them
while the DAC stays open. None goes back to the device quirk.
They are read when a format is negotiated and when a stream is opened: a
stream that is already open keeps what it started with, and
capabilities reflects a new subslot size after the
next negotiate. subslot must be 1, 2 or 4.