usb-gadget 1.2.0

Expose standard or fully custom USB peripherals (gadgets) through a USB device controller (UDC) on Linux.
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
//! USB Audio Class 1 (UAC1) and 2 (UAC2) functions.
//!
//! The Linux kernel configuration option `CONFIG_USB_CONFIGFS_F_UAC1` must be enabled for UAC1
//! and `CONFIG_USB_CONFIGFS_F_UAC2` must be enabled for UAC2.
//!
//! # UAC1 Example
//!
//! ```no_run
//! use usb_gadget::{
//!     default_udc,
//!     function::audio::{Channel, Uac1},
//!     Class, Config, Gadget, Id, Strings,
//! };
//!
//! // capture: stereo, 48000 Hz, 16 bit, playback: stereo, 48000 Hz, 16 bit
//! let (audio, func) = Uac1::new(Channel::new(0b11, 48000, 2), Channel::new(0b11, 48000, 2));
//!
//! let udc = default_udc().expect("cannot get UDC");
//! let reg = Gadget::new(
//!     Class::INTERFACE_SPECIFIC,
//!     Id::LINUX_FOUNDATION_COMPOSITE,
//!     Strings::new("Clippy Manufacturer", "Rust UAC1", "RUST0123456"),
//! )
//! .with_config(Config::new("Audio Config 1").with_function(func))
//! .bind(&udc)
//! .expect("cannot bind to UDC");
//!
//! println!(
//!     "UAC1 audio {} at {} to {} status {:?}",
//!     reg.name().to_string_lossy(),
//!     reg.path().display(),
//!     udc.name().to_string_lossy(),
//!     audio.status()
//! );
//! ```
//!
//! # UAC2 Example
//!
//! ```no_run
//! use usb_gadget::{
//!     default_udc,
//!     function::audio::{Channel, Uac2},
//!     Class, Config, Gadget, Id, Strings,
//! };
//!
//! // capture: 8 ch, 48000 Hz, 24 bit, playback: 2 ch, 48000 Hz, 16 bit
//! let (audio, func) =
//!     Uac2::new(Channel::new(0b1111_1111, 48000, 24 / 8), Channel::new(0b11, 48000, 16 / 8));
//!
//! let udc = default_udc().expect("cannot get UDC");
//! let reg = Gadget::new(
//!     Class::INTERFACE_SPECIFIC,
//!     Id::LINUX_FOUNDATION_COMPOSITE,
//!     Strings::new("Clippy Manufacturer", "Rust UAC2", "RUST0123456"),
//! )
//! .with_config(Config::new("Audio Config 1").with_function(func))
//! .bind(&udc)
//! .expect("cannot bind to UDC");
//!
//! println!(
//!     "UAC2 audio {} at {} to {} status {:?}",
//!     reg.name().to_string_lossy(),
//!     reg.path().display(),
//!     udc.name().to_string_lossy(),
//!     audio.status()
//! );
//! ```

use std::{ffi::OsString, io::Result};

use super::{
    util::{FunctionDir, Status},
    Function, Handle,
};

/// Audio channel configuration.
#[derive(Debug, Clone, Default)]
pub struct Channel {
    /// Audio channel mask. Set to 0 to disable the audio endpoint.
    ///
    /// The audio channel mask is a bit mask of the audio channels. The mask is a 32-bit integer
    /// with each bit representing a channel. The least significant bit is channel 1. The mask is
    /// used to specify the audio channels that are present in the audio stream. For example, a
    /// stereo stream would have a mask of 0x3 (channel 1 and channel 2).
    pub channel_mask: Option<u32>,
    /// Audio sample rate (Hz)
    pub sample_rate: Option<u32>,
    /// Audio sample size (bytes) so 2 bytes per sample (16 bit) would be 2.
    pub sample_size: Option<u32>,
}

impl Channel {
    /// Creates a new audio channel with the specified channel mask, sample rate (Hz), and sample
    /// size (bytes).
    pub fn new(channel_mask: u32, sample_rate: u32, sample_size: u32) -> Self {
        Self { channel_mask: Some(channel_mask), sample_rate: Some(sample_rate), sample_size: Some(sample_size) }
    }
}

