usbd-audio 0.4.0

USB Audio 1.0 class for usb-device
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! USB Audio class
//!
//! This crate provides a USB device class based on "Universal Serial Bus Device
//! Class Definition for Audio Devices", Release 1.0 (experimental
//! implementation without the aim of standard compliance).
//!
//! Since the USB descriptor can be quite large, it may be required to activate the feature
//! `control-buffer-256` of the `usb-device` crate.
//!
//! Example
//!
//! ```ignore
//! let mut usb_bus = ... // create a UsbBusAllocator in a platform specific way
//!
//! let mut usb_audio = AudioClassBuilder::new()
//!     .input(
//!         StreamConfig::new_discrete(
//!             Format::S16le,
//!             1,
//!             &[48000],
//!             TerminalType::InMicrophone).unwrap())
//!     .output(
//!         StreamConfig::new_discrete(
//!             Format::S24le,
//!             2,
//!             &[44100, 48000, 96000],
//!             TerminalType::OutSpeaker).unwrap())
//!     .build(&usb_bus)
//!     .unwrap();
//! ```
//!
//! This example creates an audio device having a one channel (Mono) microphone
//! with a fixed sampling frequency of 48 KHz and a two channel (Stereo) speaker
//! output that supports three different sampling rates.
#![no_std]

use class_codes::*;
use core::convert::From;
use usb_device::control::{Recipient, Request, RequestType};
use usb_device::device::DEFAULT_ALTERNATE_SETTING;
use usb_device::endpoint::{Endpoint, EndpointDirection, In, Out};
use usb_device::{class_prelude::*, UsbDirection};

mod terminal_type;
pub use terminal_type::TerminalType;
mod class_codes;

const ID_INPUT_TERMINAL: u8 = 0x01;
const ID_OUTPUT_TERMINAL: u8 = 0x02;

const MAX_ISO_EP_SIZE: u32 = 1023;

#[derive(Clone, Copy, Debug)]
pub enum Format {
    /// Signed, 16 bits per subframe, little endian
    S16le,
    /// Signed, 24 bits per subframe, little endian
    S24le,
}

/// Sampling rates that shall be supported by an steaming endpoint
#[derive(Debug)]
pub enum Rates<'a> {
    /// A continuous range of sampling rates in samples/second defined by a
    /// tuple including a minimum value and a maximum value. The maximum value
    /// must be greater than the minimum value.
    Continuous(u32, u32),
    /// A set of discrete sampling rates in samples/second
    Discrete(&'a [u32]),
}

#[derive(Debug)]
pub struct StreamConfig<'a> {
    format: Format,
    channels: u8,
    rates: Rates<'a>,
    terminal_type: TerminalType,
    /// ISO endpoint size calculated from format, channels and rates (may be
    /// removed in future)
    ep_size: u16,
}

impl StreamConfig<'_> {
    /// Create a stream configuration with one or more discrete sampling rates
    /// indicated in samples/second. An input stream or an output stream will
    /// have an Input Terminal or Output Terminal of Terminal Type
    /// `terminal_type`, respectively.
    pub fn new_discrete(
        format: Format,
        channels: u8,
        rates: &'_ [u32],
        terminal_type: TerminalType,
    ) -> Result<StreamConfig<'_>> {
        let max_rate = rates.iter().max().unwrap();
        let ep_size = Self::ep_size(format, channels, *max_rate)?;
        let rates = Rates::Discrete(rates);
        Ok(StreamConfig {
            format,
            channels,
            rates,
            terminal_type,
            ep_size,
        })
    }

    /// Create a stream configuration with a continuous range of supported
    /// sampling rates indicated in samples/second. An input stream or an output
    /// stream will have an Input Terminal or Output Terminal of Terminal Type
    /// `terminal_type`, respectively.
    pub fn new_continuous(
        format: Format,
        channels: u8,
        min_rate: u32,
        max_rate: u32,
        terminal_type: TerminalType,
    ) -> Result<StreamConfig<'static>> {
        if min_rate >= max_rate {
            return Err(Error::InvalidValue);
        }
        let ep_size = Self::ep_size(format, channels, max_rate)?;
        let rates = Rates::Continuous(min_rate, max_rate);
        Ok(StreamConfig {
            format,
            channels,
            rates,
            terminal_type,
            ep_size,
        })
    }

    /// calculate ISO endpoint size from format, channels and rates
    fn ep_size(format: Format, channels: u8, max_rate: u32) -> Result<u16> {
        let octets_per_frame = channels as u32
            * match format {
                Format::S16le => 2,
                Format::S24le => 3,
            };
        let ep_size = octets_per_frame * max_rate / 1000;
        if ep_size > MAX_ISO_EP_SIZE {
            return Err(Error::BandwidthExceeded);
        }
        Ok(ep_size as u16)
    }
}

