rodecaster_protocol/usb.rs
1//! USB HID transport framing and report chunking.
2//!
3//! When communicating with a RØDECaster over USB, messages are split into
4//! fixed [`REPORT_SIZE`] (64-byte) HID reports. Each report begins with a
5//! report ID byte ([`REPORT_ID_OUT`] host-to-device, [`REPORT_ID_IN`] device-to-host)
6//! followed by up to [`REPORT_PAYLOAD`] (63 bytes) of data.
7//!
8//! This module provides packet encoding and scanning so you can assemble
9//! incoming HID reports into complete protocol payloads and split outgoing
10//! messages into valid HID reports.
11//!
12//! # Sending Messages
13//!
14//! To send a message, wrap your payload in [`Packet`] and call [`Packet::to_bytes`]:
15//!
16//! ```rust
17//! use rodecaster_protocol::usb::{Packet, REPORT_SIZE};
18//!
19//! let payload = vec![0x01, 0x02, 0x03];
20//! let report_bytes = Packet::new(payload).to_bytes();
21//!
22//! // report_bytes is padded to multiples of REPORT_SIZE (64 bytes).
23//! // Write each 64-byte report to your HID device handle:
24//! for report in report_bytes.chunks_exact(REPORT_SIZE) {
25//! let _ = report;
26//! }
27//! ```
28//!
29//! # Receiving Messages
30//!
31//! As reports arrive from your HID device, append them to a buffer and call
32//! [`scan_frame`]:
33//!
34//! ```rust
35//! use rodecaster_protocol::usb::{scan_frame, FrameScan, Packet};
36//!
37//! let mut buffer = Vec::new();
38//! // buffer.extend_from_slice(&incoming_report);
39//!
40//! if let FrameScan::Complete { len } = scan_frame(&buffer) {
41//! if let Some((packet, consumed)) = Packet::from_bytes(&buffer[..len]) {
42//! buffer.drain(..consumed);
43//! // Pass packet.payload to ProtocolSession::ingest
44//! let _ = packet.payload;
45//! }
46//! }
47//! ```
48
49pub use crate::frame::FrameScan;
50
51/// HID report id for host -> device (output) reports.
52pub const REPORT_ID_OUT: u8 = 0x03;
53
54/// HID report id for device -> host (input) reports.
55pub const REPORT_ID_IN: u8 = 0x04;
56
57/// Total HID report size on the wire: one report-id byte plus the payload.
58pub const REPORT_SIZE: usize = 256;
59
60/// Usable payload bytes per HID report ([`REPORT_SIZE`] minus the report-id
61/// byte). The length-prefixed message is chunked into pieces this large.
62pub const REPORT_PAYLOAD: usize = REPORT_SIZE - 1;
63
64/// Sanity cap on a decoded message body (1 MiB). A corrupt length prefix would
65/// otherwise wedge a streaming reader on an impossible frame; past this,
66/// [`scan_frame`] reports [`FrameScan::Desync`].
67pub const MAX_MESSAGE_LEN: usize = 1024 * 1024;
68
69/// The 4-byte body the device expects as the first message after connect to
70/// start a full-state sync. Send [`handshake_bytes`]; on the wire it is the
71/// framed form `[04 00 00 00][AD 10 A7 B0]` in one report.
72pub const HANDSHAKE_BODY: [u8; 4] = [0xAD, 0x10, 0xA7, 0xB0];
73
74/// A USB HID message: the inner `body` plus its length, framed and chunked into
75/// HID reports on the wire. The USB counterpart to [`crate::Packet`] (no magic
76/// header).
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct Packet {
79 pub length: u32,
80 pub payload: Vec<u8>,
81}
82
83impl Packet {
84 #[must_use]
85 pub fn new(payload: Vec<u8>) -> Self {
86 Packet {
87 length: payload.len() as u32,
88 payload,
89 }
90 }
91
92 /// Serialize to the full HID wire form: `[u32 LE len][body]` chunked into
93 /// [`REPORT_PAYLOAD`]-byte pieces, each prefixed with [`REPORT_ID_OUT`] and
94 /// the last zero-padded to [`REPORT_SIZE`]. Write it to the device in
95 /// [`REPORT_SIZE`]-byte chunks, one report per HID write.
96 #[must_use]
97 pub fn to_bytes(&self) -> Vec<u8> {
98 let mut framed = Vec::with_capacity(4 + self.payload.len());
99 framed.extend_from_slice(&self.length.to_le_bytes());
100 framed.extend_from_slice(&self.payload);
101
102 let n_reports = framed.len().div_ceil(REPORT_PAYLOAD).max(1);
103 let mut out = vec![0u8; n_reports * REPORT_SIZE];
104 for (i, chunk) in framed.chunks(REPORT_PAYLOAD).enumerate() {
105 let base = i * REPORT_SIZE;
106 out[base] = REPORT_ID_OUT;
107 out[base + 1..=base + chunk.len()].copy_from_slice(chunk);
108 }
109 out
110 }
111
112 /// Parse one message from a buffer of raw HID reports (each [`REPORT_SIZE`]
113 /// bytes as read from the device), returning it and the raw byte count to
114 /// drain (a whole number of reports). `None` unless `buf` begins with a
115 /// complete, valid message. The report-id byte of each report is ignored, so
116 /// this decodes both [`REPORT_ID_OUT`] and [`REPORT_ID_IN`] streams.
117 #[must_use]
118 pub fn from_bytes(buf: &[u8]) -> Option<(Self, usize)> {
119 let (body_len, n_reports) = match scan_frame(buf) {
120 FrameScan::Complete { len } => (frame_len_unchecked(buf), len / REPORT_SIZE),
121 FrameScan::Incomplete | FrameScan::Desync => return None,
122 };
123 // De-chunk: concatenate each report's payload (skipping the report-id
124 // byte), then take the body that follows the 4-byte length prefix.
125 let mut framed = Vec::with_capacity(n_reports * REPORT_PAYLOAD);
126 for i in 0..n_reports {
127 let base = i * REPORT_SIZE;
128 framed.extend_from_slice(&buf[base + 1..base + REPORT_SIZE]);
129 }
130 let body = framed[4..4 + body_len].to_vec();
131 Some((
132 Packet {
133 length: body_len as u32,
134 payload: body,
135 },
136 n_reports * REPORT_SIZE,
137 ))
138 }
139}
140
141/// Read the 4-byte length prefix from the first report's payload. Caller must
142/// have confirmed `buf.len() >= REPORT_SIZE` (e.g. via [`scan_frame`]).
143fn frame_len_unchecked(buf: &[u8]) -> usize {
144 u32::from_le_bytes([buf[1], buf[2], buf[3], buf[4]]) as usize
145}
146
147/// Scan a raw HID report buffer for a complete leading message without copying
148/// the body. The USB counterpart to [`crate::scan_frame`]; `len` in
149/// [`FrameScan::Complete`] is the raw byte count to drain (a whole number of
150/// [`REPORT_SIZE`] reports). [`FrameScan::Desync`] means the length prefix is
151/// impossible (zero or over [`MAX_MESSAGE_LEN`]); drop one report and rescan.
152#[must_use]
153pub fn scan_frame(buf: &[u8]) -> FrameScan {
154 if buf.len() < REPORT_SIZE {
155 return FrameScan::Incomplete;
156 }
157 let body_len = frame_len_unchecked(buf);
158 if body_len == 0 || body_len > MAX_MESSAGE_LEN {
159 return FrameScan::Desync;
160 }
161 let n_reports = (4 + body_len).div_ceil(REPORT_PAYLOAD);
162 let total_raw = n_reports * REPORT_SIZE;
163 if buf.len() < total_raw {
164 return FrameScan::Incomplete;
165 }
166 FrameScan::Complete { len: total_raw }
167}
168
169/// Decode the payload of one complete message at the front of a raw HID report
170/// buffer. Returns an owned `Vec<u8>` with report IDs and padding stripped.
171#[must_use]
172pub fn frame_payload(buf: &[u8]) -> Option<Vec<u8>> {
173 Packet::from_bytes(buf).map(|(p, _)| p.payload)
174}
175
176/// The HID wire bytes (one [`REPORT_SIZE`] report) carrying the startup
177/// handshake ([`HANDSHAKE_BODY`]).
178#[must_use]
179pub fn handshake_bytes() -> Vec<u8> {
180 Packet::new(HANDSHAKE_BODY.to_vec()).to_bytes()
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn packet_roundtrip_single_report() {
189 let payload = vec![0x02, 0xDE, 0xAD, 0xBE, 0xEF];
190 let bytes = Packet::new(payload.clone()).to_bytes();
191 assert_eq!(bytes.len(), REPORT_SIZE);
192
193 let (parsed, consumed) = Packet::from_bytes(&bytes).unwrap();
194 assert_eq!(consumed, bytes.len());
195 assert_eq!(parsed.payload, payload);
196 assert_eq!(parsed.length as usize, payload.len());
197 }
198
199 #[test]
200 fn to_bytes_layout_is_len_payload_no_magic() {
201 let bytes = Packet::new(vec![0xAA, 0xBB]).to_bytes();
202 assert_eq!(bytes[0], REPORT_ID_OUT); // report id, not a magic word
203 assert_eq!(&bytes[1..5], &2u32.to_le_bytes()); // length, LE
204 assert_eq!(&bytes[5..7], &[0xAA, 0xBB]); // body
205 assert!(bytes[7..].iter().all(|&b| b == 0)); // zero padding
206 }
207
208 #[test]
209 fn handshake_matches_known_bytes() {
210 let bytes = handshake_bytes();
211 assert_eq!(bytes.len(), REPORT_SIZE);
212 assert_eq!(bytes[0], REPORT_ID_OUT);
213 // framed handshake: [04 00 00 00][AD 10 A7 B0]
214 assert_eq!(
215 &bytes[1..9],
216 &[0x04, 0x00, 0x00, 0x00, 0xAD, 0x10, 0xA7, 0xB0]
217 );
218 assert!(bytes[9..].iter().all(|&b| b == 0));
219 }
220
221 #[test]
222 fn packet_roundtrip_multi_report() {
223 // 600-byte body -> framed 604 -> 3 reports (3 * 256 raw bytes).
224 let payload: Vec<u8> = (0..600u32).map(|i| (i % 251) as u8).collect();
225 let bytes = Packet::new(payload.clone()).to_bytes();
226 assert_eq!(bytes.len(), 3 * REPORT_SIZE);
227
228 let (parsed, consumed) = Packet::from_bytes(&bytes).unwrap();
229 assert_eq!(consumed, 3 * REPORT_SIZE);
230 assert_eq!(parsed.payload, payload);
231 assert_eq!(frame_payload(&bytes), Some(payload));
232 }
233
234 #[test]
235 fn scan_frame_complete_incomplete_desync() {
236 let bytes = Packet::new(vec![1, 2, 3]).to_bytes();
237 assert_eq!(scan_frame(&bytes), FrameScan::Complete { len: REPORT_SIZE });
238
239 // Fewer than one report -> Incomplete.
240 assert_eq!(scan_frame(&bytes[..REPORT_SIZE - 1]), FrameScan::Incomplete);
241 assert_eq!(scan_frame(&[]), FrameScan::Incomplete);
242
243 // Multi-report message missing its last report -> Incomplete.
244 let big = Packet::new(vec![7u8; 600]).to_bytes();
245 assert_eq!(scan_frame(&big[..2 * REPORT_SIZE]), FrameScan::Incomplete);
246
247 // Zero length prefix in an otherwise full report -> Desync.
248 let zero = [0u8; REPORT_SIZE];
249 assert_eq!(scan_frame(&zero), FrameScan::Desync);
250
251 // Oversized length prefix -> Desync.
252 let mut huge = [0u8; REPORT_SIZE];
253 huge[1..5].copy_from_slice(&(MAX_MESSAGE_LEN as u32 + 1).to_le_bytes());
254 assert_eq!(scan_frame(&huge), FrameScan::Desync);
255 }
256
257 #[test]
258 fn report_aligned_stops_at_first_message_boundary() {
259 // Two messages back to back, each whole-report aligned.
260 let first = Packet::new(vec![0x02, 0xAA]).to_bytes();
261 let first_len = first.len();
262 let mut two = first;
263 two.extend_from_slice(&Packet::new(vec![0x02, 0xBB, 0xCC]).to_bytes());
264
265 // scan + payload see only the first message.
266 assert_eq!(scan_frame(&two), FrameScan::Complete { len: first_len });
267 assert_eq!(frame_payload(&two), Some(vec![0x02, 0xAA]));
268
269 // After draining the first, the second decodes.
270 let (_, consumed) = Packet::from_bytes(&two).unwrap();
271 assert_eq!(
272 frame_payload(&two[consumed..]),
273 Some(vec![0x02, 0xBB, 0xCC])
274 );
275 }
276
277 #[test]
278 fn from_bytes_ignores_report_id_so_in_stream_decodes() {
279 // Device->host reports carry REPORT_ID_IN; decode must still work.
280 let mut bytes = Packet::new(vec![0x02, 0x11, 0x22]).to_bytes();
281 bytes[0] = REPORT_ID_IN;
282 assert_eq!(frame_payload(&bytes), Some(vec![0x02, 0x11, 0x22]));
283 }
284}