ESPHome 2025.6.3
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#ifdef USE_I2S_LEGACY
6#include <driver/i2s.h>
7#else
8#include <driver/i2s_std.h>
9#endif
10
12
14#include "esphome/core/hal.h"
15#include "esphome/core/log.h"
16
17#include "esp_timer.h"
18
19namespace esphome {
20namespace i2s_audio {
21
22static const uint8_t DMA_BUFFER_DURATION_MS = 15;
23static const size_t DMA_BUFFERS_COUNT = 4;
24
25static const size_t TASK_DELAY_MS = DMA_BUFFER_DURATION_MS * DMA_BUFFERS_COUNT / 2;
26
27static const size_t TASK_STACK_SIZE = 4096;
28static const ssize_t TASK_PRIORITY = 23;
29
30static const size_t I2S_EVENT_QUEUE_COUNT = DMA_BUFFERS_COUNT + 1;
31
32static const char *const TAG = "i2s_audio.speaker";
33
34enum SpeakerEventGroupBits : uint32_t {
35 COMMAND_START = (1 << 0), // starts the speaker task
36 COMMAND_STOP = (1 << 1), // stops the speaker task
37 COMMAND_STOP_GRACEFULLY = (1 << 2), // Stops the speaker task once all data has been written
38 STATE_STARTING = (1 << 10),
39 STATE_RUNNING = (1 << 11),
40 STATE_STOPPING = (1 << 12),
41 STATE_STOPPED = (1 << 13),
42 ERR_TASK_FAILED_TO_START = (1 << 14),
43 ERR_ESP_INVALID_STATE = (1 << 15),
44 ERR_ESP_NOT_SUPPORTED = (1 << 16),
45 ERR_ESP_INVALID_ARG = (1 << 17),
46 ERR_ESP_INVALID_SIZE = (1 << 18),
47 ERR_ESP_NO_MEM = (1 << 19),
48 ERR_ESP_FAIL = (1 << 20),
49 ALL_ERR_ESP_BITS = ERR_ESP_INVALID_STATE | ERR_ESP_NOT_SUPPORTED | ERR_ESP_INVALID_ARG | ERR_ESP_INVALID_SIZE |
51 ALL_BITS = 0x00FFFFFF, // All valid FreeRTOS event group bits
52};
53
54// Translates a SpeakerEventGroupBits ERR_ESP bit to the coressponding esp_err_t
55static esp_err_t err_bit_to_esp_err(uint32_t bit) {
56 switch (bit) {
57 case SpeakerEventGroupBits::ERR_ESP_INVALID_STATE:
58 return ESP_ERR_INVALID_STATE;
59 case SpeakerEventGroupBits::ERR_ESP_INVALID_ARG:
60 return ESP_ERR_INVALID_ARG;
61 case SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE:
62 return ESP_ERR_INVALID_SIZE;
63 case SpeakerEventGroupBits::ERR_ESP_NO_MEM:
64 return ESP_ERR_NO_MEM;
65 case SpeakerEventGroupBits::ERR_ESP_NOT_SUPPORTED:
66 return ESP_ERR_NOT_SUPPORTED;
67 default:
68 return ESP_FAIL;
69 }
70}
71
81static void q15_multiplication(const int16_t *input, int16_t *output, size_t len, int16_t c) {
82 for (int i = 0; i < len; i++) {
83 int32_t acc = (int32_t) input[i] * (int32_t) c;
84 output[i] = (int16_t) (acc >> 15);
85 }
86}
87
88// Lists the Q15 fixed point scaling factor for volume reduction.
89// Has 100 values representing silence and a reduction [49, 48.5, ... 0.5, 0] dB.
90// dB to PCM scaling factor formula: floating_point_scale_factor = 2^(-db/6.014)
91// float to Q15 fixed point formula: q15_scale_factor = floating_point_scale_factor * 2^(15)
92static const std::vector<int16_t> Q15_VOLUME_SCALING_FACTORS = {
93 0, 116, 122, 130, 137, 146, 154, 163, 173, 183, 194, 206, 218, 231, 244,
94 259, 274, 291, 308, 326, 345, 366, 388, 411, 435, 461, 488, 517, 548, 580,
95 615, 651, 690, 731, 774, 820, 868, 920, 974, 1032, 1094, 1158, 1227, 1300, 1377,
96 1459, 1545, 1637, 1734, 1837, 1946, 2061, 2184, 2313, 2450, 2596, 2750, 2913, 3085, 3269,
97 3462, 3668, 3885, 4116, 4360, 4619, 4893, 5183, 5490, 5816, 6161, 6527, 6914, 7324, 7758,
98 8218, 8706, 9222, 9770, 10349, 10963, 11613, 12302, 13032, 13805, 14624, 15491, 16410, 17384, 18415,
99 19508, 20665, 21891, 23189, 24565, 26022, 27566, 29201, 30933, 32767};
100
102 ESP_LOGCONFIG(TAG, "Running setup");
103
104 this->event_group_ = xEventGroupCreate();
105
106 if (this->event_group_ == nullptr) {
107 ESP_LOGE(TAG, "Failed to create event group");
108 this->mark_failed();
109 return;
110 }
111}
112
114 ESP_LOGCONFIG(TAG,
115 "Speaker:\n"
116 " Pin: %d\n"
117 " Buffer duration: %" PRIu32,
118 static_cast<int8_t>(this->dout_pin_), this->buffer_duration_ms_);
119 if (this->timeout_.has_value()) {
120 ESP_LOGCONFIG(TAG, " Timeout: %" PRIu32 " ms", this->timeout_.value());
121 }
122#ifdef USE_I2S_LEGACY
123#if SOC_I2S_SUPPORTS_DAC
124 ESP_LOGCONFIG(TAG, " Internal DAC mode: %d", static_cast<int8_t>(this->internal_dac_mode_));
125#endif
126 ESP_LOGCONFIG(TAG, " Communication format: %d", static_cast<int8_t>(this->i2s_comm_fmt_));
127#else
128 ESP_LOGCONFIG(TAG, " Communication format: %s", this->i2s_comm_fmt_.c_str());
129#endif
130}
131
133 uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
134
135 if (event_group_bits & SpeakerEventGroupBits::STATE_STARTING) {
136 ESP_LOGD(TAG, "Starting");
138 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::STATE_STARTING);
139 }
140 if (event_group_bits & SpeakerEventGroupBits::STATE_RUNNING) {
141 ESP_LOGD(TAG, "Started");
143 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::STATE_RUNNING);
144 this->status_clear_warning();
145 this->status_clear_error();
146 }
147 if (event_group_bits & SpeakerEventGroupBits::STATE_STOPPING) {
148 ESP_LOGD(TAG, "Stopping");
150 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::STATE_STOPPING);
151 }
152 if (event_group_bits & SpeakerEventGroupBits::STATE_STOPPED) {
153 if (!this->task_created_) {
154 ESP_LOGD(TAG, "Stopped");
156 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::ALL_BITS);
157 this->speaker_task_handle_ = nullptr;
158 }
159 }
160
161 if (event_group_bits & SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START) {
162 this->status_set_error("Failed to start task");
163 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START);
164 }
165
166 if (event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS) {
167 uint32_t error_bits = event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS;
168 ESP_LOGW(TAG, "Writing failed: %s", esp_err_to_name(err_bit_to_esp_err(error_bits)));
169 this->status_set_warning();
170 }
171
172 if (event_group_bits & SpeakerEventGroupBits::ERR_ESP_NOT_SUPPORTED) {
173 this->status_set_error("Failed to adjust bus to match incoming audio");
174 ESP_LOGE(TAG, "Incompatible audio format: sample rate = %" PRIu32 ", channels = %u, bits per sample = %u",
175 this->audio_stream_info_.get_sample_rate(), this->audio_stream_info_.get_channels(),
176 this->audio_stream_info_.get_bits_per_sample());
177 }
178
179 xEventGroupClearBits(this->event_group_, ALL_ERR_ESP_BITS);
180}
181
182void I2SAudioSpeaker::set_volume(float volume) {
183 this->volume_ = volume;
184#ifdef USE_AUDIO_DAC
185 if (this->audio_dac_ != nullptr) {
186 if (volume > 0.0) {
187 this->audio_dac_->set_mute_off();
188 }
189 this->audio_dac_->set_volume(volume);
190 } else
191#endif
192 {
193 // Fallback to software volume control by using a Q15 fixed point scaling factor
194 ssize_t decibel_index = remap<ssize_t, float>(volume, 0.0f, 1.0f, 0, Q15_VOLUME_SCALING_FACTORS.size() - 1);
195 this->q15_volume_factor_ = Q15_VOLUME_SCALING_FACTORS[decibel_index];
196 }
197}
198
199void I2SAudioSpeaker::set_mute_state(bool mute_state) {
200 this->mute_state_ = mute_state;
201#ifdef USE_AUDIO_DAC
202 if (this->audio_dac_) {
203 if (mute_state) {
204 this->audio_dac_->set_mute_on();
205 } else {
206 this->audio_dac_->set_mute_off();
207 }
208 } else
209#endif
210 {
211 if (mute_state) {
212 // Fallback to software volume control and scale by 0
213 this->q15_volume_factor_ = 0;
214 } else {
215 // Revert to previous volume when unmuting
216 this->set_volume(this->volume_);
217 }
218 }
219}
220
221size_t I2SAudioSpeaker::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
222 if (this->is_failed()) {
223 ESP_LOGE(TAG, "Setup failed; cannot play audio");
224 return 0;
225 }
227 this->start();
228 }
229
230 if ((this->state_ != speaker::STATE_RUNNING) || (this->audio_ring_buffer_.use_count() != 1)) {
231 // Unable to write data to a running speaker, so delay the max amount of time so it can get ready
232 vTaskDelay(ticks_to_wait);
233 ticks_to_wait = 0;
234 }
235
236 size_t bytes_written = 0;
237 if ((this->state_ == speaker::STATE_RUNNING) && (this->audio_ring_buffer_.use_count() == 1)) {
238 // Only one owner of the ring buffer (the speaker task), so the ring buffer is allocated and no other components are
239 // attempting to write to it.
240
241 // Temporarily share ownership of the ring buffer so it won't be deallocated while writing
242 std::shared_ptr<RingBuffer> temp_ring_buffer = this->audio_ring_buffer_;
243 bytes_written = temp_ring_buffer->write_without_replacement((void *) data, length, ticks_to_wait);
244 }
245
246 return bytes_written;
247}
248
250 if (this->audio_ring_buffer_ != nullptr) {
251 return this->audio_ring_buffer_->available() > 0;
252 }
253 return false;
254}
255
256void I2SAudioSpeaker::speaker_task(void *params) {
257 I2SAudioSpeaker *this_speaker = (I2SAudioSpeaker *) params;
258 this_speaker->task_created_ = true;
259
260 uint32_t event_group_bits =
261 xEventGroupWaitBits(this_speaker->event_group_,
262 SpeakerEventGroupBits::COMMAND_START | SpeakerEventGroupBits::COMMAND_STOP |
263 SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY, // Bit message to read
264 pdTRUE, // Clear the bits on exit
265 pdFALSE, // Don't wait for all the bits,
266 portMAX_DELAY); // Block indefinitely until a bit is set
267
268 if (event_group_bits & (SpeakerEventGroupBits::COMMAND_STOP | SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY)) {
269 // Received a stop signal before the task was requested to start
270 this_speaker->delete_task_(0);
271 }
272
273 xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STARTING);
274
275 audio::AudioStreamInfo audio_stream_info = this_speaker->audio_stream_info_;
276
277 const uint32_t dma_buffers_duration_ms = DMA_BUFFER_DURATION_MS * DMA_BUFFERS_COUNT;
278 // Ensure ring buffer duration is at least the duration of all DMA buffers
279 const uint32_t ring_buffer_duration = std::max(dma_buffers_duration_ms, this_speaker->buffer_duration_ms_);
280
281 // The DMA buffers may have more bits per sample, so calculate buffer sizes based in the input audio stream info
282 const size_t data_buffer_size = audio_stream_info.ms_to_bytes(dma_buffers_duration_ms);
283 const size_t ring_buffer_size = audio_stream_info.ms_to_bytes(ring_buffer_duration);
284
285 const size_t single_dma_buffer_input_size = data_buffer_size / DMA_BUFFERS_COUNT;
286
287 if (this_speaker->send_esp_err_to_event_group_(this_speaker->allocate_buffers_(data_buffer_size, ring_buffer_size))) {
288 // Failed to allocate buffers
289 xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
290 this_speaker->delete_task_(data_buffer_size);
291 }
292
293 if (!this_speaker->send_esp_err_to_event_group_(this_speaker->start_i2s_driver_(audio_stream_info))) {
294 xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_RUNNING);
295
296 bool stop_gracefully = false;
297 uint32_t last_data_received_time = millis();
298 bool tx_dma_underflow = false;
299
300 this_speaker->accumulated_frames_written_ = 0;
301
302 // Keep looping if paused, there is no timeout configured, or data was received more recently than the configured
303 // timeout
304 while (this_speaker->pause_state_ || !this_speaker->timeout_.has_value() ||
305 (millis() - last_data_received_time) <= this_speaker->timeout_.value()) {
306 event_group_bits = xEventGroupGetBits(this_speaker->event_group_);
307
308 if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP) {
309 xEventGroupClearBits(this_speaker->event_group_, SpeakerEventGroupBits::COMMAND_STOP);
310 break;
311 }
312 if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY) {
313 xEventGroupClearBits(this_speaker->event_group_, SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY);
314 stop_gracefully = true;
315 }
316
317 if (this_speaker->audio_stream_info_ != audio_stream_info) {
318 // Audio stream info changed, stop the speaker task so it will restart with the proper settings.
319 break;
320 }
321#ifdef USE_I2S_LEGACY
322 i2s_event_t i2s_event;
323 while (xQueueReceive(this_speaker->i2s_event_queue_, &i2s_event, 0)) {
324 if (i2s_event.type == I2S_EVENT_TX_Q_OVF) {
325 tx_dma_underflow = true;
326 }
327 }
328#else
329 bool overflow;
330 while (xQueueReceive(this_speaker->i2s_event_queue_, &overflow, 0)) {
331 if (overflow) {
332 tx_dma_underflow = true;
333 }
334 }
335#endif
336
337 if (this_speaker->pause_state_) {
338 // Pause state is accessed atomically, so thread safe
339 // Delay so the task can yields, then skip transferring audio data
340 delay(TASK_DELAY_MS);
341 continue;
342 }
343
344 size_t bytes_read = this_speaker->audio_ring_buffer_->read((void *) this_speaker->data_buffer_, data_buffer_size,
345 pdMS_TO_TICKS(TASK_DELAY_MS));
346
347 if (bytes_read > 0) {
348 if ((audio_stream_info.get_bits_per_sample() == 16) && (this_speaker->q15_volume_factor_ < INT16_MAX)) {
349 // Scale samples by the volume factor in place
350 q15_multiplication((int16_t *) this_speaker->data_buffer_, (int16_t *) this_speaker->data_buffer_,
351 bytes_read / sizeof(int16_t), this_speaker->q15_volume_factor_);
352 }
353
354#ifdef USE_ESP32_VARIANT_ESP32
355 // For ESP32 8/16 bit mono mode samples need to be switched.
356 if (audio_stream_info.get_channels() == 1 && audio_stream_info.get_bits_per_sample() <= 16) {
357 size_t len = bytes_read / sizeof(int16_t);
358 int16_t *tmp_buf = (int16_t *) this_speaker->data_buffer_;
359 for (int i = 0; i < len; i += 2) {
360 int16_t tmp = tmp_buf[i];
361 tmp_buf[i] = tmp_buf[i + 1];
362 tmp_buf[i + 1] = tmp;
363 }
364 }
365#endif
366 // Write the audio data to a single DMA buffer at a time to reduce latency for the audio duration played
367 // callback.
368 const uint32_t batches = (bytes_read + single_dma_buffer_input_size - 1) / single_dma_buffer_input_size;
369
370 for (uint32_t i = 0; i < batches; ++i) {
371 size_t bytes_written = 0;
372 size_t bytes_to_write = std::min(single_dma_buffer_input_size, bytes_read);
373
374#ifdef USE_I2S_LEGACY
375 if (audio_stream_info.get_bits_per_sample() == (uint8_t) this_speaker->bits_per_sample_) {
376 i2s_write(this_speaker->parent_->get_port(), this_speaker->data_buffer_ + i * single_dma_buffer_input_size,
377 bytes_to_write, &bytes_written, pdMS_TO_TICKS(DMA_BUFFER_DURATION_MS * 5));
378 } else if (audio_stream_info.get_bits_per_sample() < (uint8_t) this_speaker->bits_per_sample_) {
379 i2s_write_expand(this_speaker->parent_->get_port(),
380 this_speaker->data_buffer_ + i * single_dma_buffer_input_size, bytes_to_write,
381 audio_stream_info.get_bits_per_sample(), this_speaker->bits_per_sample_, &bytes_written,
382 pdMS_TO_TICKS(DMA_BUFFER_DURATION_MS * 5));
383 }
384#else
385 i2s_channel_write(this_speaker->tx_handle_, this_speaker->data_buffer_ + i * single_dma_buffer_input_size,
386 bytes_to_write, &bytes_written, pdMS_TO_TICKS(DMA_BUFFER_DURATION_MS * 5));
387#endif
388
389 int64_t now = esp_timer_get_time();
390
391 if (bytes_written != bytes_to_write) {
392 xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE);
393 }
394 bytes_read -= bytes_written;
395
396 this_speaker->audio_output_callback_(audio_stream_info.bytes_to_frames(bytes_written),
397 now + dma_buffers_duration_ms * 1000);
398
399 tx_dma_underflow = false;
400 last_data_received_time = millis();
401 }
402 } else {
403 // No data received
404 if (stop_gracefully && tx_dma_underflow) {
405 break;
406 }
407 }
408 }
409
410 xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STOPPING);
411#ifdef USE_I2S_LEGACY
412 i2s_driver_uninstall(this_speaker->parent_->get_port());
413#else
414 i2s_channel_disable(this_speaker->tx_handle_);
415 i2s_del_channel(this_speaker->tx_handle_);
416#endif
417
418 this_speaker->parent_->unlock();
419 }
420
421 this_speaker->delete_task_(data_buffer_size);
422}
423
425 if (!this->is_ready() || this->is_failed() || this->status_has_error())
426 return;
427 if ((this->state_ == speaker::STATE_STARTING) || (this->state_ == speaker::STATE_RUNNING))
428 return;
429
430 if (!this->task_created_ && (this->speaker_task_handle_ == nullptr)) {
431 xTaskCreate(I2SAudioSpeaker::speaker_task, "speaker_task", TASK_STACK_SIZE, (void *) this, TASK_PRIORITY,
432 &this->speaker_task_handle_);
433
434 if (this->speaker_task_handle_ != nullptr) {
435 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_START);
436 } else {
437 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START);
438 }
439 }
440}
441
442void I2SAudioSpeaker::stop() { this->stop_(false); }
443
444void I2SAudioSpeaker::finish() { this->stop_(true); }
445
446void I2SAudioSpeaker::stop_(bool wait_on_empty) {
447 if (this->is_failed())
448 return;
449 if (this->state_ == speaker::STATE_STOPPED)
450 return;
451
452 if (wait_on_empty) {
453 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY);
454 } else {
455 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP);
456 }
457}
458
460 switch (err) {
461 case ESP_OK:
462 return false;
463 case ESP_ERR_INVALID_STATE:
464 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_STATE);
465 return true;
466 case ESP_ERR_INVALID_ARG:
467 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_ARG);
468 return true;
469 case ESP_ERR_INVALID_SIZE:
470 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE);
471 return true;
472 case ESP_ERR_NO_MEM:
473 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
474 return true;
475 case ESP_ERR_NOT_SUPPORTED:
476 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_NOT_SUPPORTED);
477 return true;
478 default:
479 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_FAIL);
480 return true;
481 }
482}
483
484esp_err_t I2SAudioSpeaker::allocate_buffers_(size_t data_buffer_size, size_t ring_buffer_size) {
485 if (this->data_buffer_ == nullptr) {
486 // Allocate data buffer for temporarily storing audio from the ring buffer before writing to the I2S bus
488 this->data_buffer_ = allocator.allocate(data_buffer_size);
489 }
490
491 if (this->data_buffer_ == nullptr) {
492 return ESP_ERR_NO_MEM;
493 }
494
495 if (this->audio_ring_buffer_.use_count() == 0) {
496 // Allocate ring buffer. Uses a shared_ptr to ensure it isn't improperly deallocated.
497 this->audio_ring_buffer_ = RingBuffer::create(ring_buffer_size);
498 }
499
500 if (this->audio_ring_buffer_ == nullptr) {
501 return ESP_ERR_NO_MEM;
502 }
503
504 return ESP_OK;
505}
506
507esp_err_t I2SAudioSpeaker::start_i2s_driver_(audio::AudioStreamInfo &audio_stream_info) {
508#ifdef USE_I2S_LEGACY
509 if ((this->i2s_mode_ & I2S_MODE_SLAVE) && (this->sample_rate_ != audio_stream_info.get_sample_rate())) { // NOLINT
510#else
511 if ((this->i2s_role_ & I2S_ROLE_SLAVE) && (this->sample_rate_ != audio_stream_info.get_sample_rate())) { // NOLINT
512#endif
513 // Can't reconfigure I2S bus, so the sample rate must match the configured value
514 return ESP_ERR_NOT_SUPPORTED;
515 }
516
517#ifdef USE_I2S_LEGACY
518 if ((i2s_bits_per_sample_t) audio_stream_info.get_bits_per_sample() > this->bits_per_sample_) {
519#else
520 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO &&
521 (i2s_slot_bit_width_t) audio_stream_info.get_bits_per_sample() > this->slot_bit_width_) {
522#endif
523 // Currently can't handle the case when the incoming audio has more bits per sample than the configured value
524 return ESP_ERR_NOT_SUPPORTED;
525 }
526
527 if (!this->parent_->try_lock()) {
528 return ESP_ERR_INVALID_STATE;
529 }
530
531 uint32_t dma_buffer_length = audio_stream_info.ms_to_frames(DMA_BUFFER_DURATION_MS);
532
533#ifdef USE_I2S_LEGACY
534 i2s_channel_fmt_t channel = this->channel_;
535
536 if (audio_stream_info.get_channels() == 1) {
537 if (this->channel_ == I2S_CHANNEL_FMT_ONLY_LEFT) {
538 channel = I2S_CHANNEL_FMT_ONLY_LEFT;
539 } else {
540 channel = I2S_CHANNEL_FMT_ONLY_RIGHT;
541 }
542 } else if (audio_stream_info.get_channels() == 2) {
543 channel = I2S_CHANNEL_FMT_RIGHT_LEFT;
544 }
545
546 i2s_driver_config_t config = {
547 .mode = (i2s_mode_t) (this->i2s_mode_ | I2S_MODE_TX),
548 .sample_rate = audio_stream_info.get_sample_rate(),
549 .bits_per_sample = this->bits_per_sample_,
550 .channel_format = channel,
551 .communication_format = this->i2s_comm_fmt_,
552 .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
553 .dma_buf_count = DMA_BUFFERS_COUNT,
554 .dma_buf_len = (int) dma_buffer_length,
555 .use_apll = this->use_apll_,
556 .tx_desc_auto_clear = true,
557 .fixed_mclk = I2S_PIN_NO_CHANGE,
558 .mclk_multiple = this->mclk_multiple_,
559 .bits_per_chan = this->bits_per_channel_,
560#if SOC_I2S_SUPPORTS_TDM
561 .chan_mask = (i2s_channel_t) (I2S_TDM_ACTIVE_CH0 | I2S_TDM_ACTIVE_CH1),
562 .total_chan = 2,
563 .left_align = false,
564 .big_edin = false,
565 .bit_order_msb = false,
566 .skip_msk = false,
567#endif
568 };
569#if SOC_I2S_SUPPORTS_DAC
570 if (this->internal_dac_mode_ != I2S_DAC_CHANNEL_DISABLE) {
571 config.mode = (i2s_mode_t) (config.mode | I2S_MODE_DAC_BUILT_IN);
572 }
573#endif
574
575 esp_err_t err =
576 i2s_driver_install(this->parent_->get_port(), &config, I2S_EVENT_QUEUE_COUNT, &this->i2s_event_queue_);
577 if (err != ESP_OK) {
578 // Failed to install the driver, so unlock the I2S port
579 this->parent_->unlock();
580 return err;
581 }
582
583#if SOC_I2S_SUPPORTS_DAC
584 if (this->internal_dac_mode_ == I2S_DAC_CHANNEL_DISABLE) {
585#endif
586 i2s_pin_config_t pin_config = this->parent_->get_pin_config();
587 pin_config.data_out_num = this->dout_pin_;
588
589 err = i2s_set_pin(this->parent_->get_port(), &pin_config);
590#if SOC_I2S_SUPPORTS_DAC
591 } else {
592 i2s_set_dac_mode(this->internal_dac_mode_);
593 }
594#endif
595
596 if (err != ESP_OK) {
597 // Failed to set the data out pin, so uninstall the driver and unlock the I2S port
598 i2s_driver_uninstall(this->parent_->get_port());
599 this->parent_->unlock();
600 }
601#else
602 i2s_chan_config_t chan_cfg = {
603 .id = this->parent_->get_port(),
604 .role = this->i2s_role_,
605 .dma_desc_num = DMA_BUFFERS_COUNT,
606 .dma_frame_num = dma_buffer_length,
607 .auto_clear = true,
608 };
609 /* Allocate a new TX channel and get the handle of this channel */
610 esp_err_t err = i2s_new_channel(&chan_cfg, &this->tx_handle_, NULL);
611 if (err != ESP_OK) {
612 this->parent_->unlock();
613 return err;
614 }
615
616 i2s_clock_src_t clk_src = I2S_CLK_SRC_DEFAULT;
617#ifdef I2S_CLK_SRC_APLL
618 if (this->use_apll_) {
619 clk_src = I2S_CLK_SRC_APLL;
620 }
621#endif
622 i2s_std_gpio_config_t pin_config = this->parent_->get_pin_config();
623
624 i2s_std_clk_config_t clk_cfg = {
625 .sample_rate_hz = audio_stream_info.get_sample_rate(),
626 .clk_src = clk_src,
627 .mclk_multiple = this->mclk_multiple_,
628 };
629
630 i2s_slot_mode_t slot_mode = this->slot_mode_;
631 i2s_std_slot_mask_t slot_mask = this->std_slot_mask_;
632 if (audio_stream_info.get_channels() == 1) {
633 slot_mode = I2S_SLOT_MODE_MONO;
634 } else if (audio_stream_info.get_channels() == 2) {
635 slot_mode = I2S_SLOT_MODE_STEREO;
636 slot_mask = I2S_STD_SLOT_BOTH;
637 }
638
639 i2s_std_slot_config_t std_slot_cfg;
640 if (this->i2s_comm_fmt_ == "std") {
641 std_slot_cfg =
642 I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG((i2s_data_bit_width_t) audio_stream_info.get_bits_per_sample(), slot_mode);
643 } else if (this->i2s_comm_fmt_ == "pcm") {
644 std_slot_cfg =
645 I2S_STD_PCM_SLOT_DEFAULT_CONFIG((i2s_data_bit_width_t) audio_stream_info.get_bits_per_sample(), slot_mode);
646 } else {
647 std_slot_cfg =
648 I2S_STD_MSB_SLOT_DEFAULT_CONFIG((i2s_data_bit_width_t) audio_stream_info.get_bits_per_sample(), slot_mode);
649 }
650#ifdef USE_ESP32_VARIANT_ESP32
651 // There seems to be a bug on the ESP32 (non-variant) platform where setting the slot bit width higher then the bits
652 // per sample causes the audio to play too fast. Setting the ws_width to the configured slot bit width seems to
653 // make it play at the correct speed while sending more bits per slot.
654 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO) {
655 std_slot_cfg.ws_width = static_cast<uint32_t>(this->slot_bit_width_);
656 }
657#else
658 std_slot_cfg.slot_bit_width = this->slot_bit_width_;
659#endif
660 std_slot_cfg.slot_mask = slot_mask;
661
662 pin_config.dout = this->dout_pin_;
663
664 i2s_std_config_t std_cfg = {
665 .clk_cfg = clk_cfg,
666 .slot_cfg = std_slot_cfg,
667 .gpio_cfg = pin_config,
668 };
669 /* Initialize the channel */
670 err = i2s_channel_init_std_mode(this->tx_handle_, &std_cfg);
671
672 if (err != ESP_OK) {
673 i2s_del_channel(this->tx_handle_);
674 this->parent_->unlock();
675 return err;
676 }
677 if (this->i2s_event_queue_ == nullptr) {
678 this->i2s_event_queue_ = xQueueCreate(1, sizeof(bool));
679 }
680 const i2s_event_callbacks_t callbacks = {
681 .on_send_q_ovf = i2s_overflow_cb,
682 };
683
684 i2s_channel_register_event_callback(this->tx_handle_, &callbacks, this);
685
686 /* Before reading data, start the TX channel first */
687 i2s_channel_enable(this->tx_handle_);
688 if (err != ESP_OK) {
689 i2s_del_channel(this->tx_handle_);
690 this->parent_->unlock();
691 }
692#endif
693
694 return err;
695}
696
697void I2SAudioSpeaker::delete_task_(size_t buffer_size) {
698 this->audio_ring_buffer_.reset(); // Releases ownership of the shared_ptr
699
700 if (this->data_buffer_ != nullptr) {
702 allocator.deallocate(this->data_buffer_, buffer_size);
703 this->data_buffer_ = nullptr;
704 }
705
706 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::STATE_STOPPED);
707
708 this->task_created_ = false;
709 vTaskDelete(nullptr);
710}
711
712#ifndef USE_I2S_LEGACY
713bool IRAM_ATTR I2SAudioSpeaker::i2s_overflow_cb(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx) {
714 I2SAudioSpeaker *this_speaker = (I2SAudioSpeaker *) user_ctx;
715 bool overflow = true;
716 xQueueOverwrite(this_speaker->i2s_event_queue_, &overflow);
717 return false;
718}
719#endif
720
721} // namespace i2s_audio
722} // namespace esphome
723
724#endif // USE_ESP32
virtual void mark_failed()
Mark this component as failed.
bool is_failed() const
bool is_ready() const
bool status_has_error() const
void status_set_warning(const char *message="unspecified")
void status_set_error(const char *message="unspecified")
void status_clear_warning()
static std::unique_ptr< RingBuffer > create(size_t len)
uint32_t get_sample_rate() const
Definition audio.h:30
virtual bool set_mute_off()=0
virtual bool set_volume(float volume)=0
virtual bool set_mute_on()=0
i2s_std_slot_mask_t std_slot_mask_
Definition i2s_audio.h:45
i2s_slot_bit_width_t slot_bit_width_
Definition i2s_audio.h:46
i2s_bits_per_chan_t bits_per_channel_
Definition i2s_audio.h:41
i2s_mclk_multiple_t mclk_multiple_
Definition i2s_audio.h:50
i2s_bits_per_sample_t bits_per_sample_
Definition i2s_audio.h:40
esp_err_t start_i2s_driver_(audio::AudioStreamInfo &audio_stream_info)
Starts the ESP32 I2S driver.
void stop_(bool wait_on_empty)
Sends a stop command to the speaker task via event_group_.
bool send_esp_err_to_event_group_(esp_err_t err)
Sets the corresponding ERR_ESP event group bits.
static bool i2s_overflow_cb(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx)
std::shared_ptr< RingBuffer > audio_ring_buffer_
void set_mute_state(bool mute_state) override
Mutes or unmute the speaker.
esp_err_t allocate_buffers_(size_t data_buffer_size, size_t ring_buffer_size)
Allocates the data buffer and ring buffer.
bool has_buffered_data() const override
size_t play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) override
Plays the provided audio data.
void set_volume(float volume) override
Sets the volume of the speaker.
static void speaker_task(void *params)
Function for the FreeRTOS task handling audio output.
void delete_task_(size_t buffer_size)
Deletes the speaker's task.
bool has_value() const
Definition optional.h:87
value_type const & value() const
Definition optional.h:89
audio_dac::AudioDac * audio_dac_
Definition speaker.h:120
audio::AudioStreamInfo audio_stream_info_
Definition speaker.h:115
__int64 ssize_t
Definition httplib.h:175
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
RAMAllocator< T > ExternalRAMAllocator
Definition helpers.h:788
std::string size_t len
Definition helpers.h:302
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
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:163
uint16_t length
Definition tt21100.cpp:0