ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
i2s_audio_speaker_standard.cpp
Go to the documentation of this file.
2
3#ifdef USE_ESP32
4
5#include <driver/i2s_std.h>
6#include <hal/dma_types.h>
7
10
11#include "esphome/core/hal.h"
12#include "esphome/core/log.h"
13
14#include "esp_timer.h"
15
16// esp-audio-libs
17#include <pcm_convert.h>
18
19namespace esphome::i2s_audio {
20
21ESPHOME_LOG_TAG(TAG, "i2s_audio.speaker.std");
22
23static constexpr uint32_t DMA_BUFFER_DURATION_MS = 10;
24static constexpr size_t DMA_BUFFERS_COUNT = 5;
25// ESP-IDF clamps each DMA descriptor to this many bytes when allocating the channel (see i2s_get_buf_size in
26// the I2S driver). Mirror its target-dependent selection so the requested dma_frame_num stays in range; the
27// speaker task reads the size actually allocated back from the driver rather than relying on this value.
28#if SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE
29static constexpr size_t I2S_DMA_BUFFER_MAX_SIZE = DMA_DESCRIPTOR_BUFFER_MAX_SIZE_64B_ALIGNED;
30#else
31static constexpr size_t I2S_DMA_BUFFER_MAX_SIZE = DMA_DESCRIPTOR_BUFFER_MAX_SIZE_4B_ALIGNED;
32#endif
33// Sized to comfortably absorb scheduling jitter: at most DMA_BUFFERS_COUNT events can be in flight,
34// doubled so that a transient backlog never overruns the queue (which would desync the lockstep
35// invariant between i2s_event_queue_ and write_records_queue_).
36static constexpr size_t I2S_EVENT_QUEUE_COUNT = DMA_BUFFERS_COUNT * 2;
37// Generous timeout for ``i2s_channel_write`` blocking. A buffer frees roughly every
38// DMA_BUFFER_DURATION_MS, so a multiple of that gives plenty of slack against scheduling jitter
39// without masking real failures.
40static constexpr TickType_t WRITE_TIMEOUT_TICKS = pdMS_TO_TICKS(DMA_BUFFER_DURATION_MS * (DMA_BUFFERS_COUNT + 1));
41
42// Requested frames per DMA buffer for the given stream, clamped so the byte size stays within the ESP-IDF
43// maximum DMA descriptor size. This is only the value handed to the channel config: ESP-IDF may still adjust
44// it (e.g. cache-line rounding on some targets), so the speaker task reads the size actually allocated back
45// from the driver instead of assuming this value. Clamping here keeps the request in range and avoids a
46// noisy ESP-IDF "dma frame num is out of dma buffer size" warning at high sample rates or bit depths.
47static uint32_t dma_buffer_frames(const audio::AudioStreamInfo &stream_info, uint32_t frame_multiple) {
48 const uint32_t frames_from_duration = stream_info.ms_to_frames(DMA_BUFFER_DURATION_MS);
49 const uint32_t max_frames = I2S_DMA_BUFFER_MAX_SIZE / stream_info.frames_to_bytes(1);
50 return (std::min(frames_from_duration, max_frames) / frame_multiple) * frame_multiple;
51}
52
55 const char *fmt_str;
56 switch (this->i2s_comm_fmt_) {
57 case I2SCommFmt::PCM:
58 fmt_str = "pcm";
59 break;
60 case I2SCommFmt::MSB:
61 fmt_str = "msb";
62 break;
63 default:
64 fmt_str = "std";
65 break;
66 }
67 ESP_LOGCONFIG(TAG, " Communication format: %s", fmt_str);
68 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO) {
69 // The width of each I2S slot. It is also the narrowing ceiling: streams wider than this are narrowed to
70 // it. A stream narrower than the slot is left at its own width and clocked into the wider slot, so this
71 // is not necessarily the sample data width (which depends on the incoming stream).
72 ESP_LOGCONFIG(TAG, " Slot bit width: %u", (unsigned) static_cast<uint32_t>(this->slot_bit_width_));
73 }
74}
75
77 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::TASK_STARTING);
78 // Stale records from the previous run would pair with the wrong DMA events
79 xQueueReset(this->i2s_event_queue_);
80 xQueueReset(this->write_records_queue_);
81
82 const uint32_t dma_buffers_duration_ms = DMA_BUFFER_DURATION_MS * DMA_BUFFERS_COUNT;
83 // Ensure ring buffer duration is at least the duration of all DMA buffers
84 const uint32_t ring_buffer_duration = std::max(dma_buffers_duration_ms, this->buffer_duration_ms_);
85
86 // The ring buffer holds input-format audio (what play() receives), so size it from the input stream info.
87 const size_t bytes_per_frame = this->current_stream_info_.frames_to_bytes(1);
88 // Hand over whole ESP32 mono sample pairs so writes stay word-aligned
89 const size_t source_alignment = bytes_per_frame * dma_frame_multiple(this->output_stream_info_);
90 const bool pair_aligned = source_alignment > bytes_per_frame;
91 // Round the ring buffer size down to a multiple of source_alignment so the wrap boundary avoids splices.
92 const size_t ring_buffer_size =
93 (this->current_stream_info_.ms_to_bytes(ring_buffer_duration) / source_alignment) * source_alignment;
94
95 // Per-frame byte widths and whether the task must narrow the bit depth before writing to the I2S peripheral.
96 const uint8_t channels = this->current_stream_info_.get_channels();
97 const uint8_t input_bytes_per_sample = this->current_stream_info_.get_bits_per_sample() / 8;
98 const uint8_t output_bytes_per_sample = this->output_stream_info_.get_bits_per_sample() / 8;
99 const bool narrowing = input_bytes_per_sample != output_bytes_per_sample;
100
101 // ESP-IDF may allocate smaller (or cache-line-rounded) DMA buffers than dma_buffer_frames() requested: it
102 // clamps each descriptor to the max DMA descriptor size and, on targets that route internal memory through
103 // the L1 cache (e.g. ESP32-P4), rounds the buffer to the cache line. Read the size the driver actually
104 // allocated so preload, silence padding, and the write/event lockstep all match it exactly. The channel is
105 // in the READY state here because start_i2s_driver() initialized it before this task was created.
106 size_t dma_buffer_bytes;
107 i2s_chan_info_t chan_info;
108 if (i2s_channel_get_info(this->tx_handle_, &chan_info) == ESP_OK && chan_info.total_dma_buf_size > 0) {
109 // total_dma_buf_size spans all DMA_BUFFERS_COUNT descriptors and is an exact multiple of the count.
110 dma_buffer_bytes = chan_info.total_dma_buf_size / DMA_BUFFERS_COUNT;
111 } else {
112 // Should not happen for a READY channel; fall back to the requested size.
113 dma_buffer_bytes = this->output_stream_info_.frames_to_bytes(
114 dma_buffer_frames(this->output_stream_info_, dma_frame_multiple(this->output_stream_info_)));
115 }
116 // dma_buffer_bytes counts output-format bytes; convert with the output stream info.
117 const uint32_t frames_per_dma_buffer = this->output_stream_info_.bytes_to_frames(dma_buffer_bytes);
118 // Soft cap for each source read: enough input-format bytes to fill one DMA buffer's worth of frames.
119 const size_t dma_buffer_input_bytes = this->current_stream_info_.frames_to_bytes(frames_per_dma_buffer);
120
121 bool successful_setup = false;
122
123 std::unique_ptr<audio::RingBufferAudioSource> audio_source;
124
125 // Pre-zeroed buffer used to silence-pad each DMA descriptor whenever real audio doesn't fully fill it.
126 RAMAllocator<uint8_t> silence_allocator;
127 uint8_t *silence_buffer = silence_allocator.allocate(dma_buffer_bytes);
128
129 if (silence_buffer != nullptr) {
130 memset(silence_buffer, 0, dma_buffer_bytes);
131
132 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = ring_buffer::RingBuffer::create(ring_buffer_size);
133 audio_source = audio::RingBufferAudioSource::create(temp_ring_buffer, dma_buffer_input_bytes,
134 static_cast<uint8_t>(source_alignment));
135
136 if (audio_source != nullptr) {
137 // audio_source is nullptr if the ring buffer fails to allocate
138 this->audio_ring_buffer_ = temp_ring_buffer;
139 successful_setup = true;
140 }
141 }
142
143 // Preload every DMA descriptor with silence and push a matching zero-real-frames record per buffer, so every
144 // on_sent event has a write record from the start. Runs with the channel disabled: at startup and after a resync.
145 auto preload_silence = [&]() -> bool {
146 for (size_t i = 0; i < DMA_BUFFERS_COUNT; i++) {
147 size_t bytes_loaded = 0;
148 esp_err_t err = i2s_channel_preload_data(this->tx_handle_, silence_buffer, dma_buffer_bytes, &bytes_loaded);
149 if (err != ESP_OK || bytes_loaded != dma_buffer_bytes) {
150 ESP_LOGV(TAG, "Failed to preload silence into DMA buffer %u (err=%d, loaded=%u)", (unsigned) i, (int) err,
151 (unsigned) bytes_loaded);
152 return false;
153 }
154 uint32_t zero_real_frames = 0;
155 if (xQueueSend(this->write_records_queue_, &zero_real_frames, 0) != pdTRUE) {
156 // Should never happen: the queue was just reset and is sized for DMA_BUFFERS_COUNT * 2 entries.
157 ESP_LOGV(TAG, "Failed to push preload write record");
158 return false;
159 }
160 }
161 return true;
162 };
163
164 if (successful_setup) {
165 successful_setup = preload_silence();
166 }
167
168 if (successful_setup) {
169 // Register the on_sent callback BEFORE enabling the channel so the very first transmitted buffer
170 // generates a queued event that pairs with the first preloaded silence record.
171 const i2s_event_callbacks_t callbacks = {.on_sent = i2s_on_sent_cb};
172 i2s_channel_register_event_callback(this->tx_handle_, &callbacks, this);
173
174 if (i2s_channel_enable(this->tx_handle_) != ESP_OK) {
175 ESP_LOGV(TAG, "Failed to enable I2S channel");
176 successful_setup = false;
177 }
178 }
179
180 if (!successful_setup) {
181 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
182 } else {
183 bool stop_gracefully = false;
184 // Number of records currently in ``write_records_queue_`` that carry real audio. Used by graceful
185 // stop to wait until every real-audio buffer has been confirmed played by an ISR event.
186 uint32_t pending_real_buffers = 0;
187 uint32_t last_data_received_time = millis();
188 bool resync_needed = false;
189 // Real frames consumed from the ring buffer that never reached a write record
190 uint32_t unrecorded_frames = 0;
191
192 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::TASK_RUNNING);
193
194 // Main speaker task loop. Continues while:
195 // - Paused, OR
196 // - No timeout configured, OR
197 // - Timeout hasn't elapsed since last data
198 //
199 // Always-fill model: every iteration writes exactly one DMA buffer's worth, mixing real audio
200 // and silence padding as needed. The blocking ``i2s_channel_write`` paces the loop at the DMA
201 // consumption rate, and every buffer write is matched 1:1 with a record on ``write_records_queue_``.
202 //
203 // While paused, the real-audio fill is skipped and the entire DMA buffer is filled with silence;
204 // the same blocking ``i2s_channel_write`` provides natural pacing (one buffer per ~DMA_BUFFER_DURATION_MS),
205 // so the lockstep invariant is preserved without burning CPU.
206 while (this->pause_state_ || !this->timeout_.has_value() ||
207 (millis() - last_data_received_time) <= this->timeout_.value()) {
208 uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
209
210 if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP) {
211 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP);
212 ESP_LOGV(TAG, "Exiting: COMMAND_STOP received");
213 break;
214 }
215 if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY) {
216 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY);
217 stop_gracefully = true;
218 }
219
220 if (this->audio_stream_info_ != this->current_stream_info_) {
221 // Audio stream info changed, stop the speaker task so it will restart with the proper settings.
222 ESP_LOGV(TAG, "Exiting: stream info changed");
223 break;
224 }
225
226 if (event_group_bits & SpeakerEventGroupBits::ERR_DROPPED_EVENT) {
227 ESP_LOGE(TAG, "ISR event queue overflow, resyncing DMA lockstep");
228 resync_needed = true;
229 }
230 if (resync_needed) {
231 // Rebuild the lockstep in place; the ring buffer keeps accepting audio throughout
232 const bool resynced = this->resync_lockstep_(unrecorded_frames, preload_silence);
233 unrecorded_frames = 0;
234 pending_real_buffers = 0;
235 resync_needed = false;
236 if (!resynced) {
237 ESP_LOGE(TAG, "DMA lockstep resync failed, restarting speaker task");
238 break;
239 }
240 }
241
242 // Drain ISR-stamped completion events. Each event corresponds 1:1 with a write_records_queue_
243 // entry by construction (preloaded records at startup, plus exactly one record pushed per
244 // iteration alongside exactly one DMA-buffer-sized write).
245 int64_t write_timestamp;
246 bool lockstep_broken = false;
247 while (xQueueReceive(this->i2s_event_queue_, &write_timestamp, 0)) {
248 uint32_t real_frames = 0;
249 if (xQueueReceive(this->write_records_queue_, &real_frames, 0) != pdTRUE) {
250 // Should never happen: would indicate the lockstep invariant is broken.
251 ESP_LOGE(TAG, "Event without matching write record, resyncing DMA lockstep");
252 lockstep_broken = true;
253 break;
254 }
255 if (real_frames > 0) {
256 pending_real_buffers--;
257 // Real audio is packed at the start of each DMA buffer with any silence padding on the
258 // tail, so the real audio finished playing earlier than the buffer-completion timestamp
259 // by the duration of the trailing zeros.
260 const uint32_t silence_frames = frames_per_dma_buffer - real_frames;
261 const int64_t adjusted_ts =
262 write_timestamp - this->current_stream_info_.frames_to_microseconds(silence_frames);
263 this->audio_output_callback_(real_frames, adjusted_ts);
264 }
265 }
266 if (lockstep_broken) {
267 resync_needed = true;
268 continue;
269 }
270
271 // Graceful stop: exit only after the source's exposed chunk is drained, the underlying ring
272 // buffer has nothing left to hand over, and every real-audio buffer we submitted has been
273 // confirmed played. ``has_buffered_data()`` returns bytes still sitting in the ring buffer
274 // awaiting fill().
275 if (stop_gracefully && audio_source->available() == 0 && !this->has_buffered_data() &&
276 pending_real_buffers == 0) {
277 ESP_LOGV(TAG, "Exiting: graceful stop complete");
278 break;
279 }
280
281 // Compose exactly one DMA buffer's worth: drain as much real audio as the source currently
282 // exposes (may take multiple fill() calls when crossing a ring buffer wrap), then pad any
283 // remainder with silence. All writes pack into the next free DMA descriptor in order, so the
284 // descriptor ends up holding [real audio][silence padding]. ``bytes_written_total`` counts
285 // output-format bytes so it tracks how full the DMA buffer is regardless of any narrowing.
286 size_t bytes_written_total = 0;
287 uint32_t real_frames_total = 0;
288 bool partial_write_failure = false;
289
290 if (!this->pause_state_) {
291 while (bytes_written_total < dma_buffer_bytes) {
292 size_t bytes_read = audio_source->fill(pdMS_TO_TICKS(DMA_BUFFER_DURATION_MS) / 2);
293 if (bytes_read > 0) {
294 // Apply volume at the input bit depth, before any narrowing, so the full precision is scaled.
295 uint8_t *new_data = audio_source->mutable_data() + audio_source->available() - bytes_read;
296 this->apply_software_volume_(new_data, bytes_read);
297 }
298
299 // Convert as many whole frames as fit in the remaining DMA space, bounded by what the source
300 // currently exposes. Frame counts are shared between input and output; only the byte widths differ.
301 uint32_t frames_available = this->current_stream_info_.bytes_to_frames(audio_source->available());
302 const uint32_t frames_room =
303 this->output_stream_info_.bytes_to_frames(dma_buffer_bytes - bytes_written_total);
304 uint32_t padding_frames = 0;
305 if (pair_aligned && frames_available == 0 && frames_room >= 2 && !audio_source->has_buffered_data()) {
306 // Silence padding follows, so write a held half pair now with a silent partner rather than strand it.
307 // Only the real frame is reported as played.
308 const size_t real_bytes = audio_source->expose_padded_partial(bytes_per_frame);
309 if (real_bytes > 0) {
310 this->apply_software_volume_(audio_source->mutable_data(), real_bytes);
311 frames_available = this->current_stream_info_.bytes_to_frames(audio_source->available());
312 padding_frames = frames_available - this->current_stream_info_.bytes_to_frames(real_bytes);
313 }
314 }
315 const uint32_t frames_to_write = std::min(frames_available, frames_room);
316 if (frames_to_write == 0) {
317 // Ring buffer has nothing more to hand over right now; pad the rest of this DMA buffer
318 // with silence so the lockstep invariant (one write per iteration) is preserved.
319 break;
320 }
321
322 const size_t input_bytes = this->current_stream_info_.frames_to_bytes(frames_to_write);
323 const size_t output_bytes = this->output_stream_info_.frames_to_bytes(frames_to_write);
324
325 uint8_t *chunk = audio_source->mutable_data();
326 if (narrowing) {
327 // Narrow the bit depth in place: output exactly aliases input with the same channel count and a
328 // smaller width, which copy_frames handles as a single forward pass. Only the frames about to be
329 // consumed are overwritten, so any unprocessed tail stays intact for the next iteration.
330 esp_audio_libs::pcm_convert::copy_frames(chunk, chunk, input_bytes_per_sample, channels,
331 output_bytes_per_sample, channels, frames_to_write);
332 }
333 this->swap_esp32_mono_samples_(chunk, output_bytes);
334
335 size_t bw = 0;
336 i2s_channel_write(this->tx_handle_, chunk, output_bytes, &bw, WRITE_TIMEOUT_TICKS);
337 if (bw != output_bytes) {
338 // A short write breaks DMA descriptor alignment for every subsequent event. Drop the chunk rather
339 // than retry it: it was already narrowed in place.
340 ESP_LOGE(TAG, "Partial DMA write (%u of %u bytes), resyncing DMA lockstep", (unsigned) bw,
341 (unsigned) output_bytes);
342 audio_source->consume(input_bytes);
343 real_frames_total += frames_to_write - padding_frames;
344 partial_write_failure = true;
345 break;
346 }
347 audio_source->consume(input_bytes);
348 bytes_written_total += output_bytes;
349 real_frames_total += frames_to_write - padding_frames;
350 if (padding_frames > 0) {
351 // The source was already empty; skip waiting on another fill() before the silence padding
352 break;
353 }
354 }
355 if (real_frames_total > 0) {
356 last_data_received_time = millis();
357 }
358 }
359
360 if (partial_write_failure) {
361 unrecorded_frames += real_frames_total;
362 resync_needed = true;
363 continue;
364 }
365
366 const size_t silence_bytes = dma_buffer_bytes - bytes_written_total;
367 if (silence_bytes > 0) {
368 size_t bw = 0;
369 i2s_channel_write(this->tx_handle_, silence_buffer, silence_bytes, &bw, WRITE_TIMEOUT_TICKS);
370 if (bw != silence_bytes) {
371 // Same descriptor-alignment hazard as a partial real-audio write.
372 ESP_LOGE(TAG, "Partial DMA write (%u of %u bytes), resyncing DMA lockstep", (unsigned) bw,
373 (unsigned) silence_bytes);
374 unrecorded_frames += real_frames_total;
375 resync_needed = true;
376 continue;
377 }
378 }
379
380 // Push the matching write record. Capacity headroom in I2S_EVENT_QUEUE_COUNT guarantees this
381 // succeeds even with a transient backlog of unprocessed events; if it ever fails the lockstep
382 // invariant is broken and every subsequent timestamp would be silently wrong, so rebuild it.
383 if (xQueueSend(this->write_records_queue_, &real_frames_total, 0) != pdTRUE) {
384 ESP_LOGE(TAG, "Write records queue full, resyncing DMA lockstep");
385 unrecorded_frames += real_frames_total;
386 resync_needed = true;
387 continue;
388 }
389 if (real_frames_total > 0) {
390 pending_real_buffers++;
391 }
392 }
393 }
394
395 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::TASK_STOPPING);
396
397 audio_source.reset();
398
399 if (silence_buffer != nullptr) {
400 silence_allocator.deallocate(silence_buffer, dma_buffer_bytes);
401 silence_buffer = nullptr;
402 }
403
404 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::TASK_STOPPED);
405
406 while (true) {
407 // Continuously delay until the loop method deletes the task
408 vTaskDelay(pdMS_TO_TICKS(10));
409 }
410}
411
413 if ((this->i2s_role_ & I2S_ROLE_SLAVE) && (this->sample_rate_ != audio_stream_info.get_sample_rate())) { // NOLINT
414 // Can't reconfigure I2S bus, so the sample rate must match the configured value
415 ESP_LOGE(TAG, "Incompatible stream settings");
416 return ESP_ERR_NOT_SUPPORTED;
417 }
418
419 // When the stream is wider than the configured slot bit width, the speaker task narrows each frame in place
420 // before handing it to the I2S peripheral. Compute the output format here so the driver, DMA buffers, and
421 // the task's conversion all agree on the clocked-out width. A stream no wider than the slot width is passed
422 // through unchanged (the slot may still be wider than the data, the existing behavior).
423 uint8_t output_bits_per_sample = audio_stream_info.get_bits_per_sample();
424 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO) {
425 const uint8_t configured_bits = static_cast<uint8_t>(this->slot_bit_width_);
426 if (output_bits_per_sample > configured_bits) {
427 output_bits_per_sample = configured_bits;
428 }
429 }
430 this->output_stream_info_ = audio::AudioStreamInfo(output_bits_per_sample, audio_stream_info.get_channels(),
431 audio_stream_info.get_sample_rate());
432
433#ifdef USE_ESP32_VARIANT_ESP32
434 // The original ESP32 I2S peripheral stores each sample in a whole number of 16-bit words (a 24-bit sample
435 // occupies 4 bytes in the DMA buffer, an 8-bit sample 2 bytes), but ESPHome's audio pipeline packs samples
436 // tightly (3 bytes for 24-bit, 1 for 8-bit). The two layouts only line up when the bit depth is a multiple
437 // of 16. The check is on the output width since that is what reaches the peripheral; a wider input is fine
438 // as long as it narrows to a 16- or 32-bit slot.
439 if (output_bits_per_sample % 16 != 0) {
440 ESP_LOGE(TAG, "ESP32 supports only 16- or 32-bit output, got %u-bit", (unsigned) output_bits_per_sample);
441 return ESP_ERR_NOT_SUPPORTED;
442 }
443#endif // USE_ESP32_VARIANT_ESP32
444
445#ifdef USE_I2S_AUDIO_FULL_DUPLEX
446 if (this->parent_->is_full_duplex()) {
447 // The parent set up the channel once from the configured format, so the stream must produce exactly that
448 const audio::AudioStreamInfo required = this->full_duplex_stream_info_();
449 if (this->output_stream_info_ != required) {
450 ESP_LOGE(TAG, "Full duplex requires %u-bit, %u channel audio at %" PRIu32 " Hz",
451 (unsigned) required.get_bits_per_sample(), (unsigned) required.get_channels(),
452 required.get_sample_rate());
453 if (this->output_stream_info_.get_channels() != required.get_channels()) {
454 ESP_LOGE(TAG, "A resampler does not change the channel count; add a mixer speaker with num_channels: %u",
455 (unsigned) required.get_channels());
456 }
457 return ESP_ERR_NOT_SUPPORTED;
458 }
459 // The speaker task will enable the channel after preloading.
460 return this->acquire_full_duplex_channel_(I2S_EVENT_QUEUE_COUNT);
461 }
462#endif // USE_I2S_AUDIO_FULL_DUPLEX
463
464 if (!this->parent_->try_lock()) {
465 ESP_LOGE(TAG, "Parent bus is busy");
466 return ESP_ERR_INVALID_STATE;
467 }
468
469 // Reuse a kept channel while the stream format matches
470 if (this->tx_handle_ != nullptr) {
471 if (this->current_stream_info_ == audio_stream_info) {
472 return ESP_OK;
473 }
474 this->delete_channel_();
475 }
476
477 this->current_stream_info_ = audio_stream_info;
478
479 i2s_chan_config_t chan_cfg;
480 i2s_std_config_t std_cfg;
481 this->build_i2s_config_(this->output_stream_info_, chan_cfg, std_cfg);
482
483 // The speaker task will enable the channel after preloading.
484 return this->init_i2s_channel_(chan_cfg, std_cfg, I2S_EVENT_QUEUE_COUNT);
485}
486
487#ifdef USE_I2S_AUDIO_FULL_DUPLEX
489 return audio::AudioStreamInfo(static_cast<uint8_t>(this->slot_bit_width_),
490 this->slot_mode_ == I2S_SLOT_MODE_STEREO ? 2 : 1, this->sample_rate_);
491}
492
493void I2SAudioSpeaker::build_full_duplex_config(i2s_chan_config_t &chan_cfg, i2s_std_config_t &std_cfg) {
494 this->build_i2s_config_(this->full_duplex_stream_info_(), chan_cfg, std_cfg);
495}
496#endif // USE_I2S_AUDIO_FULL_DUPLEX
497
498void I2SAudioSpeaker::build_i2s_config_(const audio::AudioStreamInfo &output_stream_info, i2s_chan_config_t &chan_cfg,
499 i2s_std_config_t &std_cfg) const {
500 // The DMA buffers hold output-format (post-narrowing) samples, so size them from the output stream info.
501 uint32_t dma_buffer_length = dma_buffer_frames(output_stream_info, dma_frame_multiple(output_stream_info));
502
503 // Log DMA configuration for debugging
504 ESP_LOGV(TAG, "I2S DMA config: %zu buffers x %lu frames", (size_t) DMA_BUFFERS_COUNT,
505 (unsigned long) dma_buffer_length);
506
507 chan_cfg = {
508 .id = this->parent_->get_port(),
509 .role = this->i2s_role_,
510 .dma_desc_num = DMA_BUFFERS_COUNT,
511 .dma_frame_num = dma_buffer_length,
512 .auto_clear = true,
513 .intr_priority = 3,
514 };
515
516 // Build standard I2S clock/slot/gpio configuration
517 i2s_std_clk_config_t clk_cfg = {
518 .sample_rate_hz = output_stream_info.get_sample_rate(),
519 .clk_src = this->get_clock_source_(),
520 .mclk_multiple = this->mclk_multiple_,
521 };
522
523 i2s_slot_mode_t slot_mode = this->slot_mode_;
524 i2s_std_slot_mask_t slot_mask = this->std_slot_mask_;
525 if (output_stream_info.get_channels() == 1) {
526 slot_mode = I2S_SLOT_MODE_MONO;
527 } else if (output_stream_info.get_channels() == 2) {
528 slot_mode = I2S_SLOT_MODE_STEREO;
529 slot_mask = I2S_STD_SLOT_BOTH;
530 }
531
532 // Configure the data bit width from the output (post-narrowing) format, which is what is clocked out.
533 const i2s_data_bit_width_t data_bit_width = (i2s_data_bit_width_t) output_stream_info.get_bits_per_sample();
534 i2s_std_slot_config_t slot_cfg;
535 switch (this->i2s_comm_fmt_) {
536 case I2SCommFmt::PCM:
537 slot_cfg = I2S_STD_PCM_SLOT_DEFAULT_CONFIG(data_bit_width, slot_mode);
538 break;
539 case I2SCommFmt::MSB:
540 slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(data_bit_width, slot_mode);
541 break;
542 default:
543 slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(data_bit_width, slot_mode);
544 break;
545 }
546
547#ifdef USE_ESP32_VARIANT_ESP32
548 // There seems to be a bug on the ESP32 (non-variant) platform where setting the slot bit width higher than the
549 // bits per sample causes the audio to play too fast. Setting the ws_width to the configured slot bit width seems
550 // to make it play at the correct speed while sending more bits per slot.
551 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO) {
552 uint32_t configured_bit_width = static_cast<uint32_t>(this->slot_bit_width_);
553 slot_cfg.ws_width = configured_bit_width;
554 if (configured_bit_width > 16) {
555 slot_cfg.msb_right = false;
556 }
557 }
558#else
559 slot_cfg.slot_bit_width = this->slot_bit_width_;
560 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO) {
561 slot_cfg.ws_width = static_cast<uint32_t>(this->slot_bit_width_);
562 }
563#endif // USE_ESP32_VARIANT_ESP32
564 slot_cfg.slot_mask = slot_mask;
565
566 i2s_std_gpio_config_t gpio_cfg = this->parent_->get_pin_config();
567 gpio_cfg.dout = this->dout_pin_;
568
569 std_cfg = {
570 .clk_cfg = clk_cfg,
571 .slot_cfg = slot_cfg,
572 .gpio_cfg = gpio_cfg,
573 };
574}
575
576} // namespace esphome::i2s_audio
577
578#endif // USE_ESP32
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2222
void deallocate(T *p, size_t n)
Definition helpers.h:2279
T * allocate(size_t n)
Definition helpers.h:2249
size_t ms_to_bytes(uint32_t ms) const
Converts duration to bytes.
Definition audio.h:73
size_t frames_to_bytes(uint32_t frames) const
Converts frames to bytes.
Definition audio.h:53
uint8_t get_bits_per_sample() const
Definition audio.h:28
uint32_t frames_to_microseconds(uint32_t frames) const
Computes the duration, in microseconds, the given amount of frames represents.
Definition audio.cpp:25
uint32_t bytes_to_frames(size_t bytes) const
Convert bytes to frames.
Definition audio.h:43
uint8_t get_channels() const
Definition audio.h:29
uint32_t ms_to_frames(uint32_t ms) const
Converts duration to frames.
Definition audio.h:63
uint32_t get_sample_rate() const
Definition audio.h:30
static std::unique_ptr< RingBufferAudioSource > create(std::shared_ptr< ring_buffer::RingBuffer > ring_buffer, size_t max_fill_bytes, uint8_t alignment_bytes=1)
Creates a new ring-buffer-backed audio source after validating its parameters.
i2s_std_slot_mask_t std_slot_mask_
Definition i2s_audio.h:37
i2s_slot_bit_width_t slot_bit_width_
Definition i2s_audio.h:38
i2s_clock_src_t get_clock_source_() const
Definition i2s_audio.h:26
i2s_mclk_multiple_t mclk_multiple_
Definition i2s_audio.h:41
std::weak_ptr< ring_buffer::RingBuffer > audio_ring_buffer_
void swap_esp32_mono_samples_(uint8_t *data, size_t bytes_read)
Plays the provided audio data.
audio::AudioStreamInfo full_duplex_stream_info_() const
The output format of a full duplex bus, fixed by the configuration since the channel is set up once.
static uint32_t dma_frame_multiple(const audio::AudioStreamInfo &stream_info)
Frame multiple for DMA buffers and writes; 2 keeps ESP32 mono sample pairs word-aligned.
esp_err_t start_i2s_driver(audio::AudioStreamInfo &audio_stream_info) override
void build_i2s_config_(const audio::AudioStreamInfo &output_stream_info, i2s_chan_config_t &chan_cfg, i2s_std_config_t &std_cfg) const
Builds the channel and standard mode configuration for the given output format.
void build_full_duplex_config(i2s_chan_config_t &chan_cfg, i2s_std_config_t &std_cfg) override
static std::unique_ptr< RingBuffer > create(size_t len, MemoryPreference preference=MemoryPreference::EXTERNAL_FIRST)
CallbackManager< void(uint32_t, int64_t)> audio_output_callback_
Definition speaker.h:138
audio::AudioStreamInfo audio_stream_info_
Definition speaker.h:131
ESPHOME_LOG_TAG(TAG, "i2s_audio")
auto * new_data
Definition helpers.cpp:38
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t