arduino-audio-tools
Loading...
Searching...
No Matches
Classes | Public Member Functions | Protected Types | Protected Member Functions | Static Protected Member Functions | Protected Attributes | Static Protected Attributes | List of all members
USBAudioHostBase Class Referenceabstract

USB Audio Class (UAC1 and UAC2) host: reads PCM audio from an attached USB microphone and/or writes PCM audio to an attached USB speaker or headset, using the same API as the USB Audio device (USBAudioStream). More...

#include <USBAudioHostBase.h>

Inheritance diagram for USBAudioHostBase:
USBAudioStreamBase USBAudioHostEvents AudioStream VolumeSupport BaseStream AudioInfoSupport AudioInfoSource Stream Print USBAudioHostESP32 USBAudioHostTinyUSB USBAudioHostTinyUSBFreeRTOS

Classes

struct  AltSetting
 One alternate setting of an audio streaming interface. More...
 
struct  Entity
 Audio Control entity (terminal, unit or clock) for the topology walk. More...
 
struct  RateRange
 Range of supported sample rates (UAC2 clock source GET_RANGE) More...
 
struct  Stream
 State of one direction (microphone or speaker) More...
 

Public Member Functions

 USBAudioHostBase ()=default
 
 USBAudioHostBase (USBAudioConfig cfg)
 Constructor which provides the configuration at construction time.
 
virtual void addNotifyAudioChange (AudioInfoSupport &bi)
 Adds target to be notified about audio changes.
 
virtual AudioInfo audioInfo () override
 provides the actual input AudioInfo
 
virtual AudioInfo audioInfoOut ()
 
AudioInfo audioInfoRx () const
 Negotiated format of the microphone stream (readBytes())
 
AudioInfo audioInfoTx () const
 Negotiated format of the speaker stream (write())
 
uint16_t audioPacketSize () const
 
int available () override
 Bytes of received audio waiting in the RX buffer.
 
int availableForWrite () override
 Bytes of free space in the TX buffer.
 
bool begin ()
 Start the USB host stack with the current config. The attached device is opened as soon as it has been enumerated.
 
bool begin (const USBAudioConfig &cfg)
 Apply a config and start the USB audio host.
 
virtual BaseBuffer< uint8_t > & bufferRx ()=0
 Returns the RX audio buffer. Must be overridden by subclasses.
 
virtual BaseBuffer< uint8_t > & bufferTx ()=0
 Returns the TX audio buffer. Must be overridden by subclasses.
 
virtual void clearNotifyAudioChange ()
 Deletes all change notify subscriptions.
 
const USBAudioConfig & config () const
 Provides the active configuration.
 
USBAudioConfig defaultConfig (RxTxMode mode=RXTX_MODE)
 Returns a default configuration for the requested direction. RX_MODE reads from a USB microphone, TX_MODE writes to a USB speaker, RXTX_MODE does both (headset).
 
void end ()
 Stop the streams and clear the buffers. The host stack keeps running, so the device is opened again with the next begin().
 
virtual void flush () override
 
virtual int getActualCore () const
 Returns the actual core on which the call is running (for RP2040)
 
uint32_t getRxDroppedBytes () const
 Bytes discarded because bufferRx() was full.
 
uint32_t getRxTotalBytes () const
 Total bytes received from the microphone.
 
uint32_t getRxXferCount () const
 
uint32_t getTxUnderflowBytes () const
 Bytes of silence which were sent because bufferTx() was empty.
 
uint32_t getTxXferCount () const
 Number of isochronous OUT packets which were provided to the speaker.
 
bool hasMicrophone () const
 True if the attached device provides a microphone (RX)
 
bool hasSpeaker () const
 True if the attached device provides a speaker (TX)
 
bool isEpInEnabled () const
 Returns true if the IN endpoint is enabled.
 
bool isEpOutEnabled () const
 Returns true if the OUT endpoint is enabled.
 
bool isMute (uint8_t channel=0) const
 Returns the current mute state for the given channel.
 
bool isNotifyActive ()
 Checks if the automatic AudioInfo update is active.
 
bool isStreamingActive () const
 Returns true if either the TX or RX stream is open.
 
bool isStreamingActiveRx () const override
 Returns true if the microphone stream (used by readBytes()) is open.
 
bool isStreamingActiveTx () const override
 Returns true if the speaker stream (used by write()) is open.
 
bool mounted () override
 Returns true if an audio device is attached and configured.
 
 operator bool () override
 
uint16_t pid () const
 Product id of the attached device (0 if none)
 
size_t readBytes (uint8_t *buffer, size_t bufsize)
 Receive audio data from the USB peer. Until bufferRx() has filled past config.rx_start_fill_percent at least once after begin(), no data is returned. This is a one-shot startup prime only – once reached, readBytes() keeps draining normally for the rest of the session and is not gated again by later underruns.
 
virtual size_t readSilence (uint8_t *buffer, size_t length)
 Source to generate silence: just sets the buffer to 0.
 
virtual bool removeNotifyAudioChange (AudioInfoSupport &bi)
 Removes a target in order not to be notified about audio changes.
 
virtual void serviceUSB ()=0
 Process pending USB events on platforms where the application drives the stack. No-op where a dedicated task runs the stack.
 
void setAudioInfo (AudioInfo info) override
 Defines the audio format. Before begin() all fields can be changed; once started, a new sample rate is re-negotiated with the attached device.
 
bool setMute (bool m, uint8_t channel=0)
 Set the mute state for a channel and notify the USB peer.
 
void setMuteCallback (std::function< void(bool, uint8_t)> cb)
 Register a callback invoked when the mute state changes.
 
