Files
led-controller/main/mic.c
T
jimmyandClaude Opus 5.5 4ab0c7c6d7 P4-Nano: controller port with the C6 as ESP-NOW radio, and the simulator
The controller now builds for the Waveshare ESP32-P4-Nano only (plus the linux
sim and the desktop); the S3 stays for the USB/network bridge in bridge/.

- radio-c6/: C6 firmware, esp-hosted plus ESP-NOW over peer data. The P4 loads
  it from the slave_fw partition when the C6 runs another version (c6_update.c)
- bridge_hosted.c: the C6 as the always-on "c6" bridge, and the P4 as a network
  bridge on UDP 8766 for the desktop
- Ethernet on the P4's EMAC, ES8311 mic; default address 192.168.50.20. The
  W5500, INMP441 and direct ESP-NOW code is gone
- The simulated rig at /sim/ is built into the board image, with an always-on
  "browser" bridge. Its frames go through a queue so a slow page cannot hold up
  the radio, and frames for simulated bars are not sent over the C6. Receiver
  buffers are on the heap; a bar's flash file is only written when it changes
- HTTP server: more handlers, sockets and stack for the rig
- docs/P4_NANO.md, README and Makefile updated; graphify output

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 21:45:25 +13:00

225 lines
8.6 KiB
C