/// Audio device configuration.
///
/// Fields are optional and will be set to f_uac2 default values if not specified, see
/// drivers/usb/gadget/function/u_uac2.h. Not all fields are supported by all kernels; permission
/// denied errors may occur if unsupported fields are set.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Uac2Config {
    /// Audio channel configuration.
    pub channel: Channel,
    /// Audio sync type (capture only)
    pub sync_type: Option<u32>,
    /// Capture bInterval for HS/SS (1-4: fixed, 0: auto)
    pub hs_interval: Option<u8>,
    /// If channel has mute
    pub mute_present: Option<bool>,
    /// Terminal type
    pub terminal_type: Option<u8>,
    /// If channel has volume
    pub volume_present: Option<bool>,
    /// Minimum volume (in 1/256 dB)
    pub volume_min: Option<i16>,
    /// Maximum volume (in 1/256 dB)
    pub volume_max: Option<i16>,
    /// Resolution of volume control (in 1/256 dB)
    pub volume_resolution: Option<i16>,
    /// Name of the volume control function
    pub volume_name: Option<String>,
    /// Name of the input terminal
    pub input_terminal_name: Option<String>,
    /// Name of the input terminal channel
    pub input_terminal_channel_name: Option<String>,
    /// Name of the output terminal
    pub output_terminal_name: Option<String>,
}

/// Builder for USB audio class 2 (UAC2) function.
///
/// Set capture or playback channel_mask to 0 to disable the audio endpoint.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Uac2Builder {
    /// Audio capture configuration.
    pub capture: Uac2Config,
    /// Audio playback configuration.
    pub playback: Uac2Config,
    /// Maximum extra bandwidth in async mode
    pub fb_max: Option<u32>,
    /// The number of pre-allocated request for both capture and playback
    pub request_number: Option<u32>,
    /// The name of the interface
    pub function_name: Option<String>,
    /// Topology control name
    pub control_name: Option<String>,
    /// The name of the input clock source
    pub clock_source_in_name: Option<String>,
    /// The name of the output clock source
    pub clock_source_out_name: Option<String>,
}

impl Uac2Builder {
    /// Build the USB function.
    ///
    /// The returned handle must be added to a USB gadget configuration.
    #[must_use]
    pub fn build(self) -> (Uac2, Handle) {
        let dir = FunctionDir::new();
        (Uac2 { dir: dir.clone() }, Handle::new(Uac2Function { builder: self, dir }))
    }

    /// Set audio capture configuration.
    #[must_use]
    pub fn with_capture_config(mut self, capture: Uac2Config) -> Self {
        self.capture = capture;
        self
    }

    /// Set audio playback configuration.
    #[must_use]
    pub fn with_playback_config(mut self, playback: Uac2Config) -> Self {
        self.playback = playback;
        self
    }
}

#[derive(Debug)]
struct Uac2Function {
    builder: Uac2Builder,
    dir: FunctionDir,
}

impl Function for Uac2Function {
    fn driver(&self) -> OsString {
        "uac2".into()
    }

    fn dir(&self) -> FunctionDir {
        self.dir.clone()
    }

