Skip to main content

usb_stack/device/class/
uac.rs

1//! USB Audio Class 1.0 (UAC 1.0).
2//!
3//! Implements "Universal Serial Bus Device Class Definition for Audio Devices",
4//! Release 1.0.  Supports one input stream (e.g. microphone) and/or one output
5//! stream (e.g. speaker / headphones) with discrete or continuous sampling rates.
6//!
7//! # Example — stereo speaker with microphone
8//!
9//! ```ignore
10//! use my_hal_usb::{UsbBusAllocator, UsbDeviceBuilder};
11//! use my_hal_usb::class::uac::{
12//!     AudioClassBuilder, Format, StreamConfig, TerminalType,
13//! };
14//! use my_hal_usb::MyBus;
15//!
16//! static RATES_48K: [u32; 1] = [48000];
17//!
18//! let alloc = UsbBusAllocator::new(MyBus::new(/* peripheral */));
19//! let mut audio = AudioClassBuilder::new()
20//!     .input(
21//!         StreamConfig::new_discrete(
22//!             Format::S16le, 1, &RATES_48K, TerminalType::InMicrophone,
23//!         ).unwrap())
24//!     .output(
25//!         StreamConfig::new_discrete(
26//!             Format::S24le, 2, &RATES_48K, TerminalType::OutSpeaker,
27//!         ).unwrap())
28//!     .build(&alloc);
29//!
30//! let mut dev = UsbDeviceBuilder::new(&alloc, 0x1234, 0x5678)
31//!     .product("USB Audio")
32//!     .composite_with_iads()
33//!     .build();
34//!
35//! loop {
36//!     dev.poll(&mut [&mut audio]);
37//!     let mut buf = [0u8; 288];
38//!     if let Ok(n) = audio.read(&mut buf) {
39//!         // send to DAC …
40//!     }
41//!     let pcm = [0u8; 96];
42//!     let _ = audio.write(&pcm);
43//! }
44//! ```
45
46use crate::device::bus::{InterfaceNumber, UsbBus, UsbBusAllocator};
47use crate::device::class::UsbClass;
48use crate::device::control::{ControlIn, ControlOut};
49use crate::device::descriptor::DescriptorWriter;
50use crate::device::endpoint::{EndpointIn, EndpointOut};
51use crate::device::error::{UsbError, UsbResult};
52use crate::endpoint::{EndpointAddress, EndpointType, IsoSynchronization, IsoUsage};
53use crate::request::{Recipient, RequestType};
54
55// ─── Terminal types (USB Audio 1.0) ──────────────────────────────────────────
56
57/// USB Audio Terminal Types from "Universal Serial Bus Device Class Definition
58/// for Terminal Types, Release 1.0".
59#[rustfmt::skip]
60#[repr(u16)]
61#[non_exhaustive]
62#[derive(Copy, Clone, Eq, PartialEq, Debug)]
63pub enum TerminalType {
64    // USB Terminal Types
65    /// Undefined USB terminal.
66    UsbUndefined  = 0x0100,
67    /// USB streaming terminal.
68    UsbStreaming  = 0x0101,
69    /// Vendor-specific USB terminal.
70    UsbVendor     = 0x01FF,
71
72    // Input Terminal Types
73    /// Undefined input terminal.
74    InUndefined                   = 0x0200,
75    /// Microphone input terminal.
76    InMicrophone                  = 0x0201,
77    /// Desktop microphone input terminal.
78    InDesktopMicrophone           = 0x0202,
79    /// Personal microphone input terminal.
80    InPersonalMicrophone          = 0x0203,
81    /// Omni-directional microphone input terminal.
82    InOmniDirectionalMicrophone   = 0x0204,
83    /// Microphone array input terminal.
84    InMicrophoneArray             = 0x0205,
85    /// Processing microphone array input terminal.
86    InProcessingMicrophoneArray   = 0x0206,
87
88    // Output Terminal Types
89    /// Undefined output terminal.
90    OutUndefined                  = 0x0300,
91    /// Speaker output terminal.
92    OutSpeaker                    = 0x0301,
93    /// Headphones output terminal.
94    OutHeadphones                 = 0x0302,
95    /// Head-mounted display audio output terminal.
96    OutHeadMountedDisplayAudio    = 0x0303,
97    /// Desktop speaker output terminal.
98    OutDesktopSpeaker             = 0x0304,
99    /// Room speaker output terminal.
100    OutRoomSpeaker                = 0x0305,
101    /// Communication speaker output terminal.
102    OutCommunicationSpeaker       = 0x0306,
103    /// Low-frequency-effects speaker output terminal.
104    OutLowFrequencyEffectsSpeaker = 0x0307,
105
106    // External Terminal Types
107    /// Undefined external terminal.
108    ExtUndefined               = 0x0600,
109    /// Analog connector external terminal.
110    ExtAnalogConnector         = 0x0601,
111    /// Digital audio interface external terminal.
112    ExtDigitalAudioInterface   = 0x0602,
113    /// Line connector external terminal.
114    ExtLineConnector           = 0x0603,
115    /// Legacy audio connector external terminal.
116    ExtLegacyAudioConnector    = 0x0604,
117    /// S/PDIF connector external terminal.
118    ExtSpdifConnector          = 0x0605,
119    /// IEEE 1394 DA stream external terminal.
120    Ext1394DaStream            = 0x0606,
121    /// IEEE 1394 DV stream soundtrack external terminal.
122    Ext1394DvStreamSoundtrack  = 0x0607,
123}
124
125impl From<TerminalType> for u16 {
126    fn from(t: TerminalType) -> u16 {
127        t as u16
128    }
129}
130
131// ─── UAC class-specific constants ─────────────────────────────────────────────
132
133/// Audio Interface Class Code (USB-IF).
134pub const UAC_CLASS: u8 = 0x01;
135/// Audio Control subclass.
136pub const UAC_SUBCLASS_CONTROL: u8 = 0x01;
137/// Audio Streaming subclass.
138pub const UAC_SUBCLASS_STREAMING: u8 = 0x02;
139
140/// Class-Specific Interface descriptor type (CS_INTERFACE).
141const CS_INTERFACE: u8 = 0x24;
142/// Class-Specific Endpoint descriptor type (CS_ENDPOINT).
143const CS_ENDPOINT: u8 = 0x25;
144
145// AC descriptor subtypes
146const AC_HEADER: u8 = 0x01;
147const AC_INPUT_TERMINAL: u8 = 0x02;
148const AC_OUTPUT_TERMINAL: u8 = 0x03;
149const AC_FEATURE_UNIT: u8 = 0x06;
150
151// AS descriptor subtypes
152const AS_GENERAL: u8 = 0x01;
153const AS_FORMAT_TYPE: u8 = 0x02;
154
155// EP descriptor subtypes
156const EP_GENERAL: u8 = 0x01;
157
158// Feature Unit control selectors
159const FU_MUTE: u8 = 0x01;
160const FU_VOLUME: u8 = 0x02;
161
162// Audio Class-Specific Request Codes (UAC 1.0 §5.2.2)
163const CUR_SET: u8 = 0x01;
164const CUR_GET: u8 = 0x81;
165const MIN_GET: u8 = 0x82;
166const MAX_GET: u8 = 0x83;
167const RES_GET: u8 = 0x84;
168
169/// PCM format tag (Audio Data Format Type I).
170const PCM_TAG: u16 = 0x0001;
171/// Format Type I code.
172const FORMAT_TYPE_I: u8 = 0x01;
173
174/// Terminal/Unit IDs used in the topology.
175///
176/// Output (speaker) topology: IT(USB,2) → FU(3) → OT(Speaker,4)
177/// Input (mic) topology:     IT(Mic,5)  → FU(6) → OT(USB,7)
178const TERM_ID_SPEAKER_USB: u8 = 0x02;
179const TERM_ID_SPEAKER_FU: u8 = 0x03;
180const TERM_ID_SPEAKER_OUT: u8 = 0x04;
181const TERM_ID_MIC_IN: u8 = 0x05;
182const TERM_ID_MIC_FU: u8 = 0x06;
183const TERM_ID_MIC_USB: u8 = 0x07;
184
185/// Maximum isochronous endpoint packet size for full-speed USB.
186const MAX_ISO_SIZE: u32 = 1023;
187
188// ─── Audio format ────────────────────────────────────────────────────────────
189
190/// Audio sample format.
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
192pub enum Format {
193    /// Signed 16-bit little-endian (2 bytes/subframe).
194    S16le,
195    /// Signed 24-bit little-endian (3 bytes/subframe).
196    S24le,
197}
198
199impl Format {
200    const fn bytes(self) -> u8 {
201        match self {
202            Format::S16le => 2,
203            Format::S24le => 3,
204        }
205    }
206    const fn bits(self) -> u8 {
207        match self {
208            Format::S16le => 16,
209            Format::S24le => 24,
210        }
211    }
212}
213
214// ─── Sampling rates ──────────────────────────────────────────────────────────
215
216/// Supported sampling rates for an audio stream.
217#[derive(Debug, Clone)]
218pub enum Rates {
219    /// Continuous range `[min, max]` in Hz (0 = continuous in descriptor).
220    Continuous(u32, u32),
221    /// Discrete set of frequencies in Hz.
222    Discrete(&'static [u32]),
223}
224
225// ─── StreamConfig ────────────────────────────────────────────────────────────
226
227/// Configuration for one audio stream (input or output).
228#[derive(Debug, Clone)]
229pub struct StreamConfig {
230    /// Sample format.
231    pub format: Format,
232    /// Number of channels (1 = mono, 2 = stereo, …).
233    pub channels: u8,
234    /// Supported sampling rates.
235    pub rates: Rates,
236    /// Terminal type for this stream.
237    pub terminal_type: TerminalType,
238    /// Computed maximum isochronous endpoint packet size in bytes.
239    pub ep_size: u16,
240}
241
242impl StreamConfig {
243    /// Create with one or more discrete sampling rates.
244    ///
245    /// `rates` must be a `&'static [u32]` for lifetime simplicity in `no_std`
246    /// embedded contexts.
247    pub fn new_discrete(
248        format: Format,
249        channels: u8,
250        rates: &'static [u32],
251        terminal_type: TerminalType,
252    ) -> Result<Self, UsbError> {
253        let max_rate = *rates.iter().max().unwrap_or(&48000);
254        let ep_size = Self::calc_ep_size(format, channels, max_rate)?;
255        Ok(Self {
256            format,
257            channels,
258            rates: Rates::Discrete(rates),
259            terminal_type,
260            ep_size,
261        })
262    }
263
264    /// Create with a continuous frequency range `[min_rate, max_rate]`.
265    pub fn new_continuous(
266        format: Format,
267        channels: u8,
268        min_rate: u32,
269        max_rate: u32,
270        terminal_type: TerminalType,
271    ) -> Result<Self, UsbError> {
272        if min_rate >= max_rate {
273            return Err(UsbError::InvalidState);
274        }
275        let ep_size = Self::calc_ep_size(format, channels, max_rate)?;
276        Ok(Self {
277            format,
278            channels,
279            rates: Rates::Continuous(min_rate, max_rate),
280            terminal_type,
281            ep_size,
282        })
283    }
284
285    fn calc_ep_size(format: Format, channels: u8, max_rate: u32) -> Result<u16, UsbError> {
286        let octets_per_frame = channels as u32 * format.bytes() as u32;
287        let size = octets_per_frame * max_rate / 1000;
288        if size > MAX_ISO_SIZE {
289            return Err(UsbError::BufferOverflow);
290        }
291        Ok(size as u16)
292    }
293
294    fn channel_config(&self) -> u16 {
295        match self.channels {
296            1 => 0x0001, // L
297            2 => 0x0003, // L + R
298            4 => 0x0033, // L + R + LS + RS
299            6 => 0x003F, // L + R + C + LFE + LS + RS
300            8 => 0x00FF, // L + R + C + LFE + LS + RS + LC + RC
301            _ => 0x0003, // default: stereo
302        }
303    }
304}
305
306// ─── AudioClassBuilder ───────────────────────────────────────────────────────
307
308/// Builder for [`AudioClass`].
309///
310/// Use the fluent API to configure input/output streams, then call
311/// [`build`](Self::build).
312#[derive(Default)]
313pub struct AudioClassBuilder {
314    input: Option<StreamConfig>,
315    output: Option<StreamConfig>,
316}
317
318impl AudioClassBuilder {
319    /// Create a new builder with no streams configured.
320    pub fn new() -> Self {
321        Self {
322            input: None,
323            output: None,
324        }
325    }
326
327    /// Configure an input stream (device → host, e.g. microphone).
328    ///
329    /// Calling multiple times replaces the previous configuration.
330    pub fn input(mut self, cfg: StreamConfig) -> Self {
331        self.input = Some(cfg);
332        self
333    }
334
335    /// Configure an output stream (host → device, e.g. speaker / headphones).
336    ///
337    /// Calling multiple times replaces the previous configuration.
338    pub fn output(mut self, cfg: StreamConfig) -> Self {
339        self.output = Some(cfg);
340        self
341    }
342
343    /// Build the [`AudioClass`], allocating endpoints and interfaces from `alloc`.
344    pub fn build<B: UsbBus>(self, alloc: &UsbBusAllocator<B>) -> AudioClass<'_, B> {
345        let control_iface = alloc.interface();
346
347        let (in_ep, in_iface, in_cfg, in_alt) = if let Some(cfg) = self.input {
348            let iface = alloc.interface();
349            let ep = alloc.isochronous::<crate::endpoint::In>(
350                IsoSynchronization::Asynchronous,
351                IsoUsage::Data,
352                cfg.ep_size,
353                1,
354            );
355            (Some(ep), iface, Some(cfg), 0u8)
356        } else {
357            (None, InterfaceNumber::new(0), None, 0u8)
358        };
359
360        let (out_ep, out_iface, out_cfg, out_alt) = if let Some(cfg) = self.output {
361            let iface = alloc.interface();
362            let ep = alloc.isochronous::<crate::endpoint::Out>(
363                IsoSynchronization::Adaptive,
364                IsoUsage::Data,
365                cfg.ep_size,
366                1,
367            );
368            (Some(ep), iface, Some(cfg), 0u8)
369        } else {
370            (None, InterfaceNumber::new(0), None, 0u8)
371        };
372
373        AudioClass {
374            control_iface,
375            in_ep,
376            in_iface,
377            in_cfg,
378            in_alt,
379            out_ep,
380            out_iface,
381            out_cfg,
382            out_alt,
383            configured: false,
384        }
385    }
386}
387
388// ─── AudioClass ──────────────────────────────────────────────────────────────
389
390/// USB Audio Class 1.0 device class.
391///
392/// Supports one streaming input (microphone / line-in) and/or one streaming
393/// output (speaker / headphones).  Built via [`AudioClassBuilder`].
394///
395/// The host activates a stream by selecting alternate setting 1
396/// (via `SET_INTERFACE`), and deactivates it by selecting alternate setting 0.
397pub struct AudioClass<'a, B: UsbBus> {
398    // Control interface
399    control_iface: InterfaceNumber,
400
401    // Input stream (device → host)
402    in_ep: Option<EndpointIn<'a, B>>,
403    in_iface: InterfaceNumber,
404    in_cfg: Option<StreamConfig>,
405    in_alt: u8,
406
407    // Output stream (host → device)
408    out_ep: Option<EndpointOut<'a, B>>,
409    out_iface: InterfaceNumber,
410    out_cfg: Option<StreamConfig>,
411    out_alt: u8,
412
413    configured: bool,
414}
415
416impl<'a, B: UsbBus> AudioClass<'a, B> {
417    /// Read audio data from the host (output / speaker stream).
418    ///
419    /// Returns the number of bytes read into `buf`, or
420    /// [`UsbError::WouldBlock`] when no isochronous packet is available.
421    /// Also returns [`UsbError::InvalidState`] if the stream is not
422    /// configured or not active (alt setting 0).
423    pub fn read(&self, buf: &mut [u8]) -> UsbResult<usize> {
424        let ep = self.out_ep.as_ref().ok_or(UsbError::InvalidState)?;
425        if !self.configured || self.out_alt == 0 {
426            return Err(UsbError::InvalidState);
427        }
428        ep.read(buf)
429    }
430
431    /// Write audio data to the host (input / microphone stream).
432    ///
433    /// Returns the number of bytes written, or [`UsbError::WouldBlock`]
434    /// when the previous packet has not yet been sent.  Also returns
435    /// [`UsbError::InvalidState`] if the stream is not configured or
436    /// not active (alt setting 0).
437    pub fn write(&self, buf: &[u8]) -> UsbResult<usize> {
438        let ep = self.in_ep.as_ref().ok_or(UsbError::InvalidState)?;
439        if !self.configured || self.in_alt == 0 {
440            return Err(UsbError::InvalidState);
441        }
442        ep.write(buf)
443    }
444
445    /// Current alternate setting of the input (microphone) stream.
446    /// Returns `None` if no input stream was configured.
447    pub fn input_alt_setting(&self) -> Option<u8> {
448        self.in_cfg.as_ref().map(|_| self.in_alt)
449    }
450
451    /// Current alternate setting of the output (speaker) stream.
452    /// Returns `None` if no output stream was configured.
453    pub fn output_alt_setting(&self) -> Option<u8> {
454        self.out_cfg.as_ref().map(|_| self.out_alt)
455    }
456
457    /// `true` when the device has been fully configured by the host.
458    pub fn is_configured(&self) -> bool {
459        self.configured
460    }
461
462    /// `true` when the output (speaker) stream is active (alt setting ≠ 0).
463    pub fn output_active(&self) -> bool {
464        self.configured && self.out_alt != 0
465    }
466
467    /// `true` when the input (microphone) stream is active (alt setting ≠ 0).
468    pub fn input_active(&self) -> bool {
469        self.configured && self.in_alt != 0
470    }
471
472    // ── Descriptor helpers ──────────────────────────────────────────────────
473
474    fn streaming_count(&self) -> u8 {
475        self.in_cfg.is_some() as u8 + self.out_cfg.is_some() as u8
476    }
477
478    fn write_ac_header(&self, w: &mut DescriptorWriter) -> UsbResult<()> {
479        let n = self.streaming_count();
480        let total_len = self.ac_total_length();
481        let mut hdr = [
482            AC_HEADER,
483            0x00,
484            0x01, // bcdADC = 1.00
485            total_len as u8,
486            (total_len >> 8) as u8, // wTotalLength
487            n,                      // bInCollection
488            0x00,
489            0x00, // baInterfaceNr[0..1]
490        ];
491        let mut idx = 6usize;
492        if self.in_cfg.is_some() {
493            hdr[idx] = self.in_iface.into();
494            idx += 1;
495        }
496        if self.out_cfg.is_some() {
497            hdr[idx] = self.out_iface.into();
498            idx += 1;
499        }
500        w.write(CS_INTERFACE, &hdr[..idx])
501    }
502
503    /// Compute wTotalLength for the AC interface header — sum of all
504    /// class-specific descriptor sizes within the AudioControl interface.
505    fn ac_total_length(&self) -> u16 {
506        let n = self.streaming_count() as u16;
507        // AC Header: 2 (bLength+bType) + 6 (fixed body) + n (baInterfaceNr)
508        let mut total: u16 = 8 + n;
509        for cfg in [&self.in_cfg, &self.out_cfg]
510            .iter()
511            .filter_map(|c| c.as_ref())
512        {
513            // Input Terminal: 2 + 10 = 12
514            total += 12;
515            // Feature Unit: 2 + (6 + channels) = 8 + channels
516            total += 8 + cfg.channels as u16;
517            // Output Terminal: 2 + 7 = 9
518            total += 9;
519        }
520        total
521    }
522
523    /// Return the number of channels for a given Feature Unit ID,
524    /// or 0 if the ID doesn't match any of our units.
525    fn fu_channels(&self, unit_id: u8) -> u8 {
526        if unit_id == TERM_ID_SPEAKER_FU {
527            self.out_cfg.as_ref().map_or(0, |c| c.channels)
528        } else if unit_id == TERM_ID_MIC_FU {
529            self.in_cfg.as_ref().map_or(0, |c| c.channels)
530        } else {
531            0
532        }
533    }
534
535    fn write_terminal_descriptors(
536        &self,
537        w: &mut DescriptorWriter,
538        cfg: &StreamConfig,
539        input_term_id: u8,
540        fu_id: u8,
541        output_term_id: u8,
542        is_input: bool,
543    ) -> UsbResult<()> {
544        let tt: u16 = cfg.terminal_type.into();
545        let cc = cfg.channel_config();
546
547        // ── Input Terminal (12 bytes) ────────────────────────────────────
548        let it_type = if is_input {
549            tt
550        } else {
551            TerminalType::UsbStreaming.into()
552        };
553        w.write(
554            CS_INTERFACE,
555            &[
556                AC_INPUT_TERMINAL,
557                input_term_id,
558                it_type as u8,
559                (it_type >> 8) as u8,
560                0x00,            // bAssocTerminal
561                cfg.channels,    // bNrChannels
562                cc as u8,        // wChannelConfig (lo)
563                (cc >> 8) as u8, // wChannelConfig (hi)
564                0x00,            // iChannelNames
565                0x00,            // iTerminal
566            ],
567        )?;
568
569        // ── Feature Unit (7 + ch + 1 bytes body) ─────────────────────────
570        self.write_feature_unit(w, cfg, fu_id, input_term_id)?;
571
572        // ── Output Terminal (9 bytes) ────────────────────────────────────
573        let ot_type = if is_input {
574            TerminalType::UsbStreaming.into()
575        } else {
576            tt
577        };
578        w.write(
579            CS_INTERFACE,
580            &[
581                AC_OUTPUT_TERMINAL,
582                output_term_id,
583                ot_type as u8,
584                (ot_type >> 8) as u8,
585                0x00,  // bAssocTerminal
586                fu_id, // bSourceID → comes from Feature Unit
587                0x00,  // iTerminal
588            ],
589        )
590    }
591
592    /// Write a Feature Unit descriptor with Mute + Volume controls.
593    ///
594    /// The body is: subtype(1) + unitID(1) + sourceID(1) + controlSize(1)
595    ///            + ch+1 bitmap bytes + iFeature(1)
596    /// Total body = 4 + (ch+1) + 1 = 6 + ch
597    /// Full descriptor = 2 + body
598    fn write_feature_unit(
599        &self,
600        w: &mut DescriptorWriter,
601        cfg: &StreamConfig,
602        fu_id: u8,
603        source_id: u8,
604    ) -> UsbResult<()> {
605        let ch = cfg.channels as usize;
606        // Max channels we support in the stack-allocated buffer: 8
607        let mut body = [0u8; 16]; // enough for up to 8 ch (6+8=14 bytes)
608        body[0] = AC_FEATURE_UNIT;
609        body[1] = fu_id;
610        body[2] = source_id;
611        body[3] = 1; // bControlSize: 1 byte per control
612        // Master channel: Mute + Volume
613        body[4] = FU_MUTE | FU_VOLUME; // 0x03
614        // Per-channel: Volume only
615        for i in 0..ch {
616            body[5 + i] = FU_VOLUME; // 0x02
617        }
618        body[5 + ch] = 0x00; // iFeature
619        let body_len = 6 + ch;
620        w.write(CS_INTERFACE, &body[..body_len])
621    }
622
623    fn write_as_descriptors(
624        &self,
625        w: &mut DescriptorWriter,
626        cfg: &StreamConfig,
627        iface: InterfaceNumber,
628        ep_addr: EndpointAddress,
629        is_input: bool,
630    ) -> UsbResult<()> {
631        // Alt 0 — stream inactive, 0 endpoints.
632        w.interface(iface, 0, UAC_CLASS, UAC_SUBCLASS_STREAMING, 0x00)?;
633
634        // Alt 1 — stream active, 1 isochronous endpoint.
635        w.interface_alt(iface, 1, 1, UAC_CLASS, UAC_SUBCLASS_STREAMING, 0x00)?;
636
637        // Terminal link: the terminal in the audio function that this
638        // streaming interface is associated with.
639        // - Input stream (mic): links to the USB OUT terminal in AC topology
640        // - Output stream (speaker): links to the USB IN terminal in AC topology
641        let term_link = if is_input {
642            TERM_ID_MIC_USB
643        } else {
644            TERM_ID_SPEAKER_USB
645        };
646
647        // Class-Specific AS General Interface descriptor
648        w.write(
649            CS_INTERFACE,
650            &[
651                AS_GENERAL,
652                term_link,
653                0x01, // bDelay = 1 frame
654                PCM_TAG as u8,
655                (PCM_TAG >> 8) as u8, // wFormatTag = PCM
656            ],
657        )?;
658
659        // Type I Format Type descriptor
660        self.write_format_type(w, cfg)?;
661
662        // Standard Endpoint descriptor
663        let ep_type = if is_input {
664            EndpointType::Isochronous {
665                synchronization: IsoSynchronization::Asynchronous,
666                usage: IsoUsage::Data,
667            }
668        } else {
669            EndpointType::Isochronous {
670                synchronization: IsoSynchronization::Adaptive,
671                usage: IsoUsage::Data,
672            }
673        };
674        w.endpoint(ep_addr, ep_type, cfg.ep_size, 1)?;
675
676        // Class-Specific Isoc Audio Data Endpoint descriptor
677        w.write(
678            CS_ENDPOINT,
679            &[
680                EP_GENERAL, // bDescriptorSubtype
681                0x00,       // bmAttributes
682                0x00,       // bLockDelayUnits
683                0x00, 0x00, // wLockDelay
684            ],
685        )
686    }
687
688    fn write_format_type(&self, w: &mut DescriptorWriter, cfg: &StreamConfig) -> UsbResult<()> {
689        fn put_u24(buf: &mut [u8], pos: &mut usize, v: u32) {
690            buf[*pos] = v as u8;
691            *pos += 1;
692            buf[*pos] = (v >> 8) as u8;
693            *pos += 1;
694            buf[*pos] = (v >> 16) as u8;
695            *pos += 1;
696        }
697
698        let mut buf = [0u8; 64];
699        let mut i = 0usize;
700
701        buf[i] = AS_FORMAT_TYPE;
702        i += 1;
703        buf[i] = FORMAT_TYPE_I;
704        i += 1;
705        buf[i] = cfg.channels;
706        i += 1;
707        buf[i] = cfg.format.bytes();
708        i += 1;
709        buf[i] = cfg.format.bits();
710        i += 1;
711
712        match &cfg.rates {
713            Rates::Continuous(min, max) => {
714                buf[i] = 0x00;
715                i += 1;
716                put_u24(&mut buf, &mut i, *min);
717                put_u24(&mut buf, &mut i, *max);
718            }
719            Rates::Discrete(rates) => {
720                buf[i] = rates.len() as u8;
721                i += 1;
722                for &r in *rates {
723                    put_u24(&mut buf, &mut i, r);
724                }
725            }
726        }
727        w.write(CS_INTERFACE, &buf[..i])
728    }
729}
730
731// ─── UsbClass implementation ─────────────────────────────────────────────────
732
733impl<B: UsbBus> UsbClass<B> for AudioClass<'_, B> {
734    fn configuration_descriptors(&self, w: &mut DescriptorWriter) -> UsbResult<()> {
735        // NOTE: IAD is intentionally omitted.  The kernel's snd-usb-audio
736        // driver locates the AudioControl interface by scanning for
737        // bInterfaceClass=AUDIO / bInterfaceSubClass=AUDIOCONTROL.
738        // Including an IAD can sometimes cause the USB core to misplace
739        // class-specific descriptors in the interface extra-buffer on
740        // certain host controllers.
741
742        // ── Audio Control (AC) Interface ────────────────────────────────────
743        w.interface(self.control_iface, 0, UAC_CLASS, UAC_SUBCLASS_CONTROL, 0x00)?;
744        self.write_ac_header(w)?;
745
746        if let Some(ref cfg) = self.in_cfg {
747            self.write_terminal_descriptors(
748                w,
749                cfg,
750                TERM_ID_MIC_IN,
751                TERM_ID_MIC_FU,
752                TERM_ID_MIC_USB,
753                true,
754            )?;
755        }
756        if let Some(ref cfg) = self.out_cfg {
757            self.write_terminal_descriptors(
758                w,
759                cfg,
760                TERM_ID_SPEAKER_USB,
761                TERM_ID_SPEAKER_FU,
762                TERM_ID_SPEAKER_OUT,
763                false,
764            )?;
765        }
766
767        // ── Audio Streaming (AS) Interfaces ─────────────────────────────────
768        if let Some(ref cfg) = self.in_cfg {
769            self.write_as_descriptors(
770                w,
771                cfg,
772                self.in_iface,
773                self.in_ep.as_ref().unwrap().address(),
774                true,
775            )?;
776        }
777        if let Some(ref cfg) = self.out_cfg {
778            self.write_as_descriptors(
779                w,
780                cfg,
781                self.out_iface,
782                self.out_ep.as_ref().unwrap().address(),
783                false,
784            )?;
785        }
786
787        Ok(())
788    }
789
790    fn control_in(&mut self, xfer: ControlIn<'_, B>) {
791        let req = xfer.request();
792
793        // Only handle Class requests to the Interface recipient.
794        if req.request_type != RequestType::Class || req.recipient != Recipient::Interface {
795            return;
796        }
797
798        // wIndex = (UnitID << 8) | Interface
799        let unit_id = (req.index >> 8) as u8;
800        // wValue = (ControlSelector << 8) | ChannelNumber
801        let cs = (req.value >> 8) as u8;
802
803        // Check if the request targets one of our Feature Units.
804        let channels = self.fu_channels(unit_id);
805        if channels == 0 {
806            return; // Not our unit — let the request fall through.
807        }
808
809        match req.request {
810            CUR_GET if cs == FU_MUTE => {
811                // Mute: return 0 = unmuted
812                let _ = xfer.accept_with(&[0x00]);
813            }
814            CUR_GET if cs == FU_VOLUME => {
815                // Volume CUR = 0x0000 (max / 0 dB), 16-bit signed LE
816                let _ = xfer.accept_with(&[0x00, 0x00]);
817            }
818            MIN_GET if cs == FU_VOLUME => {
819                // Volume MIN = 0x0080 (minimum, very quiet)
820                let _ = xfer.accept_with(&[0x00, 0x80]);
821            }
822            MAX_GET if cs == FU_VOLUME => {
823                // Volume MAX = 0x0000 (0 dB, max)
824                let _ = xfer.accept_with(&[0x00, 0x00]);
825            }
826            RES_GET if cs == FU_VOLUME => {
827                // Volume RES = 0x0100 (1 dB resolution)
828                let _ = xfer.accept_with(&[0x00, 0x01]);
829            }
830            _ => {
831                let _ = xfer.reject();
832            }
833        }
834    }
835
836    fn control_out(&mut self, xfer: ControlOut<'_, B>) {
837        let req = xfer.request();
838
839        if req.request_type != RequestType::Class || req.recipient != Recipient::Interface {
840            return;
841        }
842
843        let unit_id = (req.index >> 8) as u8;
844        let cs = (req.value >> 8) as u8;
845
846        if self.fu_channels(unit_id) == 0 {
847            return;
848        }
849
850        match req.request {
851            CUR_SET if cs == FU_MUTE => {
852                // Accept mute change (ignore the value for now).
853                let _ = xfer.accept();
854            }
855            CUR_SET if cs == FU_VOLUME => {
856                // Accept volume change (ignore the value for now).
857                let _ = xfer.accept();
858            }
859            _ => {
860                let _ = xfer.reject();
861            }
862        }
863    }
864
865    fn configure(&mut self) {
866        self.configured = true;
867    }
868
869    fn deconfigure(&mut self) {
870        self.configured = false;
871        self.in_alt = 0;
872        self.out_alt = 0;
873    }
874
875    fn reset(&mut self) {
876        self.configured = false;
877        self.in_alt = 0;
878        self.out_alt = 0;
879    }
880
881    fn alt_setting(&mut self, iface: InterfaceNumber) -> Option<u8> {
882        if self.in_cfg.is_some() && self.in_iface == iface {
883            return Some(self.in_alt);
884        }
885        if self.out_cfg.is_some() && self.out_iface == iface {
886            return Some(self.out_alt);
887        }
888        None
889    }
890
891    fn set_alt_setting(&mut self, iface: InterfaceNumber, alt: u8) -> bool {
892        if self.in_cfg.is_some() && self.in_iface == iface {
893            self.in_alt = alt;
894            return true;
895        }
896        if self.out_cfg.is_some() && self.out_iface == iface {
897            self.out_alt = alt;
898            return true;
899        }
900        false
901    }
902}