usbdac-core 0.1.6

Direct USB DAC playback for Rust audio applications on Android and Linux, with PCM, DoP, native DSD and bit-perfect reporting.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use super::constants::*;
use super::helpers::{read_u16_le, read_u32_le, require_len};
use super::parser_trait::DescriptorParser;
use super::types::*;
use super::validation::{
    validate_ac_interface_header, validate_feature_unit, validate_input_terminal,
    validate_output_terminal,
};
use crate::descriptors::error::DescriptorError;

pub struct AudioControlParser;

impl AudioControlParser {
    pub fn parse_ac_header(&self, data: &[u8]) -> Result<AcInterfaceHeader, DescriptorError> {
        const HEADER_LEN: usize = 9;
        require_len(data, HEADER_LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC2_AC_HEADER {
            return Err(DescriptorError::Invalid("not CS_AC header".to_string()));
        }
        let h = AcInterfaceHeader {
            bcd_adc: read_u16_le(data, 3),
            b_category: data[5],
            w_total_length: read_u16_le(data, 6),
            bm_controls: data[8] as u16,
        };
        validate_ac_interface_header(&h)?;
        Ok(h)
    }

    pub fn parse_ac_header_v1(&self, data: &[u8]) -> Result<AcInterfaceHeaderV1, DescriptorError> {
        require_len(data, 8)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC_AC_HEADER {
            return Err(DescriptorError::Invalid(
                "not UAC1 AC header".to_string(),
            ));
        }
        let bcd_adc = read_u16_le(data, 3);
        let w_total_length = read_u16_le(data, 5);
        let b_in_collection = data[7];
        let len = data[0] as usize;
        if len != 8 + b_in_collection as usize {
            return Err(DescriptorError::Invalid(
                "UAC1 AC interface collection length mismatch".to_string(),
            ));
        }
        require_len(data, len)?;
        let ba_interface_nr: Vec<u8> = data[8..len].to_vec();
        Ok(AcInterfaceHeaderV1 {
            bcd_adc,
            w_total_length,
            b_in_collection,
            ba_interface_nr,
        })
    }

    fn detect_and_parse_ac_header(&self, data: &[u8]) -> Result<AudioControlDescriptor, DescriptorError> {
        require_len(data, 5)?;
        match read_u16_le(data, 3) {
            UAC1_BCD_ADC => self.parse_ac_header_v1(data).map(AudioControlDescriptor::HeaderV1),
            UAC2_BCD_ADC => self.parse_ac_header(data).map(AudioControlDescriptor::HeaderV2),
            version => Err(DescriptorError::Invalid(format!(
                "unsupported AudioControl version 0x{version:04x}"
            ))),
        }
    }

    pub fn parse_input_terminal(&self, data: &[u8]) -> Result<InputTerminal, DescriptorError> {
        const LEN: usize = 17;
        require_len(data, LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC2_INPUT_TERMINAL {
            return Err(DescriptorError::Invalid(
                "not input terminal".to_string(),
            ));
        }
        let t = InputTerminal {
            b_terminal_id: data[3],
            w_terminal_type: read_u16_le(data, 4),
            b_assoc_terminal: data[6],
            b_c_source_id: data[7],
            b_nr_channels: data[8] as u16,
            w_channel_config: read_u32_le(data, 9),
            i_terminal: data[16],
        };
        validate_input_terminal(&t)?;
        Ok(t)
    }

    pub fn parse_output_terminal(&self, data: &[u8]) -> Result<OutputTerminal, DescriptorError> {
        const LEN: usize = 12;
        require_len(data, LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC2_OUTPUT_TERMINAL {
            return Err(DescriptorError::Invalid(
                "not output terminal".to_string(),
            ));
        }
        let t = OutputTerminal {
            b_terminal_id: data[3],
            w_terminal_type: read_u16_le(data, 4),
            b_assoc_terminal: data[6],
            b_source_id: data[7],
            i_terminal: data[11],
        };
        validate_output_terminal(&t)?;
        Ok(t)
    }

    pub fn parse_feature_unit(&self, data: &[u8]) -> Result<FeatureUnit, DescriptorError> {
        const MIN_LEN: usize = 10;
        require_len(data, MIN_LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC2_FEATURE_UNIT {
            return Err(DescriptorError::Invalid("not feature unit".to_string()));
        }
        let len = data[0] as usize;
        if len < MIN_LEN || (len - 6) % 4 != 0 {
            return Err(DescriptorError::Invalid(
                "invalid feature unit length".to_string(),
            ));
        }
        let n = (len - 6) / 4;
        require_len(data, len)?;
        let bma_controls: Vec<u32> = (0..n).map(|i| read_u32_le(data, 5 + i * 4)).collect();
        let f = FeatureUnit {
            b_unit_id: data[3],
            b_source_id: data[4],
            // UAC2 has fixed 32-bit controls and no bControlSize byte.
            b_control_size: 4,
            bma_controls,
        };
        validate_feature_unit(&f)?;
        Ok(f)
    }

    pub fn parse_input_terminal_v1(&self, data: &[u8]) -> Result<InputTerminal, DescriptorError> {
        require_len(data, 12)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC_INPUT_TERMINAL {
            return Err(DescriptorError::Invalid("not UAC1 input terminal".to_string()));
        }
        let terminal = InputTerminal {
            b_terminal_id: data[3],
            w_terminal_type: read_u16_le(data, 4),
            b_assoc_terminal: data[6],
            b_c_source_id: 0,
            b_nr_channels: data[7] as u16,
            w_channel_config: read_u16_le(data, 8) as u32,
            i_terminal: data[11],
        };
        validate_input_terminal(&terminal)?;
        Ok(terminal)
    }

    pub fn parse_output_terminal_v1(&self, data: &[u8]) -> Result<OutputTerminal, DescriptorError> {
        require_len(data, 9)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC_OUTPUT_TERMINAL {
            return Err(DescriptorError::Invalid("not UAC1 output terminal".to_string()));
        }
        let terminal = OutputTerminal {
            b_terminal_id: data[3],
            w_terminal_type: read_u16_le(data, 4),
            b_assoc_terminal: data[6],
            b_source_id: data[7],
            i_terminal: data[8],
        };
        validate_output_terminal(&terminal)?;
        Ok(terminal)
    }

    pub fn parse_feature_unit_v1(&self, data: &[u8]) -> Result<FeatureUnit, DescriptorError> {
        require_len(data, 7)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC_FEATURE_UNIT {
            return Err(DescriptorError::Invalid("not UAC1 feature unit".to_string()));
        }
        let len = data[0] as usize;
        let size = data[5] as usize;
        if !(1..=4).contains(&size) || len < 7 + size || (len - 7) % size != 0 {
            return Err(DescriptorError::Invalid("invalid UAC1 feature unit length".to_string()));
        }
        require_len(data, len)?;
        let bma_controls = data[6..len - 1].chunks_exact(size).map(|bytes| {
            let mut word = [0u8; 4];
            word[..size].copy_from_slice(bytes);
            u32::from_le_bytes(word)
        }).collect();
        let unit = FeatureUnit {
            b_unit_id: data[3],
            b_source_id: data[4],
            b_control_size: size as u8,
            bma_controls,
        };
        validate_feature_unit(&unit)?;
        Ok(unit)
    }

    pub fn parse_clock_source(&self, data: &[u8]) -> Result<ClockSource, DescriptorError> {
        const LEN: usize = 8;
        require_len(data, LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC2_CLOCK_SOURCE {
            return Err(DescriptorError::Invalid("not clock source".to_string()));
        }
        Ok(ClockSource {
            b_clock_id: data[3],
            bm_attributes: data[4],
            bm_controls: data[5],
            b_assoc_terminal: data[6],
            i_clock_source: data[7],
        })
    }

    pub fn parse_clock_selector(&self, data: &[u8]) -> Result<ClockSelector, DescriptorError> {
        const MIN_LEN: usize = 7;
        require_len(data, MIN_LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC2_CLOCK_SELECTOR {
            return Err(DescriptorError::Invalid(
                "not clock selector".to_string(),
            ));
        }
        let len = data[0] as usize;
        require_len(data, len)?;
        let b_nr_in_pins = data[4];
        let expected_len = 7 + b_nr_in_pins as usize;
        if len < expected_len {
            return Err(DescriptorError::Invalid(
                "clock selector length mismatch".to_string(),
            ));
        }
        let ba_c_source_id: Vec<u8> = data[5..5 + b_nr_in_pins as usize].to_vec();
        let bm_controls_offset = 5 + b_nr_in_pins as usize;
        let bm_controls = data.get(bm_controls_offset).copied().unwrap_or(0);
        let i_clock_selector = data.get(bm_controls_offset + 1).copied().unwrap_or(0);
        Ok(ClockSelector {
            b_clock_id: data[3],
            b_nr_in_pins,
            ba_c_source_id,
            bm_controls,
            i_clock_selector,
        })
    }

    pub fn parse_clock_multiplier(&self, data: &[u8]) -> Result<ClockMultiplier, DescriptorError> {
        const LEN: usize = 7;
        require_len(data, LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC2_CLOCK_MULTIPLIER {
            return Err(DescriptorError::Invalid(
                "not clock multiplier".to_string(),
            ));
        }
        Ok(ClockMultiplier {
            b_clock_id: data[3],
            b_c_source_id: data[4],
            bm_controls: data[5],
            i_clock_multiplier: data[6],
        })
    }

    pub fn parse_mixer_unit(&self, data: &[u8]) -> Result<MixerUnit, DescriptorError> {
        const MIN_LEN: usize = 10;
        require_len(data, MIN_LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC_MIXER_UNIT {
            return Err(DescriptorError::Invalid("not mixer unit".to_string()));
        }
        let len = data[0] as usize;
        require_len(data, len)?;
        let b_nr_in_pins = data[5];
        // For UAC1: fixed length; we'll be lenient
        let ba_source_id: Vec<u8> = data[6..6 + b_nr_in_pins as usize].to_vec();
        let channels_offset = 6 + b_nr_in_pins as usize;
        let b_nr_channels = if channels_offset + 1 < len {
            read_u16_le(data, channels_offset)
        } else {
            2
        };
        let w_channel_config = if channels_offset + 3 < len {
            read_u32_le(data, channels_offset + 2)
        } else {
            0
        };
        let i_mixer_offset = channels_offset + 6;
        let i_mixer = data.get(i_mixer_offset).copied().unwrap_or(0);
        let bm_controls: Vec<u8> = data[i_mixer_offset + 1..len].to_vec();
        Ok(MixerUnit {
            b_unit_id: data[3],
            b_nr_in_pins,
            ba_source_id,
            b_nr_channels,
            w_channel_config,
            i_mixer,
            bm_controls,
        })
    }

    pub fn parse_selector_unit(&self, data: &[u8]) -> Result<SelectorUnit, DescriptorError> {
        const MIN_LEN: usize = 6;
        require_len(data, MIN_LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC_SELECTOR_UNIT {
            return Err(DescriptorError::Invalid(
                "not selector unit".to_string(),
            ));
        }
        let len = data[0] as usize;
        require_len(data, len)?;
        let b_nr_in_pins = data[5];
        let ba_source_id: Vec<u8> = data[6..6 + b_nr_in_pins as usize].to_vec();
        let i_sel_offset = 6 + b_nr_in_pins as usize;
        let i_selector = data.get(i_sel_offset).copied().unwrap_or(0);
        let bm_controls = data.get(i_sel_offset + 1).copied();
        Ok(SelectorUnit {
            b_unit_id: data[3],
            b_nr_in_pins,
            ba_source_id,
            i_selector,
            bm_controls,
        })
    }

    pub fn parse_effect_unit(&self, data: &[u8]) -> Result<EffectUnit, DescriptorError> {
        const LEN: usize = 8;
        require_len(data, LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC_EFFECT_UNIT {
            return Err(DescriptorError::Invalid("not effect unit".to_string()));
        }
        Ok(EffectUnit {
            b_unit_id: data[3],
            b_source_id: data[4],
            b_effect_id: read_u16_le(data, 5),
            i_effect: data[7],
        })
    }

    pub fn parse_processing_unit(&self, data: &[u8]) -> Result<ProcessingUnit, DescriptorError> {
        const MIN_LEN: usize = 10;
        require_len(data, MIN_LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC_PROCESSING_UNIT {
            return Err(DescriptorError::Invalid(
                "not processing unit".to_string(),
            ));
        }
        let len = data[0] as usize;
        require_len(data, len)?;
        let b_nr_channels = read_u16_le(data, 7);
        let w_channel_config = read_u32_le(data, 9);
        let i_processing = data.get(13).copied().unwrap_or(0);
        let bm_controls = data[14..len].to_vec();
        Ok(ProcessingUnit {
            b_unit_id: data[3],
            b_source_id: data[4],
            w_process_type: read_u16_le(data, 5),
            b_nr_channels,
            w_channel_config,
            i_processing,
            bm_controls,
        })
    }

    pub fn parse_extension_unit(&self, data: &[u8]) -> Result<ExtensionUnit, DescriptorError> {
        const MIN_LEN: usize = 13;
        require_len(data, MIN_LEN)?;
        if data[1] != USB_DT_CS_INTERFACE || data[2] != UAC_EXTENSION_UNIT {
            return Err(DescriptorError::Invalid(
                "not extension unit".to_string(),
            ));
        }
        let len = data[0] as usize;
        require_len(data, len)?;
        let b_nr_in_pins = data[7];
        let ba_source_id: Vec<u8> = data[8..8 + b_nr_in_pins as usize].to_vec();
        let ch_offset = 8 + b_nr_in_pins as usize;
        let b_nr_channels = read_u16_le(data, ch_offset);
        let w_channel_config = read_u32_le(data, ch_offset + 2);
        let i_extension = data.get(ch_offset + 6).copied().unwrap_or(0);
        let bm_controls = data[ch_offset + 7..len].to_vec();
        Ok(ExtensionUnit {
            b_unit_id: data[3],
            w_extension_code: read_u16_le(data, 5),
            b_nr_in_pins,
            ba_source_id,
            b_nr_channels,
            w_channel_config,
            i_extension,
            bm_controls,
        })
    }
}

impl DescriptorParser for AudioControlParser {
    type Output = AudioControlDescriptor;

    fn parse(&self, data: &[u8]) -> Result<Self::Output, DescriptorError> {
        if data.len() < 3 {
            return Err(DescriptorError::Invalid(
                "descriptor too short".to_string(),
            ));
        }
        if data[1] != USB_DT_CS_INTERFACE {
            return Err(DescriptorError::Invalid("not CS interface".to_string()));
        }
        match data[2] {
            UAC_AC_HEADER => self.detect_and_parse_ac_header(data),
            UAC_INPUT_TERMINAL => self
                .parse_input_terminal(data)
                .map(AudioControlDescriptor::InputTerminal),
            UAC_OUTPUT_TERMINAL => self
                .parse_output_terminal(data)
                .map(AudioControlDescriptor::OutputTerminal),
            UAC_FEATURE_UNIT => self
                .parse_feature_unit(data)
                .map(AudioControlDescriptor::FeatureUnit),
            UAC2_CLOCK_SOURCE => self
                .parse_clock_source(data)
                .map(AudioControlDescriptor::ClockSource),
            UAC2_CLOCK_SELECTOR => self
                .parse_clock_selector(data)
                .map(AudioControlDescriptor::ClockSelector),
            UAC2_CLOCK_MULTIPLIER => self
                .parse_clock_multiplier(data)
                .map(AudioControlDescriptor::ClockMultiplier),
            UAC_MIXER_UNIT => self
                .parse_mixer_unit(data)
                .map(AudioControlDescriptor::MixerUnit),
            UAC_SELECTOR_UNIT => self
                .parse_selector_unit(data)
                .map(AudioControlDescriptor::SelectorUnit),
            UAC_EFFECT_UNIT => self
                .parse_effect_unit(data)
                .map(AudioControlDescriptor::EffectUnit),
            UAC_PROCESSING_UNIT => self
                .parse_processing_unit(data)
                .map(AudioControlDescriptor::ProcessingUnit),
            UAC_EXTENSION_UNIT => self
                .parse_extension_unit(data)
                .map(AudioControlDescriptor::ExtensionUnit),
            _ => Err(DescriptorError::Invalid(format!(
                "unknown AC descriptor subtype {}",
                data[2]
            ))),
        }
    }
}