    fn register(&self) -> Result<()> {
        // capture
        if let Some(channel_mask) = self.builder.capture.channel.channel_mask {
            self.dir.write("c_chmask", channel_mask.to_string())?;
        }
        if let Some(sample_rate) = self.builder.capture.channel.sample_rate {
            self.dir.write("c_srate", sample_rate.to_string())?;
        }
        if let Some(sample_size) = self.builder.capture.channel.sample_size {
            self.dir.write("c_ssize", sample_size.to_string())?;
        }
        if let Some(sync_type) = self.builder.capture.sync_type {
            self.dir.write("c_sync", sync_type.to_string())?;
        }
        if let Some(hs_interval) = self.builder.capture.hs_interval {
            self.dir.write("c_hs_bint", hs_interval.to_string())?;
        }
        if let Some(mute_present) = self.builder.capture.mute_present {
            self.dir.write("c_mute_present", (mute_present as u8).to_string())?;
        }
        if let Some(volume_present) = self.builder.capture.volume_present {
            self.dir.write("c_volume_present", (volume_present as u8).to_string())?;
        }
        if let Some(volume_min) = self.builder.capture.volume_min {
            self.dir.write("c_volume_min", volume_min.to_string())?;
        }
        if let Some(volume_max) = self.builder.capture.volume_max {
            self.dir.write("c_volume_max", volume_max.to_string())?;
        }
        if let Some(volume_resolution) = self.builder.capture.volume_resolution {
            self.dir.write("c_volume_res", volume_resolution.to_string())?;
        }
        if let Some(volume_name) = &self.builder.capture.volume_name {
            self.dir.write("c_fu_vol_name", volume_name)?;
        }
        if let Some(terminal_type) = self.builder.capture.terminal_type {
            self.dir.write("c_terminal_type", terminal_type.to_string())?;
        }
        if let Some(input_terminal_name) = &self.builder.capture.input_terminal_name {
            self.dir.write("c_it_name", input_terminal_name)?;
        }
        if let Some(input_terminal_channel_name) = &self.builder.capture.input_terminal_channel_name {
            self.dir.write("c_it_ch_name", input_terminal_channel_name)?;
        }
        if let Some(output_terminal_name) = &self.builder.capture.output_terminal_name {
            self.dir.write("c_ot_name", output_terminal_name)?;
        }

        // playback
        if let Some(channel_mask) = self.builder.playback.channel.channel_mask {
            self.dir.write("p_chmask", channel_mask.to_string())?;
        }
        if let Some(sample_rate) = self.builder.playback.channel.sample_rate {
            self.dir.write("p_srate", sample_rate.to_string())?;
        }
        if let Some(sample_size) = self.builder.playback.channel.sample_size {
            self.dir.write("p_ssize", sample_size.to_string())?;
        }
        if let Some(hs_interval) = self.builder.playback.hs_interval {
            self.dir.write("p_hs_bint", hs_interval.to_string())?;
        }
        if let Some(mute_present) = self.builder.playback.mute_present {
            self.dir.write("p_mute_present", (mute_present as u8).to_string())?;
        }
        if let Some(volume_present) = self.builder.playback.volume_present {
            self.dir.write("p_volume_present", (volume_present as u8).to_string())?;
        }
        if let Some(volume_min) = self.builder.playback.volume_min {
            self.dir.write("p_volume_min", volume_min.to_string())?;
        }
        if let Some(volume_max) = self.builder.playback.volume_max {
            self.dir.write("p_volume_max", volume_max.to_string())?;
        }
        if let Some(volume_resolution) = self.builder.playback.volume_resolution {
            self.dir.write("p_volume_res", volume_resolution.to_string())?;
        }
        if let Some(volume_name) = &self.builder.playback.volume_name {
            self.dir.write("p_fu_vol_name", volume_name)?;
        }
        if let Some(terminal_type) = self.builder.playback.terminal_type {
            self.dir.write("p_terminal_type", terminal_type.to_string())?;
        }
        if let Some(input_terminal_name) = &self.builder.playback.input_terminal_name {
            self.dir.write("p_it_name", input_terminal_name)?;
        }
        if let Some(input_terminal_channel_name) = &self.builder.playback.input_terminal_channel_name {
            self.dir.write("p_it_ch_name", input_terminal_channel_name)?;
        }
        if let Some(output_terminal_name) = &self.builder.playback.output_terminal_name {
            self.dir.write("p_ot_name", output_terminal_name)?;
        }

        // general
        if let Some(fb_max) = self.builder.fb_max {
            self.dir.write("fb_max", fb_max.to_string())?;
        }
        if let Some(request_number) = self.builder.request_number {
            self.dir.write("req_number", request_number.to_string())?;
        }
        if let Some(function_name) = &self.builder.function_name {
            self.dir.write("function_name", function_name)?;
        }
        if let Some(control_name) = &self.builder.control_name {
            self.dir.write("if_ctrl_name", control_name)?;
        }
        if let Some(clock_source_in_name) = &self.builder.clock_source_in_name {
            self.dir.write("clksrc_in_name", clock_source_in_name)?;
        }
        if let Some(clock_source_out_name) = &self.builder.clock_source_out_name {
            self.dir.write("clksrc_out_name", clock_source_out_name)?;
        }

        Ok(())
    }
}