void setNotifyActive (bool flag)
 Deactivate/Reactivate automatic AudioInfo updates: (default is active)
 
void setSampleRateCallback (std::function< void(uint32_t)> cb)
 Register a callback invoked when the sample rate changes.
 
void setStreamingStateCallback (std::function< void(bool, bool)> cb)
 Register a callback invoked when the streaming state changes (a streaming interface was opened or closed).
 
bool setVolume (float vol, uint8_t channel)
 Set the volume for a channel and notify the USB peer.
 
bool setVolume (float volume) override
 sets the volume for the master channel (channel 0)
 
void setVolumeCallback (std::function< void(float, uint8_t)> cb)
 Register a callback invoked when the volume changes.
 
void setWriteBufferSize (int size)
 
uint8_t uacVersion () const
 USB Audio Class version of the attached device: 1 or 2 (0 if none)
 
uint16_t vid () const
 Vendor id of the attached device (0 if none)
 
float volume () override
 gets the volume for the master channel (channel 0)
 
float volume (uint8_t channel)
 Returns the current volume for the given channel.
 
size_t write (const uint8_t *data, size_t len)
 Send audio data to the USB peer. Silently discards data while the TX stream is not open so StreamCopy doesn't report write errors before streaming starts.
 
virtual size_t write (uint8_t ch) override
 
virtual void writeSilence (size_t len)
 Writes len bytes of silence (=0).
 

Protected Types

enum class  Step : uint8_t {
  Idle , StopRx , StopTx , ClockRangeHeaderRx ,
  ClockRangeRx , ClockRangeHeaderTx , ClockRangeTx , Select ,
  SetClockRx , SetInterfaceRx , OpenRx , SetEpRateRx ,
  VolumeRangeRx , VolumeMaxRx , SetClockTx , SetInterfaceTx ,
  OpenTx , SetEpRateTx , VolumeRangeTx , VolumeMaxTx ,
  Done
}
 Steps of the (re)configuration state machine. More...
 

Protected Member Functions

virtual USBAudioHostBackend & backend ()=0
 Returns the backend used for all USB host stack calls.
 
bool beginUSB () override
 Override in platform subclasses to start the USB stack.
 
bool clockRange (Stream &s, std::vector< RateRange > &ranges, Step following)
 
bool clockRangeHeader (Stream &s, std::vector< RateRange > &ranges, Step on_success, Step skip)
 
uint32_t closestRate (const AltSetting &a, const std::vector< RateRange > &clock, uint32_t wanted)
 Supported sample rate which is closest to the wanted rate (0 if none)
 
bool configChanged (const USBAudioConfig &n)
 
bool executeStep ()
 
Entity * findEntity (uint8_t id)
 
void finishMount ()
 
void finishRuntimeRequest ()
 
bool fitsBandwidth (const AltSetting &a, uint32_t rate)
 
float getVolumeExt (uint8_t channel) const
 Returns the effective volume for a per-channel index (1-based). Combines master volume (index 0) with per-channel volume and mute.
 
bool issueControl (uint8_t request_type, uint8_t request, uint16_t value, uint16_t index, uint16_t length)
 
bool issueSetInterface (uint8_t itf, uint8_t alt)
 
void next (Step s)
 Advance to the next step.
 
virtual int not_supported (int out, const char *msg="")
 
void notifyAudioChange (AudioInfo info)
 
void notifyStreamingState ()
 
uint16_t onAttach (uint8_t daddr, uint16_t vid, uint16_t pid, const uint8_t *desc, uint16_t len) override
 
void onConfigured (uint8_t daddr) override
 
void onControlComplete (bool ok, uint16_t len) override
 
void onDetach (uint8_t daddr) override
 The device was removed.
 
void onFeedback (const uint8_t *data, uint16_t len)
 Explicit feedback from the speaker: samples per packet.
 
void onIsoIn (UsbHostStreamRole role, const uint8_t *data, uint16_t len) override
 One isochronous IN packet was received (RxData or Feedback).
 
uint16_t onIsoOut (uint8_t *data, uint16_t max) override
 
void onMuteChanged (uint8_t channel) override
 
void onVolumeChanged (uint8_t channel) override
 
void openStream (Stream &s, bool is_rx)
 
uint16_t packetsPerSecond (const AltSetting &a)
 
void parseAcDescriptor (const uint8_t *p)
 Audio Control interface: header, terminals, units and clocks.
 
void parseAsDescriptor (AltSetting &a, const uint8_t *p)
 Audio Streaming interface: AS_GENERAL and FORMAT_TYPE descriptors.
 
void parseClockRange (std::vector< RateRange > &ranges)
 Parses a UAC2 GET_RANGE (layout 3: 32 bit) response for the clock.
 
uint16_t parseConfiguration (const uint8_t *desc, uint16_t len)
 
void parseFeatureUnitControls (Entity &e, const uint8_t *p, bool v2)
 Determines which channels provide a host programmable mute / volume.
 
void poll ()
 Called regularly from the USB stack context.
 
void processUSB ()
 
template<typename T >
void processVolume (T *data, size_t sample_count)
 
void processVolume (uint8_t *data, size_t len)
 Process audio data for volume control.
 
void refillReadBuffer ()
 Refill small read buffer (e.g. 8 bytes) to avoid single byte reads when calling read()
 
bool requestClockRange (Stream &s, uint16_t len)
 
bool requestFeature (Stream &s, uint8_t selector, uint8_t ch, int16_t value)
 
bool requestSetClock (Stream &s)
 
bool requestSetEpRate (Stream &s)
 
bool requestVolumeRange (Stream &s, bool max)
 
void resetDevice ()
 
