interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / usb / audio.rs

515 lines · 19133 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Host-testable USB Audio Class output descriptor and PCM helpers.
17//!
18//! This parses the common single-configuration UAC1/UAC2 layout. It does not
19//! touch controller registers; packet scheduling is host-testable.
20
21use crate::usb::xhci::trb::Trb;
22
23const CONFIG: u8 = 2;
24const INTERFACE: u8 = 4;
25const ENDPOINT: u8 = 5;
26const CS_INTERFACE: u8 = 0x24;
27const CS_ENDPOINT: u8 = 0x25;
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum AudioVersion {
31 Uac1,
32 Uac2,
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub struct AudioStream {
37 pub version: AudioVersion,
38 pub control_interface: u8,
39 pub interface: u8,
40 pub alternate: u8,
41 pub endpoint_address: u8,
42 pub max_packet: u16,
43 pub interval: u8,
44 pub channels: u8,
45 pub subframe_bytes: u8,
46 pub bit_resolution: u8,
47 pub clock_source: Option<u8>,
48 /// Zero means continuous; otherwise the discrete rates advertised.
49 pub sample_rates: [u32; 8],
50 pub sample_rate_count: u8,
51}
52
53fn le24(b: &[u8]) -> u32 {
54 u32::from(b[0]) | (u32::from(b[1]) << 8) | (u32::from(b[2]) << 16)
55}
56
57/// Select the best output stream for 48 kHz, 16-bit stereo, preferring exact
58/// channel/bit matches and then the smallest packet size.
59pub fn select_output(bytes: &[u8]) -> Option<AudioStream> {
60 if bytes.len() < 9 || bytes[0] < 9 || bytes[1] != CONFIG {
61 return None;
62 }
63 let total = usize::from(u16::from_le_bytes([bytes[2], bytes[3]])).min(bytes.len());
64 let mut version = None;
65 let mut control = None;
66 let mut iface: Option<(u8, u8, bool)> = None;
67 let mut fmt: Option<(u8, u8, u8, [u32; 8], u8)> = None;
68 let mut clock = None;
69 let mut candidates: [Option<AudioStream>; 16] = [None; 16];
70 let mut n = 0;
71 let mut at = 0;
72 while at + 2 <= total {
73 let len = usize::from(bytes[at]);
74 if len < 2 || at + len > total {
75 return None;
76 }
77 let d = &bytes[at..at + len];
78 match d[1] {
79 INTERFACE if len >= 9 => {
80 iface = Some((d[2], d[3], d[5] == 1 && d[6] == 2));
81 fmt = None;
82 if d[5] == 1 && d[6] == 1 {
83 control = Some(d[2]);
84 }
85 }
86 CS_INTERFACE if len >= 3 => match d[2] {
87 1 if iface.map(|x| x.2).unwrap_or(false) => {
88 // UAC2 AS_GENERAL carries bNrChannels at offset 10. UAC1
89 // AS_GENERAL has none (offset 4 is bDelay); UAC1 channels
90 // come from FORMAT_TYPE_I below.
91 if version == Some(AudioVersion::Uac2) && d.len() >= 11 {
92 let channels = d[10];
93 if let Some((_, sub, bits, rates, count)) = fmt {
94 fmt = Some((channels, sub, bits, rates, count));
95 } else {
96 fmt = Some((channels, 0, 0, [0; 8], 0));
97 }
98 }
99 }
100 1 if d.len() >= 8 && iface.map(|x| !x.2).unwrap_or(false) => {
101 let bcd = u16::from_le_bytes([d[3], d[4]]);
102 version = Some(if bcd >= 0x0200 {
103 AudioVersion::Uac2
104 } else {
105 AudioVersion::Uac1
106 });
107 if version == Some(AudioVersion::Uac2) && d.len() >= 8 {
108 clock = Some(d[7]);
109 }
110 }
111 // FORMAT_TYPE_I. UAC1: bNrChannels[4], bSubframeSize[5],
112 // bBitResolution[6], bSamFreqType[7] (so at least 8 bytes).
113 // UAC2: bSubslotSize[4], bBitResolution[5] (at least 6 bytes).
114 2 if iface.map(|x| x.2).unwrap_or(false)
115 && d.len()
116 >= if version == Some(AudioVersion::Uac2) {
117 6
118 } else {
119 8
120 } =>
121 {
122 let (channels, sub, bits) = if version == Some(AudioVersion::Uac2) {
123 (fmt.map(|x| x.0).unwrap_or(0), d[4], d[5])
124 } else {
125 (d[4], d[5], d[6])
126 };
127 let mut rates = [0; 8];
128 let mut count = 0;
129 if version == Some(AudioVersion::Uac1) && d.len() >= 8 {
130 let nr = usize::from(d[7]);
131 if nr == 0 {
132 count = 0;
133 } else if d.len() >= 8 + nr * 3 {
134 count = nr.min(8) as u8;
135 for i in 0..usize::from(count) {
136 rates[i] = le24(&d[8 + i * 3..]);
137 }
138 }
139 } else if version == Some(AudioVersion::Uac2) {
140 // UAC2 clock rates are queried from the clock entity.
141 // This slice selects the common 48 kHz default.
142 rates[0] = 48_000;
143 count = 1;
144 }
145 fmt = Some((channels, sub, bits, rates, count));
146 }
147 0x0a if d.len() >= 4 && version == Some(AudioVersion::Uac2) => clock = Some(d[3]),
148 _ => {}
149 },
150 ENDPOINT if len >= 7 => {
151 if let (
152 Some((number, alt, true)),
153 Some((ch, sub, bits, rates, count)),
154 Some(v),
155 Some(ci),
156 ) = (iface, fmt, version, control)
157 {
158 let attr = d[3] & 3;
159 if alt != 0 && d[2] & 0x80 == 0 && attr == 1 && n < candidates.len() {
160 let mut rs = rates;
161 let rc = count;
162 // UAC2 rates belong to the clock entity, not FORMAT_TYPE.
163 if v == AudioVersion::Uac2 && rc == 1 {
164 rs[0] = 48_000;
165 }
166 candidates[n] = Some(AudioStream {
167 version: v,
168 control_interface: ci,
169 interface: number,
170 alternate: alt,
171 endpoint_address: d[2],
172 max_packet: u16::from_le_bytes([d[4], d[5]]) & 0x7ff,
173 interval: d[6],
174 channels: ch,
175 subframe_bytes: sub,
176 bit_resolution: bits,
177 clock_source: clock,
178 sample_rates: rs,
179 sample_rate_count: rc,
180 });
181 n += 1;
182 }
183 }
184 }
185 CS_ENDPOINT if len >= 8 => {}
186 _ => {}
187 }
188 at += len;
189 }
190 candidates[..n]
191 .iter()
192 .flatten()
193 .copied()
194 .filter(|s| {
195 s.channels >= 2
196 && s.subframe_bytes >= 2
197 && s.bit_resolution >= 16
198 && (s.sample_rate_count == 0
199 || s.sample_rates[..usize::from(s.sample_rate_count)].contains(&48_000))
200 })
201 .min_by_key(|s| (s.channels != 2, s.bit_resolution != 16, s.max_packet))
202}
203
204/// Exact endpoint service interval in microseconds. Full speed uses 1 ms;
205/// high speed bInterval encodes 2^(n-1) microframes of 125 us.
206pub fn service_interval_us(high_speed: bool, interval: u8) -> Option<u32> {
207 if interval == 0 {
208 return None;
209 }
210 if high_speed {
211 (interval <= 16).then(|| 125u32 << (interval - 1))
212 } else {
213 Some(1000)
214 }
215}
216
217#[derive(Clone, Copy, Debug, PartialEq, Eq)]
218pub struct PcmFramer {
219 rate: u32,
220 channels: u8,
221 sample_bytes: u8,
222 interval_us: u32,
223 remainder: u64,
224}
225impl PcmFramer {
226 pub fn new(rate: u32, channels: u8, sample_bytes: u8, interval_us: u32) -> Option<Self> {
227 (rate > 0 && channels > 0 && sample_bytes > 0 && interval_us > 0).then_some(Self {
228 rate,
229 channels,
230 sample_bytes,
231 interval_us,
232 remainder: 0,
233 })
234 }
235 /// Returns packet byte count, carrying fractional frames between packets.
236 pub fn next_packet_bytes(&mut self) -> usize {
237 let numerator = u64::from(self.rate) * u64::from(self.interval_us) + self.remainder;
238 let frames = numerator / 1_000_000;
239 self.remainder = numerator % 1_000_000;
240 frames as usize * usize::from(self.channels) * usize::from(self.sample_bytes)
241 }
242 /// Bytes the next packet will need, without advancing the framer.
243 pub fn peek_packet_bytes(&self) -> usize {
244 let numerator = u64::from(self.rate) * u64::from(self.interval_us) + self.remainder;
245 (numerator / 1_000_000) as usize
246 * usize::from(self.channels)
247 * usize::from(self.sample_bytes)
248 }
249 /// Fill one packet from interleaved PCM, wrapping the caller's ring cursor.
250 pub fn fill_i16(&mut self, ring: &[i16], cursor: &mut usize, out: &mut [i16]) -> usize {
251 let bytes = self.next_packet_bytes();
252 let samples = (bytes / 2).min(out.len());
253 if ring.is_empty() {
254 out[..samples].fill(0);
255 return samples;
256 }
257 for dst in &mut out[..samples] {
258 *dst = ring[*cursor % ring.len()];
259 *cursor = (*cursor + 1) % ring.len();
260 }
261 samples
262 }
263}
264
265/// Prepare `packets.len()` service intervals ahead of `controller_frame`.
266/// Each PCM output chunk has `packet_stride_samples` samples; its DMA address
267/// is supplied in the matching entry. Frame IDs wrap at the xHCI 11-bit field.
268pub struct AudioBatch<'a> {
269 pub controller_frame: u16,
270 pub lead_frames: u16,
271 pub packets: &'a [(u64, u16)],
272 pub pcm_ring: &'a [i16],
273 pub cursor: &'a mut usize,
274 pub pcm: &'a mut [i16],
275 pub packet_stride_samples: usize,
276 pub trbs: &'a mut [Trb],
277}
278
279pub fn schedule_isoch_ahead(framer: &mut PcmFramer, batch: &mut AudioBatch<'_>) -> usize {
280 let AudioBatch {
281 controller_frame,
282 lead_frames,
283 packets,
284 pcm_ring,
285 cursor,
286 pcm,
287 packet_stride_samples,
288 trbs,
289 } = batch;
290 let stride = *packet_stride_samples;
291 if stride == 0 {
292 return 0;
293 }
294 let slots = packets.len().min(trbs.len()).min(pcm.len() / stride);
295 let mut count = 0;
296 while count < slots {
297 // Check before consuming PCM: a packet that doesn't fit its buffer or
298 // its PCM chunk stops scheduling here, rather than being truncated
299 // while the cursor skips the samples that were cut.
300 let needed = framer.peek_packet_bytes();
301 if needed > usize::from(packets[count].1) || needed > stride * 2 {
302 break;
303 }
304 let start = count * stride;
305 let out = &mut pcm[start..start + stride];
306 let samples = framer.fill_i16(pcm_ring, cursor, out);
307 trbs[count] = Trb::isoch(
308 packets[count].0,
309 (samples * 2) as u32,
310 controller_frame
311 .wrapping_add(*lead_frames)
312 .wrapping_add(count as u16)
313 & 0x7ff,
314 false,
315 false,
316 );
317 count += 1;
318 }
319 if count > 0 {
320 // Interrupt on completion of the last packet actually scheduled.
321 let last = &trbs[count - 1];
322 trbs[count - 1] = Trb::isoch(
323 last.0[0] as u64 | (last.0[1] as u64) << 32,
324 last.0[2] & 0x1_ffff,
325 ((last.0[3] >> 20) & 0x7ff) as u16,
326 false,
327 true,
328 );
329 }
330 count
331}
332
333/// Deterministic 16-bit sine approximation using a parabolic fixed-point wave.
334#[derive(Clone, Copy, Debug, Default)]
335pub struct TestTone {
336 phase: u32,
337 step: u32,
338}
339impl TestTone {
340 pub fn new(frequency_hz: u32, sample_rate: u32) -> Option<Self> {
341 (sample_rate > 0 && frequency_hz < sample_rate / 2).then_some(Self {
342 phase: 0,
343 step: ((u64::from(frequency_hz) << 32) / u64::from(sample_rate)) as u32,
344 })
345 }
346 pub fn next_sample(&mut self) -> i16 {
347 self.phase = self.phase.wrapping_add(self.step);
348 let x = (self.phase >> 16) as i32;
349 let tri = if x < 32768 { x } else { 65535 - x };
350 let y = (4i64 * i64::from(tri) * i64::from(32767 - tri) * 2 / 32767) as i32 - 32767;
351 y.clamp(-32767, 32767) as i16
352 }
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358 // Real UAC1 shape: AC, AS alt zero, stereo Type I PCM 16-bit/48 kHz, OUT.
359 const UAC1: &[u8] = &[
360 9, 2, 73, 0, 2, 1, 0, 0x80, 50, 9, 4, 0, 0, 0, 1, 1, 0, 0, 9, 0x24, 1, 0, 1, 0x26, 0, 1, 1,
361 9, 4, 1, 0, 0, 1, 2, 0, 0, 9, 4, 1, 1, 1, 1, 2, 0, 0, 7, 0x24, 1, 1, 2, 3, 0, 11, 0x24, 2,
362 1, 2, 2, 16, 1, 0x80, 0xbb, 0, 9, 5, 1, 1, 192, 0, 1, 0, 0,
363 ];
364 // UAC2 clock source and Type I 16-bit stereo format, one 48 kHz clock.
365 const UAC2: &[u8] = &[
366 9, 2, 85, 0, 2, 1, 0, 0x80, 50, 9, 4, 0, 0, 0, 1, 1, 0, 0, 9, 0x24, 1, 0, 2, 9, 0, 1, 1, 8,
367 0x24, 0x0a, 3, 7, 0, 0, 0, 9, 4, 1, 0, 0, 1, 2, 0, 0, 9, 4, 1, 1, 1, 1, 2, 0, 0, 16, 0x24,
368 1, 1, 0, 1, 1, 0, 0, 0, 2, 3, 0, 0, 0, 0, 6, 0x24, 2, 1, 2, 16, 9, 5, 1, 1, 192, 0, 1, 0,
369 0,
370 ];
371 #[test]
372 fn parses_uac1_and_uac2() {
373 let a = select_output(UAC1).unwrap();
374 assert_eq!(
375 (
376 a.version,
377 a.interface,
378 a.alternate,
379 a.channels,
380 a.bit_resolution
381 ),
382 (AudioVersion::Uac1, 1, 1, 2, 16)
383 );
384 let b = select_output(UAC2).unwrap();
385 assert_eq!(b.version, AudioVersion::Uac2);
386 assert_eq!(b.clock_source, Some(3));
387 }
388 #[test]
389 fn fractional_44100_packet_pattern_totals_one_second() {
390 let mut f = PcmFramer::new(44100, 1, 2, 1000).unwrap();
391 let mut frames = 0;
392 let mut saw44 = false;
393 let mut saw45 = false;
394 for _ in 0..1000 {
395 let n = f.next_packet_bytes() / 2;
396 frames += n;
397 saw44 |= n == 44;
398 saw45 |= n == 45;
399 }
400 assert_eq!(frames, 44100);
401 assert!(saw44 && saw45);
402 }
403
404 #[test]
405 fn stereo_44100_scheduler_emits_one_second_of_pcm_bytes() {
406 let mut framer = PcmFramer::new(44_100, 2, 2, 1000).unwrap();
407 let mut cursor = 0;
408 let source = [7i16; 256];
409 let mut output = [0i16; 90];
410 let mut total = 0;
411 for _ in 0..1000 {
412 let n = framer.fill_i16(&source, &mut cursor, &mut output);
413 total += n * 2;
414 }
415 assert_eq!(total, 176_400);
416 }
417
418 #[test]
419 fn isoch_schedule_stays_ahead_and_wraps_frame_id() {
420 let mut framer = PcmFramer::new(48_000, 2, 2, 1000).unwrap();
421 let packets = [(0x1000, 192), (0x2000, 192)];
422 let mut pcm = [0i16; 192];
423 let mut trbs = [Trb::default(); 2];
424 let mut cursor = 0;
425 let mut batch = AudioBatch {
426 controller_frame: 2046,
427 lead_frames: 2,
428 packets: &packets,
429 pcm_ring: &[],
430 cursor: &mut cursor,
431 pcm: &mut pcm,
432 packet_stride_samples: 96,
433 trbs: &mut trbs,
434 };
435 let n = schedule_isoch_ahead(&mut framer, &mut batch);
436 assert_eq!(n, 2);
437 assert_eq!((trbs[0].0[3] >> 20) & 0x7ff, 0);
438 assert_eq!((trbs[1].0[3] >> 20) & 0x7ff, 1);
439 assert_eq!(trbs[0].0[2], 192);
440 assert_eq!(trbs[1].0[2], 192);
441 }
442 #[test]
443 fn ring_wraps_and_tone_is_bounded() {
444 let mut f = PcmFramer::new(48000, 2, 2, 1000).unwrap();
445 let ring = [1, 2, 3, 4, 5];
446 let mut cursor = 3;
447 let mut out = [0; 192];
448 assert_eq!(f.fill_i16(&ring, &mut cursor, &mut out), 96);
449 assert_eq!(&out[..4], &[4, 5, 1, 2]);
450 assert_eq!(cursor, 4);
451 let mut tone = TestTone::new(440, 48000).unwrap();
452 for _ in 0..1000 {
453 let x = tone.next_sample();
454 assert!((-32767..=32767).contains(&x));
455 }
456 }
457 #[test]
458 fn uac1_channels_come_from_format_type_not_as_general_delay() {
459 // Review regression: UAC1 AS_GENERAL offset 4 is bDelay. In the UAC1
460 // vector bDelay happened to equal the channel count (2); set it to 7.
461 let mut v = UAC1.to_vec();
462 let at = v
463 .windows(7)
464 .position(|w| w == [7, 0x24, 1, 1, 2, 3, 0])
465 .expect("AS_GENERAL present");
466 v[at + 4] = 7;
467 assert_eq!(select_output(&v).unwrap().channels, 2);
468 }
469
470 #[test]
471 fn short_uac1_format_descriptor_does_not_panic() {
472 // FORMAT_TYPE_I with bLength 7 (< 8 required for UAC1): rejected, no panic.
473 let mut v = UAC1.to_vec();
474 let at = v
475 .windows(3)
476 .position(|w| w == [11, 0x24, 2])
477 .expect("FORMAT_TYPE_I present");
478 v[at] = 7;
479 let _ = select_output(&v);
480 }
481 #[test]
482 fn oversized_packet_is_not_truncated_and_zero_stride_schedules_nothing() {
483 // Review regression: 96 kHz stereo 16-bit needs 384 B per 1 ms packet.
484 let mut framer = PcmFramer::new(96_000, 2, 2, 1000).unwrap();
485 let packets = [(0x1000, 192)];
486 let ring = [7i16; 512];
487 let mut pcm = [0i16; 256];
488 let mut trbs = [Trb::default(); 1];
489 let mut cursor = 0;
490 let mut batch = AudioBatch {
491 controller_frame: 0,
492 lead_frames: 1,
493 packets: &packets,
494 pcm_ring: &ring,
495 cursor: &mut cursor,
496 pcm: &mut pcm,
497 packet_stride_samples: 256,
498 trbs: &mut trbs,
499 };
500 assert_eq!(schedule_isoch_ahead(&mut framer, &mut batch), 0);
501 assert_eq!(cursor, 0, "no samples consumed");
502 let mut cursor = 0;
503 let mut batch = AudioBatch {
504 controller_frame: 0,
505 lead_frames: 1,
506 packets: &[(0x1000, 1024)],
507 pcm_ring: &ring,
508 cursor: &mut cursor,
509 pcm: &mut pcm,
510 packet_stride_samples: 0,
511 trbs: &mut trbs,
512 };
513 assert_eq!(schedule_isoch_ahead(&mut framer, &mut batch), 0);
514 }
515}