pub struct UsbRetirement { /* private fields */ }Expand description
A particular DAC owner’s USB retirement, independent of other devices.
Implementations§
Source§impl UsbRetirement
impl UsbRetirement
Sourcepub fn wait(&self, timeout: Duration) -> bool
pub fn wait(&self, timeout: Duration) -> bool
Examples found in repository?
examples/two_dac_smoke.rs (line 137)
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
examples/usbip_lifecycle.rs (line 453)
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 routing_hand_back_report(&self) -> Result<Option<RoutingHandBackReport>>
pub fn routing_hand_back_report(&self) -> Result<Option<RoutingHandBackReport>>
Routing hand-back outcome after this owner has retired. None means no route changes were recorded; a pending owner is an explicit error.
Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for UsbRetirement
impl !UnwindSafe for UsbRetirement
impl Forget for UsbRetirement
impl Freeze for UsbRetirementwhere
*const ArcInner<SessionContext> is !null: Freeze,
PhantomData<ArcInner<SessionContext>>: Freeze,
impl Move for UsbRetirement
impl Send for UsbRetirement
impl Sync for UsbRetirement
impl Unpin for UsbRetirement
impl UnsafeUnpin for UsbRetirementwhere
*const ArcInner<SessionContext> is !null: UnsafeUnpin,
PhantomData<ArcInner<SessionContext>>: UnsafeUnpin,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more