virtual void resizeBuffers ()=0
 Resize the platform audio buffers.
 
uint8_t resolveClock (uint8_t id)
 Follow clock selectors and multipliers to the clock source.
 
void resolveTopology (Stream &s, bool is_rx)
 
void run ()
 Runs the state machine until a control request is in flight.
 
bool selectAlt (Stream &s, const std::vector< RateRange > &clock, AudioInfo &negotiated)
 Selects the alternate setting which matches the requested format best.
 
bool sendFeature (bool is_volume, uint8_t ch)
 
bool sendFeatureFor (Stream &s)
 
bool sendFeatureNextStream ()
 
bool setClock (Stream &s, Step following)
 
void setConfig (const USBAudioConfig &cfg)
 Set the USB audio configuration (use begin(cfg) instead).
 
bool setEpRate (Stream &s, Step following)
 
bool setInterface (Stream &s, Step on_success, Step skip)
 
void setupVolumeState ()
 (Re)sizes the volume and mute state: master (index 0) + one per channel
 
void startRuntimeRequest ()
 Sends the next queued volume or mute change.
 
bool stopStream (Stream &s, Step following)
 Stop streaming before a reconfiguration: select alt 0.
 
bool supportsRate (const AltSetting &a, const std::vector< RateRange > &clock, uint32_t rate)
 True if the alternate setting supports the sample rate.
 
void updateBufferSize ()
 
bool volumeRange (Stream &s, bool max, Step on_success, Step skip)
 

Static Protected Member Functions

static uint32_t descU24 (const uint8_t *p)
 
static int16_t floatToUac2 (float vol)
 Convert linear volume (0.0–1.0) to UAC2 int16 (1/256 dB). Linear mapping: 0.0 → -100 dB (min), 1.0 → 0 dB (max).
 
static bool isValidBitsPerSample (uint8_t bps)
 
static uint16_t packetSizeFor (const AudioInfo &info)
 Bytes of one 1 ms packet for the indicated format (+1 sample margin)
 
static int16_t toDeviceVolume (const Stream &s, float vol)
 Linear mapping of 0.0..1.0 to the volume range of the device.
 
static float uac2ToFloat (int16_t v)
 Convert UAC2 int16 (1/256 dB) to linear volume (0.0–1.0). Linear mapping within the -100..0 dB range reported by GET_RANGE.
 
static uint8_t volumeRangeChannel (const Stream &s)
 Channel used to determine the volume range.
 

Protected Attributes

int _timeout = 10
 
volatile bool attached_ = false
 
uint16_t buffer_bytes_ = 0
 
std::vector< RateRange > clock_ranges_rx_
 
std::vector< RateRange > clock_ranges_tx_
 
USBAudioConfig config_
 
volatile bool configured_ = false
 
int core = -1
 
uint8_t ctrl_buf_ [kCtrlBufSize] = {}
 
bool ctrl_busy_ = false
 
uint16_t ctrl_len_ = 0
 
bool ctrl_ok_ = false
 
uint32_t ctrl_start_ms_ = 0
 
uint8_t daddr_ = 0
 
std::vector< Entity > entities_
 
bool in_run_ = false
 
AudioInfo info
 
bool is_active_ = false
 
bool is_notify_active = true
 
bool is_started_ = false
 
uint8_t itf_num_ac_ = 0
 
volatile bool mounted_ = false
 
std::vector< bool > mute_
 
std::function< void(bool, uint8_t)> mute_cb_
 
std::vector< uint8_t > mute_pending_
 
Vector< AudioInfoSupport * > notify_vector
 
uint8_t pending_channel_ = 0
 
bool pending_is_volume_ = false
 
Stream * pending_stream_ = nullptr
 
uint16_t pid_ = 0
 
volatile bool reconfigure_pending_ = false
 
bool reconfiguring_ = false
 
bool restart_pending_ = false
 
bool run_again_ = false
 
Stream rx_
 
AudioInfo rx_info_
 
bool rx_primed_ = false
 
std::function< void(uint32_t)> sample_rate_cb_
 
UsbSetupPacket setup_
 
Step step_ = Step::Idle
 
bool step_done_ = false
 
std::function< void(bool, bool)> streaming_state_cb_
 
RingBuffer< uint8_t > tmp_in {0}
 
RingBuffer< uint8_t > tmp_out {0}
 
Stream tx_
 
AudioInfo tx_info_
 
uint8_t uac_version_ = 0
 
bool usb_task_active_ = false
 
uint16_t vid_ = 0
 
std::vector< float > volume_
 
std::function< void(float, uint8_t)> volume_cb_
 
std::vector< uint8_t > volume_pending_
 
float volume_value = 1.0f
 
int write_buffer_size = MAX_SINGLE_CHARS
 

Static Protected Attributes

static constexpr uint16_t kCtrlBufSize = 2 + 12 * 24
 
static constexpr uint8_t kMaxChannels = 8
 
static constexpr uint8_t kMaxRates = 16
 
static constexpr uint8_t kReqInItf = 0xA1
 
static constexpr uint8_t kReqOutEp = 0x22
 
static constexpr uint8_t kReqOutItf = 0x21
 
static constexpr int16_t kVolumeMinDb256 = -25600
 Convert AudioTools volume (0.0–1.0) to UAC2 int16 (1/256 dB). 0.0 maps to 0x8000 (silence), 1.0 maps to 0 (0 dB).
 

Detailed Description

USB Audio Class (UAC1 and UAC2) host: reads PCM audio from an attached USB microphone and/or writes PCM audio to an attached USB speaker or headset, using the same API as the USB Audio device (USBAudioStream).

