Files
bolar_2/main/diagnostics/audio_tap.cc
2026-11-27 16:38:11 +08:00

309 lines
11 KiB
C++

#include "diagnostics/audio_tap.h"
#include <algorithm>
#include <cstring>
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_netif.h>
#include <freertos/idf_additions.h>
#include <lwip/sockets.h>
namespace borla {
namespace {
constexpr const char* kTag = "AudioTap2";
//constexpr uint32_t kTaskStackBytes = 6 * 1024;
constexpr unsigned kTaskPriority = 3;
constexpr uint32_t kBindRetryMs = 2000;
constexpr uint32_t kSampleRateHz = 48000;//24000;
constexpr uint32_t kUplinkRateHz = 16000;
} // namespace
bool AudioTap::Initialize()
{
if (initialized_) {
return true;
}
input_.data = static_cast<uint8_t*>(heap_caps_malloc(
kRingBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
output_.data = static_cast<uint8_t*>(heap_caps_malloc(
kRingBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
uplink_.data = static_cast<uint8_t*>(heap_caps_malloc(
kRingBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
if (input_.data == nullptr || output_.data == nullptr ||
uplink_.data == nullptr) {
ESP_LOGE(kTag, "ring allocation failed");
heap_caps_free(input_.data);
heap_caps_free(output_.data);
heap_caps_free(uplink_.data);
input_.data = nullptr;
output_.data = nullptr;
uplink_.data = nullptr;
return false;
}
input_.capacity = kRingBytes;
output_.capacity = kRingBytes;
uplink_.capacity = kRingBytes;
//const BaseType_t created = xTaskCreatePinnedToCoreWithCaps(
task_ = xTaskCreateStaticPinnedToCore(
&AudioTap::TaskEntry,
"audio_tap2",
//kTaskStackBytes,
sizeof(task_stack_),
this,
kTaskPriority,
// &task_,
// tskNO_AFFINITY,
// MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
// if (created != pdPASS) {
task_stack_,
&task_control_,
0);
if (task_ == nullptr) {
ESP_LOGE(kTag, "task creation failed");
heap_caps_free(input_.data);
heap_caps_free(output_.data);
heap_caps_free(uplink_.data);
input_.data = nullptr;
output_.data = nullptr;
uplink_.data = nullptr;
return false;
}
initialized_ = true;
ESP_LOGI(kTag,
"recording rings armed: 3 x %u KB PSRAM, TCP port %u",
static_cast<unsigned>(kRingBytes / 1024),
static_cast<unsigned>(kPort));
return true;
}
void AudioTap::PushInput(const int16_t* samples, size_t sample_count)
{
Push(input_,
reinterpret_cast<const uint8_t*>(samples),
sample_count * sizeof(int16_t));
}
void AudioTap::PushOutput(const int16_t* samples, size_t sample_count)
{
if (samples == nullptr) {
// Gap marker: the DAC starved between writes. Recording the silence
// keeps spk.wav on the same timeline the microphone heard — without
// it, late frames concatenate seamlessly and playout gaps become
// invisible in the file, which misread as "spk clean, mic stutters".
static const int16_t kZeroChunk[240] = {};
size_t remaining = sample_count;
while (remaining > 0) {
const size_t chunk =
remaining < sizeof(kZeroChunk) / sizeof(kZeroChunk[0])
? remaining
: sizeof(kZeroChunk) / sizeof(kZeroChunk[0]);
Push(output_,
reinterpret_cast<const uint8_t*>(kZeroChunk),
chunk * sizeof(int16_t));
remaining -= chunk;
}
return;
}
Push(output_,
reinterpret_cast<const uint8_t*>(samples),
sample_count * sizeof(int16_t));
}
void AudioTap::PushUplink(const int16_t* samples, size_t sample_count)
{
if (samples != nullptr) {
Push(uplink_,
reinterpret_cast<const uint8_t*>(samples),
sample_count * sizeof(int16_t));
return;
}
// Suppressed or idle frame: silence keeps the uplink channel's timeline
// aligned with mic/spk so "what did the server hear at second N" is a
// direct A/B listen.
static const int16_t kZeroChunk[240] = {};
size_t remaining = sample_count;
while (remaining > 0) {
const size_t chunk =
remaining < sizeof(kZeroChunk) / sizeof(kZeroChunk[0])
? remaining
: sizeof(kZeroChunk) / sizeof(kZeroChunk[0]);
Push(uplink_,
reinterpret_cast<const uint8_t*>(kZeroChunk),
chunk * sizeof(int16_t));
remaining -= chunk;
}
}
void AudioTap::Push(Ring& ring, const uint8_t* bytes, size_t size)
{
if (ring.data == nullptr || bytes == nullptr || size == 0) {
return;
}
const size_t head = ring.head.load(std::memory_order_relaxed);
const size_t tail = ring.tail.load(std::memory_order_acquire);
const size_t space = ring.capacity - (head - tail);
if (size > space) {
// Drop the NEW audio, keep the old: while no host is attached the
// ring must preserve the earliest sound after boot, not the latest.
ring.dropped_bytes.fetch_add(
static_cast<uint32_t>(size), std::memory_order_relaxed);
return;
}
const size_t offset = head % ring.capacity;
const size_t first = std::min(size, ring.capacity - offset);
std::memcpy(ring.data + offset, bytes, first);
std::memcpy(ring.data, bytes + first, size - first);
ring.head.store(head + size, std::memory_order_release);
}
void AudioTap::TaskEntry(void* context)
{
static_cast<AudioTap*>(context)->Run();
}
[[noreturn]] void AudioTap::Run()
{
// lwIP's TCP/IP thread is created by esp_netif_init(), which the WiFi
// transport calls well after this task starts. Touching the socket API
// before that is not an error return but an assert ("Invalid mbox") and
// a boot loop. A netif existing proves esp_netif_init() has completed.
// The rings keep buffering while we wait, so no boot audio is lost.
while (esp_netif_get_nr_of_ifs() == 0) {
vTaskDelay(pdMS_TO_TICKS(kBindRetryMs));
}
int listen_fd = -1;
while (true) {
listen_fd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_fd >= 0) {
const int reuse = 1;
::setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR,
&reuse, sizeof(reuse));
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
address.sin_port = htons(kPort);
if (::bind(listen_fd,
reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == 0 &&
::listen(listen_fd, 1) == 0) {
break;
}
::close(listen_fd);
}
vTaskDelay(pdMS_TO_TICKS(kBindRetryMs));
}
ESP_LOGI(kTag, "listening on port %u",
static_cast<unsigned>(kPort));
while (true) {
const int client_fd = ::accept(listen_fd, nullptr, nullptr);
if (client_fd < 0) {
vTaskDelay(pdMS_TO_TICKS(kBindRetryMs));
continue;
}
ESP_LOGI(kTag, "recorder attached");
ServeClient(client_fd);
::close(client_fd);
ESP_LOGI(kTag,
"recorder detached dropped_in=%lu dropped_out=%lu",
static_cast<unsigned long>(
input_.dropped_bytes.load()),
static_cast<unsigned long>(
output_.dropped_bytes.load()));
}
}
void AudioTap::ServeClient(int client_fd)
{
// Hello v2: magic, version, channel count, pad, mic/spk rate, uplink
// rate. The host validates this before trusting the frame stream.
uint8_t hello[16] = {'B', 'T', 'A', 'P', 2, 3, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
hello[8] = static_cast<uint8_t>(kSampleRateHz & 0xFFU);
hello[9] = static_cast<uint8_t>((kSampleRateHz >> 8U) & 0xFFU);
hello[10] = static_cast<uint8_t>((kSampleRateHz >> 16U) & 0xFFU);
hello[11] = static_cast<uint8_t>((kSampleRateHz >> 24U) & 0xFFU);
hello[12] = static_cast<uint8_t>(kUplinkRateHz & 0xFFU);
hello[13] = static_cast<uint8_t>((kUplinkRateHz >> 8U) & 0xFFU);
hello[14] = static_cast<uint8_t>((kUplinkRateHz >> 16U) & 0xFFU);
hello[15] = static_cast<uint8_t>((kUplinkRateHz >> 24U) & 0xFFU);
if (!SendAll(client_fd, hello, sizeof(hello))) {
return;
}
while (true) {
if (!DrainAndSend(client_fd, input_, 0) ||
!DrainAndSend(client_fd, output_, 1) ||
!DrainAndSend(client_fd, uplink_, 2)) {
return;
}
const bool input_empty =
input_.head.load(std::memory_order_acquire) ==
input_.tail.load(std::memory_order_relaxed);
const bool output_empty =
output_.head.load(std::memory_order_acquire) ==
output_.tail.load(std::memory_order_relaxed);
const bool uplink_empty =
uplink_.head.load(std::memory_order_acquire) ==
uplink_.tail.load(std::memory_order_relaxed);
if (input_empty && output_empty && uplink_empty) {
vTaskDelay(pdMS_TO_TICKS(kIdlePollMs));
}
}
}
bool AudioTap::DrainAndSend(
int socket_fd,
Ring& ring,
uint8_t channel)
{
uint8_t record[4 + kSendChunkBytes];
while (true) {
const size_t head = ring.head.load(std::memory_order_acquire);
const size_t tail = ring.tail.load(std::memory_order_relaxed);
const size_t available = head - tail;
if (available == 0) {
return true;
}
const size_t take = std::min(available, kSendChunkBytes);
const size_t offset = tail % ring.capacity;
const size_t first = std::min(take, ring.capacity - offset);
std::memcpy(record + 4, ring.data + offset, first);
std::memcpy(record + 4 + first, ring.data, take - first);
record[0] = channel;
record[1] = 0;
record[2] = static_cast<uint8_t>(take & 0xFFU);
record[3] = static_cast<uint8_t>((take >> 8U) & 0xFFU);
if (!SendAll(socket_fd, record, 4 + take)) {
return false;
}
// Advance only after the bytes are on the wire so a mid-record send
// failure re-sends the same audio to the next recorder instead of
// losing it.
ring.tail.store(tail + take, std::memory_order_release);
}
}
bool AudioTap::SendAll(int socket_fd, const void* data, size_t size)
{
const uint8_t* cursor = static_cast<const uint8_t*>(data);
size_t remaining = size;
while (remaining > 0) {
const ssize_t sent =
::send(socket_fd, cursor, remaining, 0);
if (sent <= 0) {
return false;
}
cursor += static_cast<size_t>(sent);
remaining -= static_cast<size_t>(sent);
}
return true;
}
} // namespace borla