/// USB audio errors, including possible USB Stack errors
#[derive(Debug)]
pub enum Error {
    InvalidValue,
    BandwidthExceeded,
    StreamNotInitialized,
    UsbError(usb_device::UsbError),
}

impl From<UsbError> for Error {
    fn from(err: UsbError) -> Self {
        Error::UsbError(err)
    }
}

/// Result type alias for the USB Audio Class
type Result<T> = core::result::Result<T, Error>;

/// Internal state related to audio streaming in a certain direction
struct AudioStream<'a, B: UsbBus, D: EndpointDirection> {
    stream_config: StreamConfig<'a>,
    interface: InterfaceNumber,
    endpoint: Endpoint<'a, B, D>,
    alt_setting: u8,
}

macro_rules! append {
    ($iter:ident, $value:expr) => {
        *($iter.next().ok_or(UsbError::BufferOverflow)?.1) = $value;
    };
}

macro_rules! append_u24le {
    ($iter:ident, $value:expr) => {
        append!($iter, $value as u8);
        append!($iter, ($value >> 8) as u8);
        append!($iter, ($value >> 16) as u8);
    };
}

impl<B: UsbBus, D: EndpointDirection> AudioStream<'_, B, D> {
    fn write_ac_descriptors(&self, writer: &mut DescriptorWriter) -> usb_device::Result<()> {
        let is_input = self.endpoint.address().direction() == UsbDirection::In;
        let terminal_type: u16 = self.stream_config.terminal_type.into();
        let id_offset = if is_input { 0 } else { 4 };

        // write Input Terminal Descriptor (12 bytes)
        let tt = if is_input {
            terminal_type
        } else {
            TerminalType::UsbStreaming.into()
        }
        .to_le_bytes();

        // Calculate wChannelConfig based on channel count
        let channel_config = match self.stream_config.channels {
            1 => 0x0001u16, // L
            2 => 0x0003u16, // L+R
            4 => 0x0033u16, // L+R+LS+RS
            6 => 0x003Fu16, // L+R+C+LFE+LS+RS
            8 => 0x00FFu16, // L+R+C+LFE+LS+RS+LC+RC
            _ => 0x0003u16, // Default to stereo for unsupported counts
        };

        writer.write(
            CS_INTERFACE,
            &[
                INPUT_TERMINAL,                // bDescriptorSubtype
                ID_INPUT_TERMINAL + id_offset, // bTerminalID
                tt[0],                         // wTerminalType
                tt[1],
                0x00,                        // bAssocTerminal
                self.stream_config.channels, // bNrChannels
                (channel_config & 0xFF) as u8,
                (channel_config >> 8) as u8, // wChannelConfig
                0x00, // iChannelNames
                0x00, // iTerminal
            ],
        )?;

        // write Output Terminal Descriptor (9 bytes)
        let tt = if is_input {
            TerminalType::UsbStreaming.into()
        } else {
            terminal_type
        }
        .to_le_bytes();
        writer.write(
            CS_INTERFACE,
            &[
                OUTPUT_TERMINAL,                // bDescriptorSubtype
                ID_OUTPUT_TERMINAL + id_offset, // bTerminalID
                tt[0],                          // wTerminalType
                tt[1],
                0x00,                          // bAssocTerminal
                ID_INPUT_TERMINAL + id_offset, // bSourceID
                0x00,                          // iTerminal
            ],
        )
    }

    fn write_as_and_ep_descriptors(&self, writer: &mut DescriptorWriter) -> usb_device::Result<()> {
        let is_input = self.endpoint.address().direction() == UsbDirection::In;
        let id_offset = if is_input { 0 } else { 4 };
        // Standard AS Interface Descriptor (Alt. Set. 0)
        writer.interface(self.interface, AUDIO, AUDIOSTREAMING, 0x00)?;

        // Standard AS Interface Descriptor (Alt. Set. 1)
        writer.interface_alt(self.interface, 0x01, AUDIO, AUDIOSTREAMING, 0x00, None)?;

        // Class-specific AS General Interface Descriptor
        let terminal_link = id_offset
            + if is_input {
                ID_OUTPUT_TERMINAL
            } else {
                ID_INPUT_TERMINAL
            };
        writer.write(
            CS_INTERFACE,
            &[
                AS_GENERAL,    // bDescriptorSubtype:
                terminal_link, // bTerminalLink
                0x01,          // bDelay
                PCM as u8,
                (PCM >> 8) as u8, // wFormatTag
            ],
        )?;

        // Type 1 Format Type Descriptor
        let mut format_desc = [0x00u8; 128];
        let mut iter = format_desc.iter_mut().enumerate();
        append!(iter, FORMAT_TYPE); // bDescriptorSubtype;
        append!(iter, FORMAT_TYPE_I); // bFormatType
        append!(iter, self.stream_config.channels); // bNrChannels
        append!(
            iter,
            match self.stream_config.format {
                // bSubFrameSize
                Format::S16le => 2,
                Format::S24le => 3,
            }
        );
        append!(
            iter,
            match self.stream_config.format {
                // bBitResolution
                Format::S16le => 16,
                Format::S24le => 24,
            }
        );
        match self.stream_config.rates {
            Rates::Continuous(min, max) => {
                append!(iter, 0x00); // bSamFreqType
                append_u24le!(iter, min);
                append_u24le!(iter, max);
            }
            Rates::Discrete(rates) => {
                append!(iter, rates.len() as u8); // bSamFreqType
                for rate in rates {
                    append_u24le!(iter, *rate);
                }
            }
        }
        let length = iter.next().unwrap().0;
        writer.write(CS_INTERFACE, &format_desc[..length])?;

        // Standard Endpoint Descriptor
        writer.endpoint(&self.endpoint)?;

        // Class-specific Isoc. Audio Data Endpoint Descriptor
        writer.write(
            0x25,
            &[
                // bDescriptorType: CS_ENDPOINT
                0x01, // bDescriptorSubtype: GENERAL
                0x00, // bmAttributes
                0x00, // bLockDelayUnits
                0x00, 0x00, // wLockDelay
            ],
        )
    }
}

