ESPHome 2026.8.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
21static const char *const 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) {
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);
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
79 const uint32_t dma_buffers_duration_ms = DMA_BUFFER_DURATION_MS * DMA_BUFFERS_COUNT;
80 // Ensure ring buffer duration is at least the duration of all DMA buffers
81 const uint32_t ring_buffer_duration = std::max(dma_buffers_duration_ms, this->buffer_duration_ms_);
82
83 // The ring buffer holds input-format audio (what play() receives), so size it from the input stream info.
84 const size_t bytes_per_frame = this->current_stream_info_.frames_to_bytes(1);
85 // Round the ring buffer size down to a multiple of bytes_per_frame so the wrap boundary stays frame-aligned and
86 // avoids unnecessary single-frame splices.
87 const size_t ring_buffer_size =
88 (this->current_stream_info_.ms_to_bytes(ring_buffer_duration) / bytes_per_frame) * bytes_per_frame;
89
90 // Per-frame byte widths and whether the task must narrow the bit depth before writing to the I2S peripheral.
91 const uint8_t channels = this->current_stream_info_.get_channels();
92 const uint8_t input_bytes_per_sample = this->current_stream_info_.get_bits_per_sample() / 8;
93 const uint8_t output_bytes_per_sample = this->output_stream_info_.get_bits_per_sample() / 8;
94 const bool narrowing = input_bytes_per_sample != output_bytes_per_sample;
95
96 // ESP-IDF may allocate smaller (or cache-line-rounded) DMA buffers than dma_buffer_frames() requested: it
97 // clamps each descriptor to the max DMA descriptor size and, on targets that route internal memory through
98 // the L1 cache (e.g. ESP32-P4), rounds the buffer to the cache line. Read the size the driver actually
99 // allocated so preload, silence padding, and the write/event lockstep all match it exactly. The channel is
100 // in the READY state here because start_i2s_driver() initialized it before this task was created.
101 size_t dma_buffer_bytes;
102 i2s_chan_info_t chan_info;
103 if (i2s_channel_get_info(this->tx_handle_, &chan_info) == ESP_OK && chan_info.total_dma_buf_size > 0) {
104 // total_dma_buf_size spans all DMA_BUFFERS_COUNT descriptors and is an exact multiple of the count.
105 dma_buffer_bytes = chan_info.total_dma_buf_size / DMA_BUFFERS_COUNT;
106 } else {
107 // Should not happen for a READY channel; fall back to the requested size.
108 dma_buffer_bytes = this->output_stream_info_.frames_to_bytes(dma_buffer_frames(this->output_stream_info_));
109 }
110 // dma_buffer_bytes counts output-format bytes; convert with the output stream info.
111 const uint32_t frames_per_dma_buffer = this->output_stream_info_.bytes_to_frames(dma_buffer_bytes);
112 // Soft cap for each source read: enough input-format bytes to fill one DMA buffer's worth of frames.
113 const size_t dma_buffer_input_bytes = this->current_stream_info_.frames_to_bytes(frames_per_dma_buffer);
114
115 bool successful_setup = false;
116
117 std::unique_ptr<audio::RingBufferAudioSource> audio_source;
118
119 // Pre-zeroed buffer used to silence-pad each DMA descriptor whenever real audio doesn't fully fill it.
120 RAMAllocator<uint8_t> silence_allocator;
121 uint8_t *silence_buffer = silence_allocator.allocate(dma_buffer_bytes);
122
123 if (silence_buffer != nullptr) {
124 memset(silence_buffer, 0, dma_buffer_bytes);
125
126 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = ring_buffer::RingBuffer::create(ring_buffer_size);
127 audio_source = audio::RingBufferAudioSource::create(temp_ring_buffer, dma_buffer_input_bytes,
128 static_cast<uint8_t>(bytes_per_frame));
129
130 if (audio_source != nullptr) {
131 // audio_source is nullptr if the ring buffer fails to allocate
132 this->audio_ring_buffer_ = temp_ring_buffer;
133 successful_setup = true;
134 }
135 }
136
137 if (successful_setup) {
138 // Preload every DMA descriptor with silence and push a matching zero-real-frames record per buffer.
139 // This guarantees that every on_sent event has a corresponding write record from the start, so
140 // ``i2s_event_queue_`` and ``write_records_queue_`` stay in lockstep for the entire task lifetime.
141 for (size_t i = 0; i < DMA_BUFFERS_COUNT; i++) {
142 size_t bytes_loaded = 0;
143 esp_err_t err = i2s_channel_preload_data(this->tx_handle_, silence_buffer, dma_buffer_bytes, &bytes_loaded);
144 if (err != ESP_OK || bytes_loaded != dma_buffer_bytes) {
145 ESP_LOGV(TAG, "Failed to preload silence into DMA buffer %u (err=%d, loaded=%u)", (unsigned) i, (int) err,
146 (unsigned) bytes_loaded);
147 successful_setup = false;
148 break;
149 }
150 uint32_t zero_real_frames = 0;
151 if (xQueueSend(this->write_records_queue_, &zero_real_frames, 0) != pdTRUE) {
152 // Should never happen: the queue was just reset and is sized for DMA_BUFFERS_COUNT * 2 entries.
153 ESP_LOGV(TAG, "Failed to push preload write record");
154 successful_setup = false;
155 break;
156 }
157 }
158 }
159
160 if (successful_setup) {
161 // Register the on_sent callback BEFORE enabling the channel so the very first transmitted buffer
162 // generates a queued event that pairs with the first preloaded silence record.
163 const i2s_event_callbacks_t callbacks = {.on_sent = i2s_on_sent_cb};
164 i2s_channel_register_event_callback(this->tx_handle_, &callbacks, this);
165
166 if (i2s_channel_enable(this->tx_handle_) != ESP_OK) {
167 ESP_LOGV(TAG, "Failed to enable I2S channel");
168 successful_setup = false;
169 }
170 }
171
172 if (!successful_setup) {
173 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
174 } else {
175 bool stop_gracefully = false;
176 // Number of records currently in ``write_records_queue_`` that carry real audio. Used by graceful
177 // stop to wait until every real-audio buffer has been confirmed played by an ISR event.
178 uint32_t pending_real_buffers = 0;
179 uint32_t last_data_received_time = millis();
180
181 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::TASK_RUNNING);
182
183 // Main speaker task loop. Continues while:
184 // - Paused, OR
185 // - No timeout configured, OR
186 // - Timeout hasn't elapsed since last data
187 //
188 // Always-fill model: every iteration writes exactly one DMA buffer's worth, mixing real audio
189 // and silence padding as needed. The blocking ``i2s_channel_write`` paces the loop at the DMA
190 // consumption rate, and every buffer write is matched 1:1 with a record on ``write_records_queue_``.
191 //
192 // While paused, the real-audio fill is skipped and the entire DMA buffer is filled with silence;
193 // the same blocking ``i2s_channel_write`` provides natural pacing (one buffer per ~DMA_BUFFER_DURATION_MS),
194 // so the lockstep invariant is preserved without burning CPU.
195 while (this->pause_state_ || !this->timeout_.has_value() ||
196 (millis() - last_data_received_time) <= this->timeout_.value()) {
197 uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
198
199 if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP) {
200 // COMMAND_STOP is set both by user-initiated stop() and by the ISR when it drops a completion
201 // event (paired with ERR_DROPPED_EVENT so loop() can distinguish the two cases).
202 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP);
203 ESP_LOGV(TAG, "Exiting: COMMAND_STOP received");
204 break;
205 }
206 if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY) {
207 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY);
208 stop_gracefully = true;
209 }
210
211 if (this->audio_stream_info_ != this->current_stream_info_) {
212 // Audio stream info changed, stop the speaker task so it will restart with the proper settings.
213 ESP_LOGV(TAG, "Exiting: stream info changed");
214 break;
215 }
216
217 // Drain ISR-stamped completion events. Each event corresponds 1:1 with a write_records_queue_
218 // entry by construction (preloaded records at startup, plus exactly one record pushed per
219 // iteration alongside exactly one DMA-buffer-sized write).
220 int64_t write_timestamp;
221 bool lockstep_broken = false;
222 while (xQueueReceive(this->i2s_event_queue_, &write_timestamp, 0)) {
223 uint32_t real_frames = 0;
224 if (xQueueReceive(this->write_records_queue_, &real_frames, 0) != pdTRUE) {
225 // Should never happen: would indicate the lockstep invariant is broken.
226 ESP_LOGV(TAG, "Event without matching write record");
228 lockstep_broken = true;
229 break;
230 }
231 if (real_frames > 0) {
232 pending_real_buffers--;
233 // Real audio is packed at the start of each DMA buffer with any silence padding on the
234 // tail, so the real audio finished playing earlier than the buffer-completion timestamp
235 // by the duration of the trailing zeros.
236 const uint32_t silence_frames = frames_per_dma_buffer - real_frames;
237 const int64_t adjusted_ts =
238 write_timestamp - this->current_stream_info_.frames_to_microseconds(silence_frames);
239 this->audio_output_callback_(real_frames, adjusted_ts);
240 }
241 }
242 if (lockstep_broken) {
243 break;
244 }
245
246 // Graceful stop: exit only after the source's exposed chunk is drained, the underlying ring
247 // buffer has nothing left to hand over, and every real-audio buffer we submitted has been
248 // confirmed played. ``has_buffered_data()`` returns bytes still sitting in the ring buffer
249 // awaiting fill().
250 if (stop_gracefully && audio_source->available() == 0 && !this->has_buffered_data() &&
251 pending_real_buffers == 0) {
252 ESP_LOGV(TAG, "Exiting: graceful stop complete");
253 break;
254 }
255
256 // Compose exactly one DMA buffer's worth: drain as much real audio as the source currently
257 // exposes (may take multiple fill() calls when crossing a ring buffer wrap), then pad any
258 // remainder with silence. All writes pack into the next free DMA descriptor in order, so the
259 // descriptor ends up holding [real audio][silence padding]. ``bytes_written_total`` counts
260 // output-format bytes so it tracks how full the DMA buffer is regardless of any narrowing.
261 size_t bytes_written_total = 0;
262 uint32_t real_frames_total = 0;
263 bool partial_write_failure = false;
264
265 if (!this->pause_state_) {
266 while (bytes_written_total < dma_buffer_bytes) {
267 size_t bytes_read = audio_source->fill(pdMS_TO_TICKS(DMA_BUFFER_DURATION_MS) / 2, false);
268 if (bytes_read > 0) {
269 // Apply volume at the input bit depth, before any narrowing, so the full precision is scaled.
270 uint8_t *new_data = audio_source->mutable_data() + audio_source->available() - bytes_read;
271 this->apply_software_volume_(new_data, bytes_read);
272 }
273
274 // Convert as many whole frames as fit in the remaining DMA space, bounded by what the source
275 // currently exposes. Frame counts are shared between input and output; only the byte widths differ.
276 const uint32_t frames_available = this->current_stream_info_.bytes_to_frames(audio_source->available());
277 const uint32_t frames_room =
278 this->output_stream_info_.bytes_to_frames(dma_buffer_bytes - bytes_written_total);
279 const uint32_t frames_to_write = std::min(frames_available, frames_room);
280 if (frames_to_write == 0) {
281 // Ring buffer has nothing more to hand over right now; pad the rest of this DMA buffer
282 // with silence so the lockstep invariant (one write per iteration) is preserved.
283 break;
284 }
285
286 const size_t input_bytes = this->current_stream_info_.frames_to_bytes(frames_to_write);
287 const size_t output_bytes = this->output_stream_info_.frames_to_bytes(frames_to_write);
288
289 uint8_t *chunk = audio_source->mutable_data();
290 if (narrowing) {
291 // Narrow the bit depth in place: output exactly aliases input with the same channel count and a
292 // smaller width, which copy_frames handles as a single forward pass. Only the frames about to be
293 // consumed are overwritten, so any unprocessed tail stays intact for the next iteration.
294 esp_audio_libs::pcm_convert::copy_frames(chunk, chunk, input_bytes_per_sample, channels,
295 output_bytes_per_sample, channels, frames_to_write);
296 }
297 this->swap_esp32_mono_samples_(chunk, output_bytes);
298
299 size_t bw = 0;
300 i2s_channel_write(this->tx_handle_, chunk, output_bytes, &bw, WRITE_TIMEOUT_TICKS);
301 if (bw != output_bytes) {
302 // A short real-audio write breaks DMA descriptor alignment for every subsequent event;
303 // the only safe recovery is to restart the task.
304 ESP_LOGV(TAG, "Partial real audio write: %u of %u bytes", (unsigned) bw, (unsigned) output_bytes);
306 partial_write_failure = true;
307 break;
308 }
309 audio_source->consume(input_bytes);
310 bytes_written_total += output_bytes;
311 real_frames_total += frames_to_write;
312 }
313 if (real_frames_total > 0) {
314 last_data_received_time = millis();
315 }
316 }
317
318 if (partial_write_failure) {
319 break;
320 }
321
322 const size_t silence_bytes = dma_buffer_bytes - bytes_written_total;
323 if (silence_bytes > 0) {
324 size_t bw = 0;
325 i2s_channel_write(this->tx_handle_, silence_buffer, silence_bytes, &bw, WRITE_TIMEOUT_TICKS);
326 if (bw != silence_bytes) {
327 // Same descriptor-alignment hazard as a partial real-audio write.
328 ESP_LOGV(TAG, "Partial silence write: %u of %u bytes", (unsigned) bw, (unsigned) silence_bytes);
330 break;
331 }
332 }
333
334 // Push the matching write record. Capacity headroom in I2S_EVENT_QUEUE_COUNT guarantees this
335 // succeeds even with a transient backlog of unprocessed events; if it ever fails the lockstep
336 // invariant is broken and every subsequent timestamp would be silently wrong, so bail.
337 if (xQueueSend(this->write_records_queue_, &real_frames_total, 0) != pdTRUE) {
338 ESP_LOGV(TAG, "Exiting: write records queue full");
340 break;
341 }
342 if (real_frames_total > 0) {
343 pending_real_buffers++;
344 }
345 }
346 }
347
348 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::TASK_STOPPING);
349
350 audio_source.reset();
351
352 if (silence_buffer != nullptr) {
353 silence_allocator.deallocate(silence_buffer, dma_buffer_bytes);
354 silence_buffer = nullptr;
355 }
356
357 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::TASK_STOPPED);
358
359 while (true) {
360 // Continuously delay until the loop method deletes the task
361 vTaskDelay(pdMS_TO_TICKS(10));
362 }
363}
364
366 this->current_stream_info_ = audio_stream_info;
367
368 if ((this->i2s_role_ & I2S_ROLE_SLAVE) && (this->sample_rate_ != audio_stream_info.get_sample_rate())) { // NOLINT
369 // Can't reconfigure I2S bus, so the sample rate must match the configured value
370 ESP_LOGE(TAG, "Incompatible stream settings");
371 return ESP_ERR_NOT_SUPPORTED;
372 }
373
374 // When the stream is wider than the configured slot bit width, the speaker task narrows each frame in place
375 // before handing it to the I2S peripheral. Compute the output format here so the driver, DMA buffers, and
376 // the task's conversion all agree on the clocked-out width. A stream no wider than the slot width is passed
377 // through unchanged (the slot may still be wider than the data, the existing behavior).
378 uint8_t output_bits_per_sample = audio_stream_info.get_bits_per_sample();
379 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO) {
380 const uint8_t configured_bits = static_cast<uint8_t>(this->slot_bit_width_);
381 if (output_bits_per_sample > configured_bits) {
382 output_bits_per_sample = configured_bits;
383 }
384 }
385 this->output_stream_info_ = audio::AudioStreamInfo(output_bits_per_sample, audio_stream_info.get_channels(),
386 audio_stream_info.get_sample_rate());
387
388#ifdef USE_ESP32_VARIANT_ESP32
389 // The original ESP32 I2S peripheral stores each sample in a whole number of 16-bit words (a 24-bit sample
390 // occupies 4 bytes in the DMA buffer, an 8-bit sample 2 bytes), but ESPHome's audio pipeline packs samples
391 // tightly (3 bytes for 24-bit, 1 for 8-bit). The two layouts only line up when the bit depth is a multiple
392 // of 16. The check is on the output width since that is what reaches the peripheral; a wider input is fine
393 // as long as it narrows to a 16- or 32-bit slot.
394 if (output_bits_per_sample % 16 != 0) {
395 ESP_LOGE(TAG, "ESP32 supports only 16- or 32-bit output, got %u-bit", (unsigned) output_bits_per_sample);
396 return ESP_ERR_NOT_SUPPORTED;
397 }
398#endif // USE_ESP32_VARIANT_ESP32
399
400 if (!this->parent_->try_lock()) {
401 ESP_LOGE(TAG, "Parent bus is busy");
402 return ESP_ERR_INVALID_STATE;
403 }
404
405 // The DMA buffers hold output-format (post-narrowing) samples, so size them from the output stream info.
406 uint32_t dma_buffer_length = dma_buffer_frames(this->output_stream_info_);
407
408 i2s_role_t i2s_role = this->i2s_role_;
409 i2s_clock_src_t clk_src = I2S_CLK_SRC_DEFAULT;
410
411#if SOC_CLK_APLL_SUPPORTED
412 if (this->use_apll_) {
413 clk_src = i2s_clock_src_t::I2S_CLK_SRC_APLL;
414 }
415#endif // SOC_CLK_APLL_SUPPORTED
416
417 // Log DMA configuration for debugging
418 ESP_LOGV(TAG, "I2S DMA config: %zu buffers x %lu frames", (size_t) DMA_BUFFERS_COUNT,
419 (unsigned long) dma_buffer_length);
420
421 i2s_chan_config_t chan_cfg = {
422 .id = this->parent_->get_port(),
423 .role = i2s_role,
424 .dma_desc_num = DMA_BUFFERS_COUNT,
425 .dma_frame_num = dma_buffer_length,
426 .auto_clear = true,
427 .intr_priority = 3,
428 };
429
430 // Build standard I2S clock/slot/gpio configuration
431 i2s_std_clk_config_t clk_cfg = {
432 .sample_rate_hz = audio_stream_info.get_sample_rate(),
433 .clk_src = clk_src,
434 .mclk_multiple = this->mclk_multiple_,
435 };
436
437 i2s_slot_mode_t slot_mode = this->slot_mode_;
438 i2s_std_slot_mask_t slot_mask = this->std_slot_mask_;
439 if (audio_stream_info.get_channels() == 1) {
440 slot_mode = I2S_SLOT_MODE_MONO;
441 } else if (audio_stream_info.get_channels() == 2) {
442 slot_mode = I2S_SLOT_MODE_STEREO;
443 slot_mask = I2S_STD_SLOT_BOTH;
444 }
445
446 // Configure the data bit width from the output (post-narrowing) format, which is what is clocked out.
447 const i2s_data_bit_width_t data_bit_width = (i2s_data_bit_width_t) this->output_stream_info_.get_bits_per_sample();
448 i2s_std_slot_config_t slot_cfg;
449 switch (this->i2s_comm_fmt_) {
450 case I2SCommFmt::PCM:
451 slot_cfg = I2S_STD_PCM_SLOT_DEFAULT_CONFIG(data_bit_width, slot_mode);
452 break;
453 case I2SCommFmt::MSB:
454 slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(data_bit_width, slot_mode);
455 break;
456 default:
457 slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(data_bit_width, slot_mode);
458 break;
459 }
460
461#ifdef USE_ESP32_VARIANT_ESP32
462 // There seems to be a bug on the ESP32 (non-variant) platform where setting the slot bit width higher than the
463 // bits per sample causes the audio to play too fast. Setting the ws_width to the configured slot bit width seems
464 // to make it play at the correct speed while sending more bits per slot.
465 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO) {
466 uint32_t configured_bit_width = static_cast<uint32_t>(this->slot_bit_width_);
467 slot_cfg.ws_width = configured_bit_width;
468 if (configured_bit_width > 16) {
469 slot_cfg.msb_right = false;
470 }
471 }
472#else
473 slot_cfg.slot_bit_width = this->slot_bit_width_;
474 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO) {
475 slot_cfg.ws_width = static_cast<uint32_t>(this->slot_bit_width_);
476 }
477#endif // USE_ESP32_VARIANT_ESP32
478 slot_cfg.slot_mask = slot_mask;
479
480 i2s_std_gpio_config_t gpio_cfg = this->parent_->get_pin_config();
481 gpio_cfg.dout = this->dout_pin_;
482
483 i2s_std_config_t std_cfg = {
484 .clk_cfg = clk_cfg,
485 .slot_cfg = slot_cfg,
486 .gpio_cfg = gpio_cfg,
487 };
488
489 esp_err_t err = this->init_i2s_channel_(chan_cfg, std_cfg, I2S_EVENT_QUEUE_COUNT);
490 if (err != ESP_OK) {
491 return err;
492 }
493
494 // The speaker task will enable the channel after preloading.
495
496 return ESP_OK;
497}
498
499} // namespace esphome::i2s_audio
500
501#endif // USE_ESP32
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2067
void deallocate(T *p, size_t n)
Definition helpers.h:2124
T * allocate(size_t n)
Definition helpers.h:2094
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 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:28
i2s_slot_bit_width_t slot_bit_width_
Definition i2s_audio.h:29
i2s_mclk_multiple_t mclk_multiple_
Definition i2s_audio.h:32
static bool i2s_on_sent_cb(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx)
Callback function used to send playback timestamps to the speaker task.
void apply_software_volume_(uint8_t *data, size_t bytes_read)
Apply software volume control using Q15 fixed-point scaling.
std::weak_ptr< ring_buffer::RingBuffer > audio_ring_buffer_
void swap_esp32_mono_samples_(uint8_t *data, size_t bytes_read)
Swap adjacent 16-bit mono samples for ESP32 (non-variant) hardware quirk.
esp_err_t init_i2s_channel_(const i2s_chan_config_t &chan_cfg, const i2s_std_config_t &std_cfg, size_t event_queue_size)
Shared I2S channel allocation, initialization, and event queue setup.
esp_err_t start_i2s_driver(audio::AudioStreamInfo &audio_stream_info) 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:122
audio::AudioStreamInfo audio_stream_info_
Definition speaker.h:114
auto * new_data
Definition helpers.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
static void uint32_t