5#include <driver/i2s_std.h>
6#include <driver/i2s_pdm.h>
20static const UBaseType_t MAX_LISTENERS = 16;
22static const uint32_t READ_DURATION_MS = 16;
24static constexpr uint32_t DMA_BUFFERS_COUNT = 4;
25static constexpr uint32_t DMA_FRAME_NUM = 256;
27static const size_t TASK_STACK_SIZE = 4096;
28static const ssize_t TASK_PRIORITY = 23;
45 ESP_LOGE(TAG,
"Creating semaphore failed");
52 ESP_LOGE(TAG,
"Creating event group failed");
57#ifdef USE_I2S_AUDIO_FULL_DUPLEX
58 if (this->
parent_->is_full_duplex() && this->parent_->is_failed()) {
59 this->
mark_failed(LOG_STR(
"Full duplex bus setup failed"));
72 " DC offset correction: %s",
77 uint8_t channel_count = 1;
78 uint8_t bits_per_sample = 16;
83 if (this->
slot_mode_ == I2S_SLOT_MODE_STEREO) {
87#ifdef USE_ESP32_VARIANT_ESP32
91 if (bits_per_sample < 16) {
93 }
else if ((bits_per_sample > 16) && (bits_per_sample <= 32)) {
113 i2s_std_slot_config_t std_slot_cfg =
118 i2s_std_gpio_config_t pin_config = this->
parent_->get_pin_config();
128 .slot_cfg = std_slot_cfg,
129 .gpio_cfg = pin_config,
133#ifdef USE_I2S_AUDIO_FULL_DUPLEX
138 this->start_capture_count_(rx_handle, dma_desc_num);
142bool I2SAudioMicrophone::start_capture_count_(i2s_chan_handle_t rx_handle,
uint32_t dma_desc_num) {
149 const i2s_event_callbacks_t callbacks = {
153 esp_err_t err = i2s_channel_register_event_callback(rx_handle, &callbacks,
this);
155 ESP_LOGE(TAG,
"Registering callbacks failed: %s", esp_err_to_name(err));
161bool I2SAudioMicrophone::read_dma_buffer_size_() {
162 i2s_chan_info_t chan_info{};
164 if ((err != ESP_OK) || (chan_info.total_dma_buf_size == 0) || (this->dma_desc_num_ == 0)) {
165 ESP_LOGE(TAG,
"Getting the DMA buffer size failed");
172bool I2SAudioMicrophone::start_driver_() {
173#ifdef USE_I2S_AUDIO_FULL_DUPLEX
174 if (this->
parent_->is_full_duplex()) {
177 ESP_LOGE(TAG,
"Full duplex channel unavailable");
181 return this->read_dma_buffer_size_();
185 if (!this->
parent_->try_lock()) {
191 i2s_chan_config_t chan_cfg = {
192 .id = this->
parent_->get_port(),
194 .dma_desc_num = DMA_BUFFERS_COUNT,
195 .dma_frame_num = DMA_FRAME_NUM,
199 err = i2s_new_channel(&chan_cfg, NULL, &this->
rx_handle_);
205#if SOC_I2S_SUPPORTS_PDM_RX
207 i2s_std_gpio_config_t pin_config = this->
parent_->get_pin_config();
208 i2s_pdm_rx_clk_config_t clk_cfg = {
215 i2s_pdm_rx_slot_config_t slot_cfg = I2S_PDM_RX_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, this->
slot_mode_);
217 case I2S_STD_SLOT_LEFT:
218 slot_cfg.slot_mask = I2S_PDM_SLOT_LEFT;
220 case I2S_STD_SLOT_RIGHT:
221 slot_cfg.slot_mask = I2S_PDM_SLOT_RIGHT;
223 case I2S_STD_SLOT_BOTH:
224 slot_cfg.slot_mask = I2S_PDM_SLOT_BOTH;
229 i2s_pdm_rx_config_t pdm_rx_cfg = {
231 .slot_cfg = slot_cfg,
234 .clk = pin_config.ws,
238 .clk_inv = pin_config.invert_flags.ws_inv,
242 err = i2s_channel_init_pdm_rx_mode(this->
rx_handle_, &pdm_rx_cfg);
246 i2s_std_config_t std_cfg;
249 err = i2s_channel_init_std_mode(this->
rx_handle_, &std_cfg);
256 if (!this->start_capture_count_(this->
rx_handle_, DMA_BUFFERS_COUNT)) {
269 return this->read_dma_buffer_size_();
280void I2SAudioMicrophone::stop_driver_() {
284#ifdef USE_I2S_AUDIO_FULL_DUPLEX
285 if (this->
parent_->is_full_duplex()) {
288 this->
parent_->release_rx_channel();
300 ESP_LOGW(TAG,
"Error stopping: %s", esp_err_to_name(err));
317 xEventGroupSetBits(this_microphone->
event_group_, MicrophoneEventGroupBits::TASK_STARTING);
330 const size_t bytes_to_read =
331 std::max<size_t>(1, (stream_info.
ms_to_bytes(READ_DURATION_MS) + dma_buffer_bytes / 2) / dma_buffer_bytes) *
336 std::vector<uint8_t> samples;
337 samples.reserve(bytes_to_read);
339 xEventGroupSetBits(this_microphone->
event_group_, MicrophoneEventGroupBits::TASK_RUNNING);
341 while (!(xEventGroupGetBits(this_microphone->
event_group_) & MicrophoneEventGroupBits::COMMAND_STOP)) {
345 samples.resize(bytes_to_read);
346 size_t bytes_read = this_microphone->read_(samples.data(), bytes_to_read, 2 * read_duration_ms);
347 if (bytes_read == 0) {
351 portENTER_CRITICAL(&this_microphone->
dma_lock_);
355 portEXIT_CRITICAL(&this_microphone->
dma_lock_);
358 bytes_received, drops, drops_before_read, receive_time_us, this_microphone->
dma_bytes_read_, bytes_read,
359 this_microphone->
dma_desc_num_, dma_buffer_bytes, stream_info);
362 samples.resize(bytes_read);
366 this_microphone->
publish_audio_(samples, stream_info, capture_time_us);
368 vTaskDelay(pdMS_TO_TICKS(READ_DURATION_MS));
373 xEventGroupSetBits(this_microphone->
event_group_, MicrophoneEventGroupBits::TASK_STOPPED);
376 vTaskDelay(pdMS_TO_TICKS(10));
383 portENTER_CRITICAL_ISR(&this_microphone->dma_lock_);
384 this_microphone->dma_bytes_received_ +=
event->size;
385 this_microphone->dma_receive_time_us_ = now;
386 portEXIT_CRITICAL_ISR(&this_microphone->dma_lock_);
394 this_microphone->
dma_buffers_dropped_.store(this_microphone->dma_buffers_dropped_.load(std::memory_order_relaxed) + 1,
395 std::memory_order_relaxed);
399size_t I2SAudioMicrophone::read_(uint8_t *buf,
size_t len,
uint32_t timeout_ms) {
400 size_t bytes_read = 0;
401 esp_err_t err = i2s_channel_read(this->
rx_handle_, buf,
len, &bytes_read, timeout_ms);
402 if ((err != ESP_OK) && ((err != ESP_ERR_TIMEOUT) || (timeout_ms != 0))) {
406 ESP_LOGW(TAG,
"Read error: %s", esp_err_to_name(err));
409 }
else if ((bytes_read == 0) && (timeout_ms > 0)) {
415#ifdef USE_ESP32_VARIANT_ESP32
418 int16_t *samples =
reinterpret_cast<int16_t *
>(buf);
419 size_t sample_count = bytes_read /
sizeof(int16_t);
420 for (
size_t i = 0; i + 1 < sample_count; i += 2) {
421 int16_t tmp = samples[i];
422 samples[i] = samples[i + 1];
423 samples[i + 1] = tmp;
433 if (event_group_bits & MicrophoneEventGroupBits::TASK_STARTING) {
434 ESP_LOGV(TAG,
"Task started, attempting to allocate buffer");
435 xEventGroupClearBits(this->
event_group_, MicrophoneEventGroupBits::TASK_STARTING);
438 if (event_group_bits & MicrophoneEventGroupBits::TASK_RUNNING) {
439 ESP_LOGV(TAG,
"Task is running and reading data");
441 xEventGroupClearBits(this->
event_group_, MicrophoneEventGroupBits::TASK_RUNNING);
445 if ((event_group_bits & MicrophoneEventGroupBits::TASK_STOPPED)) {
446 ESP_LOGV(TAG,
"Task finished, freeing resources and uninstalling driver");
450 this->stop_driver_();
475 if (!this->start_driver_()) {
476 ESP_LOGE(TAG,
"Driver failed to start; retrying in 1 second");
478 this->stop_driver_();
487 ESP_LOGE(TAG,
"Task failed to start, retrying in 1 second");
489 this->stop_driver_();
497 xEventGroupSetBits(this->
event_group_, MicrophoneEventGroupBits::COMMAND_STOP);
void mark_failed()
Mark this component as failed.
void status_set_warning()
void status_clear_error()
bool status_has_warning() const
bool status_has_error() const
void status_momentary_error(uint32_t length=5000)
Set error status flag and clear it after length ms.
void status_clear_warning()
I2SAudioComponent * parent_
size_t ms_to_bytes(uint32_t ms) const
Converts duration to bytes.
uint32_t bytes_to_frames(size_t bytes) const
Convert bytes to frames.
uint32_t get_sample_rate() const
void reset(uint32_t sample_rate)
void process(uint8_t *data, size_t size, const audio::AudioStreamInfo &stream_info)
i2s_std_slot_mask_t std_slot_mask_
i2s_slot_bit_width_t slot_bit_width_
i2s_slot_mode_t slot_mode_
i2s_clock_src_t get_clock_source_() const
i2s_mclk_multiple_t mclk_multiple_
SemaphoreHandle_t active_listeners_semaphore_
static bool i2s_on_recv_q_ovf_cb(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx)
Counts a buffer the driver dropped because the task fell behind; it will never be read.
void build_full_duplex_config(i2s_std_config_t &std_cfg) override
TaskHandle_t task_handle_
int64_t dma_receive_time_us_
DCOffsetFilter dc_offset_filter_
std::atomic< uint32_t > dma_buffers_dropped_
EventGroupHandle_t event_group_
static bool i2s_on_recv_cb(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx)
Records the byte count and time of each DMA buffer the driver queues for reading.
void configure_stream_settings_()
Starts the I2S driver.
void dump_config() override
static void mic_task(void *params)
void build_std_config_(i2s_std_config_t &std_cfg) const
Builds the standard (non-PDM) mode configuration from the configured settings.
i2s_chan_handle_t rx_handle_
uint32_t dma_bytes_received_
void full_duplex_rx_enabling(i2s_chan_handle_t rx_handle, uint32_t dma_desc_num) override
bool has_data_callbacks_() const
void publish_audio_(std::span< uint8_t > data, const audio::AudioStreamInfo &stream_info, int64_t capture_time_us=0)
While muted, data is zeroed first, so it must be a buffer the platform owns.
audio::AudioStreamInfo audio_stream_info_
const char * esp_err_to_name(esp_err_t err)
ESPHOME_LOG_TAG(TAG, "i2s_audio")
int64_t dma_capture_time_us(uint32_t bytes_received, uint32_t drops, uint32_t drops_before_read, int64_t receive_time_us, uint32_t bytes_read_before, uint32_t bytes_read, uint32_t dma_desc_num, uint32_t dma_buffer_bytes, const audio::AudioStreamInfo &stream_info)
Returns when the first frame of a read was captured, counted back from the newest DMA buffer,...
int64_t esp_timer_get_time(void)
spi_device_handle_t handle