Directions (the RxTxMode is used the same way as for the device):

The requested sample_rate, channels and bits_per_sample are matched against the alternate settings of the attached device. When the device can not provide the requested format and config.host_apply_device_format is true, the closest format is used, stored in the configuration and reported to the subscribed listeners (setAudioInfo()). In RXTX_MODE the format of the RX stream is reported; use audioInfoTx() for the TX format.

setVolume() and setMute() are forwarded to the Feature Unit of the attached device (all active directions); setAudioInfo() with a new sample rate re-negotiates the streams. When config.volume_active is true, the volume is in addition applied in software.

This class implements the USB stack independent UAC logic: the stack calls are delegated to a USBAudioHostBackend.

Note
Use the USBAudioHostStream type alias instead of this class.
Author
Phil Schatzmann

Member Enumeration Documentation

◆ Step

enum class Step : uint8_t
strongprotected

Steps of the (re)configuration state machine.

Enumerator
Idle 
StopRx 
StopTx 
ClockRangeHeaderRx 
ClockRangeRx 
ClockRangeHeaderTx 
ClockRangeTx 
Select 
SetClockRx 
SetInterfaceRx 
OpenRx 
SetEpRateRx 
VolumeRangeRx 
VolumeMaxRx 
SetClockTx 
SetInterfaceTx 
OpenTx 
SetEpRateTx 
VolumeRangeTx 
VolumeMaxTx 
Done 

Constructor & Destructor Documentation

◆ USBAudioHostBase() [1/2]

USBAudioHostBase ( )
default

◆ USBAudioHostBase() [2/2]

Constructor which provides the configuration at construction time.

Member Function Documentation

◆ addNotifyAudioChange()

virtual void addNotifyAudioChange ( AudioInfoSupport &  bi)
inlinevirtualinherited

◆ audioInfo()

virtual AudioInfo audioInfo ( )
inlineoverridevirtualinherited

◆ audioInfoOut()

virtual AudioInfo audioInfoOut ( )
inlinevirtualinherited

◆ audioInfoRx()

AudioInfo audioInfoRx ( ) const
inline

Negotiated format of the microphone stream (readBytes())

◆ audioInfoTx()

AudioInfo audioInfoTx ( ) const
inline

Negotiated format of the speaker stream (write())

◆ audioPacketSize()

uint16_t audioPacketSize ( ) const
inline

One isochronous packet (1 ms at full speed) of the largest stream in bytes

◆ available()

int available ( )
inlineoverridevirtualinherited

Bytes of received audio waiting in the RX buffer.

Reimplemented from BaseStream.

◆ availableForWrite()

int availableForWrite ( )
inlineoverridevirtualinherited

Bytes of free space in the TX buffer.

Reimplemented from BaseStream.

◆ backend()

virtual USBAudioHostBackend & backend ( )
protectedpure virtual

Returns the backend used for all USB host stack calls.

Implemented in USBAudioHostESP32, and USBAudioHostTinyUSB.

◆ begin() [1/2]

bool begin ( )
inlinevirtual

Start the USB host stack with the current config. The attached device is opened as soon as it has been enumerated.

Reimplemented from BaseStream.

◆ begin() [2/2]

bool begin ( const USBAudioConfig &  cfg)
inline

Apply a config and start the USB audio host.

Returns
true on success.

◆ beginUSB()

bool beginUSB ( )
inlineoverrideprotectedvirtual

Override in platform subclasses to start the USB stack.

Implements USBAudioStreamBase.

Reimplemented in USBAudioHostESP32, and USBAudioHostTinyUSBFreeRTOS.

◆ bufferRx()

virtual BaseBuffer< uint8_t > & bufferRx ( )
pure virtualinherited

◆ bufferTx()

virtual BaseBuffer< uint8_t > & bufferTx ( )
pure virtualinherited

◆ clearNotifyAudioChange()

virtual void clearNotifyAudioChange ( )
inlinevirtualinherited

Deletes all change notify subscriptions.

Reimplemented in RTSPClient< TcpClient, UdpSocket >.

◆ clockRange()

bool clockRange ( Stream &  s,
std::vector< RateRange > &  ranges,
Step  following 
)
inlineprotected

◆ clockRangeHeader()

bool clockRangeHeader ( Stream &  s,
std::vector< RateRange > &  ranges,
Step  on_success,
Step  skip 
)
inlineprotected

◆ closestRate()

uint32_t closestRate ( const AltSetting &  a,
const std::vector< RateRange > &  clock,
uint32_t  wanted 
)
inlineprotected

Supported sample rate which is closest to the wanted rate (0 if none)

◆ config()

const USBAudioConfig & config ( ) const
inlineinherited

Provides the active configuration.

◆ configChanged()

bool configChanged ( const USBAudioConfig &  n)
inlineprotectedinherited

◆ defaultConfig()

USBAudioConfig defaultConfig ( RxTxMode  mode = RXTX_MODE)
inline

Returns a default configuration for the requested direction. RX_MODE reads from a USB microphone, TX_MODE writes to a USB speaker, RXTX_MODE does both (headset).

◆ descU24()

static uint32_t descU24 ( const uint8_t *  p)
inlinestaticprotected

◆ end()

void end ( )
inlinevirtual

Stop the streams and clear the buffers. The host stack keeps running, so the device is opened again with the next begin().

Reimplemented from BaseStream.

◆ executeStep()

bool executeStep ( )
inlineprotected

Executes the current step. Returns false if the step could not be started and needs to be retried later.

◆ findEntity()

Entity * findEntity ( uint8_t  id)
inlineprotected

◆ finishMount()

void finishMount ( )
inlineprotected