/// USB Audio Class 2 (UAC2) function.
#[derive(Debug)]
pub struct Uac2 {
    dir: FunctionDir,
}

impl Uac2 {
    /// Creates a new USB Audio Class 2 (UAC2) builder with g_uac2 audio defaults.
    pub fn builder() -> Uac2Builder {
        Uac2Builder::default()
    }

    /// Creates a new USB Audio Class 2 (UAC2) function with the specified capture and playback
    /// channels.
    pub fn new(capture: Channel, playback: Channel) -> (Uac2, Handle) {
        let mut builder = Uac2Builder::default();
        builder.capture.channel = capture;
        builder.playback.channel = playback;
        builder.build()
    }

    /// Access to registration status.
    pub fn status(&self) -> Status {
        self.dir.status()
    }
}

/// Audio device configuration for UAC1.
///
/// Fields are optional and will be set to f_uac1 default values if not specified, see
/// `drivers/usb/gadget/function/u_uac1.h`. Not all fields are supported by all kernels; permission
/// denied errors may occur if unsupported fields are set.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Uac1Config {
    /// Audio channel configuration.
    pub channel: Channel,
    /// If channel has mute
    pub mute_present: Option<bool>,
    /// If channel has volume
    pub volume_present: Option<bool>,
    /// Minimum volume (in 1/256 dB)
    pub volume_min: Option<i16>,
    /// Maximum volume (in 1/256 dB)
    pub volume_max: Option<i16>,
    /// Resolution of volume control (in 1/256 dB)
    pub volume_resolution: Option<i16>,
    /// Name of the volume control function
    pub volume_name: Option<String>,
    /// Name of the input terminal
    pub input_terminal_name: Option<String>,
    /// Name of the input terminal channel
    pub input_terminal_channel_name: Option<String>,
    /// Name of the output terminal
    pub output_terminal_name: Option<String>,
}

/// Builder for USB audio class 1 (UAC1) function.
///
/// Set capture or playback channel_mask to 0 to disable the audio endpoint.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Uac1Builder {
    /// Audio capture configuration.
    pub capture: Uac1Config,
    /// Audio playback configuration.
    pub playback: Uac1Config,
    /// The number of pre-allocated requests for both capture and playback
    pub request_number: Option<u32>,
    /// The name of the interface
    pub function_name: Option<String>,
}

impl Uac1Builder {
    /// Build the USB function.
    ///
    /// The returned handle must be added to a USB gadget configuration.
    #[must_use]
    pub fn build(self) -> (Uac1, Handle) {
        let dir = FunctionDir::new();
        (Uac1 { dir: dir.clone() }, Handle::new(Uac1Function { builder: self, dir }))
    }

    /// Set audio capture configuration.
    #[must_use]
    pub fn with_capture_config(mut self, capture: Uac1Config) -> Self {
        self.capture = capture;
        self
    }

    /// Set audio playback configuration.
    #[must_use]
    pub fn with_playback_config(mut self, playback: Uac1Config) -> Self {
        self.playback = playback;
        self
    }
}

#[derive(Debug)]
struct Uac1Function {
    builder: Uac1Builder,
    dir: FunctionDir,
}

impl Function for Uac1Function {
    fn driver(&self) -> OsString {
        "uac1".into()
    }

    fn dir(&self) -> FunctionDir {
        self.dir.clone()
    }

