1pub const USB_CLASS_AUDIO: u8 = 0x01;
14pub const AUDIO_SUBCLASS_CONTROL: u8 = 0x01;
16pub const AUDIO_SUBCLASS_STREAMING: u8 = 0x02;
18
19pub const CS_INTERFACE: u8 = 0x24;
21pub const CS_ENDPOINT: u8 = 0x25;
23
24pub const AS_GENERAL: u8 = 0x01;
26pub const FORMAT_TYPE: u8 = 0x02;
28pub const FORMAT_TYPE_I: u8 = 0x01;
30pub const PCM_FORMAT_TAG: u16 = 0x0001;
32
33pub const UAC_SET_CUR: u8 = 0x01;
35pub const SAMPLING_FREQ_CONTROL: u16 = 0x0100;
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct UacStreamConfig {
41 pub control_interface: u8,
43 pub streaming_interface: u8,
45 pub alt_setting: u8,
47 pub iso_out_ep: u8,
49 pub max_packet_size: u16,
51 pub channels: u8,
53 pub subframe_size: u8,
55 pub bit_resolution: u8,
57 pub sample_rate: u32,
59 pub freq_control_supported: bool,
61}
62
63#[derive(Clone, Copy)]
64struct AltCandidate {
65 streaming_interface: u8,
66 alt_setting: u8,
67 iso_out_ep: u8,
68 max_packet_size: u16,
69 format_tag: u16,
70 channels: u8,
71 subframe_size: u8,
72 bit_resolution: u8,
73 sample_rate: u32,
74 freq_control_supported: bool,
75}
76
77impl AltCandidate {
78 const fn new(streaming_interface: u8, alt_setting: u8) -> Self {
79 Self {
80 streaming_interface,
81 alt_setting,
82 iso_out_ep: 0,
83 max_packet_size: 0,
84 format_tag: PCM_FORMAT_TAG,
85 channels: 2,
86 subframe_size: 2,
87 bit_resolution: 16,
88 sample_rate: 48_000,
89 freq_control_supported: false,
90 }
91 }
92
93 fn is_valid_pcm16_out(&self) -> bool {
94 self.alt_setting > 0
95 && self.iso_out_ep != 0
96 && self.max_packet_size >= 4
97 && self.format_tag == PCM_FORMAT_TAG
98 && self.subframe_size == 2
99 && self.channels >= 1
100 }
101
102 fn score(&self) -> u32 {
104 if !self.is_valid_pcm16_out() {
105 return 0;
106 }
107 let ch_score = match self.channels {
108 2 => 300,
109 1 => 200,
110 _ => 100,
111 };
112 let rate_score = match self.sample_rate {
113 48_000 => 50,
114 44_100 => 40,
115 _ => 20,
116 };
117 let bit_score = if self.bit_resolution == 16 { 10 } else { 5 };
118 ch_score + rate_score + bit_score
119 }
120}
121
122#[inline]
124pub fn decode_sample_rate_24le(b0: u8, b1: u8, b2: u8) -> u32 {
125 (b0 as u32) | ((b1 as u32) << 8) | ((b2 as u32) << 16)
126}
127
128#[inline]
130pub fn encode_sample_rate_24le(rate: u32) -> [u8; 3] {
131 [
132 (rate & 0xFF) as u8,
133 ((rate >> 8) & 0xFF) as u8,
134 ((rate >> 16) & 0xFF) as u8,
135 ]
136}
137
138fn choose_discrete_rate(rates_bytes: &[u8], count: usize) -> u32 {
140 let mut best = 0u32;
141 for idx in 0..count {
142 let off = idx * 3;
143 if off + 3 > rates_bytes.len() {
144 break;
145 }
146 let r = decode_sample_rate_24le(rates_bytes[off], rates_bytes[off + 1], rates_bytes[off + 2]);
147 if r == 0 {
148 continue;
149 }
150 if r == 48_000 {
151 return 48_000;
152 }
153 if r == 44_100 && best != 48_000 {
154 best = 44_100;
155 } else if best == 0 {
156 best = r;
157 }
158 }
159 if best == 0 { 48_000 } else { best }
160}
161
162pub fn parse_uac1_config(desc: &[u8]) -> Option<UacStreamConfig> {
164 let mut control_if: Option<u8> = None;
165 let mut in_streaming_if = false;
166 let mut current: Option<AltCandidate> = None;
167 let mut best: Option<AltCandidate> = None;
168
169 let commit_candidate = |cand: Option<AltCandidate>, best_slot: &mut Option<AltCandidate>| {
170 if let Some(c) = cand {
171 let s = c.score();
172 if s > 0 {
173 let replace = match best_slot {
174 Some(prev) => s > prev.score(),
175 None => true,
176 };
177 if replace {
178 *best_slot = Some(c);
179 }
180 }
181 }
182 };
183
184 let mut i = 0usize;
185 while i + 2 <= desc.len() {
186 let len = desc[i] as usize;
187 if len < 2 || i + len > desc.len() {
188 break;
189 }
190 let dtype = desc[i + 1];
191
192 match dtype {
193 0x04 if len >= 9 => {
194 commit_candidate(current.take(), &mut best);
196 let if_num = desc[i + 2];
197 let alt = desc[i + 3];
198 let if_class = desc[i + 5];
199 let if_subclass = desc[i + 6];
200
201 if if_class == USB_CLASS_AUDIO && if_subclass == AUDIO_SUBCLASS_CONTROL {
202 if control_if.is_none() {
203 control_if = Some(if_num);
204 }
205 in_streaming_if = false;
206 } else if if_class == USB_CLASS_AUDIO && if_subclass == AUDIO_SUBCLASS_STREAMING {
207 in_streaming_if = true;
208 current = Some(AltCandidate::new(if_num, alt));
209 } else {
210 in_streaming_if = false;
211 }
212 }
213 CS_INTERFACE if in_streaming_if && len >= 3 => {
214 let subtype = desc[i + 2];
215 if let Some(ref mut cand) = current {
216 if subtype == AS_GENERAL && len >= 7 {
217 cand.format_tag = u16::from_le_bytes([desc[i + 5], desc[i + 6]]);
218 } else if subtype == FORMAT_TYPE && len >= 8 && desc[i + 3] == FORMAT_TYPE_I {
219 cand.channels = desc[i + 4];
220 cand.subframe_size = desc[i + 5];
221 cand.bit_resolution = desc[i + 6];
222 let sam_freq_type = desc[i + 7] as usize;
223 if sam_freq_type == 0 && len >= 14 {
224 let lower = decode_sample_rate_24le(desc[i + 8], desc[i + 9], desc[i + 10]);
226 let upper = decode_sample_rate_24le(desc[i + 11], desc[i + 12], desc[i + 13]);
227 if lower > 0 && upper >= lower {
228 cand.sample_rate = 48_000u32.clamp(lower, upper);
229 }
230 } else if sam_freq_type > 0 && len >= 8 + 3 {
231 cand.sample_rate = choose_discrete_rate(&desc[i + 8..i + len], sam_freq_type);
232 }
233 }
234 }
235 }
236 0x05 if in_streaming_if && len >= 7 => {
237 let ep_addr = desc[i + 2];
239 let ep_attr = desc[i + 3];
240 let raw_mps = u16::from_le_bytes([desc[i + 4], desc[i + 5]]) & 0x07FF;
241 let is_out = (ep_addr & 0x80) == 0;
242 let is_iso = (ep_attr & 0x03) == 0x01;
243 if is_out && is_iso && (ep_addr & 0x0F) != 0 {
244 if let Some(ref mut cand) = current {
245 cand.iso_out_ep = ep_addr & 0x0F;
246 cand.max_packet_size = raw_mps;
247 }
248 }
249 }
250 CS_ENDPOINT if in_streaming_if && len >= 4 => {
251 let bm_attributes = desc[i + 3];
253 if let Some(ref mut cand) = current {
254 cand.freq_control_supported = (bm_attributes & 0x01) != 0;
255 }
256 }
257 _ => {}
258 }
259
260 i += len;
261 }
262
263 commit_candidate(current.take(), &mut best);
264
265 let chosen = best?;
266 Some(UacStreamConfig {
267 control_interface: control_if.unwrap_or(0),
268 streaming_interface: chosen.streaming_interface,
269 alt_setting: chosen.alt_setting,
270 iso_out_ep: chosen.iso_out_ep,
271 max_packet_size: chosen.max_packet_size,
272 channels: chosen.channels,
273 subframe_size: chosen.subframe_size,
274 bit_resolution: chosen.bit_resolution,
275 sample_rate: chosen.sample_rate,
276 freq_control_supported: chosen.freq_control_supported,
277 })
278}
279
280#[inline]
285pub fn src_frames_for_1ms(src_rate: u32, rem: u32) -> (usize, u32) {
286 if src_rate == 0 {
287 return (0, 0);
288 }
289 let total = src_rate + (rem % 1000);
290 ((total / 1000) as usize, total % 1000)
291}
292
293#[inline]
295pub fn dst_frames_for_1ms(dst_rate: u32, dst_channels: u8, max_packet_size: u16) -> usize {
296 if dst_rate == 0 || dst_channels == 0 {
297 return 0;
298 }
299 let frame_bytes = (dst_channels as usize) * 2;
300 let max_frames = (max_packet_size as usize) / frame_bytes;
301 let nominal = ((dst_rate + 500) / 1000) as usize;
302 nominal.min(max_frames)
303}
304
305pub fn resample_to_uac_packet(
309 src_interleaved: &[i16],
310 src_channels: u8,
311 dst_frames: usize,
312 dst_channels: u8,
313 out_bytes: &mut [u8],
314) -> usize {
315 let dst_ch = (dst_channels as usize).max(1);
316 let frame_bytes = dst_ch * 2;
317 let frames = dst_frames.min(out_bytes.len() / frame_bytes);
318 if frames == 0 {
319 return 0;
320 }
321
322 let src_ch = (src_channels as usize).clamp(1, 2);
323 let src_frames = src_interleaved.len() / src_ch;
324 if src_frames == 0 {
325 let total_bytes = frames * frame_bytes;
326 out_bytes[..total_bytes].fill(0);
327 return total_bytes;
328 }
329
330 let sample_pair = |f: usize| -> (i32, i32) {
331 let idx = f.min(src_frames - 1) * src_ch;
332 let l = src_interleaved[idx] as i32;
333 let r = if src_ch >= 2 {
334 src_interleaved[idx + 1] as i32
335 } else {
336 l
337 };
338 (l, r)
339 };
340
341 for d in 0..frames {
342 let (l, r) = if src_frames == frames {
343 sample_pair(d)
344 } else if frames <= 1 || src_frames == 1 {
345 sample_pair(0)
346 } else {
347 let pos_q16 = (((d as u64) * ((src_frames - 1) as u64)) << 16) / ((frames - 1) as u64);
349 let idx0 = (pos_q16 >> 16) as usize;
350 let frac = (pos_q16 & 0xFFFF) as i32;
351 let (l0, r0) = sample_pair(idx0);
352 let (l1, r1) = sample_pair(idx0 + 1);
353 let l = l0 + (((l1 - l0) * frac) >> 16);
354 let r = r0 + (((r1 - r0) * frac) >> 16);
355 (l, r)
356 };
357
358 let l_bytes = (l.clamp(-32768, 32767) as i16).to_le_bytes();
359 let r_bytes = (r.clamp(-32768, 32767) as i16).to_le_bytes();
360 let base = d * frame_bytes;
361 out_bytes[base] = l_bytes[0];
362 out_bytes[base + 1] = l_bytes[1];
363 if dst_ch >= 2 {
364 out_bytes[base + 2] = r_bytes[0];
365 out_bytes[base + 3] = r_bytes[1];
366 for extra_ch in 2..dst_ch {
367 out_bytes[base + extra_ch * 2] = 0;
368 out_bytes[base + extra_ch * 2 + 1] = 0;
369 }
370 }
371 }
372
373 frames * frame_bytes
374}
375
376pub fn synthesize_tone_uac_packet(
379 freq_hz: u32,
380 sample_rate: u32,
381 dst_frames: usize,
382 dst_channels: u8,
383 phase: &mut u32,
384 out_bytes: &mut [u8],
385) -> usize {
386 let dst_ch = (dst_channels as usize).max(1);
387 let frame_bytes = dst_ch * 2;
388 let frames = dst_frames.min(out_bytes.len() / frame_bytes);
389 if frames == 0 {
390 return 0;
391 }
392 if freq_hz == 0 || sample_rate == 0 {
393 let total = frames * frame_bytes;
394 out_bytes[..total].fill(0);
395 return total;
396 }
397
398 const AMPLITUDE: i16 = 5000;
399 let half_rate = sample_rate / 2;
400 let step = freq_hz % sample_rate;
401 let mut p = *phase % sample_rate;
402
403 for d in 0..frames {
404 let sample: i16 = if p < half_rate { AMPLITUDE } else { -AMPLITUDE };
405 p += step;
406 if p >= sample_rate {
407 p -= sample_rate;
408 }
409 let s_bytes = sample.to_le_bytes();
410 let base = d * frame_bytes;
411 for ch in 0..dst_ch.min(2) {
412 out_bytes[base + ch * 2] = s_bytes[0];
413 out_bytes[base + ch * 2 + 1] = s_bytes[1];
414 }
415 for extra_ch in 2..dst_ch {
416 out_bytes[base + extra_ch * 2] = 0;
417 out_bytes[base + extra_ch * 2 + 1] = 0;
418 }
419 }
420
421 *phase = p;
422 frames * frame_bytes
423}