◆ finishRuntimeRequest()

void finishRuntimeRequest ( )
inlineprotected

◆ fitsBandwidth()

bool fitsBandwidth ( const AltSetting &  a,
uint32_t  rate 
)
inlineprotected

◆ floatToUac2()

static int16_t floatToUac2 ( float  vol)
inlinestaticprotectedinherited

Convert linear volume (0.0–1.0) to UAC2 int16 (1/256 dB). Linear mapping: 0.0 → -100 dB (min), 1.0 → 0 dB (max).

◆ flush()

virtual void flush ( )
inlineoverridevirtualinherited

◆ getActualCore()

virtual int getActualCore ( ) const
inlinevirtualinherited

Returns the actual core on which the call is running (for RP2040)

Reimplemented in USBAudioDeviceBase, USBAudioDeviceESP32, USBAudioDeviceTinyUSB, and USBAudioHostESP32.

◆ getRxDroppedBytes()

uint32_t getRxDroppedBytes ( ) const
inline

Bytes discarded because bufferRx() was full.

◆ getRxTotalBytes()

uint32_t getRxTotalBytes ( ) const
inline

Total bytes received from the microphone.

◆ getRxXferCount()

uint32_t getRxXferCount ( ) const
inline

Number of isochronous IN packets which were received from the microphone

◆ getTxUnderflowBytes()

uint32_t getTxUnderflowBytes ( ) const
inline

Bytes of silence which were sent because bufferTx() was empty.

◆ getTxXferCount()

uint32_t getTxXferCount ( ) const
inline

Number of isochronous OUT packets which were provided to the speaker.

◆ getVolumeExt()

float getVolumeExt ( uint8_t  channel) const
inlineprotectedinherited

Returns the effective volume for a per-channel index (1-based). Combines master volume (index 0) with per-channel volume and mute.

◆ hasMicrophone()

bool hasMicrophone ( ) const
inline

True if the attached device provides a microphone (RX)

◆ hasSpeaker()

bool hasSpeaker ( ) const
inline

True if the attached device provides a speaker (TX)

◆ isEpInEnabled()

bool isEpInEnabled ( ) const
inlineinherited

Returns true if the IN endpoint is enabled.

◆ isEpOutEnabled()

bool isEpOutEnabled ( ) const
inlineinherited

Returns true if the OUT endpoint is enabled.

◆ isMute()

bool isMute ( uint8_t  channel = 0) const
inlineinherited

Returns the current mute state for the given channel.

Parameters
channel0 = master, 1..N = per-channel.

◆ isNotifyActive()

bool isNotifyActive ( )
inlineinherited

Checks if the automatic AudioInfo update is active.

◆ isStreamingActive()

bool isStreamingActive ( ) const
inlineinherited

Returns true if either the TX or RX stream is open.

◆ isStreamingActiveRx()

bool isStreamingActiveRx ( ) const
inlineoverridevirtual

Returns true if the microphone stream (used by readBytes()) is open.

Implements USBAudioStreamBase.

◆ isStreamingActiveTx()

bool isStreamingActiveTx ( ) const
inlineoverridevirtual

Returns true if the speaker stream (used by write()) is open.

Implements USBAudioStreamBase.

◆ issueControl()

bool issueControl ( uint8_t  request_type,
uint8_t  request,
uint16_t  value,
uint16_t  index,
uint16_t  length 
)
inlineprotected

◆ issueSetInterface()

bool issueSetInterface ( uint8_t  itf,
uint8_t  alt 
)
inlineprotected

◆ isValidBitsPerSample()

static bool isValidBitsPerSample ( uint8_t  bps)
inlinestaticprotectedinherited

◆ mounted()

bool mounted ( )
inlineoverridevirtual

Returns true if an audio device is attached and configured.

Implements USBAudioStreamBase.

◆ next()

void next ( Step  s)
inlineprotected

Advance to the next step.

◆ not_supported()

virtual int not_supported ( int  out,
const char *  msg = "" 
)
inlineprotectedvirtualinherited

◆ notifyAudioChange()

void notifyAudioChange ( AudioInfo  info)
inlineprotectedinherited

◆ notifyStreamingState()

void notifyStreamingState ( )
inlineprotectedinherited

◆ onAttach()

uint16_t onAttach ( uint8_t  daddr,
uint16_t  vid,
uint16_t  pid,
const uint8_t *  desc,
uint16_t  len 
)
inlineoverrideprotectedvirtual

A device was enumerated: desc points to the descriptors starting with an Audio Control interface descriptor and len is the number of bytes which are available after it. Returns the number of bytes which belong to the audio function (0 if the interface was not accepted).

Implements USBAudioHostEvents.

◆ onConfigured()

void onConfigured ( uint8_t  daddr)
inlineoverrideprotectedvirtual

The device configuration is active: the class logic can start to select the alternate settings and open the streaming endpoints.

Implements USBAudioHostEvents.

◆ onControlComplete()

void onControlComplete ( bool  ok,
uint16_t  len 
)
inlineoverrideprotectedvirtual

Completion of control() or setInterface(). For IN requests len is the number of bytes which were received into the request buffer.

Implements USBAudioHostEvents.

◆ onDetach()

void onDetach ( uint8_t  daddr)
inlineoverrideprotectedvirtual

The device was removed.

Implements USBAudioHostEvents.

◆ onFeedback()

void onFeedback ( const uint8_t *  data,
uint16_t  len 
)
inlineprotected

Explicit feedback from the speaker: samples per packet.

◆ onIsoIn()

void onIsoIn ( UsbHostStreamRole  role,
const uint8_t *  data,
uint16_t  len 
)
inlineoverrideprotectedvirtual

