arduino-audio-tools
Loading...
Searching...
No Matches
AudioBLE.h
Go to the documentation of this file.
1#pragma once
2
3#include "AudioToolsConfig.h"
4
5// LE Audio (BLEAudio) is provided by the ESP32 Arduino core (e.g. ESP32-S31).
6// The class is only compiled when the LC3 codec is available (checked below).
7#if defined(ESP32)
8#define AUDIOTOOLS_LE_AUDIO_AVAILABLE 1
9#include <BLE.h>
10#include <BLEAudio.h>
11
12#include <atomic>
13
17
18#if BLE_AUDIO_LC3_SUPPORTED
19
20namespace audio_tools {
21
28class AudioBLEConfig : public AudioInfo {
29 public:
30 AudioBLEConfig() {
31 sample_rate = 48000;
32 channels = 2;
33 bits_per_sample = 16;
34 }
36 RxTxMode mode = RX_MODE;
38 const char* name = "LE Audio";
41 int buffer_size = 32 * 1024;
42};
43
71class AudioBLE : public AudioStream {
72 public:
73 AudioBLE() = default;
74 // the callbacks capture this: the object must not be copied
75 AudioBLE(const AudioBLE&) = delete;
76 AudioBLE& operator=(const AudioBLE&) = delete;
77 // the BLE callbacks refer to this object: release them while it still exists
78 ~AudioBLE() override { end(); }
79
81 AudioBLEConfig defaultConfig(RxTxMode mode = RX_MODE) {
82 AudioBLEConfig cfg;
83 cfg.mode = mode;
84 return cfg;
85 }
86
88 bool begin(RxTxMode mode, const char* name) {
89 AudioBLEConfig cfg = defaultConfig(mode);
90 cfg.name = name;
91 return begin(cfg);
92 }
93
96 bool begin(AudioBLEConfig cfg) {
97 TRACEI();
98 if (is_started) {
99 LOGW("AudioBLE: already started");
100 return false;
101 }
102 if (!rx_buffer.resize(cfg.buffer_size)) {
103 LOGE("AudioBLE: allocation of %d bytes failed", cfg.buffer_size);
104 return false;
105 }
106 config = cfg;
107 rx_dropped_bytes = 0;
108 if (!setup(cfg)) {
109 end(); // release whatever was set up
110 return false;
111 }
112 // initial format, until the peer defines it: only announced once started
113 updateInfo(cfg);
114 is_started = true;
115 return true;
116 }
117
120 void end() override {
121 TRACEI();
122 // stop the data path first: the codec task must not use the buffer anymore
123 if (player) {
124 player.stopPlayback();
125 player.end();
126 }
127 if (recorder) {
128 recorder.stopCapture();
129 recorder.end();
130 }
131 // the callbacks capture this: remove them before the roles are released
132 if (unicast_server) {
133 unicast_server.stream(::BLEAudioStream::Direction::Rx).resetCallbacks();
134 unicast_server.stream(::BLEAudioStream::Direction::Tx).resetCallbacks();
135 }
136 if (audio) audio.resetCallbacks();
137 if (ble_started) {
138 BLE.end(); // stops advertising, disconnects and deinitializes the host
139 ble_started = false;
140 }
141 unicast_server = ::BLEAudioUnicastServer();
142 cap_acceptor = ::BLEAudioCapAcceptor();
143 audio = ::BLEAudio();
144 rx_buffer.reset();
145 rx_event = NoEvent;
146 tx_event = NoEvent;
147 adv_restart_pending = false;
148 is_started = false;
149 }
150
152 operator bool() override {
153 if (!is_started) return false;
154 if (config.mode == RX_MODE) return player.isRunning();
155 return recorder.isRunning();
156 }
157
159 size_t readBytes(uint8_t* data, size_t len) override {
160 poll();
161 if (config.mode != RX_MODE) return 0;
162 return rx_buffer.readArray(data, len);
163 }
164
166 int available() override {
167 poll();
168 if (config.mode != RX_MODE) return 0;
169 return rx_buffer.available();
170 }
171
174 size_t write(const uint8_t* data, size_t len) override {
175 poll();
176 if (config.mode != TX_MODE) return 0;
177 return rx_buffer.writeArray(data, len);
178 }
179
181 int availableForWrite() override {
182 poll();
183 if (config.mode != TX_MODE) return 0;
184 return rx_buffer.availableForWrite();
185 }
186
190 void setAudioInfo(AudioInfo newInfo) override {
191 if (config.mode == TX_MODE) {
192 // warn once per distinct rejected format, not on every call
193 if (newInfo != AudioStream::audioInfo() && newInfo != rejected_info) {
194 rejected_info = newInfo;
195 LOGW("AudioBLE TX: ignoring format %d Hz %d ch, using %d Hz %d ch",
196 (int)newInfo.sample_rate, (int)newInfo.channels,
197 (int)AudioStream::audioInfo().sample_rate, (int)AudioStream::audioInfo().channels);
198 }
199 return;
200 }
201 AudioStream::setAudioInfo(newInfo);
202 }
203
205 uint32_t droppedBytes() const { return rx_dropped_bytes.load(); }
206
209 void poll() {
210 // advertise again after a peer has disconnected
211 if (adv_restart_pending.exchange(false)) {
212 // the core only restarts advertising for a GATT server, not for AudioBLE
213 BTStatus st = BLE.getAdvertising().start();
214 if (!st) LOGW("AudioBLE: advertising restart failed: %s", st.toString());
215 }
216 // RX: the format is defined by the decoder once the stream runs
217 if (config.mode == RX_MODE && player.isRunning()) {
218 AudioInfo format = player_info();
219 if (format.sample_rate > 0 && format.channels > 0) {
220 updateInfo(format);
221 }
222 }
223 int rx = rx_event.exchange(NoEvent);
224 if (rx == StartEvent) {
225 player.stopPlayback();
226 if (player.attach(unicast_server.stream(::BLEAudioStream::Direction::Rx))) {
227 player.startPlayback();
228 } else {
229 LOGE("AudioBLE RX: attach failed");
230 }
231 } else if (rx == StopEvent) {
232 player.stopPlayback();
233 }
234 int tx = tx_event.exchange(NoEvent);
235 if (tx == StartEvent) {
236 // TX: the format is the one negotiated with the peer
237 AudioInfo format;
238 format.sample_rate = tx_sample_rate.load();
239 format.channels = tx_channels.load();
240 format.bits_per_sample = 16;
241 updateInfo(format);
242 recorder.stopCapture();
243 if (recorder.attach(unicast_server.stream(::BLEAudioStream::Direction::Tx))) {
244 recorder.startCapture();
245 } else {
246 LOGE("AudioBLE TX: attach failed");
247 }
248 } else if (tx == StopEvent) {
249 recorder.stopCapture();
250 }
251 }
252
255 ::BLEAudioPlayer& getPlayer() { return player; }
258 ::BLEAudioRecorder& getRecorder() { return recorder; }
259
260 protected:
261 AudioBLEConfig config;
262 bool is_started = false;
263 bool ble_started = false;
264 ::BLEAudio audio;
265 ::BLEAudioCapAcceptor cap_acceptor;
266 ::BLEAudioUnicastServer unicast_server;
267 ::BLEAudioPlayer player; // RX
268 ::BLEAudioRecorder recorder; // TX
269 // single producer / single consumer: lock-free between the loop and the codec task
270 RingBufferSPSC<uint8_t> rx_buffer;
271 // set on the BLE task, read in poll(): the flags are atomic, the values are
272 // stored before the flag is set
273 // latest request of the BLE task per direction: the last one wins
274 enum EventType : int { NoEvent = 0, StartEvent = 1, StopEvent = 2 };
275 std::atomic<int> rx_event{NoEvent};
276 std::atomic<int> tx_event{NoEvent};
277 std::atomic<bool> adv_restart_pending{false};
278 std::atomic<uint32_t> tx_sample_rate{0};
279 std::atomic<uint8_t> tx_channels{0};
280 // written on the codec task
281 std::atomic<uint32_t> rx_dropped_bytes{0};
282 // last upstream format rejected in TX (used to log it only once)
283 AudioInfo rejected_info;
284
286 bool setup(AudioBLEConfig cfg) {
287 BTStatus st = BLE.begin(cfg.name);
288 if (!st) {
289 LOGE("BLE.begin failed: %s", st.toString());
290 return false;
291 }
292 ble_started = true;
293 audio = BLE.getAudioController();
294 if (!audio) {
295 LOGE("getAudioController failed");
296 return false;
297 }
298 // a peer that disconnects is followed by advertising again (in poll())
299 audio.onDisconnected([this](uint16_t) { adv_restart_pending = true; });
300 cap_acceptor = audio.createCapAcceptor();
301 if (!cap_acceptor || !cap_acceptor.setSetSize(1) || !cap_acceptor.setRank(1)) {
302 LOGE("CAP acceptor setup failed");
303 return false;
304 }
305 unicast_server = audio.createUnicastServer();
306 if (!unicast_server) {
307 LOGE("createUnicastServer failed");
308 return false;
309 }
310
311 if (cfg.mode == RX_MODE) {
312 // one sink ASE, no source ASE
313 st = unicast_server.configureMediaSink();
314 if (st) st = unicast_server.setSourceStreams(0);
315 if (!st) {
316 LOGE("sink setup failed: %s", st.toString());
317 return false;
318 }
319 unicast_server.stream(::BLEAudioStream::Direction::Rx).onConfigured([this](::BLEAudioStream&) {
320 rx_event = StartEvent;
321 });
322 unicast_server.stream(::BLEAudioStream::Direction::Rx).onStopped([this](::BLEAudioStream&, uint8_t) {
323 rx_event = StopEvent;
324 });
325 } else {
326 // one source ASE, no sink ASE; only the LC3 preset of the configured format
327 uint32_t presets = presetMask(cfg);
328 if (presets == 0) {
329 LOGE("unsupported TX format: %d Hz, %d ch", (int)cfg.sample_rate, (int)cfg.channels);
330 return false;
331 }
332 st = unicast_server.configureHeadset();
333 if (st) st = unicast_server.setSupportedPresets(presets);
334 if (st) st = unicast_server.setSinkStreams(0);
335 if (!st) {
336 LOGE("source setup failed: %s", st.toString());
337 return false;
338 }
339 unicast_server.stream(::BLEAudioStream::Direction::Tx).onConfigured([this](::BLEAudioStream& s) {
340 tx_sample_rate = s.codecConfig().samplingRateHz;
341 tx_channels = s.codecConfig().channels();
342 tx_event = StartEvent;
343 });
344 unicast_server.stream(::BLEAudioStream::Direction::Tx).onStopped([this](::BLEAudioStream&, uint8_t) {
345 tx_event = StopEvent;
346 });
347 }
348
349 st = audio.begin();
350 if (!st) {
351 LOGE("audio.begin failed: %s", st.toString());
352 return false;
353 }
354
355 if (cfg.mode == RX_MODE) {
356 st = player.setPCMSink([this](const int16_t* pcm, size_t samples) { onPCM(pcm, samples); });
357 if (st) st = player.begin();
358 } else {
359 st = recorder.setPCMSource([this](int16_t* pcm, size_t samples) { return pullPCM(pcm, samples); });
360 if (st) st = recorder.begin();
361 }
362 if (!st) {
363 LOGE("player/recorder setup failed: %s", st.toString());
364 return false;
365 }
366
367 ::BLEAdvertising adv = BLE.getAdvertising();
368 adv.setType(BLEAdvType::ConnectableScannable);
369 adv.setName(cfg.name);
370 adv.setAppearance(BLE_APPEARANCE_GENERIC_AUDIO_SINK);
371 st = adv.start();
372 if (!st) {
373 LOGE("advertising failed: %s", st.toString());
374 return false;
375 }
376 return true;
377 }
378
379 AudioInfo player_info() {
380 AudioInfo info(player.sampleRate(), player.channels(), 16);
381 return info;
382 }
383
385 void onPCM(const int16_t* pcm, size_t samples) {
386 if (pcm == nullptr || samples == 0) return;
387 size_t bytes = samples * sizeof(int16_t);
388 int written = rx_buffer.writeArray((const uint8_t*)pcm, bytes);
389 if ((size_t)written < bytes) {
390 rx_dropped_bytes.fetch_add(bytes - (size_t)written);
391 }
392 }
393
395 size_t pullPCM(int16_t* pcm, size_t samples) {
396 int bytes = rx_buffer.readArray((uint8_t*)pcm, samples * sizeof(int16_t));
397 return bytes / sizeof(int16_t);
398 }
399
402 static uint32_t presetMask(const AudioInfo& info) {
403 bool mono = info.channels == 1;
404 if (!mono && info.channels != 2) return 0;
405 switch (info.sample_rate) {
406 case 16000:
407 return mono ? BLEAudioPresetBit(::BLEAudioCodecPreset::LC3_16_1_1) : BLEAudioPresetBit(::BLEAudioCodecPreset::LC3_16_2_1);
408 case 24000:
409 return mono ? BLEAudioPresetBit(::BLEAudioCodecPreset::LC3_24_1_1) : BLEAudioPresetBit(::BLEAudioCodecPreset::LC3_24_2_1);
410 case 48000:
411 return mono ? BLEAudioPresetBit(::BLEAudioCodecPreset::LC3_48_1_1) : BLEAudioPresetBit(::BLEAudioCodecPreset::LC3_48_2_1);
412 default:
413 return 0;
414 }
415 }
416
419 void updateInfo(AudioInfo newInfo) {
420 if (newInfo != AudioStream::audioInfo()) {
421 AudioStream::setAudioInfo(newInfo);
422 }
423 }
424};
425
426} // namespace audio_tools
427
428#endif // BLE_AUDIO_LC3_SUPPORTED
429#endif // ESP32
#define LOGW(...)
Definition AudioLoggerIDF.h:29
#define TRACEI()
Definition AudioLoggerIDF.h:32
#define LOGE(...)
Definition AudioLoggerIDF.h:30
void setup()
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition LMSEchoCancellationStream.h:6