/*
* The ESP32-P4-Nano's microphone (ES8311 codec over I2S): level meter plus a 16-bit PCM feed for streaming.
* Reads both I2S slots and uses whichever one carries sound (the ES8311 puts it in the left one),
* keeping a running RMS/peak for the last block.
* Every block also goes to the beat detector.
*/
#include <math.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/stream_buffer.h"
#include "esp_log.h"
#include "esp_check.h"
#include "driver/i2s_std.h"
#include "driver/gpio.h"
#include "driver/i2c_master.h"
#include "esp_codec_dev.h"
#include "esp_codec_dev_defaults.h"
#include "mic.h"
#include "beat.h"
#define MIC_BLOCK_SAMPLES (MIC_SAMPLE_RATE / 50) // 20 ms per read, keeps stream latency low
#define LEVEL_BLOCKS 5 // 100 ms per level reading
#define FULL_SCALE_24BIT 8388608.0f
#define DBFS_FLOOR -120.0f
#define SPL_OFFSET 120.0f // 94 dB SPL - (-26 dBFS), an INMP441 figure: rough for the ES8311
static const char *TAG = "mic";
static i2s_chan_handle_t s_rx_chan;
static portMUX_TYPE s_level_lock = portMUX_INITIALIZER_UNLOCKED;
// 16-bit PCM for the HTTP stream; only fed while a listener is attached
#define STREAM_BUF_BYTES MIC_SAMPLE_RATE // 0.5 s of 16-bit mono
static StreamBufferHandle_t s_stream_buf;
static volatile bool s_stream_active;
static mic_level_t s_level = { DBFS_FLOOR, DBFS_FLOOR, DBFS_FLOOR + SPL_OFFSET };
static float to_dbfs(float x)
{
return x > 0.0f ? fmaxf(20.0f * log10f(x), DBFS_FLOOR) : DBFS_FLOOR;
}
static void mic_task(void *arg)
{
static int32_t buf[MIC_BLOCK_SAMPLES * 2]; // interleaved L/R
static int16_t pcm[MIC_BLOCK_SAMPLES];
static float filtered[MIC_BLOCK_SAMPLES];
// One-pole high-pass to strip the mic's DC offset
float hp_prev_in = 0.0f, hp_prev_out = 0.0f;
// Level is accumulated over several short blocks so the meter stays steady
double level_sum_sq = 0.0;
float level_peak = 0.0f;
size_t level_frames = 0, level_blocks = 0;
int64_t log_count = 0;
while (true) {
size_t bytes_read = 0;
if (i2s_channel_read(s_rx_chan, buf, sizeof(buf), &bytes_read, portMAX_DELAY) != ESP_OK) {
continue;
}
size_t frames = bytes_read / (2 * sizeof(int32_t));
if (frames == 0) {
continue;
}
// The unused slot is tri-stated and reads as 0; pick the busier one
int32_t raw_min = INT32_MAX, raw_max = INT32_MIN;
size_t nonzero[2] = {0, 0};
for (size_t i = 0; i < frames; i++) {
for (int ch = 0; ch < 2; ch++) {
int32_t v = buf[i * 2 + ch];
nonzero[ch] += (v != 0);
raw_min = v < raw_min ? v : raw_min;
raw_max = v > raw_max ? v : raw_max;
}
}
int ch = nonzero[1] > nonzero[0] ? 1 : 0;
for (size_t i = 0; i < frames; i++) {
// 24-bit sample sits in the top bits of the 32-bit slot
float x = (float)(buf[i * 2 + ch] >> 8) / FULL_SCALE_24BIT;
float y = x - hp_prev_in + 0.995f * hp_prev_out;
hp_prev_in = x;
hp_prev_out = y;
filtered[i] = y;
level_sum_sq += (double)y * y;
level_peak = fmaxf(level_peak, fabsf(y));
pcm[i] = (int16_t)fmaxf(fminf(y * CONFIG_MIC_STREAM_GAIN * 32767.0f, 32767.0f), -32768.0f);
}
level_frames += frames;
beat_feed(filtered, frames);
if (s_stream_active) {
// Drop audio rather than block capture if the listener falls behind
xStreamBufferSend(s_stream_buf, pcm, frames * sizeof(int16_t), 0);
}
if (++level_blocks < LEVEL_BLOCKS) {
continue;
}
mic_level_t level;
level.rms_dbfs = to_dbfs(sqrtf((float)(level_sum_sq / level_frames)));
level.peak_dbfs = to_dbfs(level_peak);
level.spl_db = level.rms_dbfs + SPL_OFFSET;
level_sum_sq = 0.0;
level_peak = 0.0f;
level_frames = level_blocks = 0;
portENTER_CRITICAL(&s_level_lock);
s_level = level;
portEXIT_CRITICAL(&s_level_lock);
if (++log_count % 50 == 0) { // every 5 s
ESP_LOGI(TAG, "%s slot: RMS %.1f dBFS, peak %.1f dBFS, ~%.0f dB SPL",
ch ? "right" : "left", level.rms_dbfs, level.peak_dbfs, level.spl_db);
ESP_LOGI(TAG, "raw min %ld max %ld, nonzero L %u R %u of %u",
(long)raw_min, (long)raw_max, (unsigned)nonzero[0], (unsigned)nonzero[1], (unsigned)frames);
}
}
}
// The Waveshare ESP32-P4-Nano's microphone goes through the ES8311 codec's ADC. The codec needs MCLK and its
// registers set over I2C; esp_codec_dev does both and drives the I2S channel (s_rx_chan) as its data path, in the
// 32-bit stereo frames mic_task reads.
static esp_err_t codec_mic_start(void)
{
i2c_master_bus_handle_t bus;
i2c_master_bus_config_t bc = {
.i2c_port = I2C_NUM_0,
.sda_io_num = CONFIG_P4_CODEC_I2C_SDA_GPIO,
.scl_io_num = CONFIG_P4_CODEC_I2C_SCL_GPIO,
.clk_source = I2C_CLK_SRC_DEFAULT,
.glitch_ignore_cnt = 7,
.flags.enable_internal_pullup = true,
};
ESP_RETURN_ON_ERROR(i2c_new_master_bus(&bc, &bus), TAG, "I2C bus");
i2s_std_config_t std_cfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(MIC_SAMPLE_RATE), // MCLK = 256 x fs
.slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO),
.gpio_cfg = {
.mclk = CONFIG_P4_I2S_MCLK_GPIO,
.bclk = CONFIG_P4_I2S_BCLK_GPIO,
.ws = CONFIG_P4_I2S_WS_GPIO,
.dout = I2S_GPIO_UNUSED,
.din = CONFIG_P4_I2S_DIN_GPIO,
},
};
ESP_RETURN_ON_ERROR(i2s_channel_init_std_mode(s_rx_chan, &std_cfg), TAG, "I2S std mode init failed");
ESP_RETURN_ON_ERROR(i2s_channel_enable(s_rx_chan), TAG, "I2S enable failed"); // MCLK runs before the codec
audio_codec_i2s_cfg_t ic = { .port = I2S_NUM_0, .rx_handle = s_rx_chan, .tx_handle = NULL };
const audio_codec_data_if_t *data_if = audio_codec_new_i2s_data(&ic);
audio_codec_i2c_cfg_t cc = { .port = I2C_NUM_0, .addr = CONFIG_P4_CODEC_I2C_ADDR << 1, .bus_handle = bus };
const audio_codec_ctrl_if_t *ctrl_if = audio_codec_new_i2c_ctrl(&cc);
const audio_codec_gpio_if_t *gpio_if = audio_codec_new_gpio();
ESP_RETURN_ON_FALSE(data_if && ctrl_if && gpio_if, ESP_ERR_NO_MEM, TAG, "codec interfaces");
es8311_codec_cfg_t ec = {
.ctrl_if = ctrl_if,
.gpio_if = gpio_if,
.codec_mode = ESP_CODEC_DEV_WORK_MODE_ADC,
.pa_pin = -1,
.use_mclk = true,
};
const audio_codec_if_t *codec_if = es8311_codec_new(&ec);
ESP_RETURN_ON_FALSE(codec_if, ESP_FAIL, TAG, "ES8311 not found on I2C 0x%02x", CONFIG_P4_CODEC_I2C_ADDR);
esp_codec_dev_cfg_t dc = { .dev_type = ESP_CODEC_DEV_TYPE_IN, .codec_if = codec_if, .data_if = data_if };
esp_codec_dev_handle_t dev = esp_codec_dev_new(&dc);
ESP_RETURN_ON_FALSE(dev, ESP_ERR_NO_MEM, TAG, "codec device");
esp_codec_dev_sample_info_t fs = {
.bits_per_sample = 32,
.channel = 2,
.sample_rate = MIC_SAMPLE_RATE,
.mclk_multiple = 256,
};
ESP_RETURN_ON_FALSE(esp_codec_dev_open(dev, &fs) == ESP_CODEC_DEV_OK, ESP_FAIL, TAG, "codec open");
esp_codec_dev_set_in_gain(dev, CONFIG_P4_MIC_PGA_DB);
return ESP_OK;
}
esp_err_t mic_start(void)
{
s_stream_buf = xStreamBufferCreate(STREAM_BUF_BYTES, 1);
ESP_RETURN_ON_FALSE(s_stream_buf, ESP_ERR_NO_MEM, TAG, "Stream buffer alloc failed");
i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER);
ESP_RETURN_ON_ERROR(i2s_new_channel(&chan_cfg, NULL, &s_rx_chan), TAG, "I2S channel create failed");
ESP_RETURN_ON_ERROR(codec_mic_start(), TAG, "ES8311 start failed");
ESP_RETURN_ON_ERROR(beat_start(MIC_SAMPLE_RATE), TAG, "Beat detector start failed");
if (xTaskCreate(mic_task, "mic", 6144, NULL, 5, NULL) != pdPASS) {
return ESP_ERR_NO_MEM;
}
ESP_LOGI(TAG, "ES8311 microphone started at %d Hz", MIC_SAMPLE_RATE);
return ESP_OK;
}
void mic_get_level(mic_level_t *out)
{
portENTER_CRITICAL(&s_level_lock);
*out = s_level;
portEXIT_CRITICAL(&s_level_lock);
}
esp_err_t mic_stream_open(void)
{
if (s_stream_active) {
return ESP_ERR_INVALID_STATE;
}
xStreamBufferReset(s_stream_buf);
s_stream_active = true;
return ESP_OK;
}
size_t mic_stream_read(void *buf, size_t len, TickType_t timeout)
{
return xStreamBufferReceive(s_stream_buf, buf, len, timeout);
}
void mic_stream_close(void)
{
s_stream_active = false;
}