One isochronous IN packet was received (RxData or Feedback).

Implements USBAudioHostEvents.

◆ onIsoOut()

uint16_t onIsoOut ( uint8_t *  data,
uint16_t  max 
)
inlineoverrideprotectedvirtual

Provide the next isochronous OUT packet (TxData): fill at most max bytes into data and return the packet length.

Implements USBAudioHostEvents.

◆ onMuteChanged()

void onMuteChanged ( uint8_t  )
inlineoverrideprotectedvirtual

Called by setMute() after the state was updated: propagate the change to the USB peer.

Reimplemented from USBAudioStreamBase.

◆ onVolumeChanged()

void onVolumeChanged ( uint8_t  )
inlineoverrideprotectedvirtual

Called by setVolume() after the state was updated: propagate the change to the USB peer.

Reimplemented from USBAudioStreamBase.

◆ openStream()

void openStream ( Stream &  s,
bool  is_rx 
)
inlineprotected

◆ operator bool()

operator bool ( )
inlineoverridevirtualinherited

Returns true when begin() has been called and the USB connection is established.

Reimplemented from AudioStream.

◆ packetSizeFor()

static uint16_t packetSizeFor ( const AudioInfo &  info)
inlinestaticprotected

Bytes of one 1 ms packet for the indicated format (+1 sample margin)

◆ packetsPerSecond()

uint16_t packetsPerSecond ( const AltSetting &  a)
inlineprotected

◆ parseAcDescriptor()

void parseAcDescriptor ( const uint8_t *  p)
inlineprotected

Audio Control interface: header, terminals, units and clocks.

◆ parseAsDescriptor()

void parseAsDescriptor ( AltSetting &  a,
const uint8_t *  p 
)
inlineprotected

Audio Streaming interface: AS_GENERAL and FORMAT_TYPE descriptors.

◆ parseClockRange()

void parseClockRange ( std::vector< RateRange > &  ranges)
inlineprotected

Parses a UAC2 GET_RANGE (layout 3: 32 bit) response for the clock.

◆ parseConfiguration()

uint16_t parseConfiguration ( const uint8_t *  desc,
uint16_t  len 
)
inlineprotected

Parses the audio function which starts with the AC interface at desc. Returns the number of bytes which belong to the audio function.

◆ parseFeatureUnitControls()

void parseFeatureUnitControls ( Entity &  e,
const uint8_t *  p,
bool  v2 
)
inlineprotected

Determines which channels provide a host programmable mute / volume.

◆ pid()

uint16_t pid ( ) const
inline

Product id of the attached device (0 if none)

◆ poll()

void poll ( )
inlineprotected

Called regularly from the USB stack context.

◆ processUSB()

void processUSB ( )
inlineprotected

Pump the USB stack and process queued requests: called by the platform specific serviceUSB() or USB task.

◆ processVolume() [1/2]

template<typename T >
void processVolume ( T *  data,
size_t  sample_count 
)
inlineprotectedinherited

◆ processVolume() [2/2]

void processVolume ( uint8_t *  data,
size_t  len 
)
inlineprotectedinherited

Process audio data for volume control.

◆ readBytes()

size_t readBytes ( uint8_t *  buffer,
size_t  bufsize 
)
inlinevirtualinherited

Receive audio data from the USB peer. Until bufferRx() has filled past config.rx_start_fill_percent at least once after begin(), no data is returned. This is a one-shot startup prime only – once reached, readBytes() keeps draining normally for the rest of the session and is not gated again by later underruns.

Reimplemented from AudioStream.

◆ readSilence()

virtual size_t readSilence ( uint8_t *  buffer,
size_t  length 
)
inlinevirtualinherited

Source to generate silence: just sets the buffer to 0.

◆ refillReadBuffer()

void refillReadBuffer ( )
inlineprotectedinherited

Refill small read buffer (e.g. 8 bytes) to avoid single byte reads when calling read()

◆ removeNotifyAudioChange()

virtual bool removeNotifyAudioChange ( AudioInfoSupport &  bi)
inlinevirtualinherited

Removes a target in order not to be notified about audio changes.

Reimplemented in RTSPClient< TcpClient, UdpSocket >.

◆ requestClockRange()

bool requestClockRange ( Stream &  s,
uint16_t  len 
)
inlineprotected

◆ requestFeature()

bool requestFeature ( Stream &  s,
uint8_t  selector,
uint8_t  ch,
int16_t  value 
)
inlineprotected

◆ requestSetClock()

bool requestSetClock ( Stream &  s)
inlineprotected

◆ requestSetEpRate()

bool requestSetEpRate ( Stream &  s)
inlineprotected

◆ requestVolumeRange()

bool requestVolumeRange ( Stream &  s,
bool  max 
)
inlineprotected

◆ resetDevice()

void resetDevice ( )
inlineprotected

◆ resizeBuffers()

virtual void resizeBuffers ( )
protectedpure virtualinherited

◆ resolveClock()

uint8_t resolveClock ( uint8_t  id)
inlineprotected

Follow clock selectors and multipliers to the clock source.

◆ resolveTopology()

void resolveTopology ( Stream &  s,
bool  is_rx 
)
inlineprotected

Finds the Feature Unit and the Clock Source of a stream by following the entity links of its USB streaming terminal.

◆ run()

void run ( )
inlineprotected

Runs the state machine until a control request is in flight.

◆ selectAlt()

bool selectAlt ( Stream &  s,
const std::vector< RateRange > &  clock,
AudioInfo &  negotiated 
)
inlineprotected

Selects the alternate setting which matches the requested format best.

◆ sendFeature()