    fn register(&self) -> Result<()> {
        // capture
        if let Some(channel_mask) = self.builder.capture.channel.channel_mask {
            self.dir.write("c_chmask", channel_mask.to_string())?;
        }
        if let Some(sample_rate) = self.builder.capture.channel.sample_rate {
            self.dir.write("c_srate", sample_rate.to_string())?;
        }
        if let Some(sample_size) = self.builder.capture.channel.sample_size {
            self.dir.write("c_ssize", sample_size.to_string())?;
        }
        if let Some(mute_present) = self.builder.capture.mute_present {
            self.dir.write("c_mute_present", (mute_present as u8).to_string())?;
        }
        if let Some(volume_present) = self.builder.capture.volume_present {
            self.dir.write("c_volume_present", (volume_present as u8).to_string())?;
        }
        if let Some(volume_min) = self.builder.capture.volume_min {
            self.dir.write("c_volume_min", volume_min.to_string())?;
        }
        if let Some(volume_max) = self.builder.capture.volume_max {
            self.dir.write("c_volume_max", volume_max.to_string())?;
        }
        if let Some(volume_resolution) = self.builder.capture.volume_resolution {
            self.dir.write("c_volume_res", volume_resolution.to_string())?;
        }
        if let Some(volume_name) = &self.builder.capture.volume_name {
            self.dir.write("c_fu_vol_name", volume_name)?;
        }
        if let Some(input_terminal_name) = &self.builder.capture.input_terminal_name {
            self.dir.write("c_it_name", input_terminal_name)?;
        }
        if let Some(input_terminal_channel_name) = &self.builder.capture.input_terminal_channel_name {
            self.dir.write("c_it_ch_name", input_terminal_channel_name)?;
        }
        if let Some(output_terminal_name) = &self.builder.capture.output_terminal_name {
            self.dir.write("c_ot_name", output_terminal_name)?;
        }

        // playback
        if let Some(channel_mask) = self.builder.playback.channel.channel_mask {
            self.dir.write("p_chmask", channel_mask.to_string())?;
        }
        if let Some(sample_rate) = self.builder.playback.channel.sample_rate {
            self.dir.write("p_srate", sample_rate.to_string())?;
        }
        if let Some(sample_size) = self.builder.playback.channel.sample_size {
            self.dir.write("p_ssize", sample_size.to_string())?;
        }
        if let Some(mute_present) = self.builder.playback.mute_present {
            self.dir.write("p_mute_present", (mute_present as u8).to_string())?;
        }
        if let Some(volume_present) = self.builder.playback.volume_present {
            self.dir.write("p_volume_present", (volume_present as u8).to_string())?;
        }
        if let Some(volume_min) = self.builder.playback.volume_min {
            self.dir.write("p_volume_min", volume_min.to_string())?;
        }
        if let Some(volume_max) = self.builder.playback.volume_max {
            self.dir.write("p_volume_max", volume_max.to_string())?;
        }
        if let Some(volume_resolution) = self.builder.playback.volume_resolution {
            self.dir.write("p_volume_res", volume_resolution.to_string())?;
        }
        if let Some(volume_name) = &self.builder.playback.volume_name {
            self.dir.write("p_fu_vol_name", volume_name)?;
        }
        if let Some(input_terminal_name) = &self.builder.playback.input_terminal_name {
            self.dir.write("p_it_name", input_terminal_name)?;
        }
        if let Some(input_terminal_channel_name) = &self.builder.playback.input_terminal_channel_name {
            self.dir.write("p_it_ch_name", input_terminal_channel_name)?;
        }
        if let Some(output_terminal_name) = &self.builder.playback.output_terminal_name {
            self.dir.write("p_ot_name", output_terminal_name)?;
        }

        // general
        if let Some(request_number) = self.builder.request_number {
            self.dir.write("req_number", request_number.to_string())?;
        }
        if let Some(function_name) = &self.builder.function_name {
            self.dir.write("function_name", function_name)?;
        }

        Ok(())
    }
}

/// USB Audio Class 1 (UAC1) function.
///
/// UAC1 is widely supported by hosts including car stereos, older Macs, game consoles, and
/// embedded systems that may not support UAC2.
#[derive(Debug)]
pub struct Uac1 {
    dir: FunctionDir,
}

impl Uac1 {
    /// Creates a new USB Audio Class 1 (UAC1) builder with f_uac1 audio defaults.
    pub fn builder() -> Uac1Builder {
        Uac1Builder::default()
    }

    /// Creates a new USB Audio Class 1 (UAC1) function with the specified capture and playback
    /// channels.
    pub fn new(capture: Channel, playback: Channel) -> (Uac1, Handle) {
        let mut builder = Uac1Builder::default();
        builder.capture.channel = capture;
        builder.playback.channel = playback;
        builder.build()
    }

    /// Access to registration status.
    pub fn status(&self) -> Status {
        self.dir.status()
    }
}