ESPHome 2025.5.0
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, "Setting up I2S Audio Speaker...");
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 uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
115
116 if (event_group_bits & SpeakerEventGroupBits::STATE_STARTING) {
117 ESP_LOGD(TAG, "Starting Speaker");
119 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::STATE_STARTING);
120 }
121 if (event_group_bits & SpeakerEventGroupBits::STATE_RUNNING) {
122 ESP_LOGD(TAG, "Started Speaker");
124 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::STATE_RUNNING);
125 this->status_clear_warning();
126 this->status_clear_error();
127 }
128 if (event_group_bits & SpeakerEventGroupBits::STATE_STOPPING) {
129 ESP_LOGD(TAG, "Stopping Speaker");
131 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::STATE_STOPPING);
132 }
133 if (event_group_bits & SpeakerEventGroupBits::STATE_STOPPED) {
134 if (!this->task_created_) {
135 ESP_LOGD(TAG, "Stopped Speaker");
137 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::ALL_BITS);
138 this->speaker_task_handle_ = nullptr;
139 }
140 }
141
142 if (event_group_bits & SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START) {
143 this->status_set_error("Failed to start speaker task");
144 xEventGroupClearBits(this->event_group_, SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START);
145 }
146
147 if (event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS) {
148 uint32_t error_bits = event_group_bits & SpeakerEventGroupBits::ALL_ERR_ESP_BITS;
149 ESP_LOGW(TAG, "Error writing to I2S: %s", esp_err_to_name(err_bit_to_esp_err(error_bits)));
150 this->status_set_warning();
151 }
152
153 if (event_group_bits & SpeakerEventGroupBits::ERR_ESP_NOT_SUPPORTED) {
154 this->status_set_error("Failed to adjust I2S bus to match the incoming audio");
155 ESP_LOGE(TAG,
156 "Incompatible audio format: sample rate = %" PRIu32 ", channels = %" PRIu8 ", bits per sample = %" PRIu8,
157 this->audio_stream_info_.get_sample_rate(), this->audio_stream_info_.get_channels(),
158 this->audio_stream_info_.get_bits_per_sample());
159 }
160
161 xEventGroupClearBits(this->event_group_, ALL_ERR_ESP_BITS);
162}
163
164void I2SAudioSpeaker::set_volume(float volume) {
165 this->volume_ = volume;
166#ifdef USE_AUDIO_DAC
167 if (this->audio_dac_ != nullptr) {
168 if (volume > 0.0) {
169 this->audio_dac_->set_mute_off();
170 }
171 this->audio_dac_->set_volume(volume);
172 } else
173#endif
174 {
175 // Fallback to software volume control by using a Q15 fixed point scaling factor
176 ssize_t decibel_index = remap<ssize_t, float>(volume, 0.0f, 1.0f, 0, Q15_VOLUME_SCALING_FACTORS.size() - 1);
177 this->q15_volume_factor_ = Q15_VOLUME_SCALING_FACTORS[decibel_index];
178 }
179}
180
181void I2SAudioSpeaker::set_mute_state(bool mute_state) {
182 this->mute_state_ = mute_state;
183#ifdef USE_AUDIO_DAC
184 if (this->audio_dac_) {
185 if (mute_state) {
186 this->audio_dac_->set_mute_on();
187 } else {
188 this->audio_dac_->set_mute_off();
189 }
190 } else
191#endif
192 {
193 if (mute_state) {
194 // Fallback to software volume control and scale by 0
195 this->q15_volume_factor_ = 0;
196 } else {
197 // Revert to previous volume when unmuting
198 this->set_volume(this->volume_);
199 }
200 }
201}
202
203size_t I2SAudioSpeaker::play(const uint8_t *data, size_t length, TickType_t ticks_to_wait) {
204 if (this->is_failed()) {
205 ESP_LOGE(TAG, "Cannot play audio, speaker failed to setup");
206 return 0;
207 }
209 this->start();
210 }
211
212 if ((this->state_ != speaker::STATE_RUNNING) || (this->audio_ring_buffer_.use_count() != 1)) {
213 // Unable to write data to a running speaker, so delay the max amount of time so it can get ready
214 vTaskDelay(ticks_to_wait);
215 ticks_to_wait = 0;
216 }
217
218 size_t bytes_written = 0;
219 if ((this->state_ == speaker::STATE_RUNNING) && (this->audio_ring_buffer_.use_count() == 1)) {
220 // Only one owner of the ring buffer (the speaker task), so the ring buffer is allocated and no other components are
221 // attempting to write to it.
222
223 // Temporarily share ownership of the ring buffer so it won't be deallocated while writing
224 std::shared_ptr<RingBuffer> temp_ring_buffer = this->audio_ring_buffer_;
225 bytes_written = temp_ring_buffer->write_without_replacement((void *) data, length, ticks_to_wait);
226 }
227
228 return bytes_written;
229}
230
232 if (this->audio_ring_buffer_ != nullptr) {
233 return this->audio_ring_buffer_->available() > 0;
234 }
235 return false;
236}
237
238void I2SAudioSpeaker::speaker_task(void *params) {
239 I2SAudioSpeaker *this_speaker = (I2SAudioSpeaker *) params;
240 this_speaker->task_created_ = true;
241
242 uint32_t event_group_bits =
243 xEventGroupWaitBits(this_speaker->event_group_,
244 SpeakerEventGroupBits::COMMAND_START | SpeakerEventGroupBits::COMMAND_STOP |
245 SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY, // Bit message to read
246 pdTRUE, // Clear the bits on exit
247 pdFALSE, // Don't wait for all the bits,
248 portMAX_DELAY); // Block indefinitely until a bit is set
249
250 if (event_group_bits & (SpeakerEventGroupBits::COMMAND_STOP | SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY)) {
251 // Received a stop signal before the task was requested to start
252 this_speaker->delete_task_(0);
253 }
254
255 xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STARTING);
256
257 audio::AudioStreamInfo audio_stream_info = this_speaker->audio_stream_info_;
258
259 const uint32_t dma_buffers_duration_ms = DMA_BUFFER_DURATION_MS * DMA_BUFFERS_COUNT;
260 // Ensure ring buffer duration is at least the duration of all DMA buffers
261 const uint32_t ring_buffer_duration = std::max(dma_buffers_duration_ms, this_speaker->buffer_duration_ms_);
262
263 // The DMA buffers may have more bits per sample, so calculate buffer sizes based in the input audio stream info
264 const size_t data_buffer_size = audio_stream_info.ms_to_bytes(dma_buffers_duration_ms);
265 const size_t ring_buffer_size = audio_stream_info.ms_to_bytes(ring_buffer_duration);
266
267 const size_t single_dma_buffer_input_size = data_buffer_size / DMA_BUFFERS_COUNT;
268
269 if (this_speaker->send_esp_err_to_event_group_(this_speaker->allocate_buffers_(data_buffer_size, ring_buffer_size))) {
270 // Failed to allocate buffers
271 xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
272 this_speaker->delete_task_(data_buffer_size);
273 }
274
275 if (!this_speaker->send_esp_err_to_event_group_(this_speaker->start_i2s_driver_(audio_stream_info))) {
276 xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_RUNNING);
277
278 bool stop_gracefully = false;
279 uint32_t last_data_received_time = millis();
280 bool tx_dma_underflow = false;
281
282 this_speaker->accumulated_frames_written_ = 0;
283
284 // Keep looping if paused, there is no timeout configured, or data was received more recently than the configured
285 // timeout
286 while (this_speaker->pause_state_ || !this_speaker->timeout_.has_value() ||
287 (millis() - last_data_received_time) <= this_speaker->timeout_.value()) {
288 event_group_bits = xEventGroupGetBits(this_speaker->event_group_);
289
290 if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP) {
291 xEventGroupClearBits(this_speaker->event_group_, SpeakerEventGroupBits::COMMAND_STOP);
292 break;
293 }
294 if (event_group_bits & SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY) {
295 xEventGroupClearBits(this_speaker->event_group_, SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY);
296 stop_gracefully = true;
297 }
298
299 if (this_speaker->audio_stream_info_ != audio_stream_info) {
300 // Audio stream info changed, stop the speaker task so it will restart with the proper settings.
301 break;
302 }
303#ifdef USE_I2S_LEGACY
304 i2s_event_t i2s_event;
305 while (xQueueReceive(this_speaker->i2s_event_queue_, &i2s_event, 0)) {
306 if (i2s_event.type == I2S_EVENT_TX_Q_OVF) {
307 tx_dma_underflow = true;
308 }
309 }
310#else
311 bool overflow;
312 while (xQueueReceive(this_speaker->i2s_event_queue_, &overflow, 0)) {
313 if (overflow) {
314 tx_dma_underflow = true;
315 }
316 }
317#endif
318
319 if (this_speaker->pause_state_) {
320 // Pause state is accessed atomically, so thread safe
321 // Delay so the task can yields, then skip transferring audio data
322 delay(TASK_DELAY_MS);
323 continue;
324 }
325
326 size_t bytes_read = this_speaker->audio_ring_buffer_->read((void *) this_speaker->data_buffer_, data_buffer_size,
327 pdMS_TO_TICKS(TASK_DELAY_MS));
328
329 if (bytes_read > 0) {
330 if ((audio_stream_info.get_bits_per_sample() == 16) && (this_speaker->q15_volume_factor_ < INT16_MAX)) {
331 // Scale samples by the volume factor in place
332 q15_multiplication((int16_t *) this_speaker->data_buffer_, (int16_t *) this_speaker->data_buffer_,
333 bytes_read / sizeof(int16_t), this_speaker->q15_volume_factor_);
334 }
335
336#ifdef USE_ESP32_VARIANT_ESP32
337 // For ESP32 8/16 bit mono mode samples need to be switched.
338 if (audio_stream_info.get_channels() == 1 && audio_stream_info.get_bits_per_sample() <= 16) {
339 size_t len = bytes_read / sizeof(int16_t);
340 int16_t *tmp_buf = (int16_t *) this_speaker->data_buffer_;
341 for (int i = 0; i < len; i += 2) {
342 int16_t tmp = tmp_buf[i];
343 tmp_buf[i] = tmp_buf[i + 1];
344 tmp_buf[i + 1] = tmp;
345 }
346 }
347#endif
348 // Write the audio data to a single DMA buffer at a time to reduce latency for the audio duration played
349 // callback.
350 const uint32_t batches = (bytes_read + single_dma_buffer_input_size - 1) / single_dma_buffer_input_size;
351
352 for (uint32_t i = 0; i < batches; ++i) {
353 size_t bytes_written = 0;
354 size_t bytes_to_write = std::min(single_dma_buffer_input_size, bytes_read);
355
356#ifdef USE_I2S_LEGACY
357 if (audio_stream_info.get_bits_per_sample() == (uint8_t) this_speaker->bits_per_sample_) {
358 i2s_write(this_speaker->parent_->get_port(), this_speaker->data_buffer_ + i * single_dma_buffer_input_size,
359 bytes_to_write, &bytes_written, pdMS_TO_TICKS(DMA_BUFFER_DURATION_MS * 5));
360 } else if (audio_stream_info.get_bits_per_sample() < (uint8_t) this_speaker->bits_per_sample_) {
361 i2s_write_expand(this_speaker->parent_->get_port(),
362 this_speaker->data_buffer_ + i * single_dma_buffer_input_size, bytes_to_write,
363 audio_stream_info.get_bits_per_sample(), this_speaker->bits_per_sample_, &bytes_written,
364 pdMS_TO_TICKS(DMA_BUFFER_DURATION_MS * 5));
365 }
366#else
367 i2s_channel_write(this_speaker->tx_handle_, this_speaker->data_buffer_ + i * single_dma_buffer_input_size,
368 bytes_to_write, &bytes_written, pdMS_TO_TICKS(DMA_BUFFER_DURATION_MS * 5));
369#endif
370
371 int64_t now = esp_timer_get_time();
372
373 if (bytes_written != bytes_to_write) {
374 xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE);
375 }
376 bytes_read -= bytes_written;
377
378 this_speaker->audio_output_callback_(audio_stream_info.bytes_to_frames(bytes_written),
379 now + dma_buffers_duration_ms * 1000);
380
381 tx_dma_underflow = false;
382 last_data_received_time = millis();
383 }
384 } else {
385 // No data received
386 if (stop_gracefully && tx_dma_underflow) {
387 break;
388 }
389 }
390 }
391
392 xEventGroupSetBits(this_speaker->event_group_, SpeakerEventGroupBits::STATE_STOPPING);
393#ifdef USE_I2S_LEGACY
394 i2s_driver_uninstall(this_speaker->parent_->get_port());
395#else
396 i2s_channel_disable(this_speaker->tx_handle_);
397 i2s_del_channel(this_speaker->tx_handle_);
398#endif
399
400 this_speaker->parent_->unlock();
401 }
402
403 this_speaker->delete_task_(data_buffer_size);
404}
405
407 if (!this->is_ready() || this->is_failed() || this->status_has_error())
408 return;
409 if ((this->state_ == speaker::STATE_STARTING) || (this->state_ == speaker::STATE_RUNNING))
410 return;
411
412 if (!this->task_created_ && (this->speaker_task_handle_ == nullptr)) {
413 xTaskCreate(I2SAudioSpeaker::speaker_task, "speaker_task", TASK_STACK_SIZE, (void *) this, TASK_PRIORITY,
414 &this->speaker_task_handle_);
415
416 if (this->speaker_task_handle_ != nullptr) {
417 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_START);
418 } else {
419 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_TASK_FAILED_TO_START);
420 }
421 }
422}
423
424void I2SAudioSpeaker::stop() { this->stop_(false); }
425
426void I2SAudioSpeaker::finish() { this->stop_(true); }
427
428void I2SAudioSpeaker::stop_(bool wait_on_empty) {
429 if (this->is_failed())
430 return;
431 if (this->state_ == speaker::STATE_STOPPED)
432 return;
433
434 if (wait_on_empty) {
435 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP_GRACEFULLY);
436 } else {
437 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::COMMAND_STOP);
438 }
439}
440
442 switch (err) {
443 case ESP_OK:
444 return false;
445 case ESP_ERR_INVALID_STATE:
446 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_STATE);
447 return true;
448 case ESP_ERR_INVALID_ARG:
449 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_ARG);
450 return true;
451 case ESP_ERR_INVALID_SIZE:
452 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_INVALID_SIZE);
453 return true;
454 case ESP_ERR_NO_MEM:
455 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_NO_MEM);
456 return true;
457 case ESP_ERR_NOT_SUPPORTED:
458 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_NOT_SUPPORTED);
459 return true;
460 default:
461 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::ERR_ESP_FAIL);
462 return true;
463 }
464}
465
466esp_err_t I2SAudioSpeaker::allocate_buffers_(size_t data_buffer_size, size_t ring_buffer_size) {
467 if (this->data_buffer_ == nullptr) {
468 // Allocate data buffer for temporarily storing audio from the ring buffer before writing to the I2S bus
470 this->data_buffer_ = allocator.allocate(data_buffer_size);
471 }
472
473 if (this->data_buffer_ == nullptr) {
474 return ESP_ERR_NO_MEM;
475 }
476
477 if (this->audio_ring_buffer_.use_count() == 0) {
478 // Allocate ring buffer. Uses a shared_ptr to ensure it isn't improperly deallocated.
479 this->audio_ring_buffer_ = RingBuffer::create(ring_buffer_size);
480 }
481
482 if (this->audio_ring_buffer_ == nullptr) {
483 return ESP_ERR_NO_MEM;
484 }
485
486 return ESP_OK;
487}
488
489esp_err_t I2SAudioSpeaker::start_i2s_driver_(audio::AudioStreamInfo &audio_stream_info) {
490#ifdef USE_I2S_LEGACY
491 if ((this->i2s_mode_ & I2S_MODE_SLAVE) && (this->sample_rate_ != audio_stream_info.get_sample_rate())) { // NOLINT
492#else
493 if ((this->i2s_role_ & I2S_ROLE_SLAVE) && (this->sample_rate_ != audio_stream_info.get_sample_rate())) { // NOLINT
494#endif
495 // Can't reconfigure I2S bus, so the sample rate must match the configured value
496 return ESP_ERR_NOT_SUPPORTED;
497 }
498
499#ifdef USE_I2S_LEGACY
500 if ((i2s_bits_per_sample_t) audio_stream_info.get_bits_per_sample() > this->bits_per_sample_) {
501#else
502 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO &&
503 (i2s_slot_bit_width_t) audio_stream_info.get_bits_per_sample() > this->slot_bit_width_) {
504#endif
505 // Currently can't handle the case when the incoming audio has more bits per sample than the configured value
506 return ESP_ERR_NOT_SUPPORTED;
507 }
508
509 if (!this->parent_->try_lock()) {
510 return ESP_ERR_INVALID_STATE;
511 }
512
513 uint32_t dma_buffer_length = audio_stream_info.ms_to_frames(DMA_BUFFER_DURATION_MS);
514
515#ifdef USE_I2S_LEGACY
516 i2s_channel_fmt_t channel = this->channel_;
517
518 if (audio_stream_info.get_channels() == 1) {
519 if (this->channel_ == I2S_CHANNEL_FMT_ONLY_LEFT) {
520 channel = I2S_CHANNEL_FMT_ONLY_LEFT;
521 } else {
522 channel = I2S_CHANNEL_FMT_ONLY_RIGHT;
523 }
524 } else if (audio_stream_info.get_channels() == 2) {
525 channel = I2S_CHANNEL_FMT_RIGHT_LEFT;
526 }
527
528 i2s_driver_config_t config = {
529 .mode = (i2s_mode_t) (this->i2s_mode_ | I2S_MODE_TX),
530 .sample_rate = audio_stream_info.get_sample_rate(),
531 .bits_per_sample = this->bits_per_sample_,
532 .channel_format = channel,
533 .communication_format = this->i2s_comm_fmt_,
534 .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
535 .dma_buf_count = DMA_BUFFERS_COUNT,
536 .dma_buf_len = (int) dma_buffer_length,
537 .use_apll = this->use_apll_,
538 .tx_desc_auto_clear = true,
539 .fixed_mclk = I2S_PIN_NO_CHANGE,
540 .mclk_multiple = this->mclk_multiple_,
541 .bits_per_chan = this->bits_per_channel_,
542#if SOC_I2S_SUPPORTS_TDM
543 .chan_mask = (i2s_channel_t) (I2S_TDM_ACTIVE_CH0 | I2S_TDM_ACTIVE_CH1),
544 .total_chan = 2,
545 .left_align = false,
546 .big_edin = false,
547 .bit_order_msb = false,
548 .skip_msk = false,
549#endif
550 };
551#if SOC_I2S_SUPPORTS_DAC
552 if (this->internal_dac_mode_ != I2S_DAC_CHANNEL_DISABLE) {
553 config.mode = (i2s_mode_t) (config.mode | I2S_MODE_DAC_BUILT_IN);
554 }
555#endif
556
557 esp_err_t err =
558 i2s_driver_install(this->parent_->get_port(), &config, I2S_EVENT_QUEUE_COUNT, &this->i2s_event_queue_);
559 if (err != ESP_OK) {
560 // Failed to install the driver, so unlock the I2S port
561 this->parent_->unlock();
562 return err;
563 }
564
565#if SOC_I2S_SUPPORTS_DAC
566 if (this->internal_dac_mode_ == I2S_DAC_CHANNEL_DISABLE) {
567#endif
568 i2s_pin_config_t pin_config = this->parent_->get_pin_config();
569 pin_config.data_out_num = this->dout_pin_;
570
571 err = i2s_set_pin(this->parent_->get_port(), &pin_config);
572#if SOC_I2S_SUPPORTS_DAC
573 } else {
574 i2s_set_dac_mode(this->internal_dac_mode_);
575 }
576#endif
577
578 if (err != ESP_OK) {
579 // Failed to set the data out pin, so uninstall the driver and unlock the I2S port
580 i2s_driver_uninstall(this->parent_->get_port());
581 this->parent_->unlock();
582 }
583#else
584 i2s_chan_config_t chan_cfg = {
585 .id = this->parent_->get_port(),
586 .role = this->i2s_role_,
587 .dma_desc_num = DMA_BUFFERS_COUNT,
588 .dma_frame_num = dma_buffer_length,
589 .auto_clear = true,
590 };
591 /* Allocate a new TX channel and get the handle of this channel */
592 esp_err_t err = i2s_new_channel(&chan_cfg, &this->tx_handle_, NULL);
593 if (err != ESP_OK) {
594 this->parent_->unlock();
595 return err;
596 }
597
598 i2s_clock_src_t clk_src = I2S_CLK_SRC_DEFAULT;
599#ifdef I2S_CLK_SRC_APLL
600 if (this->use_apll_) {
601 clk_src = I2S_CLK_SRC_APLL;
602 }
603#endif
604 i2s_std_gpio_config_t pin_config = this->parent_->get_pin_config();
605
606 i2s_std_clk_config_t clk_cfg = {
607 .sample_rate_hz = audio_stream_info.get_sample_rate(),
608 .clk_src = clk_src,
609 .mclk_multiple = this->mclk_multiple_,
610 };
611
612 i2s_slot_mode_t slot_mode = this->slot_mode_;
613 i2s_std_slot_mask_t slot_mask = this->std_slot_mask_;
614 if (audio_stream_info.get_channels() == 1) {
615 slot_mode = I2S_SLOT_MODE_MONO;
616 } else if (audio_stream_info.get_channels() == 2) {
617 slot_mode = I2S_SLOT_MODE_STEREO;
618 slot_mask = I2S_STD_SLOT_BOTH;
619 }
620
621 i2s_std_slot_config_t std_slot_cfg;
622 if (this->i2s_comm_fmt_ == "std") {
623 std_slot_cfg =
624 I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG((i2s_data_bit_width_t) audio_stream_info.get_bits_per_sample(), slot_mode);
625 } else if (this->i2s_comm_fmt_ == "pcm") {
626 std_slot_cfg =
627 I2S_STD_PCM_SLOT_DEFAULT_CONFIG((i2s_data_bit_width_t) audio_stream_info.get_bits_per_sample(), slot_mode);
628 } else {
629 std_slot_cfg =
630 I2S_STD_MSB_SLOT_DEFAULT_CONFIG((i2s_data_bit_width_t) audio_stream_info.get_bits_per_sample(), slot_mode);
631 }
632#ifdef USE_ESP32_VARIANT_ESP32
633 // There seems to be a bug on the ESP32 (non-variant) platform where setting the slot bit width higher then the bits
634 // per sample causes the audio to play too fast. Setting the ws_width to the configured slot bit width seems to
635 // make it play at the correct speed while sending more bits per slot.
636 if (this->slot_bit_width_ != I2S_SLOT_BIT_WIDTH_AUTO) {
637 std_slot_cfg.ws_width = static_cast<uint32_t>(this->slot_bit_width_);
638 }
639#else
640 std_slot_cfg.slot_bit_width = this->slot_bit_width_;
641#endif
642 std_slot_cfg.slot_mask = slot_mask;
643
644 pin_config.dout = this->dout_pin_;
645
646 i2s_std_config_t std_cfg = {
647 .clk_cfg = clk_cfg,
648 .slot_cfg = std_slot_cfg,
649 .gpio_cfg = pin_config,
650 };
651 /* Initialize the channel */
652 err = i2s_channel_init_std_mode(this->tx_handle_, &std_cfg);
653
654 if (err != ESP_OK) {
655 i2s_del_channel(this->tx_handle_);
656 this->parent_->unlock();
657 return err;
658 }
659 if (this->i2s_event_queue_ == nullptr) {
660 this->i2s_event_queue_ = xQueueCreate(1, sizeof(bool));
661 }
662 const i2s_event_callbacks_t callbacks = {
663 .on_send_q_ovf = i2s_overflow_cb,
664 };
665
666 i2s_channel_register_event_callback(this->tx_handle_, &callbacks, this);
667
668 /* Before reading data, start the TX channel first */
669 i2s_channel_enable(this->tx_handle_);
670 if (err != ESP_OK) {
671 i2s_del_channel(this->tx_handle_);
672 this->parent_->unlock();
673 }
674#endif
675
676 return err;
677}
678
679void I2SAudioSpeaker::delete_task_(size_t buffer_size) {
680 this->audio_ring_buffer_.reset(); // Releases ownership of the shared_ptr
681
682 if (this->data_buffer_ != nullptr) {
684 allocator.deallocate(this->data_buffer_, buffer_size);
685 this->data_buffer_ = nullptr;
686 }
687
688 xEventGroupSetBits(this->event_group_, SpeakerEventGroupBits::STATE_STOPPED);
689
690 this->task_created_ = false;
691 vTaskDelete(nullptr);
692}
693
694#ifndef USE_I2S_LEGACY
695bool IRAM_ATTR I2SAudioSpeaker::i2s_overflow_cb(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx) {
696 I2SAudioSpeaker *this_speaker = (I2SAudioSpeaker *) user_ctx;
697 bool overflow = true;
698 xQueueOverwrite(this_speaker->i2s_event_queue_, &overflow);
699 return false;
700}
701#endif
702
703} // namespace i2s_audio
704} // namespace esphome
705
706#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.
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:787
std::string size_t len
Definition helpers.h:301
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:28
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:27
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:162
uint16_t length
Definition tt21100.cpp:0