/// Builder class to create an `AudioClass` structure.
pub struct AudioClassBuilder<'a> {
    input: Option<StreamConfig<'a>>,
    output: Option<StreamConfig<'a>>,
}

impl<'a> AudioClassBuilder<'a> {
    /// Create a new AudioClassBuilder
    pub fn new() -> AudioClassBuilder<'static> {
        AudioClassBuilder {
            input: None,
            output: None,
        }
    }

    /// Configure the input audio stream according to a `StreamConfig`.
    /// At most one input stream can be configured. When calling this method
    /// multiple times, the last call matters.
    pub fn input(self, input: StreamConfig<'a>) -> AudioClassBuilder<'a> {
        AudioClassBuilder {
            input: Some(input),
            output: self.output,
        }
    }

    /// Configure the output audio stream according to a `StreamConfig`.
    /// At most one output stream can be configured. When calling this method
    /// multiple times, the last call matters.
    pub fn output(self, output: StreamConfig<'a>) -> AudioClassBuilder<'a> {
        AudioClassBuilder {
            input: self.input,
            output: Some(output),
        }
    }

    /// Create the `AudioClass` structure
    pub fn build<B: UsbBus>(self, alloc: &'a UsbBusAllocator<B>) -> Result<AudioClass<'a, B>> {
        let control_iface = alloc.interface();
        let mut ac = AudioClass {
            control_iface,
            input: None,
            output: None,
        };
        if let Some(stream_config) = self.input {
            let interface = alloc.interface();
            let endpoint = alloc.alloc(
                None,
                EndpointType::Isochronous {
                    synchronization: IsochronousSynchronizationType::Asynchronous,
                    usage: IsochronousUsageType::Data,
                },
                stream_config.ep_size,
                1,
            )?;
            let alt_setting = DEFAULT_ALTERNATE_SETTING;
            ac.input = Some(AudioStream {
                stream_config,
                interface,
                endpoint,
                alt_setting,
            })
        }

        if let Some(stream_config) = self.output {
            let interface = alloc.interface();
            let endpoint = alloc.alloc(
                None,
                EndpointType::Isochronous {
                    synchronization: IsochronousSynchronizationType::Adaptive,
                    usage: IsochronousUsageType::Data,
                },
                stream_config.ep_size,
                1,
            )?;
            let alt_setting = DEFAULT_ALTERNATE_SETTING;
            ac.output = Some(AudioStream {
                stream_config,
                interface,
                endpoint,
                alt_setting,
            })
        }

        Ok(ac)
    }
}

/// USB device class for audio devices.
///
/// This device class based on the "Universal Serial Bus Device Class Definition
/// for Audio Devices", Release 1.0. It supports one input stream and/or one
/// output stream.
pub struct AudioClass<'a, B: UsbBus> {
    control_iface: InterfaceNumber,
    input: Option<AudioStream<'a, B, In>>,
    output: Option<AudioStream<'a, B, Out>>,
}

impl<B: UsbBus> AudioClass<'_, B> {
    /// Read audio frames as output by the host. Returns an Error if no output
    /// stream has been configured.
    pub fn read(&self, data: &mut [u8]) -> Result<usize> {
        if let Some(ref info) = self.output {
            info.endpoint.read(data).map_err(Error::UsbError)
        } else {
            Err(Error::StreamNotInitialized)
        }
    }

    /// Write audio frames to be input by the host. Returns an Error when no
    /// input stream has been configured.
    pub fn write(&self, data: &[u8]) -> Result<usize> {
        if let Some(ref info) = self.input {
            info.endpoint.write(data).map_err(Error::UsbError)
        } else {
            Err(Error::StreamNotInitialized)
        }
    }

    /// Get current Alternate Setting of the input stream. Returns an error if
    /// the stream is not configured.
    pub fn input_alt_setting(&self) -> Result<u8> {
        self.input
            .as_ref()
            .ok_or(Error::StreamNotInitialized)
            .map(|si| si.alt_setting)
    }

    /// Get current Alternate Setting of the output stream. Returns an error if
    /// the stream is not configured.
    pub fn output_alt_setting(&self) -> Result<u8> {
        self.output
            .as_ref()
            .ok_or(Error::StreamNotInitialized)
            .map(|si| si.alt_setting)
    }
}

