Skip to main content

StreamFormat

Struct StreamFormat 

Source
#[non_exhaustive]
pub struct StreamFormat {
Show 16 fields pub request: StreamRequest, pub encoding: Encoding, pub sample_rate: u32, pub channels: u16, pub channel_map: ChannelMap, pub valid_bits: u8, pub subslot_bytes: u8, pub interface_number: u8, pub alt_setting: u8, pub endpoint_address: u8, pub sync_type: SyncKind, pub explicit_feedback: bool, pub link_speed: LinkSpeed, pub service_interval_us: u32, pub pacing: Pacing, pub clock: Option<ClockChoice>, /* private fields */
}
Expand description

What will go on the wire, as chosen by Dac::negotiate.

A StreamFormat cannot be built by hand; pass the one negotiate returned to Dac::open_stream.

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§request: StreamRequest

The request this format answers.

§encoding: Encoding§sample_rate: u32

Frame rate on the wire: the PCM rate, the DoP carrier rate, or for native DSD the rate of subslot-sized words (bit_rate / (8 * subslot_bytes)).

§channels: u16§channel_map: ChannelMap

Descriptor-backed identities in interleaved USB wire order; unnamed when unavailable.

§valid_bits: u8

Significant bits of the alternate setting (PCM and DoP carrier). 1 for native DSD.

§subslot_bytes: u8

Bytes per sample on the wire.

§interface_number: u8§alt_setting: u8§endpoint_address: u8§sync_type: SyncKind§explicit_feedback: bool§link_speed: LinkSpeed§service_interval_us: u32§pacing: Pacing

How the stream is paced on the endpoint: what the transport does, named (see Pacing). Consistent with sync_type and explicit_feedback.

§clock: Option<ClockChoice>

The Clock Source the sample rate was set and verified on, and how it was reached from the stream’s terminal (see ClockChoice), as resolved by Dac::negotiate. None when the DAC has no clock entities to set (UAC 1.0 sets the rate on the endpoint).

Implementations§

Source§

impl StreamFormat

Source

pub fn bytes_per_frame(&self) -> usize

Bytes of one wire frame (one sample for every channel): the unit DacStream::write counts in. Also the granularity of everything the stream accepts.

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

pub fn counter_rate_hz(&self) -> u32

Rate of the unit that played_frames(), latency_frames() and the stream statistics count in. For PCM and DoP it is the wire frame rate. For native DSD it is bit_rate / 8: one frame is one DSD byte per channel (8 DSD bits per channel).

Examples found in repository?
examples/pull_adapter.rs (line 105)
102    fn position_seconds(&self) -> f64 {
103        let base = lock(&self.state).base_seconds;
104        base + self.stream.played_frames() as f64
105            / f64::from(self.stream.format().counter_rate_hz())
106    }
More examples
Hide additional examples
examples/guide_player.rs (line 122)
117    fn from(format: &StreamFormat) -> Self {
118        Self {
119            channels: usize::from(format.channels),
120            bytes_per_sample: usize::from(format.subslot_bytes),
121            sample_rate: format.sample_rate,
122            counter_rate_hz: format.counter_rate_hz(),
123        }
124    }
Source

pub fn rate_differs_from_request(&self) -> bool

Whether the DAC runs a different rate than requested (only possible with RatePolicy::NearestSupported).

Examples found in repository?
examples/guide_open.rs (line 101)
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}

Trait Implementations§

Source§

impl Clone for StreamFormat

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for StreamFormat

Source§

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

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

impl PartialEq for StreamFormat

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for StreamFormat

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

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

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.