bool sendFeature ( bool  is_volume,
uint8_t  ch 
)
inlineprotected

Sends the volume or mute of a channel to the next stream which supports it. Returns true if a request was issued.

◆ sendFeatureFor()

bool sendFeatureFor ( Stream &  s)
inlineprotected

◆ sendFeatureNextStream()

bool sendFeatureNextStream ( )
inlineprotected

◆ serviceUSB()

virtual void serviceUSB ( )
pure virtualinherited

Process pending USB events on platforms where the application drives the stack. No-op where a dedicated task runs the stack.

Implemented in USBAudioDeviceESP32, USBAudioDeviceRenesas, USBAudioDeviceTinyUSB, USBAudioHostESP32, USBAudioHostTinyUSB, and USBAudioDeviceBase.

◆ setAudioInfo()

void setAudioInfo ( AudioInfo  info)
inlineoverridevirtual

Defines the audio format. Before begin() all fields can be changed; once started, a new sample rate is re-negotiated with the attached device.

Reimplemented from AudioStream.

◆ setClock()

bool setClock ( Stream &  s,
Step  following 
)
inlineprotected

◆ setConfig()

void setConfig ( const USBAudioConfig &  cfg)
inlineprotectedinherited

Set the USB audio configuration (use begin(cfg) instead).

◆ setEpRate()

bool setEpRate ( Stream &  s,
Step  following 
)
inlineprotected

◆ setInterface()

bool setInterface ( Stream &  s,
Step  on_success,
Step  skip 
)
inlineprotected

◆ setMute()

bool setMute ( bool  m,
uint8_t  channel = 0 
)
inlineinherited

Set the mute state for a channel and notify the USB peer.

Parameters
mtrue = muted, false = unmuted.
channel0 = master, 1..N = per-channel.
Returns
true if the channel index was valid.

◆ setMuteCallback()

void setMuteCallback ( std::function< void(bool, uint8_t)>  cb)
inlineinherited

Register a callback invoked when the mute state changes.

Parameters
cbCallback receiving (bool muted, uint8_t channel).

◆ setNotifyActive()

void setNotifyActive ( bool  flag)
inlineinherited

Deactivate/Reactivate automatic AudioInfo updates: (default is active)

◆ setSampleRateCallback()

void setSampleRateCallback ( std::function< void(uint32_t)>  cb)
inlineinherited

Register a callback invoked when the sample rate changes.

Parameters
cbCallback receiving the new rate in Hz.

◆ setStreamingStateCallback()

void setStreamingStateCallback ( std::function< void(bool, bool)>  cb)
inlineinherited

Register a callback invoked when the streaming state changes (a streaming interface was opened or closed).

Parameters
cbCallback receiving (bool active_tx, bool active_rx).

◆ setupVolumeState()

void setupVolumeState ( )
inlineprotectedinherited

(Re)sizes the volume and mute state: master (index 0) + one per channel

◆ setVolume() [1/2]

bool setVolume ( float  vol,
uint8_t  channel 
)
inlineinherited

Set the volume for a channel and notify the USB peer.

Parameters
volVolume as a float 0.0 (silence) to 1.0 (0 dB).
channel0 = master, 1..N = per-channel.
Returns
true if the channel index was valid.

◆ setVolume() [2/2]

bool setVolume ( float  volume)
inlineoverridevirtualinherited

sets the volume for the master channel (channel 0)

Reimplemented from VolumeSupport.

◆ setVolumeCallback()

void setVolumeCallback ( std::function< void(float, uint8_t)>  cb)
inlineinherited

Register a callback invoked when the volume changes.

Parameters
cbCallback receiving (float volume, uint8_t channel).

◆ setWriteBufferSize()

void setWriteBufferSize ( int  size)
inlineinherited

◆ startRuntimeRequest()

void startRuntimeRequest ( )
inlineprotected

Sends the next queued volume or mute change.

◆ stopStream()

bool stopStream ( Stream &  s,
Step  following 
)
inlineprotected

Stop streaming before a reconfiguration: select alt 0.

◆ supportsRate()

bool supportsRate ( const AltSetting &  a,
const std::vector< RateRange > &  clock,
uint32_t  rate 
)
inlineprotected

True if the alternate setting supports the sample rate.

◆ toDeviceVolume()

static int16_t toDeviceVolume ( const Stream &  s,
float  vol 
)
inlinestaticprotected

Linear mapping of 0.0..1.0 to the volume range of the device.

◆ uac2ToFloat()

static float uac2ToFloat ( int16_t  v)
inlinestaticprotectedinherited

Convert UAC2 int16 (1/256 dB) to linear volume (0.0–1.0). Linear mapping within the -100..0 dB range reported by GET_RANGE.

◆ uacVersion()

uint8_t uacVersion ( ) const
inline

USB Audio Class version of the attached device: 1 or 2 (0 if none)

◆ updateBufferSize()

void updateBufferSize ( )
inlineprotected

Make sure that the buffers can hold fifo_packets packets of the negotiated format

◆ vid()

uint16_t vid ( ) const
inline

Vendor id of the attached device (0 if none)

◆ volume() [1/2]

float volume ( )
inlineoverridevirtualinherited

gets the volume for the master channel (channel 0)

Reimplemented from VolumeSupport.

◆ volume() [2/2]

float volume ( uint8_t  channel)
inlineinherited

Returns the current volume for the given channel.

Parameters
channel0 = master, 1..N = per-channel.
Returns
Volume as a float in the range 0.0 (silence) to 1.0 (0 dB).

◆ volumeRange()

bool volumeRange ( Stream &  s,
bool  max,
Step  on_success,
Step  skip 
)
inlineprotected