impl<B: UsbBus> UsbClass<B> for AudioClass<'_, B> {
    fn get_configuration_descriptors(
        &self,
        writer: &mut DescriptorWriter,
    ) -> usb_device::Result<()> {
        let mut in_collection = 0u8;
        if self.input.is_some() {
            in_collection += 1;
        }
        if self.output.is_some() {
            in_collection += 1;
        }

        writer.iad(
            self.control_iface,
            in_collection + 1, // Number of interfaces: control + streaming
            AUDIO,             // bFunctionClass
            AUDIOCONTROL,
            0x00, // bFunctionProtocol
            None, // iFunction
        )?;

        // write Class-specific Audio Control (AC) Interface Descriptors
        writer.interface(self.control_iface, AUDIO, AUDIOCONTROL, 0x00)?;

        let total_length = 8u16 + (1 + 21) * in_collection as u16;

        let mut ac_header = [
            HEADER, // bDescriptorSubtype
            0x00,
            0x01, // bcdADC
            total_length as u8,
            (total_length >> 8) as u8, // wTotalLength
            in_collection,             // number of AS interfaces
            0x00,
            0x00, // placeholders for baInterfaceNr
        ];
        let mut ndx = 6;
        if let Some(ref input) = self.input {
            ac_header[ndx] = input.interface.into();
            ndx += 1;
        }
        if let Some(ref output) = self.output {
            ac_header[ndx] = output.interface.into();
            ndx += 1;
        }
        writer.write(CS_INTERFACE, &ac_header[..ndx])?;
        if let Some(ref a) = self.input {
            a.write_ac_descriptors(writer)?;
        }
        if let Some(ref a) = self.output {
            a.write_ac_descriptors(writer)?;
        }

        // write Audio Streaming (AS) and endpoint (EP) descriptors
        if let Some(ref a) = self.input {
            a.write_as_and_ep_descriptors(writer)?;
        }
        if let Some(ref a) = self.output {
            a.write_as_and_ep_descriptors(writer)?;
        }
        Ok(())
    }

    fn control_in(&mut self, xfer: ControlIn<B>) {
        let req = xfer.request();
        if req.request_type == RequestType::Standard
            && req.recipient == Recipient::Interface
            && req.request == Request::GET_INTERFACE
            && req.length == 1
        {
            let iface = req.index as u8;
            if let Some(info) = self.input.as_ref() {
                if iface == info.interface.into() {
                    xfer.accept_with(&[info.alt_setting]).ok();
                    return;
                }
            }
            if let Some(info) = self.output.as_ref() {
                if iface == info.interface.into() {
                    xfer.accept_with(&[info.alt_setting]).ok();
                }
            }
        }
    }

    fn control_out(&mut self, xfer: ControlOut<B>) {
        let req = xfer.request();
        if req.request_type == RequestType::Standard
            && req.recipient == Recipient::Interface
            && req.request == Request::SET_INTERFACE
        {
            let iface = req.index as u8;
            let alt_setting = req.value;

            if let Some(info) = self.input.as_mut() {
                if iface == info.interface.into() {
                    info.alt_setting = alt_setting as u8;
                    xfer.accept().ok();
                    return;
                }
            }
            if let Some(info) = self.output.as_mut() {
                if iface == info.interface.into() {
                    info.alt_setting = alt_setting as u8;
                    xfer.accept().ok();
                }
            }
        }
    }
}