#include "es8311_audio_codec.h" #include #include #define TAG "Es8311AudioCodec" Es8311AudioCodec::Es8311AudioCodec(void* i2c_master_handle, i2c_port_t i2c_port, int input_sample_rate, int output_sample_rate, gpio_num_t mclk, gpio_num_t bclk, gpio_num_t ws, gpio_num_t dout, gpio_num_t din, gpio_num_t pa_pin, uint8_t es8311_addr, bool use_mclk, bool pa_inverted) { duplex_ = true; // 是否双工 input_reference_ = false; // 是否使用参考输入,实现回声消除 input_channels_ = 1; // 输入通道数 input_sample_rate_ = input_sample_rate; output_sample_rate_ = output_sample_rate; pa_pin_ = pa_pin; pa_inverted_ = pa_inverted; input_gain_ = 30; assert(input_sample_rate_ == output_sample_rate_); CreateDuplexChannels(mclk, bclk, ws, dout, din); // Do initialize of related interface: data_if, ctrl_if and gpio_if audio_codec_i2s_cfg_t i2s_cfg = { .port = I2S_NUM_0, .rx_handle = rx_handle_, .tx_handle = tx_handle_, }; data_if_ = audio_codec_new_i2s_data(&i2s_cfg); assert(data_if_ != NULL); // Output audio_codec_i2c_cfg_t i2c_cfg = { .port = i2c_port, .addr = es8311_addr, .bus_handle = i2c_master_handle, }; ctrl_if_ = audio_codec_new_i2c_ctrl(&i2c_cfg); assert(ctrl_if_ != NULL); gpio_if_ = audio_codec_new_gpio(); assert(gpio_if_ != NULL); es8311_codec_cfg_t es8311_cfg = {}; es8311_cfg.ctrl_if = ctrl_if_; es8311_cfg.gpio_if = gpio_if_; es8311_cfg.codec_mode = ESP_CODEC_DEV_WORK_MODE_BOTH; es8311_cfg.pa_pin = pa_pin; es8311_cfg.use_mclk = use_mclk; es8311_cfg.hw_gain.pa_voltage = 5.0; es8311_cfg.hw_gain.codec_dac_voltage = 3.3; es8311_cfg.pa_reverted = pa_inverted_; codec_if_ = es8311_codec_new(&es8311_cfg); if (codec_if_ == nullptr) { ESP_LOGE(TAG, "Failed to create Es8311AudioCodec"); } else { ESP_LOGI(TAG, "Es8311AudioCodec initialized"); } } Es8311AudioCodec::~Es8311AudioCodec() { esp_codec_dev_delete(dev_); audio_codec_delete_codec_if(codec_if_); audio_codec_delete_ctrl_if(ctrl_if_); audio_codec_delete_gpio_if(gpio_if_); audio_codec_delete_data_if(data_if_); } void Es8311AudioCodec::UpdateDeviceState() { if ((input_enabled_ || output_enabled_) && dev_ == nullptr) { esp_codec_dev_cfg_t dev_cfg = { .dev_type = ESP_CODEC_DEV_TYPE_IN_OUT, .codec_if = codec_if_, .data_if = data_if_, }; dev_ = esp_codec_dev_new(&dev_cfg); assert(dev_ != NULL); esp_codec_dev_sample_info_t fs = { .bits_per_sample = 16, .channel = 1, .channel_mask = 0, .sample_rate = (uint32_t)input_sample_rate_, .mclk_multiple = 0, }; esp_err_t err = esp_codec_dev_open(dev_, &fs); if (err != ESP_OK) { if (!device_open_error_reported_) { ESP_LOGE(TAG, "Failed to open ES8311 codec device: %s", esp_err_to_name(err)); device_open_error_reported_ = true; } esp_codec_dev_delete(dev_); dev_ = nullptr; return; } err = esp_codec_dev_set_in_gain(dev_, input_gain_); if (err != ESP_OK) { if (!device_open_error_reported_) { ESP_LOGE(TAG, "Failed to set ES8311 input gain: %s", esp_err_to_name(err)); device_open_error_reported_ = true; } esp_codec_dev_close(dev_); esp_codec_dev_delete(dev_); dev_ = nullptr; return; } // Always pin the hardware DAC at 100% so software gain in Write() // gets the full output headroom. SetOutputVolume() never re-touches // the hardware DAC — it only updates output_volume_ used by the // software gain. If we wrote NVS-cached value here, vol later set to // 100 would max software gain but hit a hardware ceiling, sounding // identical to vol=70. err = esp_codec_dev_set_out_vol(dev_, 100); if (err != ESP_OK) { if (!device_open_error_reported_) { ESP_LOGE(TAG, "Failed to set ES8311 output volume: %s", esp_err_to_name(err)); device_open_error_reported_ = true; } esp_codec_dev_close(dev_); esp_codec_dev_delete(dev_); dev_ = nullptr; return; } } else if (!input_enabled_ && !output_enabled_ && dev_ != nullptr) { esp_codec_dev_close(dev_); dev_ = nullptr; } if (pa_pin_ != GPIO_NUM_NC) { int level = output_enabled_ ? 1 : 0; gpio_set_level(pa_pin_, pa_inverted_ ? !level : level); } if (dev_ != nullptr && device_open_error_reported_) { device_open_error_reported_ = false; } } void Es8311AudioCodec::CreateDuplexChannels(gpio_num_t mclk, gpio_num_t bclk, gpio_num_t ws, gpio_num_t dout, gpio_num_t din) { assert(input_sample_rate_ == output_sample_rate_); i2s_chan_config_t chan_cfg = { .id = I2S_NUM_0, .role = I2S_ROLE_MASTER, .dma_desc_num = AUDIO_CODEC_DMA_DESC_NUM, .dma_frame_num = AUDIO_CODEC_DMA_FRAME_NUM, .auto_clear_after_cb = true, .auto_clear_before_cb = false, .intr_priority = 0, }; ESP_ERROR_CHECK(i2s_new_channel(&chan_cfg, &tx_handle_, &rx_handle_)); i2s_std_config_t std_cfg = { .clk_cfg = { .sample_rate_hz = (uint32_t)output_sample_rate_, .clk_src = I2S_CLK_SRC_DEFAULT, .mclk_multiple = I2S_MCLK_MULTIPLE_256, #ifdef I2S_HW_VERSION_2 .ext_clk_freq_hz = 0, #endif }, .slot_cfg = { .data_bit_width = I2S_DATA_BIT_WIDTH_16BIT, .slot_bit_width = I2S_SLOT_BIT_WIDTH_AUTO, .slot_mode = I2S_SLOT_MODE_MONO, .slot_mask = I2S_STD_SLOT_LEFT, .ws_width = I2S_DATA_BIT_WIDTH_16BIT, .ws_pol = false, .bit_shift = true, #ifdef I2S_HW_VERSION_2 .left_align = true, .big_endian = false, .bit_order_lsb = false #endif }, .gpio_cfg = { .mclk = mclk, .bclk = bclk, .ws = ws, .dout = dout, .din = din, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false } } }; ESP_ERROR_CHECK(i2s_channel_init_std_mode(tx_handle_, &std_cfg)); ESP_ERROR_CHECK(i2s_channel_init_std_mode(rx_handle_, &std_cfg)); ESP_LOGI(TAG, "Duplex channels created"); } void Es8311AudioCodec::SetOutputVolume(int volume) { if (volume == output_volume_) return; // Software volume scaling happens in Write(); just update member + NVS. AudioCodec::SetOutputVolume(volume); ESP_LOGI(TAG, "Output volume set to %d (software scaling)", volume); } //ALEX 重写 void Es8311AudioCodec::SetInputGain(float gain) { std::lock_guard lock(data_if_mutex_); if (codec_if_ == nullptr) return; if (gain == input_gain_) return; AudioCodec::SetInputGain(gain); // 调用基类设置变量 UpdateDeviceState(); // 关键:更新硬件寄存器 ESP_LOGI(TAG, "ES8311 hardware gain set to %.1f", gain); } void Es8311AudioCodec::EnableInput(bool enable) { std::lock_guard lock(data_if_mutex_); if (codec_if_ == nullptr) { return; } if (enable == input_enabled_) { return; } AudioCodec::EnableInput(enable); UpdateDeviceState(); } void Es8311AudioCodec::EnableOutput(bool enable) { std::lock_guard lock(data_if_mutex_); if (codec_if_ == nullptr) { return; } if (enable == output_enabled_) { return; } AudioCodec::EnableOutput(enable); UpdateDeviceState(); } int Es8311AudioCodec::Read(int16_t* dest, int samples) { if (input_enabled_) { //2026-6-19 ckkj debug if (dev_ == nullptr) { ESP_LOGW(TAG, "Read called before codec device is ready; retrying"); UpdateDeviceState(); if (dev_ == nullptr) { ESP_LOGW(TAG, "ES8311 input unavailable, dropping %d samples", samples); return samples; } } //end debug ESP_ERROR_CHECK_WITHOUT_ABORT(esp_codec_dev_read(dev_, (void*)dest, samples * sizeof(int16_t))); } return samples; } int Es8311AudioCodec::Write(const int16_t* data, int samples) { //if (!output_enabled_) return samples; //2026-6-19 ckkj debug if (!output_enabled_) { ESP_LOGD(TAG, "Codec output disabled, skip write"); return samples; } if (dev_ == nullptr) { ESP_LOGW(TAG, "Write called before codec device is ready; retrying"); UpdateDeviceState(); if (dev_ == nullptr) { ESP_LOGW(TAG, "ES8311 output unavailable, dropping %d samples", samples); return samples; } } //end debug if (data == nullptr || samples <= 0) { return 0; } // Volume curve: linear software gain on top of a hardware DAC pinned at 100%. // gain = output_volume_ / 100 (0..1.0) // Hardware ceiling is the true 100% acoustic output; we never amplify // beyond it, so vol=100 is the genuine maximum (no clipping/distortion). if (output_volume_ <= 0) { std::vector silence(samples, 0); ESP_ERROR_CHECK_WITHOUT_ABORT(esp_codec_dev_write(dev_, silence.data(), samples * sizeof(int16_t))); return samples; } int vol = output_volume_; if (vol > 100) vol = 100; float gain = static_cast(vol) / 100.0f; // Fixed-point: gain × 256 (range 0..256) int32_t gain_fp = static_cast(gain * 256.0f); std::vector scaled(samples); for (int i = 0; i < samples; i++) { int32_t s = (static_cast(data[i]) * gain_fp) >> 8; // Clamp to int16 range if (s > 32767) s = 32767; if (s < -32768) s = -32768; scaled[i] = static_cast(s); } ESP_ERROR_CHECK_WITHOUT_ABORT(esp_codec_dev_write(dev_, scaled.data(), samples * sizeof(int16_t))); return samples; }