Files
Hodor/main/audio.c
T

227 lines
8.1 KiB
C

#include "sdkconfig.h"
#include <esp_log.h>
#include <esp_system.h>
#include <nvs_flash.h>
#include <sys/param.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/i2c_master.h"
#include "driver/i2s_std.h"
#include "esp_io_expander.h"
#include "esp_codec_dev.h"
#include "esp_codec_dev_defaults.h"
#include "audio.h"
#include "board.h"
static StreamBufferHandle_t s_play_sb; // mono 16-bit PCM from the browser
static esp_codec_dev_handle_t spk_dev, mic_dev;
static i2s_chan_handle_t tx_chan = NULL;
static i2s_chan_handle_t rx_chan = NULL;
static volatile int s_audio_fd = -1;
static httpd_handle_t s_audio_hd = NULL;
esp_err_t audio_ws_handler(httpd_req_t *req)
{
if (req->method == HTTP_GET) { // WebSocket handshake
s_audio_hd = req->handle;
s_audio_fd = httpd_req_to_sockfd(req);
ESP_LOGI("AUDIO", "WS client connected, fd=%d", s_audio_fd);
return ESP_OK;
}
if (req->method == HTTP_GET) {
s_audio_hd = req->handle;
s_audio_fd = httpd_req_to_sockfd(req);
int one = 1;
setsockopt(s_audio_fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
return ESP_OK;
}
static int16_t in[2048]; // mono from browser (max 4096 bytes)
// static int16_t st[4096]; // stereo for the codec
httpd_ws_frame_t pkt = {0};
esp_err_t ret = httpd_ws_recv_frame(req, &pkt, 0);
if (ret != ESP_OK) return ret;
if (pkt.type == HTTPD_WS_TYPE_CLOSE) { s_audio_fd = -1; return ESP_OK; }
if (pkt.type == HTTPD_WS_TYPE_TEXT) { // control messages
char txt[16] = {0};
if (pkt.len >= sizeof(txt)) return ESP_FAIL;
pkt.payload = (uint8_t *)txt;
ret = httpd_ws_recv_frame(req, &pkt, pkt.len);
if (ret != ESP_OK) return ret;
int v;
if (sscanf(txt, "VOL:%d", &v) == 1) {
if (v < 0) v = 0;
if (v > 100) v = 100;
esp_codec_dev_set_out_vol(spk_dev, v);
}
return ESP_OK;
}
if (pkt.len == 0 || pkt.len > sizeof(in)) return ESP_FAIL;
pkt.payload = (uint8_t *)in;
ret = httpd_ws_recv_frame(req, &pkt, pkt.len);
if (ret != ESP_OK) return ret;
int n = pkt.len / 2;
size_t len = pkt.len & ~1u;
if (xStreamBufferSpacesAvailable(s_play_sb) >= len)
xStreamBufferSend(s_play_sb, in, len, 0); // never blocks
// else: buffer is full, drop this packet to keep latency bounded
return ESP_OK;
// esp_codec_dev_write(spk_dev, st, n * 4);
// return ESP_OK;
}
httpd_handle_t start_audio_server(void) {
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.server_port = 81;
config.ctrl_port = 32769;
config.max_open_sockets = 3;
httpd_handle_t audio_server = NULL;
if (httpd_start(&audio_server, &config) == ESP_OK) {
httpd_uri_t uri_audio_ws = {
.uri = "/audio",
.method = HTTP_GET,
.handler = audio_ws_handler,
.is_websocket = true
};
httpd_register_uri_handler(audio_server, &uri_audio_ws);
ESP_LOGI("AUDIO", "Audio WebSocket Server started on port 81");
}
return audio_server;
}
void mic_task(void *arg)
{
static int16_t st[512]; // 512 stereo frames
static int16_t mono[256];
int blocks = 0, sendFail = 0, pkL = 0, pkR = 0;
while (1) {
int rd = esp_codec_dev_read(mic_dev, st, sizeof(st));
if (rd != ESP_CODEC_DEV_OK) {
ESP_LOGE("MIC", "read error %d", rd);
vTaskDelay(pdMS_TO_TICKS(50));
continue;
}
long eL = 0, eR = 0;
for (int i = 0; i < 256; i++) {
int l = abs(st[2*i]), r = abs(st[2*i+1]);
eL += l; eR += r;
if (l > pkL) pkL = l;
if (r > pkR) pkR = r;
}
int useRight = eR > eL;
if (s_audio_fd >= 0) {
for (int i = 0; i < 256; i++) {
int v = (useRight ? st[2*i+1] : st[2*i]) * MIC_BOOST;
if (v > 32767) v = 32767;
if (v < -32768) v = -32768;
mono[i] = (int16_t)v;
}
httpd_ws_frame_t f = { .payload = (uint8_t *)mono, .len = sizeof(mono),
.type = HTTPD_WS_TYPE_BINARY };
if (httpd_ws_send_frame_async(s_audio_hd, s_audio_fd, &f) != ESP_OK)
sendFail++;
}
if (++blocks >= 62) { // about once per second
ESP_LOGI("MIC", "peakL=%d peakR=%d client_fd=%d sendFail=%d",
pkL, pkR, (int)s_audio_fd, sendFail);
blocks = 0; pkL = pkR = 0; sendFail = 0;
}
}
}
static void play_task(void *arg)
{
static int16_t mono[256];
static int16_t st[512];
while (1) {
size_t got = xStreamBufferReceive(s_play_sb, mono, sizeof(mono), pdMS_TO_TICKS(50));
got &= ~1u; // whole samples only
if (!got) continue;
int n = got / 2;
for (int i = 0; i < n; i++) { st[2*i] = mono[i]; st[2*i+1] = mono[i]; }
esp_codec_dev_write(spk_dev, st, n * 4);
}
}
esp_err_t audio_init(i2c_master_bus_handle_t bus)
{
// 2) One I2S port, full duplex (shared clocks)
i2s_chan_config_t cc = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER);
cc.auto_clear = true;
cc.dma_desc_num = 4;
cc.dma_frame_num = 160; // about 40 ms total instead of about 90 ms
ESP_ERROR_CHECK(i2s_new_channel(&cc, &tx_chan, &rx_chan));
i2s_std_config_t std = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(SR),
.slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT,
I2S_SLOT_MODE_STEREO),
.gpio_cfg = { .mclk = I2S_MCLK, .bclk = I2S_BCLK, .ws = I2S_WS,
.dout = I2S_DOUT, .din = I2S_DIN },
};
ESP_ERROR_CHECK(i2s_channel_init_std_mode(tx_chan, &std));
ESP_ERROR_CHECK(i2s_channel_init_std_mode(rx_chan, &std));
ESP_ERROR_CHECK(i2s_channel_enable(tx_chan));
ESP_ERROR_CHECK(i2s_channel_enable(rx_chan));
audio_codec_i2s_cfg_t i2s_cfg = { .port = I2S_NUM_0,
.tx_handle = tx_chan, .rx_handle = rx_chan };
const audio_codec_data_if_t *data_if = audio_codec_new_i2s_data(&i2s_cfg);
const audio_codec_gpio_if_t *gpio_if = audio_codec_new_gpio();
// 3) Speaker: ES8311
audio_codec_i2c_cfg_t out_i2c = { .port = 0, .addr = ES8311_CODEC_DEFAULT_ADDR,
.bus_handle = bus };
es8311_codec_cfg_t es8311_cfg = {
.ctrl_if = audio_codec_new_i2c_ctrl(&out_i2c),
.gpio_if = gpio_if,
.codec_mode = ESP_CODEC_DEV_TYPE_OUT,
.pa_pin = -1, // amp is on the IO expander, handled above
.use_mclk = true,
};
esp_codec_dev_cfg_t spk_cfg = { .dev_type = ESP_CODEC_DEV_TYPE_OUT,
.codec_if = es8311_codec_new(&es8311_cfg), .data_if = data_if };
spk_dev = esp_codec_dev_new(&spk_cfg);
// 4) Mic: ES7210
audio_codec_i2c_cfg_t in_i2c = { .port = 0, .addr = ES7210_CODEC_DEFAULT_ADDR,
.bus_handle = bus };
es7210_codec_cfg_t es7210_cfg = {
.ctrl_if = audio_codec_new_i2c_ctrl(&in_i2c),
.mic_selected = ES7210_SEL_MIC1 | ES7210_SEL_MIC2,
};
esp_codec_dev_cfg_t mic_cfg = { .dev_type = ESP_CODEC_DEV_TYPE_IN,
.codec_if = es7210_codec_new(&es7210_cfg), .data_if = data_if };
mic_dev = esp_codec_dev_new(&mic_cfg);
// 5) Open both
esp_codec_dev_sample_info_t fs = { .sample_rate = SR, .channel = 2,
.bits_per_sample = 16 };
ESP_ERROR_CHECK(esp_codec_dev_open(spk_dev, &fs) == ESP_CODEC_DEV_OK ? ESP_OK : ESP_FAIL);
ESP_ERROR_CHECK(esp_codec_dev_open(mic_dev, &fs) == ESP_CODEC_DEV_OK ? ESP_OK : ESP_FAIL);
esp_codec_dev_set_out_vol(spk_dev, 100);
esp_codec_dev_set_in_gain(mic_dev, 30.0);
s_play_sb = xStreamBufferCreate(4096, 1); // about 128 ms maximum queue
xTaskCreate(play_task, "play", 4096, NULL, 6, NULL);
return ESP_OK;
}