BLEAudio API
This is the per-class, per-method reference for BLEAudio. The signatures and descriptions are rendered from the Doxygen comments in the headers through esp-docs and Breathe.
See BLE Audio for concepts, setup, examples and behavior.
BLEAudio.h
-
class BLEAudio
Public Types
Public Functions
-
explicit operator bool() const
Whether this handle references the live controller (minted after BLE.begin()).
-
BTStatus begin()
Make the controller ready: initialize the engine and commit every role.
First use initializes the engine (common init, which takes over the host GAP/GATT callbacks; the rest of the library keeps working through forwarding). Then it runs each role’s staged registration (PACS/ASCS/BASS/VCS/…), registers the merged PACS records, and performs the single coordinated GATT commit, exposing the audio services and any
BLEServerservices at once. This is the publish event: the table freezes for the session afterwards. Create and configure every role (and any plain (non-audio) GATT services) before calling it.Calling it again after success is a no-op. The commit always runs, even with no staged audio roles: plain GATT services and the broadcast engine still need the single GATT publish. Busy is transient (retryable) and never poisons the controller; any other failure is terminal until end().
This is the controller commit, not the LC3 data path: it does not start decoding or encoding. Attach the streams and call
BLEAudioPlayer::startPlayback()/BLEAudioRecorder::startCapture()separately when the streams are configured.Security: PACS/ASCS characteristics require an encrypted link, so when
BLESecuritywas not configured by the sketch, begin() applies the default audio policy (Just Works: NoInputNoOutput, bonding, Secure Connections, no MITM) and logs it. ExplicitBLESecuritysetup and setAutoSecurityPolicy() may come in any order before begin(); call setAutoSecurityPolicy(false) and configureBLESecurityexplicitly to override. With the automatic policy off and no sketch configuration, links stay unencrypted and audio discovery fails.A failed begin() leaves earlier roles registered: do not retry begin(). Run end(), fix the role set, then begin() again.
-
BTStatus setAutoSecurityPolicy(bool enable)
Whether begin() may install the default audio security policy.
On by default (existing sketches keep working); turn off before begin() and configure
BLESecurityexplicitly for an opt-in policy.- Returns:
BTStatus::OK when stored; InvalidState on a null handle.
-
bool autoSecurityPolicy() const
Current setAutoSecurityPolicy() value (default true).
-
BTStatus end()
Release every audio profile, ISO resource and all engine state.
Stops leftover BAP transports and waits for ISO idle before native deinit. Refused while a CONNECTED ISO channel remains: stop the streams first. After a successful end(), roles may be created and begin() may run again with a new set of roles. Also run by
BLE.end(). Does not shut down the host stack.Called from a Bluetooth stack/audio callback, end() is refused with Busy because it must join the ISO teardown; defer it to loop().
- Returns:
BTStatus::OK (also when not active); Fail/InvalidState while streams are still up; Busy from a stack callback.
-
bool isActive() const
Whether the engine is initialized and end() has not been called (false on a null handle).
-
bool isCommitted() const
Whether begin() committed the roles and the GATT table (false on a null handle).
-
inline bool isStarted() const
Deprecated alias for isCommitted().
-
BTStatus connect(const BTAddress &address)
Connect to a unicast server / CAP acceptor as central (non-blocking).
Use this instead of
BLEClient::connect()for audio peers: on Bluedroid the link must be opened through the audio engine’s GATT client. Once the ACL is up the link is encrypted (with theBLESecuritysettings) as PACS/ASCS require, the ATT MTU is exchanged and the peer’s services are discovered; onLinkReady() then reports the link.Note
One connection attempt at a time: wait for onLinkReady() or onDisconnected() before connecting to the next peer.
- Parameters:
address – Peer address (type included).
- Returns:
BTStatus::OK when the connection attempt started; InvalidState before the commit; another error when the host refused the attempt.
-
BTStatus disconnect(uint16_t connHandle)
Disconnect an LE Audio ACL.
Closes the link whether it was opened by connect() or by the peer. The engine emits its normal
BLE_AUDIO_EVT_ACL_DISCONNECTEDand onDisconnected() fires.- Parameters:
connHandle – Connection handle reported by onLinkReady().
- Returns:
BTStatus::OK when the disconnect was issued; NotConnected when no live link matches; InvalidState before the commit or during shutdown.
-
void onLinkReady(LinkCallback cb)
The link is ready for this device’s roles.
Fires for every audio link, whether opened by connect() or by the peer. Client roles (unicast client, volume controller, …) may use
connHandlefrom this point on. A peer-opened link is GATT-discovered only when a client role is registered; with server-only roles this fires after the MTU exchange, without discovering the central’s database.- Parameters:
cb – Callback receiving the ready link’s
connHandle. Runs on the Bluetooth host task; keep it short.
-
void onDisconnected(LinkCallback cb)
An ACL link used by LE Audio went down, or connect() failed.
- Parameters:
cb – Callback receiving the lost link’s
connHandle. Runs on the Bluetooth host task; keep it short.
-
void resetCallbacks()
Clear the onLinkReady() and onDisconnected() callbacks.
Safe to call on any task; a no-op on a null handle.
-
BTStatus setPresentationDelay(uint32_t delayUs)
Presentation delay the roles advertise (servers) or request (clients, sources).
- Parameters:
delayUs – Delay in microseconds (default 40000; BAP presets use 40 ms). Stored as-is (no range check); applied to the preset QoS of roles started afterwards.
- Returns:
BTStatus::OK when stored; InvalidState on a null handle.
-
uint32_t getPresentationDelay() const
Current default presentation delay in microseconds.
- Returns:
The setPresentationDelay() value (default 40000; also 40000 on a null handle).
-
BLEAudioUnicastServer createUnicastServer()
BAP Unicast Server (ASCS + PACS): accepts unicast streams from a client.
Configure the ASE counts, capabilities and contexts before the commit; the peer then configures the server’s streams (see
BLEAudioStream::onConfigured).- Returns:
The configured server handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when the role is disabled in Kconfig.
-
BLEAudioUnicastClient createUnicastClient()
BAP Unicast Client: discovers a connected server and sets up streams on it.
Connect with connect(), then configure streams once onLinkReady() fires.
- Returns:
The configured client handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when the role is disabled in Kconfig.
-
BLEAudioBroadcastSource createBroadcastSource()
BAP Broadcast Source (Auracast transmitter).
Configure the preset, channels and broadcast metadata; the source’s own start() brings up the extended/periodic advertising and the BIG.
- Returns:
The configured source handle, or an empty handle when the engine cannot initialize or the role is disabled in Kconfig. Unlike service roles it may also be created after the commit (audio.begin()).
-
BLEAudioBroadcastSink createBroadcastSink()
BAP Broadcast Sink (Auracast receiver), optionally a BASS Scan Delegator.
Scans for announcements and syncs to a source; with the delegator enabled a Broadcast Assistant can drive it remotely.
- Returns:
The configured sink handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when the role is disabled in Kconfig.
-
BLEAudioBroadcastAssistant createBroadcastAssistant()
BAP Broadcast Assistant: finds sources for a remote sink (BASS client).
Scans for broadcast sources and adds, modifies or removes them on a connected Scan Delegator, including the Broadcast Code and PAST.
- Returns:
The configured assistant handle, or an empty handle when the engine cannot initialize or the role is disabled in Kconfig. Unlike service roles it may also be created after the commit (audio.begin()) (engine unit inits eagerly then).
-
BLEAudioCapAcceptor createCapAcceptor()
CAP Acceptor: publishes CAS (with an included CSIS when part of a set).
- Returns:
The configured acceptor handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioCapInitiator createCapInitiator()
CAP Initiator: starts, updates and stops audio on one or more acceptors.
- Returns:
The configured initiator handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioCapCommander createCapCommander()
CAP Commander: coordinated volume, mute and broadcast reception control.
- Returns:
The configured commander handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioCoordinatedSetMember createCoordinatedSetMember()
CSIP Set Member: publishes CSIS (SIRK, set size, rank, lock).
- Returns:
The configured member handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioCoordinatedSetCoordinator createCoordinatedSetCoordinator()
CSIP Set Coordinator: discovers and locks the members of a coordinated set.
- Returns:
The configured coordinator handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioVolumeRenderer createVolumeRenderer()
VCP Volume Renderer: publishes VCS (plus the compiled-in VOCS/AICS).
- Returns:
The configured renderer handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioVolumeController createVolumeController()
VCP Volume Controller: drives a connected renderer’s volume and mute.
- Returns:
The configured controller handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioMicDevice createMicDevice()
MICP Microphone Device: publishes MICS (plus its AICS).
- Returns:
The configured device handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioMicController createMicController()
MICP Microphone Controller: drives a connected device’s mute state.
- Returns:
The configured controller handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioMediaPlayer createMediaPlayer()
MCP Media Player: publishes the engine’s media player as MCS/GMCS.
- Returns:
The configured player handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioMediaController createMediaController()
MCP Media Controller: drives playback on a connected media player.
- Returns:
The configured controller handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioCallServer createCallServer()
CCP Call Server: publishes a Generic Telephone Bearer (GTBS).
- Returns:
The configured server handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioCallController createCallController()
CCP Call Controller: observes and drives calls on a connected call server.
- Returns:
The configured controller handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioHearingAidDevice createHearingAidDevice()
HAP Hearing Aid: publishes HAS with named presets.
- Returns:
The configured device handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioHearingAidController createHearingAidController()
HAP Hearing Aid Controller: reads and switches a connected hearing aid’s presets.
- Returns:
The configured controller handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
BLEAudioTmap createTmap()
TMAP identity: publishes TMAS with the local roles, or discovers a peer’s.
The audio itself still flows through CAP, BAP and the control profiles.
- Returns:
The configured TMAP handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when the role is disabled in Kconfig.
-
BLEAudioGmap createGmap()
GMAP identity: publishes GMAS with the local gaming roles, or discovers a peer’s.
- Returns:
The configured GMAP handle, or an empty handle when the engine cannot initialize, when called after the commit (audio.begin()), or when disabled.
-
explicit operator bool() const
BLEAudioBroadcastAssistant.h
-
class BLEAudioBroadcastAssistant
BAP Broadcast Assistant (BASS client), bound to one sink at a time.
Created by BLEAudio::createBroadcastAssistant() while the engine is active (also accepted after audio.begin(); the engine unit then inits eagerly). Control point operations return once the write is queued; their outcome arrives through onResult and the sink’s state through onReceiveState. Calls before discover() return BTStatus::NotConnected. Results run on the Bluetooth host task; keep callbacks short.
Public Types
-
enum class Op : uint8_t
Operation reported by onResult; runs on the Bluetooth host task.
Values:
-
enumerator ScanStart
Remote Scan Started write.
-
enumerator ScanStop
Remote Scan Stopped write.
-
enumerator AddSource
Add Source write.
-
enumerator ModifySource
Modify Source write.
-
enumerator RemoveSource
Remove Source write.
-
enumerator BroadcastCode
Set Broadcast_Code write.
-
enumerator Past
SyncInfo transfer requested by the sink.
-
enumerator ScanStart
-
using DiscoverCallback = std::function<void(BTStatus status, uint8_t receiveStates)>
Discovery result, with the number of Broadcast Receive State characteristics.
- Param status:
Engine discovery status.
- Param receiveStates:
BASS Broadcast Receive State count on the sink.
-
using SourceFoundCallback = std::function<void(const BLEAudioBroadcastSourceInfo &source)>
A broadcast found by the remote scan.
- Param source:
Advertiser, SID, Broadcast ID, name, RSSI and PA interval.
-
using ReceiveStateCallback = std::function<void(const BLEAudioReceiveState &state)>
A Broadcast Receive State was read or notified.
- Param state:
Sink state for one source (
removedset when the sink forgot it).
Public Functions
-
explicit operator bool() const
Whether this handle references a created assistant.
- Returns:
True after createBroadcastAssistant(); false on an empty handle.
-
BTStatus discover(uint16_t connHandle)
Discover the sink’s BASS on
connHandle; later calls act on this link.Switching peers stops the previous remote scan and forgets its Source_IDs; a disconnect of the bound peer unbinds it (getConnHandle() then reports none).
- Parameters:
connHandle – ACL connection of the Scan Delegator.
- Returns:
BTStatus::OK when discovery started; InvalidState on an empty handle; another error when the engine refused the discovery.
-
uint16_t getConnHandle() const
The connection passed to discover(), or BLE_AUDIO_CONN_NONE.
- Returns:
The bound peer, or BLE_AUDIO_CONN_NONE before discover() or after its disconnect; also BLE_AUDIO_CONN_NONE on an empty handle.
-
BTStatus startRemoteScan()
Tell the sink we scan for it and start a passive extended scan.
Uses the shared
BLE.getScan(); returns Busy instead of stealing an extended scan already started by another role. Each broadcast is reported once per remote scan through onSourceFound(). A second call while the remote scan is active is a no-op.
-
BTStatus stopRemoteScan()
Stop the local scan and tell the sink the remote scan ended.
Only acts when startRemoteScan() is in effect, so calling it twice (or from audio.end()) sends no redundant Scan Stopped write. With no peer left it still releases the local scan and returns NotConnected.
-
BTStatus addSource(const BLEAudioBroadcastSourceInfo &source, bool syncPa = true, uint32_t bisMask = 0xFFFFFFFF)
Ask the sink to receive
source.- Parameters:
source – Source report from onSourceFound() (address, SID, Broadcast ID, PA interval).
syncPa – Sync to the source’s periodic advertising.
bisMask – BIS indexes to sync (bit n = BIS n+1); 0xFFFFFFFF lets the sink choose.
- Returns:
BTStatus::OK when queued (onResult(AddSource) follows); InvalidState on an empty handle; NotConnected with no bound peer; another error when the engine refused the write.
-
BTStatus modifySource(uint8_t sourceId, bool syncPa, uint32_t bisMask)
Change PA / BIS sync of a source (e.g. syncPa = false, bisMask = 0 to pause).
- Parameters:
sourceId – Source_ID assigned by the sink.
syncPa – Whether the sink stays synced to the periodic advertising.
bisMask – BIS indexes to sync (bit n = BIS n+1), applied to every subgroup unless it names BISes of the first subgroup only; 0 = none, 0xFFFFFFFF = no preference.
- Returns:
BTStatus::OK when queued (onResult(ModifySource) follows); InvalidState on an empty handle; NotConnected with no bound peer; another error when the engine refused the write.
-
BTStatus removeSource(uint8_t sourceId)
Ask the sink to forget
sourceId.BASS lets the sink refuse while it is still synced; unsync first with modifySource(sourceId, false, 0).
- Parameters:
sourceId – Source_ID assigned by the sink.
- Returns:
BTStatus::OK when queued (onResult(RemoveSource) follows); InvalidState on an empty handle; NotConnected with no bound peer; another error (including the sink’s refusal) when the engine refused the write.
-
BTStatus setBroadcastCode(uint8_t sourceId, const String &code)
Send the Broadcast Code (up to 16 characters) of an encrypted source.
- Parameters:
sourceId – Source_ID assigned by the sink.
code – Broadcast Code; longer than 16 characters is rejected. Shorter codes are zero-padded to 16 octets as BAP requires.
- Returns:
BTStatus::OK when queued (onResult(BroadcastCode) follows); InvalidState on an empty handle; NotConnected with no bound peer; InvalidParam for an overlong code; another error when the engine refused the write.
-
void onDiscovered(DiscoverCallback cb)
BASS discovery finished.
- Parameters:
cb – Callback receiving the discovery
statusandreceiveStatescount.
-
void onSourceFound(SourceFoundCallback cb)
A broadcast was found during the remote scan.
- Parameters:
cb – Callback receiving each matching
source.
-
void onReceiveState(ReceiveStateCallback cb)
The sink’s receive state for a source changed (or was read at discovery).
- Parameters:
cb – Callback receiving each
state.
-
void onResult(ResultCallback cb)
Outcome of each control point operation.
- Parameters:
cb – Callback receiving the finished
opand itsstatus.
-
void resetCallbacks()
Drop every registered callback.
-
enum class Op : uint8_t
-
struct BLEAudioBroadcastSourceInfo
A broadcast source seen while scanning.
Public Members
-
uint8_t sid = 0
Advertising SID of the periodic train.
-
uint32_t broadcastId = 0
24-bit Broadcast_ID
-
String name
Broadcast Name, else the device name.
-
int8_t rssi = 0
dBm, from the report that found it
-
uint16_t paInterval = 0xFFFF
Periodic advertising interval (1.25 ms units), 0xFFFF unknown.
-
uint8_t sid = 0
-
struct BLEAudioReceiveState
A Broadcast Receive State of the remote sink.
Public Types
-
enum class PaState : uint8_t
PA_Sync_State values defined by BASS.
Values:
-
enumerator NotSynced
Not synchronized to the periodic advertising.
-
enumerator SyncInfoRequested
The sink asks the assistant for SyncInfo (PAST).
-
enumerator Synced
Synchronized.
-
enumerator Failed
Synchronization failed.
-
enumerator NoPast
No PAST available; the sink must scan itself.
-
enumerator NotSynced
Public Members
-
uint8_t sourceId = 0
Source_ID assigned by the sink; used by modify/remove/code calls.
-
bool removed = false
The source was removed; only sourceId is meaningful.
-
uint8_t sid = 0
Source advertising SID.
-
uint8_t badCode[16] = {}
Code the sink rejected (Encryption::BadCode).
-
uint8_t numSubgroups = 0
As reported; only the first kMaxSubgroups have a bisSync entry.
-
uint32_t bisSync[kMaxSubgroups] = {}
BIS indexes synced, per subgroup (bit n = BIS n+1).
Public Static Attributes
-
static uint8_t kMaxSubgroups = 4
Size of bisSync.
-
enum class PaState : uint8_t
BLEAudioBroadcastSink.h
-
struct BLEAudioBroadcastBaseInfo
Summary of the BASE (Broadcast Audio Source Endpoint) of the synced source.
Public Members
-
uint32_t bisMask = 0
BIT(index - 1) for every BIS in the BASE.
-
uint8_t subgroups = 0
Subgroups in the BASE.
-
uint32_t presentationDelayUs = 0
Presentation delay the source requests.
-
BLEAudioCodecConfig codec
Codec of the first subgroup.
-
uint32_t bisMask = 0
-
class BLEAudioBroadcastSink
Public Types
-
using SourceFoundCallback = std::function<void(const BLEAudioBroadcastSourceInfo &source)>
A broadcast source was seen while scanning.
-
using BaseCallback = std::function<void(const BLEAudioBroadcastBaseInfo &base)>
The BASE of the synced source was received.
-
using Callback = std::function<void()>
A state change with no payload (synced, BIG joined).
Runs on the Bluetooth host task; keep it short.
-
using ReasonCallback = std::function<void(uint8_t reason)>
Sync lost or BIG left;
reasonis the HCI reason code.Runs on the Bluetooth host task; keep it short.
Public Functions
-
explicit operator bool() const
Whether this handle references a sink (false when the factory failed).
-
BTStatus setStreams(uint8_t count)
Number of BISes to join: 1 = mono (default), 2 = stereo.
Streams are (re)allocated immediately, so attach stream callbacks after calling it.
- Parameters:
count – 1 = mono (one BIS), 2 = stereo (two BISes).
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin(); InvalidParam unless
countis 1 or 2.
-
BTStatus setSupportedPresets(uint32_t presetMask)
LC3 presets advertised in the sink PAC (BLEAudioPresetBit() mask).
Only BISes whose codec fits this PAC can be joined. Default: 16 and 24 kHz (10 ms) plus every 48 kHz preset.
- Parameters:
presetMask – OR of BLEAudioPresetBit() values.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin(); InvalidParam for a zero mask.
-
BTStatus setMaxChannelsPerStream(uint8_t channels)
Channels one BIS may carry in the sink PAC: 1 or 2 (default 2).
- Parameters:
channels – 1 = mono, 2 = mono or stereo per BIS.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin(); InvalidParam unless
channelsis 1 or 2.
-
BTStatus setLocation(BLEAudioLocation location)
Sink Audio Locations published in PACS (default Mono).
- Parameters:
location – Union of the speaker positions the sink renders.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BTStatus setContexts(BLEAudioContext contexts)
Sink contexts published in PACS (default Unspecified | Media).
- Parameters:
contexts – Bitfield of BLEAudioContext values the sink renders.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BTStatus setScanDelegator(bool enable)
Publish BASS so Broadcast Assistants can control the sink. Default on when compiled in.
- Parameters:
enable – True to publish the Scan Delegator (BASS) role.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BTStatus setBroadcastCode(const String &code)
Broadcast Code (up to 16 characters) for encrypted broadcasts.
Empty (default): only unencrypted broadcasts can be joined, unless an assistant provides the code. Takes effect immediately after audio.begin().
- Parameters:
code – Broadcast Code, empty (open) or up to 16 characters.
- Returns:
BTStatus::OK when applied; InvalidState on an empty handle; InvalidParam when
codeis longer than 16 characters.
-
BTStatus setTargetName(const String &name)
Only auto-sync to sources with this Broadcast Name (empty = any).
- Parameters:
name – Name filter; empty disables the name filter.
- Returns:
BTStatus::OK when applied; InvalidState on an empty handle.
-
BTStatus setTargetBroadcastId(uint32_t broadcastId)
Only auto-sync to this 24-bit Broadcast ID (0 = any).
- Parameters:
broadcastId – Only the low 24 bits are kept.
- Returns:
BTStatus::OK when applied; InvalidState on an empty handle.
-
BTStatus setBisMask(uint32_t mask)
Preferred BIS indexes as BIT(index - 1).
Takes effect at the next BIG sync; safe to call any time.
- Parameters:
mask – 0 (default) joins the lowest indexes in the BASE.
- Returns:
BTStatus::OK when applied; InvalidState on an empty handle.
-
BTStatus setAutoSync(bool enable)
Sync to the first matching source automatically. Default on.
- Parameters:
enable – False to pick sources manually with syncTo().
- Returns:
BTStatus::OK when applied; InvalidState on an empty handle.
-
BTStatus configureAuracast(const String &targetName = "", uint8_t streams = 2)
Configure a ready-to-start Auracast receiver.
Shorthand for:
setStreams(streams); setLocation(streams == 2 ? FrontLeft | FrontRight : Mono); setContexts(Media); setTargetName(targetName); setAutoSync(true);
Call it after createBroadcastSink() and before audio.begin(), then start() to begin scanning. The Scan Delegator stays enabled when compiled in, so a phone or Broadcast Assistant can also select a source. Encryption stays opt-in: call setBroadcastCode() separately.
- Parameters:
targetName – Only sync to this Broadcast Name; empty (default) syncs to the first source found. With a name set, the sink ignores other broadcasts in range.
streams – 1 = mono (one BIS), 2 = stereo (two BISes). Default 2.
- Returns:
BTStatus::OK when every setter was applied; the first error otherwise (InvalidState on an empty handle or after audio.begin(); InvalidParam for a bad
streamscount).
-
BTStatus start()
Start scanning for sources (no-op when already synced).
Scanning continues until a PA sync is established and restarts on its own when the sync is lost, until stop().
- Returns:
BTStatus::OK when scanning; InvalidState before audio.begin(); another error when the scan could not start.
-
BTStatus syncTo(const BLEAudioBroadcastSourceInfo &source)
Sync to
source(from onSourceFound()); use with setAutoSync(false).- Parameters:
source – Source report to sync to (address, SID and Broadcast ID are used).
- Returns:
BTStatus::OK when the PA sync is being created; InvalidState before audio.begin() or while a sync is pending or established.
-
BTStatus stop()
Leave the BIG, drop the PA sync and stop scanning.
Blocks until the BIG is down so a following
audio.end()/BLE.end()does not tear the host down over a live ISO channel. Called from a Bluetooth stack callback, stop() is refused with Busy because it must wait for the asynchronous BIG leave; defer it to loop().- Returns:
BTStatus::OK on success; InvalidState on an empty handle; Busy from a stack callback; another error (engine status, Timeout) when the teardown failed or stalled.
-
bool isStreaming() const
Whether the BIG is joined (between onStarted() and onStopped()).
- Returns:
True while the BIG streams; false on an empty handle.
-
size_t streamCount() const
Number of streams (= setStreams() count, fewer if the pool ran out).
-
BLEAudioStream stream(size_t index) const
Stream
indexin [0, streamCount()); empty handle when out of range.- Parameters:
index – BIS position in join order.
- Returns:
The stream, or an empty handle when
indexis out of range.
-
void onSourceFound(SourceFoundCallback cb)
A broadcast source was seen while scanning (repeats per advertising report).
- Parameters:
cb – Callback receiving each matching source
report.
-
void onSynced(Callback cb)
Periodic advertising sync established; the BASE and BIG sync follow.
- Parameters:
cb – Callback fired once the PA sync is established.
-
void onBaseReceived(BaseCallback cb)
The BASE of the synced source was received (once per PA sync).
Fires before the BIG sync, so setBisMask() may still pick the BISes to join.
- Parameters:
cb – Callback receiving the BASE
summary.
-
void onBroadcastCodeReceived(Callback cb)
A Broadcast Assistant provided the Broadcast Code (Scan Delegator).
The code replaces the one from setBroadcastCode() from the next BIG sync attempt.
- Parameters:
cb – Callback fired once the code arrives.
-
void onSyncLost(ReasonCallback cb)
Periodic advertising sync lost; scanning resumes while started.
- Parameters:
cb – Callback receiving the HCI loss
reason.
-
void onSyncFailed(ErrorCallback cb)
Joining the BIG failed.
NotFound: no BIS matches the sink PAC; PermissionDenied: the broadcast is encrypted and no (or a wrong) Broadcast Code is set.
- Parameters:
cb – Callback receiving the failure
status.
-
void onStarted(Callback cb)
The BIG is joined: every stream is streaming.
- Parameters:
cb – Callback fired once the BIG streams.
-
void onStopped(ReasonCallback cb)
The BIG was left (stop(), source stopped, or sync lost).
- Parameters:
cb – Callback receiving the HCI leave
reason.
-
void resetCallbacks()
Clear every callback of this role.
-
using SourceFoundCallback = std::function<void(const BLEAudioBroadcastSourceInfo &source)>
BLEAudioBroadcastSource.h
-
class BLEAudioBroadcastSource
Public Types
-
using Callback = std::function<void()>
The BIG is up: every stream is streaming.
Runs on the Bluetooth host task; keep it short.
Public Functions
-
explicit operator bool() const
Whether this handle references a source (false when the factory failed).
-
BTStatus setPreset(BLEAudioCodecPreset preset)
Codec and QoS from a BAP preset (broadcast table). Default LC3_16_2_1.
- Parameters:
preset – Preset to use.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or while starting or streaming; InvalidParam for an unknown preset.
-
BTStatus setQos(const BLEAudioQos &qos)
Replace the preset’s QoS with a custom one.
Without it, the preset QoS is used with the controller’s presentation delay.
- Parameters:
qos – Custom QoS applied instead of the preset one from the next start().
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or while starting or streaming.
-
BTStatus setChannels(uint8_t channels)
Number of channels, one BIS each: 1 = mono (default), 2 = stereo (FL + FR).
A stopped engine source is deleted before the stream vector is resized, so the engine never points at freed slots. Streams are (re)allocated immediately; attach callbacks afterwards.
- Parameters:
channels – 1 = mono (one BIS), 2 = stereo (two BISes).
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or while starting or streaming; InvalidParam unless
channelsis 1 or 2.
-
BTStatus setBroadcastId(uint32_t broadcastId)
24-bit Broadcast ID receivers use to recognize the source. Default: random.
- Parameters:
broadcastId – Only the low 24 bits are kept; advertised, not baked into the source.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle.
-
BTStatus setBroadcastCode(const String &code)
Broadcast Code (up to 16 characters) that encrypts the BIG.
Empty (default) = unencrypted. Receivers need the same code to decode.
- Parameters:
code – Broadcast Code, empty (open) or up to 16 characters.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle; InvalidParam when
codeis longer than 16 characters.
-
BTStatus setName(const String &name)
Broadcast Name shown by scanners (up to 32 characters). Default: the device name.
- Parameters:
name – Name advertised in the extended advertising; empty falls back to the device name.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle; InvalidParam when
nameis longer than 32 characters.
-
BTStatus setContext(BLEAudioContext context)
Streaming context in the BASE metadata. Default Media.
- Parameters:
context – Context announced in the BASE.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle.
-
BTStatus setPublicBroadcast(bool enable)
Advertise a Public Broadcast Announcement (Auracast, PBP builds only).
Lets phones list the broadcast with its quality and encryption flags. Default on; ignored when PBP is not compiled in.
- Parameters:
enable – True to advertise the PBA alongside the announcement.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle.
-
BTStatus configureAuracast(const String &name, uint8_t channels = 2, BLEAudioCodecPreset preset = BLEAudioCodecPreset::LC3_48_2_1)
Configure a ready-to-start Auracast transmitter.
Shorthand for:
setPreset(preset); setChannels(channels); setName(name); setContext(Media); setPublicBroadcast(true);
Call it before the commit (audio.begin()). Encryption stays opt-in: call setBroadcastCode() separately. Individual setters can still override any field afterwards.
- Parameters:
name – Broadcast Name shown by receivers and phone Auracast UIs (up to 32 characters, must not be empty).
channels – 1 = mono (one BIS), 2 = stereo (front-left + front-right BISes). Default 2.
preset – Codec/QoS preset. Default LC3_48_2_1: 48 kHz music, the usual Auracast quality.
- Returns:
BTStatus::OK when every setter was applied; the first error otherwise (InvalidState on an empty handle or while starting or streaming; InvalidParam for an empty or overlong
name, a badchannelscount or an unknownpreset).
-
BTStatus start(uint8_t advInstance = 0)
Start advertising and create the BIG (non-blocking; onStarted() follows).
Re-creates the source first when the configuration changed since the last start().
- Parameters:
advInstance – Extended advertising instance reserved for the broadcast. Must be a user-addressable set (below the reserved legacy instance). Default 0 is the first user set; 1 is the legacy instance on targets with only two extended slots (e.g. ESP32-S31).
- Returns:
BTStatus::OK when started; InvalidState before audio.begin(), while streaming or without streams; another error when creating the source or the advertising failed.
-
BTStatus stop()
Terminate the BIG and stop the advertising instance (onStopped() follows).
Blocks until the BIG is down (or 5 s) so a following
audio.end()/BLE.end()does not tear the host down over a live ISO channel. Called from a Bluetooth stack/audio callback, stop() is refused with Busy because it must wait for the asynchronous BIG terminate; defer it to loop().- Returns:
BTStatus::OK on success (also when already stopped); InvalidState when not started or on an empty handle; Busy from a stack callback; another error when the teardown stalled (retry stop()).
-
bool isStreaming() const
Whether the BIG is up (between onStarted() and onStopped()).
- Returns:
True while the BIG streams; false on an empty handle.
-
BTStatus updateContext(BLEAudioContext context)
Change the streaming context in the BASE while running.
- Parameters:
context – Context written into the existing source metadata in place.
- Returns:
BTStatus::OK on success; InvalidState before the first start() or on an empty handle; another error when the engine refused the update.
-
uint32_t getBroadcastId() const
Broadcast ID in use (random unless set).
- Returns:
The staged ID (masked to 24 bits); 0 on an empty handle.
-
size_t streamCount() const
Number of streams (= channels, fewer if the pool ran out).
-
BLEAudioStream stream(size_t index) const
Stream
index:0 = mono or front left, 1 = front right. Empty when out of range.- Parameters:
index – BIS position (0 = mono/front left, 1 = front right).
- Returns:
The stream, or an empty handle when
indexis out of range.
-
void onStarted(Callback cb)
The BIG is up: every stream is streaming.
- Parameters:
cb – Callback fired once the BIG streams.
-
void onStopped(StoppedCallback cb)
The BIG was terminated.
- Parameters:
cb – Callback receiving the HCI termination
reason.
-
void resetCallbacks()
Clear every callback of this role.
-
using Callback = std::function<void()>
BLEAudioCall.h
-
class BLEAudioCallController
CCP Call Control Client (the headset side), bound to one peer.
Created by BLEAudio::createCallController() while the engine is active and before audio.begin(). Operations are control point writes: OK means the write was queued, and the server’s answer arrives through onResult; the resulting state changes arrive through onCallState. Operations before discover() return BTStatus::InvalidState.
Public Types
-
using DiscoveredCallback = std::function<void(BTStatus status, bool gtbsFound)>
Discovery result.
- Param status:
OK when discovery finished; error status when it failed.
- Param gtbsFound:
True when the peer exposes GTBS.
-
using ResultCallback = std::function<void(BLEAudioCallOperation operation, BTStatus status, uint8_t callIndex)>
The server’s answer to a call operation.
- Param operation:
The operation the answer refers to.
- Param status:
OK when the server accepted the operation; error status otherwise.
- Param callIndex:
Index of the affected call.
-
using CallStateCallback = std::function<void(uint8_t callIndex, BLEAudioCallState state)>
State of one call.
- Param callIndex:
Index of the call.
- Param state:
Current call state (Ended once the call is gone).
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle refers to a created controller.
-
BTStatus discover(uint16_t connHandle)
Discover the peer’s telephone bearers on
connHandle(after audio.begin()).Waits for the engine’s GATT discovery of the link if needed; the current calls are read right after onDiscovered. Every call below acts on the peer’s GTBS.
- Parameters:
connHandle – ACL connection handle of the peer.
- Returns:
BTStatus::InvalidState when the handle is empty, before audio.begin(), or for BLE_AUDIO_CONN_NONE; OK when discovery started or was deferred until GATT discovery; another status when discovery failed to start.
-
uint16_t getConnHandle() const
- Returns:
The connection passed to discover(), or BLE_AUDIO_CONN_NONE.
-
BTStatus originate(const String &uri)
Ask the server to call
uri(a scheme it lists, e.g. “tel:+15551234567”).- Parameters:
uri – Destination URI to dial.
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the control-point write was queued (answer via onResult); another status when the write failed to start.
-
BTStatus accept(uint8_t callIndex)
Answer an incoming call.
- Parameters:
callIndex – Index reported by onCallState().
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the control-point write was queued (answer via onResult); another status when the write failed to start.
-
BTStatus terminate(uint8_t callIndex)
End a call.
- Parameters:
callIndex – Index reported by onCallState().
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the control-point write was queued (answer via onResult); another status when the write failed to start.
-
BTStatus hold(uint8_t callIndex)
Put a call on local hold.
- Parameters:
callIndex – Index reported by onCallState().
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the control-point write was queued (answer via onResult); another status when the write failed to start.
-
BTStatus retrieve(uint8_t callIndex)
Resume a locally held call.
- Parameters:
callIndex – Index reported by onCallState().
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the control-point write was queued (answer via onResult); another status when the write failed to start.
-
BTStatus readCalls()
Re-read the call list (answered via onCallState, one call each).
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the read was queued; another status when the read failed to start.
-
void onDiscovered(DiscoveredCallback cb)
Discovery finished; also fires with an error when a deferred discovery could not start.
-
void onResult(ResultCallback cb)
Completion of each call operation.
-
void onCallState(CallStateCallback cb)
Call state reads and notifications; Ended once a call is gone.
-
void resetCallbacks()
Drop every registered callback.
-
using DiscoveredCallback = std::function<void(BTStatus status, bool gtbsFound)>
-
class BLEAudioCallServer
CCP Call Control Server (the phone side, GTBS).
Created by BLEAudio::createCallServer() while the engine is active and before audio.begin(). The application drives the calls (incoming call, far end answered or hung up); connected controllers see every state change. Copies of the handle control the same server; an empty handle does nothing, and its BTStatus calls return InvalidState.
Public Types
-
using OriginateCallback = std::function<bool(uint8_t callIndex, const String &uri)>
A controller asked to place an outgoing call.
- Param callIndex:
Index already assigned to the new call.
- Param uri:
Requested destination URI.
- Return:
true to accept the outgoing call request.
-
using TerminatedCallback = std::function<void(uint8_t callIndex, uint8_t reason)>
A controller ended a call.
- Param callIndex:
Index of the ended call.
- Param reason:
TBS termination reason code.
-
using CallControlCallback = std::function<void(BLEAudioCallOperation operation, uint8_t callIndex)>
A controller accepted, held or retrieved a call.
- Param operation:
The requested operation (Accept, Hold or Retrieve).
- Param callIndex:
Index of the affected call.
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle refers to a created server.
-
BTStatus setProviderName(const String &name)
Default “ESP Phone”.
- Returns:
BTStatus::OK when staged; InvalidParam when
nameis empty; InvalidState when the handle is empty or audio is already started.
-
BTStatus setUci(const String &uci)
Uniform Caller Identifier. Default “un000”.
- Returns:
BTStatus::OK when staged; InvalidParam when
uciis empty; InvalidState when the handle is empty or audio is already started.
-
BTStatus setUriSchemes(const String &schemes)
Comma-separated URI schemes, e.g. “tel,skype”. Default “tel”.
- Returns:
BTStatus::OK when staged; InvalidParam when
schemeshas no usable scheme; InvalidState when the handle is empty or audio is already started.
-
BTStatus incomingCall(const String &from, uint8_t &callIndex, const String &friendlyName = "")
Raise an incoming call (state Incoming).
- Parameters:
from – Caller URI, e.g. “tel:+15551234567”; also used as the caller name when
friendlyNameis empty.callIndex – Receives the index that identifies the call from now on.
friendlyName – Shown to the peer instead of the URI when non-empty.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status (OK when the call was raised).
-
BTStatus accept(uint8_t callIndex)
Answer locally.
- Parameters:
callIndex – Index from incomingCall() or onOriginate().
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
BTStatus hold(uint8_t callIndex)
Put the call on local hold.
- Parameters:
callIndex – Index of the call to hold.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
BTStatus retrieve(uint8_t callIndex)
Resume a locally held call.
- Parameters:
callIndex – Index of the held call.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
BTStatus terminate(uint8_t callIndex)
Hang up locally.
- Parameters:
callIndex – Index of the call to end.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
BTStatus remoteAnswered(uint8_t callIndex)
The far end answered an outgoing call.
- Parameters:
callIndex – Index of the outgoing call.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
BTStatus remoteTerminated(uint8_t callIndex)
The far end hung up.
- Parameters:
callIndex – Index of the ended call.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
BTStatus updateProviderName(const String &name)
Change the bearer provider name at runtime; controllers are notified.
- Parameters:
name – New provider name.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
void onOriginate(OriginateCallback cb)
A controller asked to place a call. Default: accept.
-
void onTerminated(TerminatedCallback cb)
A controller ended a call.
-
void onCallControl(CallControlCallback cb)
A controller accepted, held or retrieved a call.
-
void resetCallbacks()
Drop every registered callback.
-
using OriginateCallback = std::function<bool(uint8_t callIndex, const String &uri)>
-
enum class BLEAudioCallOperation : uint8_t
Call control point operations reported by callbacks.
Values:
-
enumerator Originate
Place an outgoing call.
-
enumerator Accept
Answer an incoming call.
-
enumerator Terminate
End a call.
-
enumerator Hold
Put a call on local hold.
-
enumerator Retrieve
Resume a locally held call.
-
enumerator Originate
-
enum class BLEAudioCallState : uint8_t
Telephone Bearer call states, plus Ended once a call is gone.
Values:
-
enumerator Incoming
Incoming call ringing locally.
-
enumerator Dialing
Outgoing call being dialed.
-
enumerator Alerting
Far end is being alerted.
-
enumerator Active
Call is active.
-
enumerator LocallyHeld
Call held locally.
-
enumerator RemotelyHeld
Call held by the far end.
-
enumerator LocallyAndRemotelyHeld
Call held on both ends.
-
enumerator Ended
Call is gone; reported once via onCallState.
-
enumerator Incoming
BLEAudioCap.h
-
class BLEAudioCapAcceptor
CAP Acceptor: CAS with an included CSIS instance.
Created by BLEAudio::createCapAcceptor() while the engine is active and before audio.begin(); the set configuration is registered by start(). The audio itself flows through the BAP roles the sketch creates next to it.
Public Functions
-
explicit operator bool() const
Whether this handle references an acceptor (false when the factory failed).
-
BTStatus setSirk(const uint8_t sirk[BLE_AUDIO_SIRK_SIZE])
See BLEAudioCoordinatedSetMember::setSirk().
- Parameters:
sirk – 16-octet Set Identity Resolving Key shared by the set; null is rejected.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin(); InvalidParam for a null
sirk.
-
BTStatus setSetSize(uint8_t size)
See BLEAudioCoordinatedSetMember::setSetSize().
- Parameters:
size – Total devices in the set; must be non-zero.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin(); InvalidParam for a zero
size.
-
BTStatus setRank(uint8_t rank)
See BLEAudioCoordinatedSetMember::setRank().
- Parameters:
rank – 1-based rank of this device; zero is rejected.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin(); InvalidParam for a zero
rank.
-
BTStatus setLockable(bool lockable)
See BLEAudioCoordinatedSetMember::setLockable().
- Parameters:
lockable – Whether a coordinator may lock this device for ordered access.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BLEAudioCoordinatedSetMember coordinatedSet() const
The CAS-included CSIS instance: RSI, lock state and callbacks.
-
explicit operator bool() const
-
class BLEAudioCapCommander
CAP Commander: rendering, capture and broadcast reception control of every discovered acceptor at once.
Created by BLEAudio::createCapCommander(). Each procedure returns once started and reports through onResult().
Public Types
-
enum class Operation : uint8_t
Procedure reported by onResult().
Values:
-
enumerator Volume
-
enumerator VolumeOffset
-
enumerator MicMute
-
enumerator MicGain
-
enumerator BroadcastReceptionStart
-
enumerator BroadcastReceptionStop
-
enumerator BroadcastCode
-
enumerator Volume
-
using DiscoveredCallback = std::function<void(BTStatus status, uint16_t connHandle, bool coordinatedSet, bool broadcastReception)>
coordinatedSet:part of a set;broadcastReception:BASS available.
-
using ResultCallback = std::function<void(Operation op, BTStatus status)>
Completion of procedure
opover all acceptors.
-
using ReceiveStateCallback = std::function<void(const ReceiveState &state)>
An acceptor’s receive state was read or notified.
Public Functions
-
explicit operator bool() const
Whether this handle references a commander (false when the factory failed).
-
BTStatus discover(uint16_t connHandle)
Discover CAS and the rendering/capture/BASS services of an acceptor.
Starts once
BLEAudio::onLinkReady()fired forconnHandle. Every procedure below then acts on all discovered acceptors at once; each reports through onResult(). NotSupported when the matching controller profile (VCP, VOCS, MICP, AICS, BAP assistant) is not in the build.- Parameters:
connHandle – ACL connection of the acceptor; GATT discovery of the link gates the start (deferred until onLinkReady() when pending).
- Returns:
BTStatus::OK when discovery started or is deferred to the link’s GATT discovery; InvalidState before audio.begin() or for an invalid handle; another error when the engine refused the discovery.
-
BTStatus setCoordinated(bool enable)
Run procedures with CSIP ordered access when the acceptors form one set.
Off by default (AD_HOC). When on, every procedure uses the stack’s CSIP set type — lock, rank-ordered execution and unlock inside the stack — if every driven acceptor belongs to one discovered coordinated set (run CSIP coordinator discovery on each link first); mixed or undiscovered sets fall back to AD_HOC with a warning. Can be toggled any time; takes effect on the next procedure. Returns NotSupported when the CSIP coordinator is compiled out.
- Parameters:
enable – True for rank-ordered execution with CSIP lock/unlock, false for AD_HOC.
- Returns:
BTStatus::OK when queued; InvalidState on an empty handle; NotSupported when the CSIP coordinator is compiled out; another error when the engine refused.
-
BTStatus setVolume(uint8_t volume)
Set the absolute volume (0..255) of every acceptor (VCP).
- Parameters:
volume – Absolute volume step.
- Returns:
BTStatus::OK when queued; InvalidState on an empty handle; another error (including NotSupported with no VCP controller in the build) otherwise.
-
BTStatus setMute(bool mute)
Mute or unmute the rendering of every acceptor (VCP).
- Parameters:
mute – True to mute, false to unmute.
- Returns:
BTStatus::OK when queued; InvalidState on an empty handle; another error otherwise.
-
BTStatus setVolumeOffset(int16_t offset)
Set the volume offset (-255..255) of every acceptor’s first VOCS instance.
- Parameters:
offset – Offset step.
- Returns:
BTStatus::OK when queued; InvalidState on an empty handle; another error (including NotSupported with no VOCS in the build) otherwise.
-
BTStatus setMicMute(bool mute)
Mute or unmute the microphone of every acceptor (MICP).
- Parameters:
mute – True to mute, false to unmute.
- Returns:
BTStatus::OK when queued; InvalidState on an empty handle; another error otherwise.
-
BTStatus setMicGain(int8_t gain)
Set the gain of every acceptor’s first microphone AICS instance.
- Parameters:
gain – Gain step.
- Returns:
BTStatus::OK when queued; InvalidState on an empty handle; another error (including NotSupported with no AICS in the build) otherwise.
-
BTStatus startBroadcastReception(const BTAddress &source, uint8_t sid, uint32_t broadcastId, uint32_t bisSync = 0, uint16_t paInterval = 0xFFFF)
Ask the acceptors to receive a broadcast.
- Parameters:
source – Advertiser address of the broadcast source.
sid – Advertising SID of the source.
broadcastId – 24-bit Broadcast ID of the source.
bisSync – BIS indexes to sync (bit n-1 = BIS n); 0 = no preference.
paInterval – PA interval in 1.25 ms units; 0xFFFF = unknown.
- Returns:
BTStatus::OK when queued; InvalidState on an empty handle; another error (including NotSupported with no BASS client in the build) otherwise.
-
BTStatus stopBroadcastReception()
Ask the acceptors to stop receiving the broadcast started above.
- Returns:
BTStatus::OK when queued; InvalidState on an empty handle; another error otherwise.
-
BTStatus distributeBroadcastCode(const String &code)
Send the Broadcast Code of an encrypted broadcast to the acceptors.
- Parameters:
code – Non-empty code (up to 16 characters); an empty code is rejected.
- Returns:
BTStatus::OK when queued; InvalidParam for an empty code; InvalidState on an empty handle; another error otherwise.
-
void onDiscovered(DiscoveredCallback cb)
Commander discovery of an acceptor finished.
- Parameters:
cb – Callback receiving the
status, the acceptorconnHandle, and whether it iscoordinatedSet/broadcastReceptioncapable.
-
void onResult(ResultCallback cb)
A procedure finished.
- Parameters:
cb – Callback receiving the finished
opand itsstatus.
-
void onReceiveState(ReceiveStateCallback cb)
Acceptor receive states.
- Parameters:
cb – Callback receiving each read/notified receive
state.
-
void resetCallbacks()
Clear every callback of this role.
-
struct ReceiveState
Broadcast receive state reported by an acceptor (BASS).
Public Members
-
uint16_t connHandle
Acceptor that reported it.
-
uint8_t sourceId
Source_ID assigned by the acceptor.
-
uint8_t paSyncState
0 not synced, 1 SyncInfo request, 2 synced, 3 failed, 4 no PAST.
-
uint8_t encryptionState
0 unencrypted, 1 code requested, 2 decrypting, 3 bad code.
-
uint32_t bisSync
BIS indexes synced in any subgroup (bit n-1 = BIS n).
-
uint16_t connHandle
-
enum class Operation : uint8_t
-
class BLEAudioCapInitiator
CAP Initiator: drives every discovered acceptor as one unit.
Created by BLEAudio::createCapInitiator(). Procedures return once started; completion is reported through the matching callback.
Like all role handles, the initiator’s methods must be called from one task (normally loop()): start/stop/update/handover serialize against each other through the hoBusy guard, which is a check-then-act sequence, not a lock held across the asynchronous engine call. Concurrent calls from two tasks can interleave a stop with an in-flight handover and corrupt the shared unicast parameters; the engine does not second-guess the caller.
Public Types
-
using DiscoveredCallback = std::function<void(BTStatus status, const BLEAudioCapPeerInfo &peer)>
Discovery result for one acceptor.
-
using Callback = std::function<void()>
Event without payload.
-
using StoppedCallback = std::function<void(uint8_t reason)>
The broadcast stopped;
reasonis the HCI reason (0 after stopBroadcast()).
Public Functions
-
explicit operator bool() const
Whether this handle references an initiator (false when the factory failed).
-
BTStatus setPreset(BLEAudioCodecPreset preset)
Codec and QoS of every stream, from a BAP preset. Default LC3_16_2_1.
- Parameters:
preset – Preset to use; an unknown preset is rejected.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin(); InvalidParam for an unknown
preset.
-
BTStatus setQos(const BLEAudioQos &qos)
Replace the preset QoS;
maxSduis recomputed per stream.- Parameters:
qos – Custom QoS applied instead of the preset one from the next session.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BTStatus setContext(BLEAudioContext context)
Streaming context of unicast and broadcast streams. Default Media.
- Parameters:
context – Context sent with Enable and in the BASE metadata.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BTStatus setSinkStreams(uint8_t perPeer)
Unicast streams this device sends, per acceptor. Default 1.
- Parameters:
perPeer – Requested sink ASEs per acceptor, capped by what the acceptor has.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BTStatus setSourceStreams(uint8_t perPeer)
Unicast streams this device receives, per acceptor. Default 0.
- Parameters:
perPeer – Requested source ASEs per acceptor, capped by what the acceptor has.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BTStatus setBroadcastId(uint32_t broadcastId)
24-bit Broadcast ID. Default random.
- Parameters:
broadcastId – Only the low 24 bits are kept.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
uint32_t getBroadcastId() const
The Broadcast ID used by startBroadcast() and handovers.
- Returns:
The staged ID (masked to 24 bits); 0 on an empty handle.
-
BTStatus setBroadcastCode(const String &code)
Broadcast Code (up to 16 characters); empty = unencrypted.
- Parameters:
code – Longer codes are truncated with a warning and zero-padded per spec.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BTStatus setBroadcastName(const String &name)
Broadcast Name; empty = device name.
- Parameters:
name – Name advertised in the extended advertising.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BTStatus discover(uint16_t connHandle)
Discover CAS, PACS and ASCS on a connected acceptor.
Starts once
BLEAudio::onLinkReady()fired forconnHandle; the result is reported by onDiscovered(). Discovered acceptors take part in every following unicast session and handover. Calling it again for a known acceptor, or before its link is GATT-ready, defers to (or reports) the in-flight discovery.- Parameters:
connHandle – ACL connection of the acceptor.
- Returns:
BTStatus::OK when discovery started, is in flight, or the acceptor is already discovered; InvalidState before audio.begin(); another error when the engine refused the discovery.
-
BTStatus startUnicast()
Start streams on every discovered acceptor (onUnicastStarted() follows).
- Returns:
BTStatus::OK when the setup started; InvalidState when already running/starting, handed over, a handover is busy, or no discovered acceptor has a usable endpoint; NoMemory when the stream pool is exhausted; another error when the engine refused the start.
-
BTStatus updateUnicast(BLEAudioContext context)
Change the streaming context of the running streams (onUnicastUpdated()).
- Parameters:
context – Context applied to the running session.
- Returns:
BTStatus::OK when the update started; InvalidState when no unicast session is running or a handover is busy; another error otherwise.
-
BTStatus stopUnicast()
Release every unicast stream (onUnicastStopped() follows).
- Returns:
BTStatus::OK when the release started; InvalidState when no session (running or handed-over) exists or a handover is busy; another error when the engine refused the stop.
-
bool isUnicastStreaming() const
- Returns:
true while the unicast streams carry audio (after a successful start or a handover back).
-
BTStatus startBroadcast(uint8_t channels = 1, uint8_t advInstance = 0)
Start a broadcast source with
channelsBIS on advertising instanceadvInstance(onBroadcastStarted() follows).
-
BTStatus stopBroadcast()
Stop and delete the broadcast source (onBroadcastStopped() follows).
Refused with InvalidState while a handover owns the broadcast (hoBusy); wait for its completion instead. Returns Fail (state retained for a retry) when the source is still live after the teardown wait.
-
bool isBroadcasting() const
- Returns:
true while a broadcast (plain or handed over) is streaming.
-
BTStatus handoverToBroadcast(uint8_t advInstance = 0)
Move the running unicast session to a broadcast on
advInstance.The acceptors are told to receive the broadcast; the sink streams keep their handles and go on carrying audio as BIS. Source streams stop.
Note
If the procedure fails, the initiator also stops the unicast session (onUnicastStopped() fires) so startUnicast() can rebuild it.
- Parameters:
advInstance – Extended advertising instance for the broadcast.
- Returns:
BTStatus::OK when the handover started (onHandover() follows); InvalidState when no unicast session streams, a broadcast already runs, or a handover is busy; NotSupported when handover is disabled (CONFIG_BT_CAP_HANDOVER); another error when the engine or the advertising refused the start.
-
BTStatus handoverToUnicast()
Move a handed-over broadcast back to unicast on the same acceptors.
- Returns:
BTStatus::OK when the handover started (onHandover() follows); InvalidState when no handover is in effect, a handover is busy, or the acceptors changed since the handover to broadcast; NotSupported when handover is disabled (CONFIG_BT_CAP_HANDOVER); another error when the engine refused the start.
-
size_t streamCount() const
Streams of the current session: unicast (also after a handover) or broadcast.
-
BLEAudioStream stream(size_t index) const
Stream
indexof the current session, or an empty stream.- Parameters:
index – Position in request order (per acceptor: sink streams, then source).
- Returns:
The stream, or an empty handle when
indexis out of range.
-
BLEAudioStream stream(BLEAudioStream::Direction dir, uint8_t index = 0) const
The
index-thstream of directiondirin the current session, or an empty stream.- Parameters:
dir – Tx = streams this device sends; Rx = streams it receives.
index – Position among the streams of
dir.
- Returns:
The stream, or an empty handle when fewer streams exist in
dir.
-
void onDiscovered(DiscoveredCallback cb)
CAP discovery of an acceptor finished.
- Parameters:
cb – Callback receiving the discovery
statusand the acceptorpeer.
-
void onUnicastStarted(StatusCallback cb)
startUnicast() finished; the streams carry audio on success.
- Parameters:
cb – Callback receiving the procedure
status.
-
void onUnicastUpdated(StatusCallback cb)
updateUnicast() finished.
- Parameters:
cb – Callback receiving the procedure
status.
-
void onUnicastStopped(Callback cb)
The unicast streams were released.
- Parameters:
cb – Callback fired after the release.
-
void onBroadcastStarted(Callback cb)
The broadcast source is streaming.
- Parameters:
cb – Callback fired once the broadcast streams.
-
void onBroadcastStopped(StoppedCallback cb)
The broadcast stopped.
- Parameters:
cb – Callback receiving the HCI
reason(0 after stopBroadcast()).
-
void onHandover(HandoverCallback cb)
A handover procedure finished.
- Parameters:
cb – Callback receiving the
statusand thetoBroadcastdirection.
-
void resetCallbacks()
Clear every callback of this role.
-
using DiscoveredCallback = std::function<void(BTStatus status, const BLEAudioCapPeerInfo &peer)>
-
struct BLEAudioCapPeerInfo : public BLEAudioUnicastPeerInfo
A CAP acceptor as discovered by the initiator (CAS + PACS + ASCS).
Public Members
-
bool coordinatedSet = false
CAS includes a CSIS instance (one device of a set).
-
bool coordinatedSet = false
BLEAudioCoordinatedSet.h
-
class BLEAudioCoordinatedSetCoordinator
CSIP Set Coordinator (CSIP client).
Created by BLEAudio::createCoordinatedSetCoordinator() while the engine is active and before audio.begin().
Public Types
-
using DiscoveredCallback = std::function<void(BTStatus status, const BLEAudioCoordinatedSetInfo &info)>
Set information read from one member.
- Param status:
OK when discovery finished; error status when it failed.
- Param info:
Set information (setCount 0 when
statusis an error).
-
using LockCallback = std::function<void(BTStatus status, bool locked)>
lock() (
lockedtrue) or unlock() finished on every member.- Param status:
OK when the procedure finished; error status when it failed.
- Param locked:
True when the set is now locked.
-
using LockChangedCallback = std::function<void(bool locked, uint16_t connHandle)>
A member reported a lock change made by another client.
- Param locked:
True when the set is now locked.
- Param connHandle:
Member that reported the change.
Public Functions
-
explicit operator bool() const
Whether this handle references a coordinator (false when the factory failed).
-
BTStatus discover(uint16_t connHandle)
Read the set information of a connected member.
Starts once
BLEAudio::onLinkReady()fired forconnHandle; the result is reported by onDiscovered(). The first member discovered defines the set used by isSetMember(), lock() and unlock().- Parameters:
connHandle – ACL connection handle of the member.
- Returns:
BTStatus::InvalidState when the handle is empty, before audio.begin(), or for BLE_AUDIO_CONN_NONE; OK when discovery started or was deferred until GATT discovery; another status when discovery failed to start.
-
bool isSetMember(const uint8_t *advPayload, size_t len) const
Whether an advertising payload carries an RSI of the discovered set.
- Parameters:
advPayload – Advertising payload to scan for an RSI.
len – Octets in
advPayload.
- Returns:
True when an RSI of the discovered set was found; false otherwise (including no discovered set yet).
-
BTStatus lock()
Lock every connected, discovered member of the set, in rank order.
- Returns:
BTStatus::InvalidState when the handle is empty or no set was discovered yet; otherwise the stack status (OK when the procedure started, result via onLock).
-
BTStatus unlock()
Release the lock on every member.
- Returns:
BTStatus::InvalidState when the handle is empty or no set was discovered yet; otherwise the stack status (OK when the procedure started, result via onLock).
-
BLEAudioCoordinatedSetInfo setInfo() const
The set of the first discovered member (setCount 0 before).
-
void onDiscovered(DiscoveredCallback cb)
Result of each discover().
- Parameters:
cb – Callback receiving the discovery
statusandinfo.
-
void onLock(LockCallback cb)
-
- Parameters:
cb – Callback receiving the procedure
statusandlockedstate.
-
void onLockChanged(LockChangedCallback cb)
A member’s lock changed outside this coordinator.
- Parameters:
cb – Callback receiving the
lockedstate and the memberconnHandle.
-
void resetCallbacks()
Clear every callback of this role.
-
using DiscoveredCallback = std::function<void(BTStatus status, const BLEAudioCoordinatedSetInfo &info)>
-
struct BLEAudioCoordinatedSetInfo
Set information read from one member.
Public Members
-
uint16_t connHandle = 0xFFFF
Member the information was read from.
-
uint8_t setCount = 0
CSIS instances on the member (0: not in a set).
-
uint8_t setSize = 0
Devices in the set.
-
uint8_t rank = 0
Position of this member in the set.
-
bool lockable = false
The set can be locked.
-
uint8_t sirk[BLE_AUDIO_SIRK_SIZE] = {}
SIRK read from the member.
-
uint16_t connHandle = 0xFFFF
-
class BLEAudioCoordinatedSetMember
CSIP Set Member (CSIS server).
Created by BLEAudio::createCoordinatedSetMember() while the engine is active and before audio.begin(), which registers it.
Public Types
-
enum class SirkAccess : uint8_t
Answer to a client reading the SIRK (see onSirkRead()).
Values:
-
enumerator Accept
Send the SIRK in plain text.
-
enumerator AcceptEncrypted
Send the SIRK encrypted with the link key.
-
enumerator Reject
Refuse the read.
-
enumerator OobOnly
The SIRK is only available out of band.
-
enumerator Accept
-
using LockCallback = std::function<void(bool locked, uint16_t connHandle)>
The set lock changed.
- Param locked:
True when the set is now locked.
- Param connHandle:
Client that (un)locked the set.
-
using SirkReadCallback = std::function<SirkAccess(uint16_t connHandle)>
A client reads the SIRK.
- Param connHandle:
Client requesting the SIRK.
- Return:
How to answer the read.
Public Functions
-
explicit operator bool() const
Whether this handle references a member (false when the factory failed).
-
BTStatus setSirk(const uint8_t sirk[BLE_AUDIO_SIRK_SIZE])
Set Identity Resolving Key shared by every member. Default: a fixed demo SIRK; products must set their own.
- Parameters:
sirk – 16-octet SIRK; null is rejected.
- Returns:
BTStatus::OK when staged (or live-updated when running); InvalidState on an empty handle; InvalidParam for a null
sirk.
-
BTStatus setSetSize(uint8_t size)
Number of devices in the set. Default 2.
- Parameters:
size – Devices in the set; must be non-zero.
- Returns:
BTStatus::OK when staged (or live-updated when running); InvalidState on an empty handle; InvalidParam for a zero
size.
-
BTStatus setRank(uint8_t rank)
Position of this device in the set, 1..size (lock order). Default 1.
- Parameters:
rank – 1-based rank; zero is rejected.
- Returns:
BTStatus::OK when staged (or live-updated when running); InvalidState on an empty handle; InvalidParam for a zero
rank.
-
BTStatus setLockable(bool lockable)
Whether clients may lock the set. Default true. Only read at audio.begin().
- Parameters:
lockable – True to allow locking.
- Returns:
BTStatus::OK when staged; InvalidState on an empty handle or after audio.begin().
-
BTStatus setName(const String &name)
Optional set name exposed to clients.
- Parameters:
name – New name (empty = none).
- Returns:
BTStatus::OK when staged (before start) or applied (once running); InvalidState on an empty handle; another error when the stack refused the live update.
-
BTStatus generateRsi(uint8_t rsi[BLE_AUDIO_RSI_SIZE]) const
Generate a fresh Resolvable Set Identifier to advertise (AD type 0x2E).
- Parameters:
rsi – Destination buffer of BLE_AUDIO_RSI_SIZE octets.
- Returns:
BTStatus::InvalidState when the handle is empty, before audio.begin(), or for a null
rsi; otherwise the stack status.
-
BTStatus lock()
Lock the set locally, as a client would.
- Returns:
BTStatus::InvalidState when the handle is empty or before audio.begin(); otherwise the stack status.
-
BTStatus unlock(bool force = false)
Release the lock;
forcealso releases a lock held by a client.- Parameters:
force – True to release a client-held lock as well.
- Returns:
BTStatus::InvalidState when the handle is empty or before audio.begin(); otherwise the stack status.
-
bool isLocked() const
- Returns:
true while the set is locked, locally or by a client.
-
void onLockChanged(LockCallback cb)
Lock changes, local or remote.
- Parameters:
cb – Callback receiving the locked state and the client
connHandle.
-
void onSirkRead(SirkReadCallback cb)
Without a callback every read is accepted.
- Parameters:
cb – Callback answering a SIRK read.
-
void resetCallbacks()
Clear every callback of this role.
-
enum class SirkAccess : uint8_t
BLEAudioHearingAid.h
-
class BLEAudioHearingAidController
HAP Hearing Aid Unicast Client (HAS client), bound to one peer.
Created by BLEAudio::createHearingAidController() while the engine is active and before audio.begin(). Requests are GATT operations: OK means the request was queued, and the answer arrives through onPreset / onPresetSwitch. Requests fail until discover() has bound a peer.
Public Types
-
using DiscoveredCallback = std::function<void(BTStatus status, BLEHearingAidType type)>
Discovery result.
- Param status:
OK when discovery finished; error status when it failed.
- Param type:
The peer’s hearing aid type.
-
using PresetCallback = std::function<void(uint8_t index, bool available, const String &name, bool isLast)>
One preset record, from readPresets() or a peer notification.
- Param index:
Preset index.
- Param available:
Whether the preset is selectable.
- Param name:
Preset name.
- Param isLast:
True for the last record of a readPresets() batch.
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle refers to a created controller.
-
BTStatus discover(uint16_t connHandle)
Discover the peer’s HAS on
connHandle(after audio.begin()).Waits for the engine’s GATT discovery of the link if needed. Only one peer is driven at a time: discovering another one replaces it.
- Parameters:
connHandle – ACL connection handle of the peer.
- Returns:
BTStatus::InvalidState when the handle is empty, before audio.begin(), or for BLE_AUDIO_CONN_NONE; OK when discovery started or was deferred until GATT discovery; another status when discovery failed to start.
-
uint16_t getConnHandle() const
- Returns:
The connection passed to discover(), or BLE_AUDIO_CONN_NONE.
-
BTStatus readPresets(uint8_t startIndex = 1, uint8_t maxCount = 255)
Read presets from the peer (one onPreset each, the last with isLast).
- Parameters:
startIndex – First preset index to read.
maxCount – Maximum number of presets to read.
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the request was queued (answers via onPreset); another status when the request failed to start.
-
BTStatus setActivePreset(uint8_t index, bool sync = false)
Activate preset
indexon the peer.- Parameters:
index – Preset index to activate.
sync – Ask the peer to switch its binaural partner too (needs preset sync support on the peer).
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the request was queued (answer via onPresetSwitch); another status when the request failed to start.
-
BTStatus nextPreset(bool sync = false)
Activate the peer’s next available preset.
- Parameters:
sync – As in setActivePreset().
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the request was queued (answer via onPresetSwitch); another status when the request failed to start.
-
BTStatus previousPreset(bool sync = false)
Activate the peer’s previous available preset.
- Parameters:
sync – As in setActivePreset().
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the request was queued (answer via onPresetSwitch); another status when the request failed to start.
-
BTStatus renamePreset(uint8_t index, const String &name)
Rename a writable preset on the peer.
- Parameters:
index – Preset index to rename.
name – New preset name.
- Returns:
BTStatus::InvalidState when the handle is empty or no peer is discovered/active; OK when the request was queued; another status when the request failed to start.
-
uint8_t getActivePreset() const
- Returns:
the peer’s last reported active preset, 0 when unknown.
-
void onDiscovered(DiscoveredCallback cb)
Discovery finished; also fires with an error when a deferred discovery could not start.
-
void onPreset(PresetCallback cb)
Preset records (reads and change notifications).
-
void onPresetSwitch(SwitchCallback cb)
The peer’s active preset changed.
-
void resetCallbacks()
Drop every registered callback.
-
using DiscoveredCallback = std::function<void(BTStatus status, BLEHearingAidType type)>
-
class BLEAudioHearingAidDevice
HAP Hearing Aid (HAS server).
Created by BLEAudio::createHearingAidDevice() while the engine is active and before audio.begin(). Copies of the handle control the same device; an empty handle does nothing, and its BTStatus calls return InvalidState.
Public Types
-
using SelectCallback = std::function<void(uint8_t index, bool sync)>
A controller selected a preset.
- Param index:
Selected preset index.
- Param sync:
True when the controller asked the binaural pair to follow.
-
using RenameCallback = std::function<void(uint8_t index, const String &name)>
A controller renamed a preset.
- Param index:
Renamed preset index.
- Param name:
New preset name.
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle refers to a created device.
-
BTStatus setType(BLEHearingAidType type)
Default Monaural.
- Returns:
BTStatus::OK when staged; InvalidState when the handle is empty or after audio.begin().
-
BTStatus setPresetSync(bool enabled)
Keep presets in sync across a binaural pair. Default off.
- Returns:
BTStatus::OK when staged; InvalidState when the handle is empty or after audio.begin().
-
BTStatus addPreset(uint8_t index, const String &name, bool available = true, bool writable = false)
Add a preset (index >= 1, unique).
Presets added before audio.begin() are registered by start(); later ones are registered at once. At most CONFIG_BT_HAS_PRESET_COUNT presets;
writableneeds CONFIG_BT_HAS_PRESET_NAME_DYNAMIC.- Parameters:
index – Preset index (>= 1, unique; 0 is logged and ignored).
name – Preset name shown to controllers.
available – Whether controllers may select the preset.
writable – Whether controllers may rename the preset.
- Returns:
BTStatus::OK when staged or registered; InvalidState when the handle is empty; InvalidParam for index 0 or an empty/duplicate name; another status when registration failed.
-
BTStatus removePreset(uint8_t index)
Unregister preset
index.- Parameters:
index – Preset index to remove.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
BTStatus setPresetAvailable(uint8_t index, bool available)
Mark preset
index(un)available; controllers cannot select an unavailable one.- Parameters:
index – Preset index to update.
available – True to make the preset selectable.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
BTStatus renamePreset(uint8_t index, const String &name)
Rename preset
indexlocally.- Parameters:
index – Preset index to rename.
name – New preset name.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
BTStatus setActivePreset(uint8_t index)
Activate preset
indexlocally.- Parameters:
index – Preset index to activate.
- Returns:
BTStatus::InvalidState when the handle is empty; otherwise the stack status.
-
uint8_t getActivePreset() const
- Returns:
the active preset index, 0 when none.
-
void onPresetSelected(SelectCallback cb)
A controller selected a preset.
-
void onPresetRenamed(RenameCallback cb)
A controller renamed a writable preset.
-
void resetCallbacks()
Drop every registered callback.
-
using SelectCallback = std::function<void(uint8_t index, bool sync)>
BLEAudioMedia.h
-
class BLEAudioMediaController
MCP Media Controller (client of one peer’s GMCS).
Created by BLEAudio::createMediaController() while the engine is active and before audio.begin(). Commands and reads are GATT operations: OK means the request was queued, and the answer arrives through the matching callback. Requests before discover() return BTStatus::InvalidState.
Stack Kconfig matrix (a call returns NotSupported when its option is off): sendCommand()/play()/pause()/stop()/nextTrack()/previousTrack() need CONFIG_BT_MCC_SET_MEDIA_CONTROL_POINT; readState() needs CONFIG_BT_MCC_READ_MEDIA_STATE; readTrackTitle() needs CONFIG_BT_MCC_READ_TRACK_TITLE; readPlayerName() is always available. Only the GMCS instance is driven; discrete MCS and OTS are not exposed.
Public Types
-
using DiscoveredCallback = std::function<void(BTStatus status)>
Discovery (and subscription) result.
-
using StateCallback = std::function<void(BLEAudioMediaState state)>
The peer’s media state.
-
using CommandCallback = std::function<void(BLEAudioMediaCommand command, BTStatus result)>
The peer’s answer to
command.
-
using TextCallback = std::function<void(const String &text)>
A text characteristic value (player name or track title).
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle refers to a created controller.
-
BTStatus discover(uint16_t connHandle)
Discover the peer’s media player on
connHandleand subscribe to it (after audio.begin()).Waits for the engine’s GATT discovery of the link if needed; the media state is read right after onDiscovered. Every call below targets this peer.
- Parameters:
connHandle – ACL connection of the peer’s media player.
- Returns:
BTStatus::OK when discovery started (or was deferred until the engine’s GATT discovery finishes); InvalidState when the handle is empty, audio is not started, or
connHandleis BLE_AUDIO_CONN_NONE; another error when the stack refused discovery.
-
uint16_t getConnHandle() const
- Returns:
The connection passed to discover(), or BLE_AUDIO_CONN_NONE.
-
BTStatus sendCommand(BLEAudioMediaCommand command)
Write
commandto the peer’s Media Control Point (answered via onCommandResult).- Parameters:
command – Media Control Point opcode to write.
- Returns:
BTStatus::OK when the write was queued (the answer arrives via onCommandResult); InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); NotSupported without CONFIG_BT_MCC_SET_MEDIA_CONTROL_POINT; another error when the stack refused the write.
-
BTStatus play()
sendCommand(Play).
- Returns:
As sendCommand().
-
BTStatus pause()
sendCommand(Pause).
- Returns:
As sendCommand().
-
BTStatus stop()
sendCommand(Stop).
- Returns:
As sendCommand().
-
BTStatus nextTrack()
sendCommand(NextTrack).
- Returns:
As sendCommand().
-
BTStatus previousTrack()
sendCommand(PreviousTrack).
- Returns:
As sendCommand().
-
BTStatus readState()
Read the media state (answered via onStateChanged).
- Returns:
BTStatus::OK when the read was queued; InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); NotSupported without CONFIG_BT_MCC_READ_MEDIA_STATE; another error when the stack refused the read.
-
BTStatus readPlayerName()
Read the player name (answered via onPlayerName).
- Returns:
BTStatus::OK when the read was queued; InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); another error when the stack refused the read.
-
BTStatus readTrackTitle()
Read the track title (answered via onTrackTitle).
- Returns:
BTStatus::OK when the read was queued; InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); NotSupported without CONFIG_BT_MCC_READ_TRACK_TITLE; another error when the stack refused the read.
-
BLEAudioMediaState getState() const
Last state reported by the peer (Inactive after disconnect).
-
void onDiscovered(DiscoveredCallback cb)
Discovery finished; also fires with an error when a deferred discovery could not start.
-
void onStateChanged(StateCallback cb)
State reads and notifications.
-
void onCommandResult(CommandCallback cb)
Media Control Point results.
-
void onPlayerName(TextCallback cb)
Player name reads.
-
void onTrackTitle(TextCallback cb)
Track title reads and notifications.
-
void resetCallbacks()
Drop every registered callback.
-
using DiscoveredCallback = std::function<void(BTStatus status)>
-
class BLEAudioMediaPlayer
MCP Media Player (GMCS server).
Created by BLEAudio::createMediaPlayer() while the engine is active and before audio.begin(). Copies of the handle control the same player; an empty handle does nothing, and its BTStatus calls return InvalidState.
Public Types
-
using StateCallback = std::function<void(BLEAudioMediaState state)>
New media state.
-
using CommandCallback = std::function<void(BLEAudioMediaCommand command, BTStatus result)>
Outcome of
command.
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle refers to a created player.
-
BTStatus setPlayerName(const String &name)
Player name; applied at audio.begin(), or immediately (and notified) once running.
- Parameters:
name – New player name.
- Returns:
BTStatus::OK when the name was staged (before start) or applied (once running); InvalidState when the handle is empty; another error when the stack refused the new text (the previous text is kept).
-
BTStatus setTrackTitle(const String &title)
Current track title; same timing as setPlayerName().
- Parameters:
title – New track title.
- Returns:
BTStatus::OK when the title was staged (before start) or applied (once running); InvalidState when the handle is empty; another error when the stack refused the new text (the previous text is kept).
-
BTStatus sendCommand(BLEAudioMediaCommand command)
Run
commandon the local player; the outcome arrives through onCommandResult.- Parameters:
command – Media Control Point opcode to run.
- Returns:
BTStatus::OK when the command was sent (the outcome arrives via onCommandResult); InvalidState when the handle is empty or the player is not running yet; NotSupported without CONFIG_BT_MCTL_LOCAL_PLAYER_LOCAL_CONTROL; another error when the stack refused the command.
-
BTStatus play()
sendCommand(Play).
- Returns:
As sendCommand().
-
BTStatus pause()
sendCommand(Pause).
- Returns:
As sendCommand().
-
BTStatus stop()
sendCommand(Stop).
- Returns:
As sendCommand().
-
BTStatus nextTrack()
sendCommand(NextTrack).
- Returns:
As sendCommand().
-
BTStatus previousTrack()
sendCommand(PreviousTrack).
- Returns:
As sendCommand().
-
BLEAudioMediaState getState() const
Last state reported by the player.
-
void onStateChanged(StateCallback cb)
Player state changes, whoever caused them.
-
void onCommandResult(CommandCallback cb)
Result of every command, local or from a remote controller.
-
void resetCallbacks()
Drop every registered callback.
-
using StateCallback = std::function<void(BLEAudioMediaState state)>
-
enum class BLEAudioMediaCommand : uint8_t
Media Control Point opcodes.
Values:
-
enumerator Play
Start playback.
-
enumerator Pause
Pause playback.
-
enumerator FastRewind
Fast rewind.
-
enumerator FastForward
Fast forward.
-
enumerator Stop
Stop playback.
-
enumerator PreviousTrack
Skip to the previous track.
-
enumerator NextTrack
Skip to the next track.
-
enumerator FirstTrack
Skip to the first track.
-
enumerator LastTrack
Skip to the last track.
-
enumerator PreviousGroup
Skip to the previous group.
-
enumerator NextGroup
Skip to the next group.
-
enumerator Play
BLEAudioMic.h
-
class BLEAudioMicController
MICP Microphone Controller (client of one device at a time).
Created by BLEAudio::createMicController() while the engine is active and before audio.begin(). Commands are GATT writes: OK means the write was queued. Success arrives as onMuteChanged / onInputChanged; a rejected write arrives as onResult and changes nothing. Cached state is cleared on disconnect. Commands before discover() return BTStatus::InvalidState. Only the first AICS instance is driven; more instances are reported in onDiscovered and otherwise ignored. A second discover() replaces the peer.
Public Types
-
enum class Operation : uint8_t
Queued control-point operation reported by onResult.
Values:
-
enumerator Unknown
No operation in flight.
-
enumerator ReadMute
-
enumerator SetInputGain
-
enumerator Unknown
-
using DiscoveredCallback = std::function<void(BTStatus status, uint8_t inputCount)>
Discovery result, with the number of microphone AICS instances found.
-
using MuteCallback = std::function<void(bool muted)>
The device’s mute state.
-
using InputCallback = std::function<void(int8_t gain, bool muted)>
Gain and mute of the device’s first microphone AICS instance.
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle refers to a created controller.
-
BTStatus discover(uint16_t connHandle)
Discover the microphone device on
connHandle(after audio.begin()).Waits for the engine’s GATT discovery of the link if needed; the peer’s mute state is read right after onDiscovered. Every call below targets this peer.
- Parameters:
connHandle – ACL connection of the microphone device.
- Returns:
BTStatus::OK when discovery started (or was deferred until the engine’s GATT discovery finishes); InvalidState when the handle is empty, audio is not started, or
connHandleis BLE_AUDIO_CONN_NONE; another error when the stack refused discovery.
-
uint16_t getConnHandle() const
- Returns:
The connection passed to discover(), or BLE_AUDIO_CONN_NONE.
-
BTStatus mute()
Mute the device’s microphone.
- Returns:
BTStatus::OK when the write was queued (reported via onMuteChanged, or via onResult on failure); InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); another error when the stack refused the write.
-
BTStatus unmute()
Unmute the device’s microphone (fails at the peer while its mute is disabled).
- Returns:
BTStatus::OK when the write was queued (reported via onMuteChanged, or via onResult on failure); InvalidState when the handle is empty, no peer is discovered (also while discovery is still deferred), or the peer currently reports mute as disabled; another error when the stack refused the write.
-
BTStatus readMute()
Re-read the peer’s mute state (answered via onMuteChanged).
- Returns:
BTStatus::OK when the read was queued; InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); another error when the stack refused the read.
-
bool isMuted() const
Last mute state reported by the peer (false while disabled; cleared on disconnect).
-
bool isMuteDisabled() const
Whether the peer currently reports mute as disabled.
-
BTStatus setInputGain(int8_t gain)
Gain of the peer’s first microphone AICS instance.
- Parameters:
gain – New gain, in the peer’s gain units.
- Returns:
BTStatus::OK when the write was queued (reported via onInputChanged, or via onResult on failure); InvalidState when the handle is empty, no peer is discovered, or the peer exposed no AICS instance; NotSupported when this build has no AICS controller support; another error when the stack refused the write.
-
void onDiscovered(DiscoveredCallback cb)
Discovery finished; also fires with an error when a deferred discovery could not start.
-
void onMuteChanged(MuteCallback cb)
The device’s mute state was read or changed.
-
void onInputChanged(InputCallback cb)
The device’s microphone input gain or mute changed.
-
void onResult(ResultCallback cb)
A queued operation failed; the state did not change.
The op is the most recently queued one (best effort: concurrent writes share one notification channel, so with several in flight the reported op may be a sibling). Unknown when no operation was queued. NotConnected when the link dropped while an operation was in flight.
-
void resetCallbacks()
Drop every registered callback.
-
enum class Operation : uint8_t
-
class BLEAudioMicDevice
MICP Microphone Device (Microphone Control Service server).
Created by BLEAudio::createMicDevice() while the engine is active and before audio.begin(). Copies of the handle control the same device; an empty handle does nothing, and its BTStatus calls return InvalidState.
Public Types
-
enum class Operation : uint8_t
Local control-point operation reported by onResult.
Values:
-
enumerator Unknown
No operation in flight.
-
enumerator DisableMute
-
enumerator Unknown
-
using MuteCallback = std::function<void(bool muted)>
Mute state after a change.
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle refers to a created device.
-
BTStatus setInitialMute(bool muted)
Default unmuted. Before audio.begin().
- Returns:
BTStatus::OK when staged; InvalidState when the handle is empty or audio is already started.
-
BTStatus mute()
Mute locally (after audio.begin()); connected controllers are notified.
- Returns:
BTStatus::OK when the change was queued (reported via onMuteChanged, or via onResult on failure); InvalidState when the handle is empty or audio is not started; another error when the stack refused the request.
-
BTStatus unmute()
Unmute; also re-enables a disabled mute.
- Returns:
BTStatus::OK when the change was queued (reported via onMuteChanged, or via onResult on failure); InvalidState when the handle is empty or audio is not started; another error when the stack refused the request.
-
BTStatus disableMute()
Report mute as unavailable; controllers can no longer change it.
- Returns:
BTStatus::OK when the change was queued (reported via onMuteChanged, or via onResult on failure); InvalidState when the handle is empty or audio is not started; another error when the stack refused the request.
-
bool isMuted() const
- Returns:
The initial mute before start, then the last reported mute (false while disabled).
-
bool isMuteDisabled() const
Whether mute is currently reported as disabled (neither muted nor unmuted).
-
void onMuteChanged(MuteCallback cb)
Every mute change, local or remote (disabled reports unmuted/false: see isMuteDisabled()).
-
void onResult(ResultCallback cb)
A queued local operation failed; the state did not change.
-
void resetCallbacks()
Drop every registered callback.
-
enum class Operation : uint8_t
BLEAudioPCM.h
-
using BLEAudioPCMSink = std::function<void(const int16_t *pcm, size_t samples)>
Consumer of decoded PCM, called on the codec task once per LC3 frame.
Real-time budget: return within one frame interval (7.5/10 ms nominal, 8.16/10.88 ms at 44.1 kHz); overruns stall the output and count as underruns. Must not block on BLE, call attach()/start()/stop()/end(), or touch stream taps (use loop() for teardown). Reentrant-safe: it runs on the codec task, never on the BT host or Arduino loop tasks.
- Param pcm:
Interleaved 16-bit PCM with
channels()channels.- Param samples:
Total samples (frames x channels).
-
using BLEAudioPCMSource = std::function<size_t(int16_t *pcm, size_t samples)>
Producer of PCM to encode, called on the codec task once per LC3 frame.
Same real-time budget and restrictions as the sink: fill fast, never block on BLE or the data path. A short return is padded with silence.
- Param pcm:
Fill with interleaved 16-bit PCM with
channels()channels.- Param samples:
Total samples wanted (frames x channels).
- Return:
Samples produced; the rest of the frame is padded with silence.
BLEAudioPlayer.h
-
class BLEAudioPlayer
Public Functions
-
BTStatus begin()
Use the built-in I2S output, or no I2S when a PCM sink is set.
With no pins, this is only valid after setPCMSink(): the player then delivers frames to the callback and never opens an I2S port. For I2S, use begin(bclk, ws, dout) instead.
- Returns:
InvalidParam without a PCM sink or I2S pins, InvalidState while playback is running.
-
BTStatus begin(int bclk, int ws, int dout, int mclk = -1, int port = 0)
Select the I2S output pins.
- Parameters:
bclk – Bit clock (SCLK) GPIO.
ws – Word select (LRCLK/WS) GPIO.
dout – Data out GPIO (player -> DAC).
mclk – Master clock GPIO, or -1 when not wired.
port – I2S peripheral port (default 0).
- Returns:
InvalidParam when a required pin is missing, InvalidState while playback is running.
-
void end()
Stop, detach and release everything.
Called from a PCM sink callback (codec task), the release is deferred: the task is asked to stop and end() must be called again from loop() to free the Impl. This avoids destroying the codec task from inside itself.
-
BTStatus setPCMSink(BLEAudioPCMSink sink)
Deliver decoded PCM to
sinkinstead of I2S (before begin(); InvalidState once begun/running).A set sink wins over I2S: begin(pins) then only logs and keeps the sink.
- Returns:
BTStatus::OK when stored; InvalidState when begun or running.
-
BTStatus setJitterDepth(uint8_t sdus)
Jitter-buffer depth in SDUs (min 2, max 16); 0 = from the stream QoS (default).
Larger requests are clamped to 16 with a warning when the session builds; a presentation delay that needs more than 16 SDUs underruns by design.
- Returns:
BTStatus::OK when stored; InvalidState while running.
-
BTStatus attach(BLEAudioStream stream)
Play one Rx stream (mono or interleaved stereo).
One argument: the stream carries mono or interleaved stereo (1 or 2 channels). Use the two-argument overload for two separate mono streams.
-
BTStatus attach(BLEAudioStream stream, BLEAudioStream right)
Play two separate mono Rx streams (left, right).
Both handles must be non-empty, carry exactly one channel and describe the same codec/QoS; otherwise the data path cannot pair them.
-
BTStatus startPlayback()
Start the decode task; playback follows the attached streams’ start/stop.
This is not BLEAudio::begin(): the controller commits the roles and GATT table, while this method starts the LC3 task that consumes the streams.
-
void stopPlayback()
Stop the decode task; attachments are kept, so startPlayback() resumes.
-
bool isRunning() const
- Returns:
true while the decode task runs.
-
uint8_t channels() const
PCM channels handed to the sink (I2S is always stereo); 0 while idle.
-
uint32_t sampleRate() const
Current sample rate in Hz; 0 while idle.
-
uint32_t sdusReceived() const
SDUs delivered by the stack, whatever their status.
-
uint32_t sdusDropped() const
SDUs discarded because the jitter buffer was full.
-
uint32_t sdusLost() const
SDUs flagged lost/invalid by the controller or with an unexpected length.
-
uint32_t plcFrames() const
LC3 frames (per channel) produced by packet-loss concealment.
-
uint32_t underruns() const
SDU intervals in which a streaming stream had nothing queued.
-
uint32_t lateResyncs() const
PCM-sink timeline restarts after falling behind (tick quantization, no data lost).
-
BTStatus begin()
BLEAudioProfiles.h
-
class BLEAudioGmap
GMAP identity (GMAS server and GMAP client).
Public Types
-
using DiscoverCallback = std::function<void(uint16_t connHandle, BTStatus status, BLEAudioGmapRole peerRoles, const BLEAudioGmapFeatures &peerFeatures)>
Roles and features read from the peer.
- Param connHandle:
ACL connection handle the roles were read from.
- Param status:
OK when the read finished; error status when it failed.
- Param peerRoles:
Roles published by the peer.
- Param peerFeatures:
Features published by the peer (zero when
statusis an error).
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle was created by BLEAudio::createGmap().
-
BTStatus setRoles(BLEAudioGmapRole roles)
Roles published by GMAS (before
audio.begin()).- Returns:
BTStatus::OK when staged; InvalidState when the handle is empty or after audio.begin(); InvalidParam for unknown role bits.
-
BTStatus setFeatures(const BLEAudioGmapFeatures &features)
Features of the published roles (before
audio.begin()).- Returns:
BTStatus::OK when staged; InvalidState when the handle is empty or after audio.begin(); InvalidParam for unknown feature bits.
-
BTStatus setFeatures(uint8_t unicastGateway, uint8_t unicastTerminal, uint8_t broadcastSender, uint8_t broadcastReceiver)
Same as setFeatures(const BLEAudioGmapFeatures &), one bitfield per role.
- Returns:
-
BLEAudioGmapRole getRoles() const
- Returns:
The local roles set with setRoles().
-
BTStatus discover(uint16_t connHandle)
Read the GMAP roles and features of a connected peer (result in onDiscovered()).
- Parameters:
connHandle – ACL connection handle of the peer.
- Returns:
BTStatus::InvalidState when the handle is empty, before audio.begin(), or for BLE_AUDIO_CONN_NONE; OK when discovery started or was deferred until GATT discovery; another status when discovery failed to start.
-
void onDiscovered(DiscoverCallback cb)
Result of each discover().
-
void resetCallbacks()
Drop every registered callback.
-
using DiscoverCallback = std::function<void(uint16_t connHandle, BTStatus status, BLEAudioGmapRole peerRoles, const BLEAudioGmapFeatures &peerFeatures)>
-
struct BLEAudioGmapFeatures
GMAP feature bitfields, one per role; a role’s field is ignored unless the role is set.
-
class BLEAudioPublicBroadcast
Public Broadcast Announcement (PBP) builder / parser.
Needs PBP in the packaged libraries (
BLE_AUDIO_PBP_SUPPORTED); without it both helpers fail.Public Types
Public Static Functions
-
static size_t buildAnnouncement(uint8_t features, const uint8_t *metadata, size_t metadataLen, uint8_t *out, size_t outCap)
Build the value of a Service Data 16-bit AD structure.
outreceives the 0x1856 UUID (2 bytes, little-endian), the features, the metadata length and the metadata.- Parameters:
- Returns:
Bytes written (4 +
metadataLen), or 0 on error.
-
static bool parseAnnouncement(const uint8_t *data, size_t dataLen, uint8_t &featuresOut, const uint8_t *&metadataOut, size_t &metadataLenOut)
Parse a Service Data 16-bit AD value (starting with its UUID).
- Parameters:
data – Announcement bytes starting with the 16-bit UUID.
dataLen – Octets in
data.featuresOut – Receives the feature bits.
metadataOut – Points into
data(null when there is no metadata).metadataLenOut – Receives the octets in
metadataOut.
- Returns:
false if
datais not a Public Broadcast Announcement.
-
static size_t buildAnnouncement(uint8_t features, const uint8_t *metadata, size_t metadataLen, uint8_t *out, size_t outCap)
-
class BLEAudioTmap
TMAP identity (TMAS server and TMAP client).
Public Types
-
using DiscoverCallback = std::function<void(uint16_t connHandle, BTStatus status, BLEAudioTmapRole peerRoles)>
Roles read from the peer.
- Param connHandle:
ACL connection handle the roles were read from.
- Param status:
OK when the read finished; error status when it failed.
- Param peerRoles:
Roles published by the peer (None when
statusis an error).
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle was created by BLEAudio::createTmap().
-
BTStatus setRoles(BLEAudioTmapRole roles)
Roles published by TMAS (before
audio.begin()).- Returns:
BTStatus::OK when staged; InvalidState when the handle is empty or after audio.begin(); InvalidParam for unknown role bits.
-
BLEAudioTmapRole getRoles() const
- Returns:
The local roles set with setRoles().
-
BTStatus discover(uint16_t connHandle)
Read the TMAP roles of a connected peer (result in onDiscovered()).
- Parameters:
connHandle – ACL connection handle of the peer.
- Returns:
BTStatus::InvalidState when the handle is empty, before audio.begin(), or for BLE_AUDIO_CONN_NONE; OK when discovery started or was deferred until GATT discovery; another status when discovery failed to start.
-
void onDiscovered(DiscoverCallback cb)
Result of each discover().
-
void resetCallbacks()
Drop every registered callback.
-
using DiscoverCallback = std::function<void(uint16_t connHandle, BTStatus status, BLEAudioTmapRole peerRoles)>
-
enum class BLEAudioGmapRole : uint8_t
GMAP roles (GMAP Role characteristic bits).
Each role also needs its CONFIG_BT_GMAP_<role>_SUPPORTED option in the packaged libraries; otherwise
audio.begin()fails with InvalidParam.Values:
-
enumerator None
-
enumerator UnicastGameGateway
UGG: the console / PC end.
-
enumerator UnicastGameTerminal
UGT: the headset end.
-
enumerator BroadcastGameSender
BGS.
-
enumerator BroadcastGameReceiver
BGR.
-
enumerator None
-
enum class BLEAudioTmapRole : uint16_t
TMAP roles (TMAP Role characteristic bits).
Values:
-
enumerator None
No TMAP role.
-
enumerator CallGateway
CG: places / controls calls.
-
enumerator CallTerminal
CT: the headset end of a call.
-
enumerator UnicastMediaSender
UMS.
-
enumerator UnicastMediaReceiver
UMR.
-
enumerator BroadcastMediaSender
BMS: Auracast transmitter.
-
enumerator BroadcastMediaReceiver
BMR: Auracast receiver.
-
enumerator None
-
inline bool operator&(BLEAudioGmapRole a, BLEAudioGmapRole b)
- Returns:
true when
aandbshare a role.
-
inline bool operator&(BLEAudioTmapRole a, BLEAudioTmapRole b)
- Returns:
true when
aandbshare a role (e.g.roles & CallTerminal).
-
inline BLEAudioGmapRole operator|(BLEAudioGmapRole a, BLEAudioGmapRole b)
Combine GMAP roles.
-
inline BLEAudioTmapRole operator|(BLEAudioTmapRole a, BLEAudioTmapRole b)
Combine TMAP roles.
-
inline BLEAudioGmapRole &operator|=(BLEAudioGmapRole &a, BLEAudioGmapRole b)
-
inline BLEAudioTmapRole &operator|=(BLEAudioTmapRole &a, BLEAudioTmapRole b)
BLEAudioRecorder.h
-
class BLEAudioRecorder
Public Functions
-
BTStatus begin()
Use the built-in I2S input, or no I2S when a PCM source is set.
With no pins, this is only valid after setPCMSource(): the recorder then takes frames from the callback and never opens an I2S port. For I2S, use begin(bclk, ws, din) instead.
- Returns:
InvalidParam without a PCM source or I2S pins, InvalidState while capture is running.
-
BTStatus begin(int bclk, int ws, int din, int mclk = -1, int port = 0)
Select the I2S input pins.
- Parameters:
bclk – Bit clock (SCLK) GPIO.
ws – Word select (LRCLK/WS) GPIO.
din – Data in GPIO (recorder <- ADC/mic).
mclk – Master clock GPIO, or -1 when not wired.
port – I2S peripheral port (default 0).
- Returns:
InvalidParam when a required pin is missing, InvalidState while capture is running.
-
void end()
Stop, detach and release everything.
Called from a PCM source callback (codec task), the release is deferred: the task is asked to stop and end() must be called again from loop() to free the Impl and its timer. This avoids destroying the codec task from inside itself.
-
BTStatus setPCMSource(BLEAudioPCMSource source)
Take PCM from
sourceinstead of I2S (before begin(); InvalidState once begun/running).- Returns:
BTStatus::OK when stored; InvalidState when begun or running.
-
BTStatus attach(BLEAudioStream stream)
Feed one Tx stream (mono or interleaved stereo).
One argument: the stream carries mono or interleaved stereo (1 or 2 channels). Use the two-argument overload for two separate mono streams.
-
BTStatus attach(BLEAudioStream stream, BLEAudioStream right)
Feed two separate mono Tx streams (left, right).
Both handles must be non-empty, carry exactly one channel and describe the same codec/QoS; otherwise the data path cannot pair them.
-
BTStatus startCapture()
Start the encode task; sending follows the attached streams’ start/stop.
This is not BLEAudio::begin(): the controller commits the roles and GATT table, while this method starts the LC3 task that produces the streams.
-
void stopCapture()
Stop the encode task; attachments are kept, so startCapture() resumes.
-
bool isRunning() const
- Returns:
true while the encode task runs.
-
uint8_t channels() const
PCM channels taken from the source/I2S; 0 while idle.
-
uint32_t sampleRate() const
Current sample rate in Hz; 0 while idle.
-
uint32_t sdusSent() const
SDUs accepted by the stack (counted per stream).
-
uint32_t sendErrors() const
SDUs that failed to encode or were refused by the stack.
-
uint32_t txStalls() const
Resync episodes after the controller stopped releasing SDUs (TX stall).
-
BTStatus begin()
BLEAudioStream.h
-
class BLEAudioStream
Public Types
-
enum class Direction : uint8_t
Data direction as seen from the local device.
Values:
-
enumerator Unknown
Not configured yet (unicast server stream before the peer configures it).
-
enumerator Tx
This device sends SDUs (unicast source ASE, or a broadcast source BIS).
-
enumerator Rx
This device receives SDUs (unicast sink ASE, or a broadcast sink BIS).
-
enumerator Unknown
-
using Callback = std::function<void(BLEAudioStream &stream)>
State change of
stream(configured, started, SDU sent).
-
using StoppedCallback = std::function<void(BLEAudioStream &stream, uint8_t reason)>
streamleft the Streaming state;reasonis the HCI or ASCS reason code.
-
using ReceiveCallback = std::function<void(BLEAudioStream &stream, const BLEAudioSduInfo &info, const uint8_t *sdu, uint16_t len)>
One SDU arrived on
stream.- Param info:
Sequence number, timestamp and packet status.
- Param sdu:
Payload; only valid during the call. Empty when
info.statusis Lost.- Param len:
Payload length in octets.
Public Functions
-
BLEAudioStream()
Create an empty stream handle.
Get a live one from a role’s stream(); the empty handle reports Unknown / defaults for state, refuses write() with InvalidParam and ignores every callback setter.
-
BLEAudioStream(const BLEAudioStream&) = default
Share the referenced stream (copying never duplicates the engine slot).
-
BLEAudioStream &operator=(const BLEAudioStream&) = default
Share the referenced stream (copying never duplicates the engine slot).
-
BLEAudioStream(BLEAudioStream&&) = default
Move the stream reference.
-
BLEAudioStream &operator=(BLEAudioStream&&) = default
Move the stream reference.
-
explicit operator bool() const
Whether this handle references a stream (false for the handles returned on error).
-
inline bool operator==(const BLEAudioStream &other) const
Two handles are equal when they reference the same stream.
- Parameters:
other – Handle to compare with.
- Returns:
True when both reference the same engine slot (two empty handles compare equal).
-
inline bool operator!=(const BLEAudioStream &other) const
Two handles differ when they reference different streams.
- Parameters:
other – Handle to compare with.
- Returns:
True when the handles reference different engine slots.
-
Direction direction() const
Direction of the stream.
Unicast streams report Unknown until the endpoint is bound; broadcast source streams are always Tx and broadcast sink streams always Rx, even before the codec is configured.
-
bool isStreaming() const
Whether the stream is in the Streaming state (SDUs may flow).
- Returns:
True while streaming; false on an empty handle.
-
uint16_t connHandle() const
ACL connection of a unicast stream; 0xFFFF for broadcast or unbound streams.
- Returns:
The connection handle, or BLE_AUDIO_CONN_NONE (0xFFFF) for broadcast, unbound or empty handles.
-
BLEAudioCodecConfig codecConfig() const
Codec configuration in use; defaults until the stream is configured.
- Returns:
The negotiated codec, or a default BLEAudioCodecConfig on an empty handle.
-
BLEAudioQos qos() const
QoS in use; defaults until QoS is configured.
- Returns:
The negotiated QoS, or a default BLEAudioQos on an empty handle.
-
BTStatus write(const uint8_t *sdu, uint16_t len)
Send one SDU on a streaming Tx stream.
Call once per SDU interval (
qos().sduIntervalUs) withcodecConfig().sduOctets()bytes. The sequence number is managed internally and advances only when the controller accepted the SDU.- Parameters:
sdu – SDU payload (copied before the call returns).
len – Payload length in octets.
- Returns:
BTStatus::OK when queued; InvalidParam for an empty payload or a null handle; InvalidState on an Rx stream or one that is not streaming; another error when the controller refused the SDU.
-
void onConfigured(Callback cb)
Codec configured: by the peer (unicast), at create (broadcast source) or at sync (broadcast sink).
- Parameters:
cb – Callback receiving the configured
stream.
-
void onStarted(Callback cb)
The stream entered the Streaming state.
- Parameters:
cb – Callback receiving the started
stream.
-
void onStopped(StoppedCallback cb)
The stream left the Streaming state (disable, release, CIS/BIG loss).
- Parameters:
cb – Callback receiving the stopped
streamand the HCI/ASCSreason.
-
void onReceive(ReceiveCallback cb)
An SDU arrived on an Rx stream.
- Parameters:
cb – Callback receiving the
stream,info,sduandlen.
-
void onSent(Callback cb)
The controller released a queued SDU of a Tx stream (one call per write()).
- Parameters:
cb – Callback receiving the
streamwhose SDU was released.
-
void resetCallbacks()
Clear every callback of this stream.
Leaves the data-path tap (BLEAudioPlayer/BLEAudioRecorder) untouched.
-
enum class Direction : uint8_t
BLEAudioTypes.h
-
struct BLEAudioCodecConfig
LC3 codec configuration of one stream.
Prefer building it with fromPreset(); set the fields directly only for a custom configuration. All fields use the specification’s units. A stream negotiated by a peer reports its actual configuration through
BLEAudioStream::codecConfig().Public Functions
-
uint8_t channels() const
Channels carried by one stream: set bits of channelAllocation, 1 for Mono.
- Returns:
The channel count (at least 1).
-
inline uint16_t samplesPerFrame() const
PCM samples per channel in one LC3 frame (e.g. 160 at 16 kHz / 10 ms).
LC3 runs 44.1 kHz with the 48 kHz frame length (480 / 360 samples), so the actual frame there lasts 10.884 / 8.163 ms instead of the nominal frameDurationUs.
-
inline uint16_t sduOctets() const
Octets in one SDU: octets per frame x channels x frame blocks.
- Returns:
The SDU payload size in octets.
Public Members
-
uint32_t samplingRateHz = 16000
PCM sampling rate (8000 to 48000).
-
uint16_t frameDurationUs = 10000
LC3 frame duration: 7500 or 10000.
-
uint16_t octetsPerFrame = 40
Encoded octets per channel per frame.
-
uint8_t framesPerSdu = 1
Codec frame blocks packed into one SDU.
-
BLEAudioLocation channelAllocation = BLEAudioLocation::Mono
One channel per set bit.
Public Static Functions
-
static BLEAudioCodecConfig fromPreset(BLEAudioCodecPreset preset)
Build the configuration of a standard BAP preset (mono).
- Parameters:
preset – Preset whose codec configuration to return.
- Returns:
The preset configuration; a default configuration (with an error log) when
presetis unknown.
-
uint8_t channels() const
-
struct BLEAudioQos
Isochronous QoS of one stream.
fromPreset() returns the BAP low-latency values for a preset; override fields only for a custom link. The presentation delay is the time between the SDU reference anchor and the moment the audio is rendered; every device of a group renders at the same instant thanks to it.
Public Members
-
uint32_t sduIntervalUs = 10000
Time between SDUs; matches the frame duration.
-
uint16_t maxSdu = 40
Largest SDU in octets (all channels, all blocks).
-
uint8_t retransmissions = 2
Controller retransmission number (RTN).
-
uint16_t maxTransportLatencyMs = 10
Upper bound on the controller’s transport latency.
-
uint32_t presentationDelayUs = 40000
Render delay after the SDU anchor.
-
uint8_t phy = 0x02
PHY bitmask: 0x01 1M, 0x02 2M, 0x04 Coded.
-
bool framed = false
Framed ISO (required by the 44.1 kHz presets).
Public Static Functions
-
static BLEAudioQos fromPreset(BLEAudioCodecPreset preset, bool broadcast = false)
Build the low-latency QoS of a BAP preset.
- Parameters:
preset – Preset whose QoS to return.
broadcast – Use the broadcast table (BAP Table 6.4), whose RTN differs from unicast at 44.1 and 48 kHz.
- Returns:
The preset QoS; a default QoS (with an error log) when
presetis unknown.
-
uint32_t sduIntervalUs = 10000
-
struct BLEAudioSduInfo
Per-SDU metadata handed to
BLEAudioStream::onReceivecallbacks.Public Types
-
enum class BLEAudioCodecPreset : uint8_t
Standard BAP LC3 presets (“LC3_<rate>_<variant>_1”, BAP Tables 5.2 / 6.4).
Each preset fixes the sampling rate, frame duration and octets per frame, and brings the matching low-latency QoS (SDU interval, retransmissions, max transport latency and a 40 ms presentation delay). The 44.1 kHz presets use framed ISO because their frames do not divide the SDU interval evenly.
The enumerator order is part of the engine contract: it indexes the preset table in
BLEAudioEngine.c, so never reorder or insert values.Values:
-
enumerator LC3_8_1_1
8 kHz, 7.5 ms, 26 octets
-
enumerator LC3_8_2_1
8 kHz, 10 ms, 30 octets
-
enumerator LC3_16_1_1
16 kHz, 7.5 ms, 30 octets
-
enumerator LC3_16_2_1
16 kHz, 10 ms, 40 octets (mandatory for most roles)
-
enumerator LC3_24_1_1
24 kHz, 7.5 ms, 45 octets
-
enumerator LC3_24_2_1
24 kHz, 10 ms, 60 octets
-
enumerator LC3_32_1_1
32 kHz, 7.5 ms, 60 octets
-
enumerator LC3_32_2_1
32 kHz, 10 ms, 80 octets
-
enumerator LC3_441_1_1
44.1 kHz, 7.5 ms, 97 octets (framed)
-
enumerator LC3_441_2_1
44.1 kHz, 10 ms, 130 octets (framed)
-
enumerator LC3_48_1_1
48 kHz, 7.5 ms, 75 octets
-
enumerator LC3_48_2_1
48 kHz, 10 ms, 100 octets
-
enumerator LC3_48_3_1
48 kHz, 7.5 ms, 90 octets
-
enumerator LC3_48_4_1
48 kHz, 10 ms, 120 octets
-
enumerator LC3_48_5_1
48 kHz, 7.5 ms, 117 octets
-
enumerator LC3_48_6_1
48 kHz, 10 ms, 155 octets
-
enumerator LC3_8_1_1
-
enum class BLEAudioContext : uint16_t
Audio context types (Assigned Numbers, “Context Type” bitfield).
Describes what a stream carries and which contexts a device supports or currently makes available. PACS publishes them as “Supported” and “Available” Audio Contexts; a unicast client sends one with Enable, and a broadcast source puts one in its BASE metadata. Combine with
operator|.Values:
-
enumerator Prohibited
No context; also “not available right now”.
-
enumerator Unspecified
Any audio not covered by another type.
-
enumerator Conversational
Phone or video call.
-
enumerator Media
Music, radio, podcast, video soundtrack.
-
enumerator Game
Game audio.
-
enumerator Instructional
Navigation, announcements, user guidance.
-
enumerator VoiceAssistants
Man-machine voice interaction.
-
enumerator Live
Live audio (e.g. a venue broadcast).
-
enumerator SoundEffects
Keyboard and touch feedback, UI sounds.
-
enumerator Notifications
Incoming message alerts.
-
enumerator Ringtone
Incoming call alert.
-
enumerator Alerts
Alarms and timers.
-
enumerator EmergencyAlarm
Emergency sounds (e.g. fire alarm).
-
enumerator Prohibited
-
enum class BLEAudioLocation : uint32_t
Audio channel allocation (Assigned Numbers, “Audio Location” bitfield).
A 32-bit bitmap of speaker positions.
Monois the special all-zero value (one channel with no position). A stream carries one channel per set bit; a device publishes the union of the locations it can render or capture. Only the common positions are named; any other Assigned Numbers bit can be passed with a cast.Values:
-
enumerator Mono
-
enumerator FrontLeft
-
enumerator FrontRight
-
enumerator FrontCenter
-
enumerator LowFreqEffects1
-
enumerator BackLeft
-
enumerator BackRight
-
enumerator SideLeft
-
enumerator SideRight
-
enumerator Mono
-
inline uint32_t BLEAudioPresetBit(BLEAudioCodecPreset p)
Bit of preset
pin a preset mask.Used by the roles that publish capabilities, e.g.
server.setSupportedPresets(LC3_16_2_1 | LC3_48_2_1)(plain presets may be OR-ed directly; wrapping single presets in BLEAudioPresetBit() works too).- Parameters:
p – Preset whose mask bit to return.
- Returns:
1 shifted by the preset enumerator (bit
p).
-
inline uint32_t operator&(BLEAudioCodecPreset a, uint32_t b)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
inline uint32_t operator&(uint32_t a, BLEAudioCodecPreset b)
Test whether a preset mask contains
b.Lets call sites write
(peer.sinkPresets & LC3_48_2_1)instead of wrapping the preset in BLEAudioPresetBit().
-
inline uint32_t operator|(BLEAudioCodecPreset a, BLEAudioCodecPreset b)
Combine presets (or a mask and presets) into a preset mask.
Lets call sites write
LC3_16_2_1 | LC3_48_2_1instead of wrapping every preset in BLEAudioPresetBit(). Mixing with an existing mask works too:mask | LC3_48_1_1. Fully backward compatible: plainBLEAudioPresetBit(...)expressions are unchangeduint32_tarithmetic.
-
inline uint32_t operator|(BLEAudioCodecPreset a, uint32_t b)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
inline BLEAudioContext operator|(BLEAudioContext a, BLEAudioContext b)
Combine two context sets.
- Parameters:
a – Left set.
b – Right set.
- Returns:
The union of
aandb.
-
inline BLEAudioLocation operator|(BLEAudioLocation a, BLEAudioLocation b)
Combine two location sets.
- Parameters:
a – Left set.
b – Right set.
- Returns:
The union of
aandb.
-
inline uint32_t operator|(uint32_t a, BLEAudioCodecPreset b)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
inline BLEAudioContext &operator|=(BLEAudioContext &a, BLEAudioContext b)
Add
bto the context seta.- Parameters:
a – Set to extend.
b – Bits to add.
- Returns:
Reference to
a.
-
inline BLEAudioLocation &operator|=(BLEAudioLocation &a, BLEAudioLocation b)
Add
bto the location seta.- Parameters:
a – Set to extend.
b – Bits to add.
- Returns:
Reference to
a.
BLEAudioUnicastClient.h
-
class BLEAudioUnicastClient
Public Types
-
enum class Step : uint8_t
Stream setup step that failed (see onError()).
Values:
-
enumerator Config
ASCS Config Codec.
-
enumerator Qos
ASCS Config QoS.
-
enumerator Enable
ASCS Enable.
-
enumerator Start
ASCS Receiver Start Ready.
-
enumerator Connect
CIS creation.
-
enumerator Group
CIG creation (controller rejected the QoS / stream set).
-
enumerator Config
-
using DiscoveredCallback = std::function<void(const BLEAudioUnicastPeerInfo &peer)>
A peer finished discovery;
peerlists what it supports.
-
using Callback = std::function<void()>
A setup-wide event with no payload (all streams streaming / released).
Runs on the Bluetooth host task; keep it short.
-
using ErrorCallback = std::function<void(Step step, uint8_t responseCode, uint8_t reason)>
Stream setup failed at
step; the client then releases every stream.- Param responseCode:
ASCS response code from the server, or 0 when the local request failed (CIG/CIS creation included).
- Param reason:
ASCS reason from the server, or 0 for local failures.
Public Functions
-
explicit operator bool() const
Whether this handle references a client (false when the factory failed).
-
BTStatus setPreset(BLEAudioCodecPreset preset)
Codec and QoS of every stream, from a BAP preset. Default LC3_16_2_1.
- Parameters:
preset – Preset to use.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or while running; InvalidParam for an unknown preset.
-
BTStatus setQos(const BLEAudioQos &qos)
Replace the preset’s QoS with a custom one.
Without it, the preset QoS is used with the controller’s presentation delay.
maxSduis always recomputed per stream from its codec.- Parameters:
qos – Custom QoS applied instead of the preset one from the next start().
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or while running.
-
BTStatus setContext(BLEAudioContext context)
Streaming context sent with Enable. Default Media.
- Parameters:
context – Context announced when the streams are enabled.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or while running.
-
BTStatus setSinkStreams(uint8_t perPeer)
Streams this device sends, per peer (remote sink ASEs). Default 1.
- Parameters:
perPeer – Requested Tx streams per peer, capped by the peer’s sink endpoints.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or while running.
-
BTStatus setSourceStreams(uint8_t perPeer)
Streams this device receives, per peer (remote source ASEs). Default 0.
- Parameters:
perPeer – Requested Rx streams per peer, capped by the peer’s source endpoints.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or while running.
-
BTStatus addPeer(uint16_t connHandle)
Add a connected server and discover its PACS and ASCS.
When the peer’s GATT database is not known yet, discovery starts on its own once
BLEAudio::onLinkReady()fires forconnHandle. The result is reported by onDiscovered(). Adding a known peer again is a no-op.- Returns:
BTStatus::OK when discovery started or is pending; InvalidState before audio.begin(); another error when discovery failed to start.
-
BTStatus start()
Configure and start streams on every discovered peer.
Per peer, requests at most as many streams as the peer has endpoints. Non-blocking: onStarted() fires once every stream streams, onError() if a step fails.
- Returns:
BTStatus::OK when the setup started; InvalidState when already running or when no discovered peer has a usable endpoint; NoMemory when the stream pool is exhausted.
-
BTStatus connectAndStart(uint16_t connHandle)
addPeer(), then start() as soon as the peer is discovered.
Clearer name for connect(uint16_t); both are equivalent. A peer that is already discovered starts immediately, otherwise on discovery.
- Parameters:
connHandle – ACL connection of the server.
- Returns:
BTStatus::OK when discovery is pending or the setup started; the addPeer() error when discovery failed to start.
-
BTStatus stop()
Release every stream and remove the CIG (onStopped() follows).
- Returns:
BTStatus::OK when the release started; InvalidState when not running.
-
bool isStreaming() const
Whether every requested stream is streaming (between onStarted() and onStopped()).
- Returns:
True while the UC_STARTED state holds; false on an empty handle.
-
size_t streamCount() const
Streams of the current setup, in request order (per peer: sink streams, then source).
-
BLEAudioStream stream(size_t index) const
Stream
indexin [0, streamCount()); empty handle when out of range.- Parameters:
index – Position in request order (per peer: sink streams, then source).
- Returns:
The stream, or an empty handle when
indexis out of range.
-
BLEAudioStream stream(BLEAudioStream::Direction dir, uint8_t index = 0) const
The
index-thstream in directiondir(Tx = to a remote sink).- Parameters:
dir – Tx = streams this device sends; Rx = streams it receives.
index – Position among the streams of
dir.
- Returns:
An empty handle when there are fewer streams in
dir.
-
void onDiscovered(DiscoveredCallback cb)
A peer finished PACS/ASCS discovery.
- Parameters:
cb – Callback receiving the discovered
peerinfo.
-
void onStarted(Callback cb)
Every stream of the setup is streaming.
- Parameters:
cb – Callback fired once all streams stream.
-
void onStopped(Callback cb)
Every stream was released (after stop() or a failure).
- Parameters:
cb – Callback fired once the streams are released.
-
void onError(ErrorCallback cb)
A setup step failed; onStopped() follows once the streams are released.
- Parameters:
cb – Callback receiving the failed
step,responseCodeandreason.
-
void resetCallbacks()
Clear every callback of this role.
-
enum class Step : uint8_t
-
struct BLEAudioUnicastPeerInfo
What a unicast server exposes, as discovered by the client (PACS + ASCS).
Reported per peer through onDiscovered() after addPeer()/connectAndStart(); sinkPresets/sourcePresets accumulate one BLEAudioPresetBit() per remote LC3 PAC record as they arrive.
Subclassed by BLEAudioCapPeerInfo
Public Members
-
uint16_t connHandle = 0xFFFF
ACL connection of the server.
-
uint8_t sinkEndpoints = 0
Remote sink ASEs: streams this device can send.
-
uint8_t sourceEndpoints = 0
Remote source ASEs: streams this device can receive.
-
BLEAudioLocation sinkLocation = BLEAudioLocation::Mono
Locations the server renders.
-
BLEAudioLocation sourceLocation = BLEAudioLocation::Mono
Locations the server captures.
-
BLEAudioContext sinkContexts = BLEAudioContext::Prohibited
Contexts available for sink streams now.
-
BLEAudioContext sourceContexts = BLEAudioContext::Prohibited
Contexts available for source streams now.
-
uint32_t sinkPresets = 0
Presets the server’s sink PAC records accept (BLEAudioPresetBit() mask): what this device can send.
-
uint32_t sourcePresets = 0
Presets the server’s source PAC records accept (BLEAudioPresetBit() mask): what this device can receive.
-
uint16_t connHandle = 0xFFFF
BLEAudioUnicastServer.h
-
class BLEAudioUnicastServer
Public Functions
-
BLEAudioUnicastServer()
Create an empty server handle.
Get a live one from BLEAudio::createUnicastServer() while the engine is active and before audio.begin(); the empty handle reports InvalidState from every setter and empty stream from every stream().
-
BLEAudioUnicastServer(const BLEAudioUnicastServer&) = default
Share the referenced server (copying never duplicates the engine registration).
-
BLEAudioUnicastServer &operator=(const BLEAudioUnicastServer&) = default
Share the referenced server (copying never duplicates the engine registration).
-
BLEAudioUnicastServer(BLEAudioUnicastServer&&) = default
Move the server reference.
-
BLEAudioUnicastServer &operator=(BLEAudioUnicastServer&&) = default
Move the server reference.
-
explicit operator bool() const
Whether this handle references a server (false when the factory failed).
-
BTStatus setSinkStreams(uint8_t count)
Number of sink ASEs to publish (streams the client sends to).
- Parameters:
count – 0 disables the sink direction. Default 1; capped by the packaged Kconfig ASE count (the stream pool logs when full).
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or after audio.begin().
-
BTStatus setSourceStreams(uint8_t count)
Number of source ASEs to publish (streams the client receives).
- Parameters:
count – 0 disables the source direction. Default 1; same cap as setSinkStreams().
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or after audio.begin().
-
BTStatus setSupportedPresets(uint32_t presetMask)
LC3 presets advertised in PACS, as a mask of BLEAudioPresetBit().
The server publishes one PAC record covering the union of the presets (rates, durations, octet range), so a client may pick any combination inside it. Default: every 10 ms preset at 16, 24, 32 and 48 kHz. A zero mask keeps the current value.
- Parameters:
presetMask – OR of BLEAudioPresetBit() values; 0 keeps the current mask.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or after audio.begin(); InvalidParam for a zero mask.
-
BTStatus setMaxChannelsPerStream(uint8_t channels)
Channels one ASE may carry: 1 (default) or 2.
- Parameters:
channels – 1 = mono, 2 = mono or stereo per ASE.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or after audio.begin(); InvalidParam for a value other than 1 or 2.
-
BTStatus setSinkContexts(BLEAudioContext contexts)
Contexts the sink supports (PACS “Supported Audio Contexts”); also the initial available set.
- Parameters:
contexts – Bitfield of BLEAudioContext values the sink renders.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or after audio.begin().
-
BTStatus setSourceContexts(BLEAudioContext contexts)
Contexts the source supports; also the initial available set.
- Parameters:
contexts – Bitfield of BLEAudioContext values the source captures.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or after audio.begin().
-
BTStatus setSinkLocation(BLEAudioLocation location)
Sink Audio Locations published in PACS (default Mono).
- Parameters:
location – Union of the speaker positions the sink renders.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or after audio.begin().
-
BTStatus setSourceLocation(BLEAudioLocation location)
Source Audio Locations published in PACS (default Mono).
- Parameters:
location – Union of the positions the source captures.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or after audio.begin().
-
BTStatus setPresentationDelayRange(uint32_t minUs, uint32_t maxUs)
Presentation delay range the server supports (ASCS QoS preferences).
- Parameters:
minUs – Minimum delay (default 20000 us).
maxUs – Maximum delay; 0 (default) uses the controller’s BLEAudio::setPresentationDelay() value.
- Returns:
BTStatus::OK on success; InvalidState on an empty handle or after audio.begin(); InvalidParam when
maxUsis nonzero andminUsexceeds it.
-
BTStatus configureMediaSink()
Configure the usual speaker shape: one stereo-capable sink ASE.
Shorthand for:
setSinkStreams(1); setSourceStreams(0); setMaxChannelsPerStream(2); setSupportedPresets(LC3_16_2_1 | LC3_24_2_1 | LC3_48_2_1); setSinkContexts(Media | Conversational); setSinkLocation(FrontLeft | FrontRight);
The single ASE accepts mono or stereo, so a phone can send one interleaved stream instead of one stream per speaker. Call it after createUnicastServer() and before audio.begin(); individual setters can still override any field afterwards.
- Returns:
BTStatus::OK on success; the first failing setter’s status otherwise (InvalidState on an empty handle or after audio.begin()).
-
BTStatus configureHeadset()
Configure the usual headset shape: one sink ASE and one source ASE.
Shorthand for:
setSinkStreams(1); setSourceStreams(1); setMaxChannelsPerStream(2); setSupportedPresets(LC3_16_2_1 | LC3_24_2_1 | LC3_48_2_1); setSinkContexts(Media | Conversational); setSourceContexts(Conversational | Media); setSinkLocation(FrontLeft | FrontRight); setSourceLocation(Mono);
The sink ASE renders phone media and call audio; the source ASE carries the headset microphone back to the phone. Call it after createUnicastServer() and before audio.begin(); individual setters can still override any field afterwards.
- Returns:
BTStatus::OK on success; the first failing setter’s status otherwise (InvalidState on an empty handle or after audio.begin()).
-
BTStatus setAvailableContexts(BLEAudioContext sink, BLEAudioContext source)
Change the contexts currently available (PACS “Available Audio Contexts”).
A client only enables streams for an available context; publish
Prohibitedwhile busy (e.g. in a call on another link).- Parameters:
sink – Contexts currently available on the sink ASEs.
source – Contexts currently available on the source ASEs.
- Returns:
BTStatus::OK on success; InvalidState before audio.begin().
-
size_t streamCount() const
Streams owned by the server (sink + source count, fewer if the pool ran out).
-
BLEAudioStream stream(size_t index) const
Stream
indexin [0, streamCount()); empty handle when out of range.- Parameters:
index – Position in allocation order (sink streams first, then source).
- Returns:
The stream, or an empty handle when
indexis out of range.
-
BLEAudioStream stream(BLEAudioStream::Direction dir, uint8_t index = 0) const
The
index-thstream a client configured in directiondir.- Parameters:
dir – Tx = stream the client receives from here (source ASE); Rx = stream the client sends to here (sink ASE).
index – Position among the streams configured in
dir.
- Returns:
An empty handle when fewer streams are configured in
dir.
-
BLEAudioUnicastServer()
BLEAudioVolume.h
-
class BLEAudioVolumeController
VCP Volume Controller (client of one renderer at a time).
Created by BLEAudio::createVolumeController() while the engine is active and before audio.begin(). Commands are GATT writes: a returned OK means the write was queued. Success arrives as onStateChanged / onOffsetChanged / onInputChanged when the renderer notifies; a rejected write arrives as onResult (best effort op attribution, see onResult()) and changes nothing. Cached state is cleared on disconnect. Commands before discover() return BTStatus::InvalidState. Only the first VOCS/AICS instance is driven; more instances are reported in onDiscovered and otherwise ignored. A second discover() replaces the peer.
Public Types
-
enum class Operation : uint8_t
Queued control-point operation reported by onResult.
Values:
-
enumerator Unknown
No operation in flight.
-
enumerator SetVolume
-
enumerator VolumeUp
-
enumerator VolumeDown
-
enumerator ReadState
-
enumerator SetOffset
-
enumerator SetInputGain
-
enumerator Unknown
-
using DiscoveredCallback = std::function<void(BTStatus status, uint8_t offsetCount, uint8_t inputCount)>
Discovery result, with the number of VOCS and AICS instances found.
-
using StateCallback = std::function<void(uint8_t volume, bool muted)>
Renderer volume (0..255) and mute.
-
using OffsetCallback = std::function<void(int16_t offset)>
Volume offset of the renderer’s first VOCS instance.
-
using InputCallback = std::function<void(int8_t gain, bool muted)>
Gain and mute of the renderer’s first AICS instance.
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle refers to a created controller.
-
BTStatus discover(uint16_t connHandle)
Discover the renderer on
connHandle(after audio.begin()).Waits for the engine’s GATT discovery of the link if needed. onDiscovered fires once the peer’s current volume is known (followed by onStateChanged); every other call below targets this peer.
- Parameters:
connHandle – ACL connection of the renderer.
- Returns:
BTStatus::OK when discovery started (or was deferred until the engine’s GATT discovery finishes); InvalidState when the handle is empty, audio is not started, or
connHandleis BLE_AUDIO_CONN_NONE; another error when the stack refused discovery.
-
uint16_t getConnHandle() const
- Returns:
The connection passed to discover(), or BLE_AUDIO_CONN_NONE.
-
BTStatus setVolume(uint8_t volume)
Write an absolute volume, 0..255.
- Parameters:
volume – New volume (0..255).
- Returns:
BTStatus::OK when the write was queued (reported via onStateChanged, or via onResult on failure); InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); another error when the stack refused the write.
-
BTStatus mute()
Mute the renderer.
- Returns:
BTStatus::OK when the write was queued (reported via onStateChanged, or via onResult on failure); InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); another error when the stack refused the write.
-
BTStatus unmute()
Unmute the renderer.
- Returns:
BTStatus::OK when the write was queued (reported via onStateChanged, or via onResult on failure); InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); another error when the stack refused the write.
-
BTStatus volumeUp()
Relative volume up by the renderer’s own step.
- Returns:
BTStatus::OK when the write was queued (reported via onStateChanged, or via onResult on failure); InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); another error when the stack refused the write.
-
BTStatus volumeDown()
Relative volume down by the renderer’s own step.
- Returns:
BTStatus::OK when the write was queued (reported via onStateChanged, or via onResult on failure); InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); another error when the stack refused the write.
-
BTStatus readState()
Re-read the peer’s volume state (answered via onStateChanged).
- Returns:
BTStatus::OK when the read was queued; InvalidState when the handle is empty or no peer is discovered (also while discovery is still deferred); another error when the stack refused the read.
-
uint8_t getVolume() const
Last volume reported by the peer.
-
bool isMuted() const
Last mute state reported by the peer.
-
BTStatus setVolumeOffset(int16_t offset)
Volume offset of the peer’s first VOCS instance, -255..255.
- Parameters:
offset – New offset (-255..255).
- Returns:
BTStatus::OK when the write was queued (reported via onOffsetChanged, or via onResult on failure); InvalidState when the handle is empty, no peer is discovered, or the peer exposed no VOCS instance; NotSupported when this build has no VOCS controller support; another error when the stack refused the write.
-
BTStatus setInputGain(int8_t gain)
Gain of the peer’s first AICS instance, in the peer’s gain units.
- Parameters:
gain – New gain, in the peer’s gain units.
- Returns:
BTStatus::OK when the write was queued (reported via onInputChanged, or via onResult on failure); InvalidState when the handle is empty, no peer is discovered, or the peer exposed no AICS instance; NotSupported when this build has no AICS controller support; another error when the stack refused the write.
-
void onDiscovered(DiscoveredCallback cb)
Discovery finished; also fires with an error when a deferred discovery could not start.
-
void onStateChanged(StateCallback cb)
The renderer’s volume or mute changed.
-
void onOffsetChanged(OffsetCallback cb)
The renderer’s volume offset changed.
-
void onInputChanged(InputCallback cb)
The renderer’s audio input gain or mute changed.
-
void onResult(ResultCallback cb)
A queued operation failed; the state did not change.
The op is the most recently queued one (best effort: concurrent writes share one notification channel, so with several in flight the reported op may be a sibling). Unknown when no operation was queued. NotConnected when the link dropped while an operation was in flight.
-
void resetCallbacks()
Drop every registered callback.
-
enum class Operation : uint8_t
-
class BLEAudioVolumeRenderer
VCP Volume Renderer (Volume Control Service server).
Created by BLEAudio::createVolumeRenderer() while the engine is active and before audio.begin(). The handle is a cheap shared reference; copies control the same renderer. A default-constructed (or failed) handle is empty: calls on it do nothing, and those returning BTStatus return InvalidState.
Public Types
-
enum class Operation : uint8_t
Local control-point operation reported by onResult.
Values:
-
enumerator Unknown
No operation in flight.
-
enumerator SetVolume
-
enumerator VolumeUp
-
enumerator VolumeDown
-
enumerator SetStep
setVolumeStep() applied at runtime.
-
enumerator Unknown
-
using StateCallback = std::function<void(uint8_t volume, bool muted)>
Volume (0..255) and mute after a change.
Public Functions
-
explicit operator bool() const
- Returns:
true when the handle refers to a created renderer.
-
BTStatus setInitialVolume(uint8_t volume)
Default 100.
- Returns:
BTStatus::OK when staged; InvalidState when the handle is empty or audio is already started.
-
BTStatus setInitialMute(bool muted)
Default unmuted.
- Returns:
BTStatus::OK when staged; InvalidState when the handle is empty or audio is already started.
-
BTStatus setVolumeStep(uint8_t step)
Step used by volumeUp()/volumeDown() and remote relative writes; 1..255, default 1. Also at runtime.
- Returns:
BTStatus::OK when staged (before start) or applied (once running); InvalidParam when
stepis 0; InvalidState when the handle is empty; another error when the stack refused the runtime update (the previous step is kept).
-
BTStatus setVolume(uint8_t volume)
Set the absolute volume, 0..255.
- Parameters:
volume – New volume (0..255).
- Returns:
BTStatus::OK when the change was queued (reported via onStateChanged, or via onResult on failure); InvalidState when the handle is empty or audio is not started; another error when the stack refused the request.
-
BTStatus mute()
Mute; the volume setting is kept.
- Returns:
BTStatus::OK when the change was queued (reported via onStateChanged, or via onResult on failure); InvalidState when the handle is empty or audio is not started; another error when the stack refused the request.
-
BTStatus unmute()
Unmute.
- Returns:
BTStatus::OK when the change was queued (reported via onStateChanged, or via onResult on failure); InvalidState when the handle is empty or audio is not started; another error when the stack refused the request.
-
BTStatus volumeUp()
Raise the volume by the step (saturates at 255).
- Returns:
BTStatus::OK when the change was queued (reported via onStateChanged, or via onResult on failure); InvalidState when the handle is empty or audio is not started; another error when the stack refused the request.
-
BTStatus volumeDown()
Lower the volume by the step (saturates at 0).
- Returns:
BTStatus::OK when the change was queued (reported via onStateChanged, or via onResult on failure); InvalidState when the handle is empty or audio is not started; another error when the stack refused the request.
-
uint8_t getVolume() const
- Returns:
The initial volume before start, then the last reported volume.
-
bool isMuted() const
- Returns:
The initial mute before start, then the last reported mute.
-
void onStateChanged(StateCallback cb)
Every volume/mute change, local or remote.
-
void onResult(ResultCallback cb)
A queued local operation failed; the state did not change.
-
void resetCallbacks()
Drop every registered callback.
-
enum class Operation : uint8_t