use crate::device::bus::{InterfaceNumber, UsbBus, UsbBusAllocator};
use crate::device::class::UsbClass;
use crate::device::control::{ControlIn, ControlOut};
use crate::device::descriptor::DescriptorWriter;
use crate::device::endpoint::{EndpointIn, EndpointOut};
use crate::device::error::{UsbError, UsbResult};
use crate::endpoint::{EndpointAddress, EndpointType, IsoSynchronization, IsoUsage};
use crate::request::{Recipient, RequestType};
#[rustfmt::skip]
#[repr(u16)]
#[non_exhaustive]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum TerminalType {
UsbUndefined = 0x0100,
UsbStreaming = 0x0101,
UsbVendor = 0x01FF,
InUndefined = 0x0200,
InMicrophone = 0x0201,
InDesktopMicrophone = 0x0202,
InPersonalMicrophone = 0x0203,
InOmniDirectionalMicrophone = 0x0204,
InMicrophoneArray = 0x0205,
InProcessingMicrophoneArray = 0x0206,
OutUndefined = 0x0300,
OutSpeaker = 0x0301,
OutHeadphones = 0x0302,
OutHeadMountedDisplayAudio = 0x0303,
OutDesktopSpeaker = 0x0304,
OutRoomSpeaker = 0x0305,
OutCommunicationSpeaker = 0x0306,
OutLowFrequencyEffectsSpeaker = 0x0307,
ExtUndefined = 0x0600,
ExtAnalogConnector = 0x0601,
ExtDigitalAudioInterface = 0x0602,
ExtLineConnector = 0x0603,
ExtLegacyAudioConnector = 0x0604,
ExtSpdifConnector = 0x0605,
Ext1394DaStream = 0x0606,
Ext1394DvStreamSoundtrack = 0x0607,
}
impl From<TerminalType> for u16 {
fn from(t: TerminalType) -> u16 {
t as u16
}
}
pub const UAC_CLASS: u8 = 0x01;
pub const UAC_SUBCLASS_CONTROL: u8 = 0x01;
pub const UAC_SUBCLASS_STREAMING: u8 = 0x02;
const CS_INTERFACE: u8 = 0x24;
const CS_ENDPOINT: u8 = 0x25;
const AC_HEADER: u8 = 0x01;
const AC_INPUT_TERMINAL: u8 = 0x02;
const AC_OUTPUT_TERMINAL: u8 = 0x03;
const AC_FEATURE_UNIT: u8 = 0x06;
const AS_GENERAL: u8 = 0x01;
const AS_FORMAT_TYPE: u8 = 0x02;
const EP_GENERAL: u8 = 0x01;
const FU_MUTE: u8 = 0x01;
const FU_VOLUME: u8 = 0x02;
const CUR_SET: u8 = 0x01;
const CUR_GET: u8 = 0x81;
const MIN_GET: u8 = 0x82;
const MAX_GET: u8 = 0x83;
const RES_GET: u8 = 0x84;
const PCM_TAG: u16 = 0x0001;
const FORMAT_TYPE_I: u8 = 0x01;
const TERM_ID_SPEAKER_USB: u8 = 0x02;
const TERM_ID_SPEAKER_FU: u8 = 0x03;
const TERM_ID_SPEAKER_OUT: u8 = 0x04;
const TERM_ID_MIC_IN: u8 = 0x05;
const TERM_ID_MIC_FU: u8 = 0x06;
const TERM_ID_MIC_USB: u8 = 0x07;
const MAX_ISO_SIZE: u32 = 1023;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
S16le,
S24le,
}
impl Format {
const fn bytes(self) -> u8 {
match self {
Format::S16le => 2,
Format::S24le => 3,
}
}
const fn bits(self) -> u8 {
match self {
Format::S16le => 16,
Format::S24le => 24,
}
}
}
#[derive(Debug, Clone)]
pub enum Rates {
Continuous(u32, u32),
Discrete(&'static [u32]),
}
#[derive(Debug, Clone)]
pub struct StreamConfig {
pub format: Format,
pub channels: u8,
pub rates: Rates,
pub terminal_type: TerminalType,
pub ep_size: u16,
}
impl StreamConfig {
pub fn new_discrete(
format: Format,
channels: u8,
rates: &'static [u32],
terminal_type: TerminalType,
) -> Result<Self, UsbError> {
let max_rate = *rates.iter().max().unwrap_or(&48000);
let ep_size = Self::calc_ep_size(format, channels, max_rate)?;
Ok(Self {
format,
channels,
rates: Rates::Discrete(rates),
terminal_type,
ep_size,
})
}
pub fn new_continuous(
format: Format,
channels: u8,
min_rate: u32,
max_rate: u32,
terminal_type: TerminalType,
) -> Result<Self, UsbError> {
if min_rate >= max_rate {
return Err(UsbError::InvalidState);
}
let ep_size = Self::calc_ep_size(format, channels, max_rate)?;
Ok(Self {
format,
channels,
rates: Rates::Continuous(min_rate, max_rate),
terminal_type,
ep_size,
})
}
fn calc_ep_size(format: Format, channels: u8, max_rate: u32) -> Result<u16, UsbError> {
let octets_per_frame = channels as u32 * format.bytes() as u32;
let size = octets_per_frame * max_rate / 1000;
if size > MAX_ISO_SIZE {
return Err(UsbError::BufferOverflow);
}
Ok(size as u16)
}
fn channel_config(&self) -> u16 {
match self.channels {
1 => 0x0001, 2 => 0x0003, 4 => 0x0033, 6 => 0x003F, 8 => 0x00FF, _ => 0x0003, }
}
}
#[derive(Default)]
pub struct AudioClassBuilder {
input: Option<StreamConfig>,
output: Option<StreamConfig>,
}
impl AudioClassBuilder {
pub fn new() -> Self {
Self {
input: None,
output: None,
}
}
pub fn input(mut self, cfg: StreamConfig) -> Self {
self.input = Some(cfg);
self
}
pub fn output(mut self, cfg: StreamConfig) -> Self {
self.output = Some(cfg);
self
}
pub fn build<B: UsbBus>(self, alloc: &UsbBusAllocator<B>) -> AudioClass<'_, B> {
let control_iface = alloc.interface();
let (in_ep, in_iface, in_cfg, in_alt) = if let Some(cfg) = self.input {
let iface = alloc.interface();
let ep = alloc.isochronous::<crate::endpoint::In>(
IsoSynchronization::Asynchronous,
IsoUsage::Data,
cfg.ep_size,
1,
);
(Some(ep), iface, Some(cfg), 0u8)
} else {
(None, InterfaceNumber::new(0), None, 0u8)
};
let (out_ep, out_iface, out_cfg, out_alt) = if let Some(cfg) = self.output {
let iface = alloc.interface();
let ep = alloc.isochronous::<crate::endpoint::Out>(
IsoSynchronization::Adaptive,
IsoUsage::Data,
cfg.ep_size,
1,
);
(Some(ep), iface, Some(cfg), 0u8)
} else {
(None, InterfaceNumber::new(0), None, 0u8)
};
AudioClass {
control_iface,
in_ep,
in_iface,
in_cfg,
in_alt,
out_ep,
out_iface,
out_cfg,
out_alt,
configured: false,
}
}
}
pub struct AudioClass<'a, B: UsbBus> {
control_iface: InterfaceNumber,
in_ep: Option<EndpointIn<'a, B>>,
in_iface: InterfaceNumber,
in_cfg: Option<StreamConfig>,
in_alt: u8,
out_ep: Option<EndpointOut<'a, B>>,
out_iface: InterfaceNumber,
out_cfg: Option<StreamConfig>,
out_alt: u8,
configured: bool,
}
impl<'a, B: UsbBus> AudioClass<'a, B> {
pub fn read(&self, buf: &mut [u8]) -> UsbResult<usize> {
let ep = self.out_ep.as_ref().ok_or(UsbError::InvalidState)?;
if !self.configured || self.out_alt == 0 {
return Err(UsbError::InvalidState);
}
ep.read(buf)
}
pub fn write(&self, buf: &[u8]) -> UsbResult<usize> {
let ep = self.in_ep.as_ref().ok_or(UsbError::InvalidState)?;
if !self.configured || self.in_alt == 0 {
return Err(UsbError::InvalidState);
}
ep.write(buf)
}
pub fn input_alt_setting(&self) -> Option<u8> {
self.in_cfg.as_ref().map(|_| self.in_alt)
}
pub fn output_alt_setting(&self) -> Option<u8> {
self.out_cfg.as_ref().map(|_| self.out_alt)
}
pub fn is_configured(&self) -> bool {
self.configured
}
pub fn output_active(&self) -> bool {
self.configured && self.out_alt != 0
}
pub fn input_active(&self) -> bool {
self.configured && self.in_alt != 0
}
fn streaming_count(&self) -> u8 {
self.in_cfg.is_some() as u8 + self.out_cfg.is_some() as u8
}
fn write_ac_header(&self, w: &mut DescriptorWriter) -> UsbResult<()> {
let n = self.streaming_count();
let total_len = self.ac_total_length();
let mut hdr = [
AC_HEADER,
0x00,
0x01, total_len as u8,
(total_len >> 8) as u8, n, 0x00,
0x00, ];
let mut idx = 6usize;
if self.in_cfg.is_some() {
hdr[idx] = self.in_iface.into();
idx += 1;
}
if self.out_cfg.is_some() {
hdr[idx] = self.out_iface.into();
idx += 1;
}
w.write(CS_INTERFACE, &hdr[..idx])
}
fn ac_total_length(&self) -> u16 {
let n = self.streaming_count() as u16;
let mut total: u16 = 8 + n;
for cfg in [&self.in_cfg, &self.out_cfg]
.iter()
.filter_map(|c| c.as_ref())
{
total += 12;
total += 8 + cfg.channels as u16;
total += 9;
}
total
}
fn fu_channels(&self, unit_id: u8) -> u8 {
if unit_id == TERM_ID_SPEAKER_FU {
self.out_cfg.as_ref().map_or(0, |c| c.channels)
} else if unit_id == TERM_ID_MIC_FU {
self.in_cfg.as_ref().map_or(0, |c| c.channels)
} else {
0
}
}
fn write_terminal_descriptors(
&self,
w: &mut DescriptorWriter,
cfg: &StreamConfig,
input_term_id: u8,
fu_id: u8,
output_term_id: u8,
is_input: bool,
) -> UsbResult<()> {
let tt: u16 = cfg.terminal_type.into();
let cc = cfg.channel_config();
let it_type = if is_input {
tt
} else {
TerminalType::UsbStreaming.into()
};
w.write(
CS_INTERFACE,
&[
AC_INPUT_TERMINAL,
input_term_id,
it_type as u8,
(it_type >> 8) as u8,
0x00, cfg.channels, cc as u8, (cc >> 8) as u8, 0x00, 0x00, ],
)?;
self.write_feature_unit(w, cfg, fu_id, input_term_id)?;
let ot_type = if is_input {
TerminalType::UsbStreaming.into()
} else {
tt
};
w.write(
CS_INTERFACE,
&[
AC_OUTPUT_TERMINAL,
output_term_id,
ot_type as u8,
(ot_type >> 8) as u8,
0x00, fu_id, 0x00, ],
)
}
fn write_feature_unit(
&self,
w: &mut DescriptorWriter,
cfg: &StreamConfig,
fu_id: u8,
source_id: u8,
) -> UsbResult<()> {
let ch = cfg.channels as usize;
let mut body = [0u8; 16]; body[0] = AC_FEATURE_UNIT;
body[1] = fu_id;
body[2] = source_id;
body[3] = 1; body[4] = FU_MUTE | FU_VOLUME; for i in 0..ch {
body[5 + i] = FU_VOLUME; }
body[5 + ch] = 0x00; let body_len = 6 + ch;
w.write(CS_INTERFACE, &body[..body_len])
}
fn write_as_descriptors(
&self,
w: &mut DescriptorWriter,
cfg: &StreamConfig,
iface: InterfaceNumber,
ep_addr: EndpointAddress,
is_input: bool,
) -> UsbResult<()> {
w.interface(iface, 0, UAC_CLASS, UAC_SUBCLASS_STREAMING, 0x00)?;
w.interface_alt(iface, 1, 1, UAC_CLASS, UAC_SUBCLASS_STREAMING, 0x00)?;
let term_link = if is_input {
TERM_ID_MIC_USB
} else {
TERM_ID_SPEAKER_USB
};
w.write(
CS_INTERFACE,
&[
AS_GENERAL,
term_link,
0x01, PCM_TAG as u8,
(PCM_TAG >> 8) as u8, ],
)?;
self.write_format_type(w, cfg)?;
let ep_type = if is_input {
EndpointType::Isochronous {
synchronization: IsoSynchronization::Asynchronous,
usage: IsoUsage::Data,
}
} else {
EndpointType::Isochronous {
synchronization: IsoSynchronization::Adaptive,
usage: IsoUsage::Data,
}
};
w.endpoint(ep_addr, ep_type, cfg.ep_size, 1)?;
w.write(
CS_ENDPOINT,
&[
EP_GENERAL, 0x00, 0x00, 0x00, 0x00, ],
)
}
fn write_format_type(&self, w: &mut DescriptorWriter, cfg: &StreamConfig) -> UsbResult<()> {
fn put_u24(buf: &mut [u8], pos: &mut usize, v: u32) {
buf[*pos] = v as u8;
*pos += 1;
buf[*pos] = (v >> 8) as u8;
*pos += 1;
buf[*pos] = (v >> 16) as u8;
*pos += 1;
}
let mut buf = [0u8; 64];
let mut i = 0usize;
buf[i] = AS_FORMAT_TYPE;
i += 1;
buf[i] = FORMAT_TYPE_I;
i += 1;
buf[i] = cfg.channels;
i += 1;
buf[i] = cfg.format.bytes();
i += 1;
buf[i] = cfg.format.bits();
i += 1;
match &cfg.rates {
Rates::Continuous(min, max) => {
buf[i] = 0x00;
i += 1;
put_u24(&mut buf, &mut i, *min);
put_u24(&mut buf, &mut i, *max);
}
Rates::Discrete(rates) => {
buf[i] = rates.len() as u8;
i += 1;
for &r in *rates {
put_u24(&mut buf, &mut i, r);
}
}
}
w.write(CS_INTERFACE, &buf[..i])
}
}
impl<B: UsbBus> UsbClass<B> for AudioClass<'_, B> {
fn configuration_descriptors(&self, w: &mut DescriptorWriter) -> UsbResult<()> {
w.interface(self.control_iface, 0, UAC_CLASS, UAC_SUBCLASS_CONTROL, 0x00)?;
self.write_ac_header(w)?;
if let Some(ref cfg) = self.in_cfg {
self.write_terminal_descriptors(
w,
cfg,
TERM_ID_MIC_IN,
TERM_ID_MIC_FU,
TERM_ID_MIC_USB,
true,
)?;
}
if let Some(ref cfg) = self.out_cfg {
self.write_terminal_descriptors(
w,
cfg,
TERM_ID_SPEAKER_USB,
TERM_ID_SPEAKER_FU,
TERM_ID_SPEAKER_OUT,
false,
)?;
}
if let Some(ref cfg) = self.in_cfg {
self.write_as_descriptors(
w,
cfg,
self.in_iface,
self.in_ep.as_ref().unwrap().address(),
true,
)?;
}
if let Some(ref cfg) = self.out_cfg {
self.write_as_descriptors(
w,
cfg,
self.out_iface,
self.out_ep.as_ref().unwrap().address(),
false,
)?;
}
Ok(())
}
fn control_in(&mut self, xfer: ControlIn<'_, B>) {
let req = xfer.request();
if req.request_type != RequestType::Class || req.recipient != Recipient::Interface {
return;
}
let unit_id = (req.index >> 8) as u8;
let cs = (req.value >> 8) as u8;
let channels = self.fu_channels(unit_id);
if channels == 0 {
return; }
match req.request {
CUR_GET if cs == FU_MUTE => {
let _ = xfer.accept_with(&[0x00]);
}
CUR_GET if cs == FU_VOLUME => {
let _ = xfer.accept_with(&[0x00, 0x00]);
}
MIN_GET if cs == FU_VOLUME => {
let _ = xfer.accept_with(&[0x00, 0x80]);
}
MAX_GET if cs == FU_VOLUME => {
let _ = xfer.accept_with(&[0x00, 0x00]);
}
RES_GET if cs == FU_VOLUME => {
let _ = xfer.accept_with(&[0x00, 0x01]);
}
_ => {
let _ = xfer.reject();
}
}
}
fn control_out(&mut self, xfer: ControlOut<'_, B>) {
let req = xfer.request();
if req.request_type != RequestType::Class || req.recipient != Recipient::Interface {
return;
}
let unit_id = (req.index >> 8) as u8;
let cs = (req.value >> 8) as u8;
if self.fu_channels(unit_id) == 0 {
return;
}
match req.request {
CUR_SET if cs == FU_MUTE => {
let _ = xfer.accept();
}
CUR_SET if cs == FU_VOLUME => {
let _ = xfer.accept();
}
_ => {
let _ = xfer.reject();
}
}
}
fn configure(&mut self) {
self.configured = true;
}
fn deconfigure(&mut self) {
self.configured = false;
self.in_alt = 0;
self.out_alt = 0;
}
fn reset(&mut self) {
self.configured = false;
self.in_alt = 0;
self.out_alt = 0;
}
fn alt_setting(&mut self, iface: InterfaceNumber) -> Option<u8> {
if self.in_cfg.is_some() && self.in_iface == iface {
return Some(self.in_alt);
}
if self.out_cfg.is_some() && self.out_iface == iface {
return Some(self.out_alt);
}
None
}
fn set_alt_setting(&mut self, iface: InterfaceNumber, alt: u8) -> bool {
if self.in_cfg.is_some() && self.in_iface == iface {
self.in_alt = alt;
return true;
}
if self.out_cfg.is_some() && self.out_iface == iface {
self.out_alt = alt;
return true;
}
false
}
}