Files
Hodor/main/audio.c
T
Aida_Lashkari 72a2d714ab Add : RTSP audio/video with back channel, and auth
- cam_stream: shared JPEG feed for /pic, /stream and RTSP; RTSP server
  (port 554, TCP) with MJPEG video, G.711 mic audio and an ONVIF-style
  back channel to the speaker
- cam_auth: RTSP Digest login and HTTP Basic / ?key= check on all endpoints
- Mic task feeds HTTP and RTSP with a sticky channel choice
2026-10-08 14:12:48 +03:30

283 lines
10 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include "driver/i2c_master.h"
#include "driver/i2s_std.h"
#include "esp_codec_dev.h"
#include "esp_codec_dev_defaults.h"
#include "cam_stream.h"
#include "board.h"
#define I2S_MCLK GPIO_NUM_10
#define I2S_BCLK GPIO_NUM_11
#define I2S_WS GPIO_NUM_12
#define I2S_DOUT GPIO_NUM_14 // ESP -> ES8311 DSDIN
#define I2S_DIN GPIO_NUM_13 // ES7210 SDOUT -> ESP
#define SR 16000
#define MIC_BOOST 4 // software gain, raise if still quiet
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;
static StreamBufferHandle_t s_mic_sb;
static volatile bool s_mic_on = false;
// void mic_task(void *arg)
// {
// static int16_t st[512]; // 256 stereo frames
// static int16_t mono[256];
// while (1) {
// if (esp_codec_dev_read(mic_dev, st, sizeof(st)) != ESP_CODEC_DEV_OK) {
// vTaskDelay(pdMS_TO_TICKS(10));
// continue;
// }
// if (!s_mic_on) continue; // nobody listening, just drain
// long eL = 0, eR = 0;
// for (int i = 0; i < 256; i++) { eL += abs(st[2*i]); eR += abs(st[2*i+1]); }
// int useRight = eR > eL;
// 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;
// }
// xStreamBufferSend(s_mic_sb, mono, sizeof(mono), 0); // drops if full
// }
// }
void mic_task(void *arg)
{
static int16_t st[512]; // 256 stereo frames
static int16_t mono[256];
long aL = 0, aR = 0;
int useRight = 0;
while (1) {
if (esp_codec_dev_read(mic_dev, st, sizeof(st)) != ESP_CODEC_DEV_OK) {
vTaskDelay(pdMS_TO_TICKS(10));
continue;
}
if (!s_mic_on && !cam_audio_wanted()) continue; // nobody listening
long eL = 0, eR = 0;
for (int i = 0; i < 256; i++) { eL += abs(st[2*i]); eR += abs(st[2*i+1]); }
aL += (eL - aL) / 16; // smoothed level per channel
aR += (eR - aR) / 16;
if (!useRight && aR > 2 * aL) useRight = 1; // switch only on a clear difference
else if (useRight && aL > 2 * aR) useRight = 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;
}
if (s_mic_on && xStreamBufferSpacesAvailable(s_mic_sb) >= sizeof(mono))
xStreamBufferSend(s_mic_sb, mono, sizeof(mono), 0);
cam_audio_push(mono, 256); // RTSP sessions
}
}
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);
}
}
void rtsp_speaker_sink(const int16_t *pcm, size_t samples)
{
size_t bytes = samples * sizeof(int16_t);
if (xStreamBufferSpacesAvailable(s_play_sb) >= bytes)
xStreamBufferSend(s_play_sb, pcm, bytes, 0); // full: drop, keeps delay bounded
}
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
s_mic_sb = xStreamBufferCreate(4096, 1);
xTaskCreate(play_task, "play", 4096, NULL, 6, NULL);
return ESP_OK;
}
static void cors(httpd_req_t *req) {
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
httpd_resp_set_hdr(req, "Cache-Control", "no-store");
}
// GET /mic : endless raw PCM stream (16 kHz, 16-bit, mono)
// 44-byte WAV header: PCM, mono, 16 kHz, 16-bit, unknown length
static const uint8_t WAV_HDR[44] = {
'R','I','F','F', 0xFF,0xFF,0xFF,0xFF, 'W','A','V','E',
'f','m','t',' ', 16,0,0,0,
1,0, // PCM
1,0, // mono
0x80,0x3E,0,0, // 16000 Hz
0x00,0x7D,0,0, // byte rate 32000
2,0, // block align
16,0, // bits per sample
'd','a','t','a', 0xFF,0xFF,0xFF,0xFF
};
static esp_err_t mic_handler(httpd_req_t *req)
{
static int16_t buf[256];
if (!cam_http_check(req)) return ESP_OK;
cors(req);
httpd_resp_set_type(req, "audio/wav");
xStreamBufferReset(s_mic_sb);
if (httpd_resp_send_chunk(req, (const char *)WAV_HDR, sizeof(WAV_HDR)) != ESP_OK)
return ESP_FAIL;
s_mic_on = true;
esp_err_t res = ESP_OK;
while (1) {
size_t n = xStreamBufferReceive(s_mic_sb, buf, sizeof(buf), pdMS_TO_TICKS(200));
if (!n) continue;
res = httpd_resp_send_chunk(req, (const char *)buf, n);
if (res != ESP_OK) break;
}
s_mic_on = false;
return res;
}
// POST /spk : body = mono 16-bit PCM
static esp_err_t spk_handler(httpd_req_t *req)
{
static uint8_t body[4096];
if (!cam_http_check(req)) return ESP_FAIL;;
cors(req);
size_t total = req->content_len;
if (total == 0 || total > sizeof(body)) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad length");
return ESP_FAIL;
}
size_t got = 0;
while (got < total) {
int r = httpd_req_recv(req, (char *)body + got, total - got);
if (r <= 0) return ESP_FAIL;
got += r;
}
size_t len = got & ~1u;
if (xStreamBufferSpacesAvailable(s_play_sb) >= len)
xStreamBufferSend(s_play_sb, body, len, 0); // else drop, keeps latency bounded
httpd_resp_set_status(req, "204 No Content");
return httpd_resp_send(req, NULL, 0);
}
// GET /vol?v=85
static esp_err_t vol_handler(httpd_req_t *req)
{
char q[32], val[8];
if (!cam_http_check(req)) return ESP_OK;
cors(req);
if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK &&
httpd_query_key_value(q, "v", val, sizeof(val)) == ESP_OK) {
int v = atoi(val);
if (v < 0) v = 0;
if (v > 100) v = 100;
esp_codec_dev_set_out_vol(spk_dev, v);
}
httpd_resp_set_status(req, "204 No Content");
return httpd_resp_send(req, NULL, 0);
}
void start_audio_server(void)
{
httpd_handle_t h;
httpd_config_t c1 = HTTPD_DEFAULT_CONFIG();
c1.server_port = 81; c1.ctrl_port = 32769; c1.stack_size = 6144;
if (httpd_start(&h, &c1) == ESP_OK) {
httpd_uri_t u = { .uri = "/mic", .method = HTTP_GET, .handler = mic_handler };
httpd_register_uri_handler(h, &u);
}
httpd_config_t c2 = HTTPD_DEFAULT_CONFIG();
c2.server_port = 82; c2.ctrl_port = 32770; c2.stack_size = 6144;
c2.lru_purge_enable = true;
if (httpd_start(&h, &c2) == ESP_OK) {
httpd_uri_t s = { .uri = "/spk", .method = HTTP_POST, .handler = spk_handler };
httpd_uri_t v = { .uri = "/vol", .method = HTTP_GET, .handler = vol_handler };
httpd_register_uri_handler(h, &s);
httpd_register_uri_handler(h, &v);
}
}