ESPHome 2026.10.0-dev
Loading...
Searching...
No Matches
i2s_audio_speaker.cpp
Go to the documentation of this file.
1#include "i2s_audio_speaker.h"
2
3#ifdef USE_ESP32
4
5#include <driver/gpio.h>
6#include <driver/i2s_std.h>
7
10
12#include "esphome/core/hal.h"
13#include "esphome/core/log.h"
14
15#include "esp_timer.h"
16
17// esp-audio-libs
18#include <gain.h>
19
20namespace esphome::i2s_audio {
21
22static const char *const TAG = "i2s_audio.speaker";
23
24// Software volume control maps the user-facing [0.0, 1.0] range to a Q31 scale factor.
25// Volumes in (0.0, 1.0) map linearly to a dB reduction in [-49.0, 0.0] dB.
26static constexpr float SOFTWARE_VOLUME_MIN_DB = -49.0f;
27
29 this->event_group_ = xEventGroupCreate();
30
31 if (this->event_group_ == nullptr) {
32 ESP_LOGE(TAG, "Event group creation failed");
33 this->mark_failed();
34 return;
35 }
36
37 // Initialize volume control. When audio_dac is configured, this sets the DAC volume.
38 // When no audio_dac is configured, this initializes software volume control.
39 this->set_volume(this->volume_);
40}
41
43 ESP_LOGCONFIG(TAG,
44 "Speaker:\n"
45 " Pin: %d\n"
46 " Buffer duration: %" PRIu32,
47 static_cast<int8_t>(this->dout_pin_), this->buffer_duration_ms_);
48 if (this->timeout_.has_value()) {
49 ESP_LOGCONFIG(TAG, " Timeout: %" PRIu32 " ms", this->timeout_.value());
50 }
51}
52
54 uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
55
56 if ((event_group_bits & SpeakerEventGroupBits::COMMAND_START) && (this->state_ == speaker::STATE_STOPPED)) {
58 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::COMMAND_START);
59 }
60
61 // Handle the task's state
62 if (event_group_bits & SpeakerEventGroupBits::TASK_STARTING) {
63 ESP_LOGD(TAG, "Starting");
64 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::TASK_STARTING);
65 }
66 if (event_group_bits & SpeakerEventGroupBits::TASK_RUNNING) {
67 ESP_LOGV(TAG, "Started");
68 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::TASK_RUNNING);
70 }
71 if (event_group_bits & SpeakerEventGroupBits::TASK_STOPPING) {
72 ESP_LOGV(TAG, "Stopping");
73 // Lockstep-breaking error bits are latched by the task and cleared along with all other bits
74 // when TASK_STOPPED is processed; log them here, exactly once, as the task winds down.
75 if (event_group_bits & SpeakerEventGroupBits::ERR_DROPPED_EVENT) {
76 ESP_LOGE(TAG, "ISR event queue overflow, restarting speaker task to recover timestamp sync");
77 }
78 if (event_group_bits & SpeakerEventGroupBits::ERR_PARTIAL_WRITE) {
79 ESP_LOGE(TAG, "Partial DMA write broke buffer alignment, restarting speaker task");
80 }
81 if (event_group_bits & SpeakerEventGroupBits::ERR_LOCKSTEP_DESYNC) {
82 ESP_LOGE(TAG, "Event/record queues desynced, restarting speaker task");
83 }
84 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::TASK_STOPPING);
86 }
87 if (event_group_bits & SpeakerEventGroupBits::TASK_STOPPED) {
88 ESP_LOGD(TAG, "Stopped");
89
90 vTaskDelete(this->speaker_task_handle_);
91 this->speaker_task_handle_ = nullptr;
92
93 this->stop_i2s_driver_();
94 // ALL_BITS includes COMMAND_START. Take the bits from the clear itself, not from the snapshot at
95 // the top of loop(): the audio source's task can raise a start at any point above, including
96 // during stop_i2s_driver_(), and nothing would ever re-issue it.
97 const EventBits_t bits_before_clear = xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::ALL_BITS);
98 if (bits_before_clear & SpeakerEventGroupBits::COMMAND_START) {
99 ESP_LOGD(TAG, "Start requested while stopping; keeping the request");
100 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_START);
101 }
102 this->status_clear_error();
103
104 this->on_task_stopped();
105
107 }
108
109 if (event_group_bits & SpeakerEventGroupBits::ERR_ESP_NO_MEM) {
110 ESP_LOGE(TAG, "Speaker task setup failed (allocation, preload, or channel enable)");
111 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
112 }
113
114 // Handle the speaker's state
115 switch (this->state_) {
117 if (this->status_has_error()) {
118 break;
119 }
120
121 // Still starting up or winding down from a previous run
122 if ((this->tx_handle_ != nullptr) || (this->speaker_task_handle_ != nullptr)) {
123 break;
124 }
125
126 if (this->start_i2s_driver(this->audio_stream_info_) != ESP_OK) {
127 ESP_LOGE(TAG, "Driver failed to start; retrying in 1 second");
128 this->status_momentary_error("driver-failure", 1000);
129 break;
130 }
131
132 xTaskCreate(I2SAudioSpeakerBase::speaker_task, "speaker_task", TASK_STACK_SIZE, (void *) this, TASK_PRIORITY,
133 &this->speaker_task_handle_);
134
135 if (this->speaker_task_handle_ == nullptr) {
136 ESP_LOGE(TAG, "Task failed to start, retrying in 1 second");
137 this->status_momentary_error("task-failure", 1000);
138 this->stop_i2s_driver_(); // Stops the driver to return the lock; will be reloaded in next attempt
139 }
140 break;
141 case speaker::STATE_RUNNING: // Intentional fallthrough
142 case speaker::STATE_STOPPING: // Intentional fallthrough
144 break;
145 }
146}
147
148void I2SAudioSpeakerBase::set_volume(float volume) {
149 this->volume_ = volume;
150#ifdef USE_AUDIO_DAC
151 if (this->audio_dac_ != nullptr) {
152 if (volume > 0.0f) {
153 this->audio_dac_->set_mute_off();
154 }
155 this->audio_dac_->set_volume(volume);
156 } else
157#endif // USE_AUDIO_DAC
158 {
159 // Fallback to software volume control by using a Q31 fixed point scaling factor.
160 // At maximum volume (1.0), set to INT32_MAX to bypass volume processing entirely
161 // and avoid any floating-point precision issues that could cause slight volume reduction.
162 if (volume >= 1.0f) {
163 this->q31_volume_factor_ = INT32_MAX;
164 } else if (volume <= 0.0f) {
165 this->q31_volume_factor_ = 0;
166 } else {
167 this->q31_volume_factor_ =
168 esp_audio_libs::gain::db_to_q31(remap<float, float>(volume, 0.0f, 1.0f, SOFTWARE_VOLUME_MIN_DB, 0.0f));
169 }
170 }
171}
172
173void I2SAudioSpeakerBase::set_mute_state(bool mute_state) {
174 this->mute_state_ = mute_state;
175#ifdef USE_AUDIO_DAC
176 if (this->audio_dac_) {
177 if (mute_state) {
178 this->audio_dac_->set_mute_on();
179 } else {
180 this->audio_dac_->set_mute_off();
181 }
182 } else
183#endif // USE_AUDIO_DAC
184 {
185 if (mute_state) {
186 // Fallback to software volume control and scale by 0
187 this->q31_volume_factor_ = 0;
188 } else {
189 // Revert to previous volume when unmuting
190 this->set_volume(this->volume_);
191 }
192 }
193}
194
195size_t I2SAudioSpeakerBase::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
196 if (this->is_failed()) {
197 ESP_LOGE(TAG, "Setup failed; cannot play audio");
198 return 0;
199 }
200
202 this->start();
203 }
204
205 if (this->state_ != speaker::STATE_RUNNING) {
206 // Unable to write data to a running speaker, so delay the max amount of time so it can get ready
207 vTaskDelay(ticks_to_wait);
208 ticks_to_wait = 0;
209 }
210
211 size_t bytes_written = 0;
212 if (this->state_ == speaker::STATE_RUNNING) {
213 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = this->audio_ring_buffer_.lock();
214 if (temp_ring_buffer != nullptr) {
215 // The weak_ptr locks successfully only while the speaker task owns the ring buffer, so it is safe to write
216 bytes_written = temp_ring_buffer->write_without_replacement((void *) data, length, ticks_to_wait);
217 }
218 }
219
220 return bytes_written;
221}
222
224 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = this->audio_ring_buffer_.lock();
225 if (temp_ring_buffer != nullptr) {
226 return temp_ring_buffer->available() > 0;
227 }
228 return false;
229}
230
231void I2SAudioSpeakerBase::speaker_task(void *params) {
232 I2SAudioSpeakerBase *this_speaker = (I2SAudioSpeakerBase *) params;
233 this_speaker->run_speaker_task();
234}
235
237 if (!this->is_ready() || this->is_failed() || this->status_has_error())
238 return;
239 if ((this->state_ == speaker::STATE_STARTING) || (this->state_ == speaker::STATE_RUNNING))
240 return;
241
242 // Mark STARTING immediately to avoid transient STOPPED observations before loop() processes COMMAND_START.
244 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_START);
245}
246
247void I2SAudioSpeakerBase::stop() { this->stop_(false); }
248
249void I2SAudioSpeakerBase::finish() { this->stop_(true); }
250
251void I2SAudioSpeakerBase::stop_(bool wait_on_empty) {
252 if (this->is_failed())
253 return;
254 if (this->state_ == speaker::STATE_STOPPED)
255 return;
256
257 if (wait_on_empty) {
259 } else {
260 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP);
261 }
262}
263
264esp_err_t I2SAudioSpeakerBase::init_i2s_channel_(const i2s_chan_config_t &chan_cfg, const i2s_std_config_t &std_cfg,
265 size_t event_queue_size) {
266 esp_err_t err = i2s_new_channel(&chan_cfg, &this->tx_handle_, NULL);
267 if (err != ESP_OK) {
268 ESP_LOGE(TAG, "I2S channel allocation failed: %s", esp_err_to_name(err));
269 this->parent_->unlock();
270 return err;
271 }
272
273 err = i2s_channel_init_std_mode(this->tx_handle_, &std_cfg);
274 if (err != ESP_OK) {
275 ESP_LOGE(TAG, "Failed to initialize I2S channel");
276 i2s_del_channel(this->tx_handle_);
277 this->tx_handle_ = nullptr;
278 this->parent_->unlock();
279 return err;
280 }
281
282 if (this->i2s_event_queue_ == nullptr) {
283 this->i2s_event_queue_ = xQueueCreate(event_queue_size, sizeof(int64_t));
284 } else {
285 // Reset queue to clear any stale events from previous task
286 xQueueReset(this->i2s_event_queue_);
287 }
288
289 // Lockstep records queue. One record per in-flight DMA buffer; sized to match the I2S event queue
290 // so a fully-saturated DMA pipeline cannot overflow either side before drain.
291 if (this->write_records_queue_ == nullptr) {
292 this->write_records_queue_ = xQueueCreate(event_queue_size, sizeof(uint32_t));
293 } else {
294 xQueueReset(this->write_records_queue_);
295 }
296
297 if (this->i2s_event_queue_ == nullptr || this->write_records_queue_ == nullptr) {
298 ESP_LOGE(TAG, "Failed to allocate I2S event queue(s)");
299 i2s_del_channel(this->tx_handle_);
300 this->tx_handle_ = nullptr;
301 this->parent_->unlock();
302 return ESP_ERR_NO_MEM;
303 }
304
305 return ESP_OK;
306}
307
309 if (this->tx_handle_ != nullptr) {
310 i2s_channel_disable(this->tx_handle_);
311 i2s_del_channel(this->tx_handle_);
312 this->tx_handle_ = nullptr;
313
314 // i2s_del_channel() leaves dout wired to this port's data-out signal in the GPIO matrix: it only
315 // clears an internal reservation mask, never the esp_rom_gpio_connect_out_signal() routing that
316 // setup installed. If another speaker reuses this port (shared bus), its audio still reaches our
317 // dout. Detach the pin and drive it low so a stale output stops driving downstream hardware: a
318 // SPDIF optical transmitter would otherwise stay lit, and an analog DAC would emit noise.
319 gpio_reset_pin(this->dout_pin_);
320 gpio_set_direction(this->dout_pin_, GPIO_MODE_OUTPUT);
321 gpio_set_level(this->dout_pin_, 0);
322 }
323 this->parent_->unlock();
324}
325
326bool IRAM_ATTR I2SAudioSpeakerBase::i2s_on_sent_cb(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx) {
327 int64_t now = esp_timer_get_time();
328
329 BaseType_t need_yield1 = pdFALSE;
330 BaseType_t need_yield2 = pdFALSE;
331 BaseType_t need_yield3 = pdFALSE;
332
333 I2SAudioSpeakerBase *this_speaker = (I2SAudioSpeakerBase *) user_ctx;
334
335 if (xQueueIsQueueFullFromISR(this_speaker->i2s_event_queue_)) {
336 // Queue is full, so discard the oldest event. Once we drop a completion event, ``i2s_event_queue_``
337 // and any per-buffer record queue maintained by the task are permanently desynced, so the task
338 // must restart to recover. Set both ERR_DROPPED_EVENT (so loop() can log it) and COMMAND_STOP
339 // (so the task bails immediately, closing the race where loop() could clear the error bit
340 // before the task observes it).
341 int64_t dummy;
342 xQueueReceiveFromISR(this_speaker->i2s_event_queue_, &dummy, &need_yield1);
343 xEventGroupSetBitsFromISR(this_speaker->event_group_,
345 &need_yield2);
346 }
347
348 xQueueSendToBackFromISR(this_speaker->i2s_event_queue_, &now, &need_yield3);
349
350 return need_yield1 | need_yield2 | need_yield3;
351}
352
353void I2SAudioSpeakerBase::apply_software_volume_(uint8_t *data, size_t bytes_read) {
354 if (this->q31_volume_factor_ == INT32_MAX) {
355 return; // Max volume, no processing needed
356 }
357
358 const size_t bytes_per_sample = this->current_stream_info_.samples_to_bytes(1);
359 const uint32_t len = bytes_read / bytes_per_sample;
360
361 esp_audio_libs::gain::apply(data, data, this->q31_volume_factor_, len, bytes_per_sample);
362}
363
364void I2SAudioSpeakerBase::swap_esp32_mono_samples_(uint8_t *data, size_t bytes_read) {
365#ifdef USE_ESP32_VARIANT_ESP32
366 // For ESP32 16-bit mono mode, adjacent samples need to be swapped.
367 if (this->output_stream_info_.get_channels() == 1 && this->output_stream_info_.get_bits_per_sample() == 16) {
368 int16_t *samples = reinterpret_cast<int16_t *>(data);
369 size_t sample_count = bytes_read / sizeof(int16_t);
370 for (size_t i = 0; i + 1 < sample_count; i += 2) {
371 int16_t tmp = samples[i];
372 samples[i] = samples[i + 1];
373 samples[i + 1] = tmp;
374 }
375 }
376#endif // USE_ESP32_VARIANT_ESP32
377}
378
379} // namespace esphome::i2s_audio
380
381#endif // USE_ESP32
void mark_failed()
Mark this component as failed.
void status_momentary_error(const char *name, uint32_t length=5000)
Set error status flag and automatically clear it after a timeout.
bool is_failed() const
Definition component.h:272
void status_clear_error()
Definition component.h:295
bool is_ready() const
bool status_has_error() const
Definition component.h:280
size_t samples_to_bytes(uint32_t samples) const
Converts samples to bytes.
Definition audio.h:58
uint8_t get_channels() const
Definition audio.h:29
virtual bool set_mute_off()=0
virtual bool set_volume(float volume)=0
virtual bool set_mute_on()=0
Abstract base class for I2S audio speaker implementations.
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 stop_i2s_driver_()
Stops the I2S driver and unlocks the I2S port.
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.
virtual esp_err_t start_i2s_driver(audio::AudioStreamInfo &audio_stream_info)=0
Starts the ESP32 I2S driver.
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.
virtual void on_task_stopped()
Called in loop() when the task has stopped. Override for mode-specific cleanup.
void stop_(bool wait_on_empty)
Plays the provided audio data.
virtual size_t play(const uint8_t *data, size_t length)=0
Plays the provided audio data.
virtual void set_volume(float volume)
Definition speaker.h:70
audio_dac::AudioDac * audio_dac_
Definition speaker.h:119
virtual void set_mute_state(bool mute_state)
Definition speaker.h:80
virtual bool has_buffered_data() const =0
audio::AudioStreamInfo audio_stream_info_
Definition speaker.h:114
const void size_t len
Definition hal.h:64
T remap(U value, U min, U max, T min_out, T max_out)
Remap value from the range (min, max) to (min_out, max_out).
Definition helpers.h:790
int64_t esp_timer_get_time(void)
static void uint32_t
uint16_t length
Definition tt21100.cpp:0
spi_device_handle_t handle