◆ volumeRangeChannel()

static uint8_t volumeRangeChannel ( const Stream &  s)
inlinestaticprotected

Channel used to determine the volume range.

◆ write() [1/2]

size_t write ( const uint8_t *  data,
size_t  len 
)
inlinevirtualinherited

Send audio data to the USB peer. Silently discards data while the TX stream is not open so StreamCopy doesn't report write errors before streaming starts.

Reimplemented from AudioStream.

◆ write() [2/2]

virtual size_t write ( uint8_t  ch)
inlineoverridevirtualinherited

◆ writeSilence()

virtual void writeSilence ( size_t  len)
inlinevirtualinherited

Writes len bytes of silence (=0).

Member Data Documentation

◆ _timeout

int _timeout = 10
protectedinherited

◆ attached_

volatile bool attached_ = false
protected

◆ buffer_bytes_

uint16_t buffer_bytes_ = 0
protected

◆ clock_ranges_rx_

std::vector<RateRange> clock_ranges_rx_
protected

◆ clock_ranges_tx_

std::vector<RateRange> clock_ranges_tx_
protected

◆ config_

USBAudioConfig config_
protectedinherited

◆ configured_

volatile bool configured_ = false
protected

◆ core

int core = -1
protectedinherited

◆ ctrl_buf_

uint8_t ctrl_buf_[kCtrlBufSize] = {}
protected

◆ ctrl_busy_

bool ctrl_busy_ = false
protected

◆ ctrl_len_

uint16_t ctrl_len_ = 0
protected

◆ ctrl_ok_

bool ctrl_ok_ = false
protected

◆ ctrl_start_ms_

uint32_t ctrl_start_ms_ = 0
protected

◆ daddr_

uint8_t daddr_ = 0
protected

◆ entities_

std::vector<Entity> entities_
protected

◆ in_run_

bool in_run_ = false
protected

◆ info

AudioInfo info
protectedinherited

◆ is_active_

bool is_active_ = false
protectedinherited

◆ is_notify_active

bool is_notify_active = true
protectedinherited

◆ is_started_

bool is_started_ = false
protectedinherited

◆ itf_num_ac_

uint8_t itf_num_ac_ = 0
protected

◆ kCtrlBufSize

constexpr uint16_t kCtrlBufSize = 2 + 12 * 24
staticconstexprprotected

◆ kMaxChannels

constexpr uint8_t kMaxChannels = 8
staticconstexprprotected

◆ kMaxRates

constexpr uint8_t kMaxRates = 16
staticconstexprprotected

◆ kReqInItf

constexpr uint8_t kReqInItf = 0xA1
staticconstexprprotected

◆ kReqOutEp

constexpr uint8_t kReqOutEp = 0x22
staticconstexprprotected

◆ kReqOutItf

constexpr uint8_t kReqOutItf = 0x21
staticconstexprprotected

◆ kVolumeMinDb256

constexpr int16_t kVolumeMinDb256 = -25600
staticconstexprprotectedinherited

Convert AudioTools volume (0.0–1.0) to UAC2 int16 (1/256 dB). 0.0 maps to 0x8000 (silence), 1.0 maps to 0 (0 dB).

◆ mounted_

volatile bool mounted_ = false
protected

◆ mute_

std::vector<bool> mute_
protectedinherited

◆ mute_cb_

std::function<void(bool, uint8_t)> mute_cb_
protectedinherited

◆ mute_pending_

std::vector<uint8_t> mute_pending_
protected

◆ notify_vector

Vector<AudioInfoSupport*> notify_vector
protectedinherited

◆ pending_channel_

uint8_t pending_channel_ = 0
protected

◆ pending_is_volume_

bool pending_is_volume_ = false
protected

◆ pending_stream_

Stream* pending_stream_ = nullptr
protected

◆ pid_

uint16_t pid_ = 0
protected

◆ reconfigure_pending_

volatile bool reconfigure_pending_ = false
protected

◆ reconfiguring_

bool reconfiguring_ = false
protected

◆ restart_pending_

bool restart_pending_ = false
protected

◆ run_again_

bool run_again_ = false
protected

◆ rx_

Stream rx_
protected

◆ rx_info_

AudioInfo rx_info_
protected

◆ rx_primed_

bool rx_primed_ = false
protectedinherited

◆ sample_rate_cb_

std::function<void(uint32_t)> sample_rate_cb_
protectedinherited

◆ setup_

UsbSetupPacket setup_
protected

◆ step_

Step step_ = Step::Idle
protected

◆ step_done_

bool step_done_ = false
protected

◆ streaming_state_cb_

std::function<void(bool, bool)> streaming_state_cb_
protectedinherited

◆ tmp_in

RingBuffer<uint8_t> tmp_in {0}
protectedinherited

◆ tmp_out

RingBuffer<uint8_t> tmp_out {0}
protectedinherited

◆ tx_

Stream tx_
protected

◆ tx_info_

AudioInfo tx_info_
protected

◆ uac_version_

uint8_t uac_version_ = 0
protected

◆ usb_task_active_

bool usb_task_active_ = false
protectedinherited

◆ vid_

uint16_t vid_ = 0
protected

◆ volume_

std::vector<float> volume_
protectedinherited

◆ volume_cb_

std::function<void(float, uint8_t)> volume_cb_
protectedinherited

◆ volume_pending_

std::vector<uint8_t> volume_pending_
protected

◆ volume_value

float volume_value = 1.0f
protectedinherited

◆ write_buffer_size

int write_buffer_size = MAX_SINGLE_CHARS
protectedinherited

The documentation for this class was generated from the following file: