knob_os/slave_audio/slave_audio.ino

355 lines
13 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// slave_audio.ino —— 副控 ESP32-U4WDH 音频固件(双音源版)
//
// 两个音源共用同一路 I2S → PCM5100:
// [BT ] A2DP Sink(手机/电脑连 TAIJI_KNOB_AUDIO 推音频)—— 保住原厂的蓝牙能力
// [UART] 主控 KnobOS 推的 MP3 码流(AA 55 帧)—— TF 卡/网络音乐
//
// 仲裁规则(后到者赢):
// - 蓝牙第一包音频到达 → 抢占输出,UART 播放立即停(ring 清空)
// - 主控发 START → 抢占输出,蓝牙被 pause(保持连接不踢下线)
// - 蓝牙断开 → 输出归还空闲
//
// 接线(来自原理图,不是封装引脚序号):
// I2S BCK=GPIO25 DIN=GPIO26 LRCK=GPIO27 XSMT(静音脚)=GPIO32,拉高才出声
// UART RX=GPIO18(收主控 TX40) TX=GPIO23(发主控 RX39) 921600 8N1
//
// 帧格式:AA 55 | cmd | len_lo len_hi | payload | crc8(0x07, init 0)
// 主控→副控:01 START / 02 DATA / 03 END / 04 PAUSE / 05 VOL / 06 STOP
// 副控→主控:30 STATUS payload = [state, freeKbHi, freeKbLo, 0]
//
// 烧录:副控的 USB 走 CH340C(UART0 = GPIO1/3),板子选 "ESP32 Dev Module"
//(4MB Flash,无 PSRAM),分区表用平台官方 no_fs(双 OTA 槽各 2MB + coredump)。
// 注意:烧录会覆盖原厂固件,务必先 read-flash 备份整个 4MB!
#include <Arduino.h>
#include "driver/i2s.h"
#include "BluetoothA2DPSink.h"
extern "C" {
#define MINIMP3_IMPLEMENTATION
#include "minimp3.h"
}
// ------------------------------ 引脚 ------------------------------
#define PIN_I2S_BCK 25
#define PIN_I2S_DIN 26
#define PIN_I2S_LRCK 27
#define PIN_XSMT 32
#define PIN_UART_RX 18
#define PIN_UART_TX 23
#define UART_SPEED 921600
// ---------------------------- 缓冲与状态 ----------------------------
// 64KB 码流缓冲;U4WDH 只有 320KB DRAM 还要养蓝牙栈,
// malloc 失败就降 32KB —— 320kbps 码流下 32KB 也有约 0.8 秒余量。
static const uint32_t RING = 64 * 1024;
static uint32_t s_ringSize = 0;
static uint8_t* s_ring = nullptr;
static uint32_t s_w = 0, s_r = 0; // 自由递增游标,用差值算占用
static uint8_t s_vol = 80;
static bool s_playing = false;
static bool s_paused = false;
static bool s_eos = false;
static bool s_btConnected = false;
static uint8_t s_src = 0; // 0 空闲 / 1 uart / 2 蓝牙
static uint32_t s_underrun = 0, s_decodeErr = 0, s_frames = 0;
static uint32_t s_lastStatus = 0;
BluetoothA2DPSink a2dp_sink;
static inline uint32_t ringAvail() { return s_w - s_r; }
static inline uint32_t ringSpace() { return s_ringSize - ringAvail(); }
static void ringPush(const uint8_t* d, uint32_t n) {
uint32_t sp = ringSpace();
if (n > sp) n = sp; // 满了就丢(主控有流控,正常不会到这)
uint32_t off = s_w % s_ringSize;
uint32_t first = s_ringSize - off;
if (first > n) first = n;
memcpy(s_ring + off, d, first);
if (n > first) memcpy(s_ring, d + first, n - first);
s_w += n;
}
static void ringPop(uint8_t* d, uint32_t n) {
uint32_t off = s_r % s_ringSize;
uint32_t first = s_ringSize - off;
if (first > n) first = n;
memcpy(d, s_ring + off, first);
if (n > first) memcpy(d + first, s_ring, n - first);
s_r += n;
}
static void ringClear() { s_w = s_r = 0; }
// ------------------------------ I2S ------------------------------
static int s_hz = 0;
static void i2sSetup(uint32_t hz) {
if (s_hz == (int)hz) return;
if (s_hz == 0) {
i2s_config_t cfg = {};
cfg.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX);
cfg.sample_rate = hz;
cfg.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT;
cfg.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT;
cfg.communication_format = I2S_COMM_FORMAT_STAND_I2S;
cfg.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1;
cfg.dma_buf_count = 8;
cfg.dma_buf_len = 256;
cfg.use_apll = false;
cfg.tx_desc_auto_clear = true;
i2s_driver_install(I2S_NUM_0, &cfg, 0, nullptr);
i2s_pin_config_t pins = {};
pins.bck_io_num = PIN_I2S_BCK;
pins.ws_io_num = PIN_I2S_LRCK;
pins.data_out_num = PIN_I2S_DIN;
pins.data_in_num = -1;
i2s_set_pin(I2S_NUM_0, &pins);
i2s_zero_dma_buffer(I2S_NUM_0);
} else {
i2s_set_clk(I2S_NUM_0, hz, I2S_BITS_PER_SAMPLE_16BIT, I2S_CHANNEL_STEREO);
}
s_hz = (int)hz;
}
static void i2sWrite(const int16_t* d, size_t samples) { // samples = 每声道采样数
size_t bytes = samples * 2 * sizeof(int16_t);
size_t done = 0;
i2s_write(I2S_NUM_0, d, bytes, &done, portMAX_DELAY);
}
// ------------------------------ 解码 ------------------------------
static mp3dec_t s_dec;
static int16_t s_pcm[MINIMP3_MAX_SAMPLES_PER_FRAME];
static uint8_t s_stage[4096];
static int16_t s_silence[1152 * 2] = {0};
static void applyVolume(int16_t* pcm, size_t n) {
if (s_vol >= 100) return;
int32_t g = s_vol;
for (size_t i = 0; i < n; i++) pcm[i] = (int16_t)((int32_t)pcm[i] * g / 100);
}
static void audioStep() {
uint32_t avail = ringAvail();
// 欠载:补一小段静音拖住 I2S 时钟,否则 PCM5100 会听到"咔"
if (avail < 512 && !(s_eos && avail > 0)) {
if (s_playing && !s_paused) { s_underrun++; i2sWrite(s_silence, 1152); }
return;
}
uint32_t take = avail > sizeof(s_stage) ? sizeof(s_stage) : avail;
ringPop(s_stage, take);
mp3dec_frame_info_t info = {};
int samples = mp3dec_decode_frame(&s_dec, s_stage, (int)take, s_pcm, &info);
if (info.frame_bytes == 0) {
// 没找到帧头:扔 1 字节重新对齐
s_r -= (take - 1);
s_decodeErr++;
return;
}
s_r -= (take - info.frame_bytes); // 没吃完的还给缓冲
if (samples <= 0) return;
i2sSetup(info.hz > 0 ? (uint32_t)info.hz : 44100);
size_t n = (size_t)samples * (size_t)info.channels;
if (info.channels == 1) {
// 单声道复制成双声道
for (int i = samples - 1; i >= 0; i--) {
s_pcm[i * 2 + 1] = s_pcm[i];
s_pcm[i * 2] = s_pcm[i];
}
n = (size_t)samples * 2;
}
applyVolume(s_pcm, n);
i2sWrite(s_pcm, (size_t)samples);
s_frames++;
}
// ---------------------------- 音源仲裁 ----------------------------
static void releaseIfIdle() {
if (s_src == 0 && !s_playing) digitalWrite(PIN_XSMT, LOW);
}
// 蓝牙数据到达:抢占输出(后到者赢),UART 播放立即停
static void a2dpDataCb(const uint8_t* data, uint32_t len) {
if (s_src != 2) {
s_src = 2;
if (s_playing || s_paused) { // 打断 UART 播放
s_playing = false; s_paused = false; s_eos = false;
ringClear();
}
i2sSetup(44100);
digitalWrite(PIN_XSMT, HIGH);
}
if (len == 0) return;
size_t done = 0;
// 蓝牙任务里不能无限阻塞:50ms 写不进就丢,I2S DMA 8x256 能扛 23ms
i2s_write(I2S_NUM_0, data, len, &done, pdMS_TO_TICKS(50));
}
// 蓝牙连接状态:断开时把输出还给空闲
static void a2dpConnCb(esp_a2d_connection_state_t st, void*) {
if (st == ESP_A2D_CONNECTION_STATE_CONNECTED) {
s_btConnected = true;
Serial.println("BT connected");
} else if (st == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
s_btConnected = false;
if (s_src == 2) s_src = 0;
releaseIfIdle();
Serial.println("BT disconnected");
}
}
// ---------------------------- 帧解析 ----------------------------
enum : uint8_t { H0, H1, CMD, LEN0, LEN1, PAY, CRC };
static uint8_t s_st = H0;
static uint8_t s_cmd = 0;
static uint16_t s_len = 0, s_idx = 0;
static uint8_t s_crc = 0;
static uint8_t s_ctrl[8];
static uint8_t crc8Update(uint8_t c, uint8_t b) {
c ^= b;
for (int i = 0; i < 8; i++) c = (c & 0x80) ? (uint8_t)((c << 1) ^ 0x07) : (uint8_t)(c << 1);
return c;
}
static void sendStatus() {
uint32_t freeKb = ringSpace() / 1024;
if (freeKb > 0xFFFF) freeKb = 0xFFFF;
uint8_t st = s_playing ? (s_paused ? 2 : (s_eos ? 3 : 1)) : 0;
uint8_t f[10] = {0xAA, 0x55, 0x30, 0x04, 0x00, st,
(uint8_t)(freeKb >> 8), (uint8_t)(freeKb & 0xFF), 0x00, 0x00};
uint8_t c = 0;
for (int i = 2; i < 9; i++) c = crc8Update(c, f[i]);
f[9] = c;
Serial2.write(f, sizeof(f));
}
static void handleCmd(uint8_t cmd) {
switch (cmd) {
case 0x01: // START:抢占输出
if (s_btConnected) a2dp_sink.pause(); // 蓝牙让路但保持连接
ringClear();
mp3dec_init(&s_dec);
s_playing = true; s_paused = false; s_eos = false;
s_src = 1;
i2sSetup(44100);
digitalWrite(PIN_XSMT, HIGH); // PCM5100 解除静音
Serial.println("START");
break;
case 0x03: // END
s_eos = true;
break;
case 0x04: // PAUSE
s_paused = (s_len >= 1 && s_ctrl[0] != 0);
Serial.printf("PAUSE %d\n", s_paused);
break;
case 0x05: // VOL(只作用于 UART 源;蓝牙音量在手机端)
if (s_len >= 1) s_vol = s_ctrl[0] > 100 ? 100 : s_ctrl[0];
break;
case 0x06: // STOP
s_playing = false; s_paused = false; s_eos = false;
s_src = 0;
ringClear();
releaseIfIdle();
Serial.println("STOP");
break;
default:
break;
}
}
static void feedByte(uint8_t b) {
switch (s_st) {
case H0: if (b == 0xAA) s_st = H1; break;
case H1: s_st = (b == 0x55) ? CMD : H0; break;
case CMD: s_cmd = b; s_crc = crc8Update(0, b); s_st = LEN0; break;
case LEN0: s_len = b; s_crc = crc8Update(s_crc, b); s_st = LEN1; break;
case LEN1:
s_len |= (uint16_t)b << 8;
s_crc = crc8Update(s_crc, b);
s_idx = 0;
if (s_len > 1024) { s_st = H0; break; } // 异常长度,重新同步
s_st = s_len ? PAY : CRC;
break;
case PAY:
s_crc = crc8Update(s_crc, b);
if (s_cmd == 0x02) ringPush(&b, 1); // DATA 直接进环形缓冲
else if (s_idx < sizeof(s_ctrl)) s_ctrl[s_idx] = b;
if (++s_idx >= s_len) s_st = CRC;
break;
case CRC:
if (b == s_crc) handleCmd(s_cmd);
else if (s_cmd == 0x02) s_decodeErr++; // 码流帧校验失败:记一笔,解码器会自己找同步
s_st = H0;
break;
default:
s_st = H0;
break;
}
}
// ------------------------------ 主流程 ------------------------------
void setup() {
Serial.begin(115200);
delay(150);
Serial.println("\n=== slave_audio (A2DP sink + uart mp3 + PCM5100) ===");
pinMode(PIN_XSMT, OUTPUT);
digitalWrite(PIN_XSMT, LOW); // 先静音,等有源再放开
s_ring = (uint8_t*)malloc(RING);
s_ringSize = RING;
if (!s_ring) { // 内存紧(蓝牙栈先吃了一口)就降半
s_ring = (uint8_t*)malloc(RING / 2);
s_ringSize = RING / 2;
}
if (!s_ring) {
Serial.println("!! ring alloc failed");
while (true) delay(1000);
}
Serial.printf("ring=%uKB\n", (unsigned)(s_ringSize / 1024));
Serial2.setRxBufferSize(4096);
Serial2.begin(UART_SPEED, SERIAL_8N1, PIN_UART_RX, PIN_UART_TX);
Serial.printf("uart2 rx=%d tx=%d @%d\n", PIN_UART_RX, PIN_UART_TX, UART_SPEED);
i2sSetup(44100);
mp3dec_init(&s_dec);
// A2DP Sink:数据已被库应用了 AVRC 音量,i2s_output=false 表示我们自己写 I2S
a2dp_sink.set_stream_reader(a2dpDataCb, false);
a2dp_sink.set_on_connection_state_changed(a2dpConnCb);
a2dp_sink.set_auto_reconnect(true);
a2dp_sink.start("NEX_BUDDY_AUDIO");
Serial.println("ready");
}
void loop() {
// 收包(一次最多消费一批,避免饿死解码)
int budget = 1024;
while (Serial2.available() && budget-- > 0) feedByte((uint8_t)Serial2.read());
if (s_playing && s_src == 1) audioStep();
uint32_t now = millis();
if (now - s_lastStatus >= 250) {
s_lastStatus = now;
sendStatus();
if (s_playing && (now % 5000) < 250) {
Serial.printf("frames=%u under=%u err=%u free=%uKB src=%u\n",
(unsigned)s_frames, (unsigned)s_underrun,
(unsigned)s_decodeErr, (unsigned)(ringSpace() / 1024), s_src);
}
}
}