Add PUT /api/stream/phone: raw PCM audio push from a phone app

New endpoint accepts chunked, header-less, 16-bit LE stereo PCM @ 48 kHz
in the request body and writes it straight to the shared I2S sink for as
long as the connection stays open. Chosen deliberately unencoded (no
MP3/AAC/Opus decode) to keep this path as simple and low-risk as
possible — the companion app controls the encoding on its side.

Extracted the I2S TX channel that used to be owned outright by
web_radio_stream.cpp into main/esp32_i2s_sink.cpp, shared by both
producers with a simple tryAcquire()/release() exclusivity guard — web
radio streaming and a phone PCM stream would otherwise fight over the
same physical wire. web_radio_stream.cpp now acquires/releases around
each streamWhileEnabled() cycle instead of owning the channel itself.

net::PhoneStreamSink is a plain function-pointer struct (not a class
hierarchy) threaded through NetBootstrap::start() -> SetupWebServer::start()
-> HttpRouteContext, so components/net stays free of I2S driver headers;
main/phone_stream.cpp supplies the concrete functions (bound to
esp32_i2s_sink) and does the int16->ADAU 32-bit-slot conversion, batched
per chunk rather than per sample for the same reason as the web radio
stutter fix (6974095/7e65394 lineage).

Verified by build only — not confirmed live yet (board disconnected this
session); the actual phone app that will exercise this endpoint doesn't
exist yet either.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178rASQ6ZETPMUamvpoR2KR
This commit is contained in:
2026-08-18 08:03:39 +02:00
co-authored by Claude Sonnet 5
parent 39984a97d1
commit e8f79c4b79
11 changed files with 394 additions and 70 deletions
@@ -86,6 +86,7 @@ public:
* @param integration Application orchestration for preset recall.
* @param ota Firmware OTA service for POST /api/system/ota.
* @param webRadio Streaming config for GET/POST /api/streaming.
* @param phoneStream I2S write-through for PUT /api/stream/phone.
* @param companionChips Boot flags exposed on GET /api/health.
* @param deviceIdentity EEPROM-derived SSID, hostname, and serial.
* @return NetBootstrap on success, or a NetError.
@@ -101,6 +102,7 @@ public:
integration::IntegrationService& integration,
ota::OtaService& ota,
webradio::WebRadioService& webRadio,
PhoneStreamSink& phoneStream,
core::CompanionChipStatus companionChips,
const core::DeviceIdentity& deviceIdentity);
@@ -24,6 +24,8 @@
#include "net/NetState.hpp"
#include "esp_http_server.h"
#include <cstddef>
#include <cstdint>
#include <expected>
namespace audio {
@@ -58,6 +60,31 @@ struct httpd_handle;
namespace net {
/**
* @brief PhoneStreamSink — plain function pointers over the shared I2S
* TX channel, so net/ (protocol-only) never includes I2S driver
* headers directly; main/esp32_i2s_sink.cpp supplies them.
*
* @dname PhoneStreamSink
* @return n/a (type)
* @pubstate All members are free functions with process lifetime; no
* per-instance state.
*
* @author Michele Bigi
* @date 2026-08-18
*/
struct PhoneStreamSink {
/** Claim exclusive use of the sink; false if already held (e.g. by
* the web radio stream). */
bool (*tryAcquire)();
/** Release a previously acquired claim. */
void (*release)();
/** Write one chunk of interleaved 16-bit stereo PCM @ 48 kHz.
* @return false on an I2S write error. */
bool (*writePcm16Stereo)(const std::int16_t* interleaved,
std::size_t frameCount);
};
/**
* @brief HttpRouteContext — dependencies injected into HTTP handlers.
*
@@ -78,6 +105,7 @@ struct HttpRouteContext {
integration::IntegrationService* integration; ///< Preset recall orchestration.
ota::OtaService* ota; ///< Firmware OTA streaming.
webradio::WebRadioService* webRadio; ///< Streaming config REST routes.
PhoneStreamSink* phoneStream; ///< PUT /api/stream/phone I2S write-through.
core::CompanionChipStatus companionChips; ///< Boot flags for /api/health.
core::DeviceIdentity deviceIdentity; ///< EEPROM-derived unit identity.
};
@@ -158,6 +186,7 @@ public:
* @param integration Application orchestration for preset recall.
* @param ota Firmware OTA service for POST /api/system/ota.
* @param webRadio Streaming config for GET/POST /api/streaming.
* @param phoneStream I2S write-through for PUT /api/stream/phone.
* @param companionChips Boot flags for GET /api/health.
* @param deviceIdentity Unit identity for /api/health serialNumber.
* @return Ok on success, or NetError::HttpServerStartFailed.
@@ -174,6 +203,7 @@ public:
integration::IntegrationService& integration,
ota::OtaService& ota,
webradio::WebRadioService& webRadio,
PhoneStreamSink& phoneStream,
core::CompanionChipStatus companionChips,
const core::DeviceIdentity& deviceIdentity);
+8 -4
View File
@@ -104,6 +104,7 @@ startSetupMode(core::ISecureStore& store, tuner::TunerService& tuner,
integration::IntegrationService& integration,
ota::OtaService& ota,
webradio::WebRadioService& webRadio,
PhoneStreamSink& phoneStream,
core::CompanionChipStatus companionChips,
const core::DeviceIdentity& deviceIdentity)
{
@@ -119,7 +120,7 @@ startSetupMode(core::ISecureStore& store, tuner::TunerService& tuner,
if (auto webResult =
webServer.start(store, NetState::SoftApSetup, tuner, audio,
bluetooth, stations, integration, ota, webRadio,
companionChips, deviceIdentity);
phoneStream, companionChips, deviceIdentity);
!webResult) {
return std::unexpected(webResult.error());
}
@@ -156,6 +157,7 @@ startStaMode(core::ISecureStore& store, tuner::TunerService& tuner,
integration::IntegrationService& integration,
ota::OtaService& ota,
webradio::WebRadioService& webRadio,
PhoneStreamSink& phoneStream,
core::CompanionChipStatus companionChips,
const core::DeviceIdentity& deviceIdentity)
{
@@ -186,7 +188,7 @@ startStaMode(core::ISecureStore& store, tuner::TunerService& tuner,
if (auto webResult =
webServer.start(store, NetState::StaConnected, tuner, audio,
bluetooth, stations, integration, ota, webRadio,
companionChips, deviceIdentity);
phoneStream, companionChips, deviceIdentity);
!webResult) {
return std::unexpected(webResult.error());
}
@@ -214,6 +216,7 @@ NetBootstrap::start(core::ISecureStore& store, tuner::TunerService& tuner,
integration::IntegrationService& integration,
ota::OtaService& ota,
webradio::WebRadioService& webRadio,
PhoneStreamSink& phoneStream,
core::CompanionChipStatus companionChips,
const core::DeviceIdentity& deviceIdentity)
{
@@ -227,7 +230,7 @@ NetBootstrap::start(core::ISecureStore& store, tuner::TunerService& tuner,
if (store.hasWifiCredentials()) {
auto staResult = startStaMode(store, tuner, audio, bluetooth, stations,
integration, ota, webRadio,
integration, ota, webRadio, phoneStream,
companionChips, deviceIdentity);
if (staResult) {
return staResult;
@@ -240,7 +243,8 @@ NetBootstrap::start(core::ISecureStore& store, tuner::TunerService& tuner,
}
return startSetupMode(store, tuner, audio, bluetooth, stations, integration,
ota, webRadio, companionChips, deviceIdentity);
ota, webRadio, phoneStream, companionChips,
deviceIdentity);
}
NetBootstrap::NetBootstrap(std::optional<SoftApHost> softAp,
@@ -56,6 +56,7 @@
#include "freertos/task.h"
#include <array>
#include <cstring>
#include <algorithm>
#include <cstdint>
#include <cstdio>
@@ -97,6 +98,7 @@ extern const uint8_t index_html_gz_end[] asm(
.integration = nullptr,
.ota = nullptr,
.webRadio = nullptr,
.phoneStream = nullptr,
.companionChips = {},
.deviceIdentity = core::DeviceIdentity::unknown(),
};
@@ -924,6 +926,74 @@ esp_err_t dspParamPutHandler(httpd_req_t* req)
return httpd_resp_send(req, json.c_str(), json.size());
}
/**
* @brief phoneStreamPutHandler — receive raw PCM audio from a phone app.
*
* @dname phoneStreamPutHandler
* @param req HTTP request handle from esp_http_server.
* @return ESP_OK on success, or an esp_err_t error code.
* @pubstate blocks for the lifetime of the connection, writing each chunk
* straight to the shared I2S sink; not part of AudioProfile,
* nothing persisted.
*
* Body: raw interleaved 16-bit little-endian PCM, stereo, 48 kHz, no
* header or framing — just samples. Send with chunked transfer encoding
* (no Content-Length needed) and close the connection to stop the stream.
* Rejected with 409 if the web radio stream (or another phone stream)
* currently owns the I2S sink.
*
* @author Michele Bigi
* @date 2026-08-18
*/
esp_err_t phoneStreamPutHandler(httpd_req_t* req)
{
auto* ctx = routeContextFrom(req);
if (ctx == nullptr || ctx->phoneStream == nullptr) {
httpd_resp_set_status(req, "503 Service Unavailable");
return httpd_resp_send(req, nullptr, 0);
}
if (!ctx->phoneStream->tryAcquire()) {
httpd_resp_set_status(req, "409 Conflict");
return httpd_resp_send(req, nullptr, 0);
}
constexpr std::size_t kFrameBytes = 4U; // int16 left + int16 right
std::array<char, 4096> chunk{};
std::array<std::int16_t, chunk.size() / sizeof(std::int16_t)> frames{};
std::size_t leftover = 0U; // always < kFrameBytes between reads
bool ok = true;
while (true) {
const int n = httpd_req_recv(req, chunk.data() + leftover,
chunk.size() - leftover);
if (n <= 0) {
break; // client closed the connection (or a real error) — done
}
const std::size_t available =
leftover + static_cast<std::size_t>(n);
const std::size_t usable = available - (available % kFrameBytes);
if (usable > 0U) {
std::memcpy(frames.data(), chunk.data(), usable);
if (!ctx->phoneStream->writePcm16Stereo(frames.data(),
usable / kFrameBytes)) {
ok = false;
break;
}
}
leftover = available - usable;
if (leftover > 0U) {
std::memmove(chunk.data(), chunk.data() + usable, leftover);
}
}
ctx->phoneStream->release();
if (!ok) {
httpd_resp_set_status(req, "500 Internal Server Error");
return httpd_resp_send(req, nullptr, 0);
}
return httpd_resp_send(req, nullptr, 0);
}
/**
* @brief streamingGetHandler — serve GET /api/streaming as JSON.
*
@@ -1794,6 +1864,7 @@ std::expected<void, NetError> SetupWebServer::start(
integration::IntegrationService& integration,
ota::OtaService& ota,
webradio::WebRadioService& webRadio,
PhoneStreamSink& phoneStream,
core::CompanionChipStatus companionChips,
const core::DeviceIdentity& deviceIdentity)
{
@@ -1817,6 +1888,7 @@ std::expected<void, NetError> SetupWebServer::start(
routeContext.integration = &integration;
routeContext.ota = &ota;
routeContext.webRadio = &webRadio;
routeContext.phoneStream = &phoneStream;
routeContext.companionChips = companionChips;
routeContext.deviceIdentity = deviceIdentity;
@@ -1989,6 +2061,14 @@ std::expected<void, NetError> SetupWebServer::start(
};
httpd_register_uri_handler(server_, &dspParamUri);
const httpd_uri_t phoneStreamUri = {
.uri = "/api/stream/phone",
.method = HTTP_PUT,
.handler = phoneStreamPutHandler,
.user_ctx = routeCtx,
};
httpd_register_uri_handler(server_, &phoneStreamUri);
const httpd_uri_t streamingGetUri = {
.uri = "/api/streaming",
.method = HTTP_GET,
+2
View File
@@ -3,6 +3,8 @@ idf_component_register(
"main.cpp"
"hardware_bootstrap.cpp"
"web_radio_stream.cpp"
"esp32_i2s_sink.cpp"
"phone_stream.cpp"
"$<$<BOOL:${CONFIG_TEST_FIRMWARE}>:test_firmware.cpp>"
"$<$<BOOL:${CONFIG_I2S_SDATA_PROBE}>:i2s_sdata_probe.cpp>"
INCLUDE_DIRS "."
+109
View File
@@ -0,0 +1,109 @@
/**
* @file esp32_i2s_sink.cpp
* @brief Shared ESP32 -> ADAU1701 I2S TX channel (web radio / phone stream).
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*/
#include "esp32_i2s_sink.hpp"
#include "board_pins.hpp"
#include "driver/i2s_std.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include <atomic>
namespace esp32_i2s_sink {
namespace {
constexpr char kTag[] = "i2s_sink";
constexpr int kSampleRateHz = 48000;
i2s_chan_handle_t gTxHandle = nullptr;
std::atomic<bool> gInUse{false};
} // namespace
bool open()
{
if (gTxHandle != nullptr) {
return true;
}
i2s_chan_config_t chanCfg =
I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_SLAVE);
// See main/web_radio_stream.cpp history: default (6 x 240 frames =
// ~30 ms) leaves almost no headroom against producer jitter (network
// stalls, HTTP scheduling); widen it for both producers that share
// this channel.
chanCfg.dma_desc_num = 12;
chanCfg.dma_frame_num = 480;
if (i2s_new_channel(&chanCfg, &gTxHandle, nullptr) != ESP_OK) {
ESP_LOGE(kTag, "i2s_new_channel failed");
gTxHandle = nullptr;
return false;
}
i2s_std_config_t stdCfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(kSampleRateHz),
// 32-bit slots match ADAU1701 SerialOutRegister1 (64 BCLKs/frame).
.slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(
I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO),
.gpio_cfg = {
.mclk = I2S_GPIO_UNUSED,
.bclk = static_cast<gpio_num_t>(board::pins::I2sBclk),
.ws = static_cast<gpio_num_t>(board::pins::I2sLrclk),
.dout = static_cast<gpio_num_t>(board::pins::I2sDataOut),
.din = I2S_GPIO_UNUSED,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false,
},
},
};
if (i2s_channel_init_std_mode(gTxHandle, &stdCfg) != ESP_OK
|| i2s_channel_enable(gTxHandle) != ESP_OK) {
ESP_LOGE(kTag, "I2S TX channel init/enable failed");
i2s_del_channel(gTxHandle);
gTxHandle = nullptr;
return false;
}
ESP_LOGI(kTag, "I2S slave TX started (BCLK=%d WS=%d DOUT=%d)",
board::pins::I2sBclk, board::pins::I2sLrclk,
board::pins::I2sDataOut);
return true;
}
bool tryAcquire()
{
bool expected = false;
return gInUse.compare_exchange_strong(expected, true);
}
void release()
{
gInUse.store(false);
}
bool writeSamples(const std::int32_t* samples, std::size_t sampleCount)
{
if (gTxHandle == nullptr) {
return false;
}
std::size_t written = 0U;
const esp_err_t err =
i2s_channel_write(gTxHandle, samples, sampleCount * sizeof(std::int32_t),
&written, portMAX_DELAY);
return err == ESP_OK;
}
} // namespace esp32_i2s_sink
+45
View File
@@ -0,0 +1,45 @@
/**
* @file esp32_i2s_sink.hpp
* @brief Shared ESP32 -> ADAU1701 I2S TX channel (web radio / phone stream).
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <cstddef>
#include <cstdint>
namespace esp32_i2s_sink {
/**
* Open the shared I2S TX channel (ESP32 as I2S slave, ADAU1701 as master)
* on first call; a no-op on later calls. Not thread-safe to call
* concurrently with itself — call once during boot.
* @return true on success.
*/
bool open();
/**
* Claim exclusive use of the channel for one producer (web radio stream or
* a phone PCM stream). Only one producer may hold it at a time, since both
* would otherwise fight over the same physical wire.
* @return true if acquired, false if another producer already holds it.
*/
bool tryAcquire();
/** Release a previously acquired claim. Safe to call even if not held. */
void release();
/**
* Write one frame's worth of already-32-bit-slot-formatted stereo samples
* (left, right pairs). Blocks until the DMA accepts the data.
* @param samples Interleaved L,R int32 samples (top-aligned 24-bit).
* @param sampleCount Number of int32 values in samples (2x frame count).
* @return true on success.
*/
bool writeSamples(const std::int32_t* samples, std::size_t sampleCount);
} // namespace esp32_i2s_sink
+8
View File
@@ -23,6 +23,8 @@
#include "si4684/Si4684Tuner.hpp"
#include "station/StationService.hpp"
#include "tuner/TunerService.hpp"
#include "esp32_i2s_sink.hpp"
#include "phone_stream.hpp"
#include "web_radio_stream.hpp"
#include "webradio/WebRadioService.hpp"
@@ -197,6 +199,11 @@ extern "C" void app_main()
static webradio::WebRadioService webRadioService(store);
if (!esp32_i2s_sink::open()) {
ESP_LOGW(kTag, "shared I2S sink open failed — web radio and phone "
"streaming will be unavailable");
}
auto netResult = net::NetBootstrap::start(
store,
tunerService,
@@ -206,6 +213,7 @@ extern "C" void app_main()
integration,
otaService,
webRadioService,
phone_stream::sink(),
hardware::HardwareBootstrap::companionChipStatus(),
hardware::HardwareBootstrap::deviceIdentity());
if (!netResult) {
+65
View File
@@ -0,0 +1,65 @@
/**
* @file phone_stream.cpp
* @brief net::PhoneStreamSink implementation over the shared I2S sink.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*/
#include "phone_stream.hpp"
#include "esp32_i2s_sink.hpp"
#include <array>
#include <cstdint>
namespace phone_stream {
namespace {
/** Convert one chunk of interleaved 16-bit stereo PCM to the ADAU's
* 32-bit-slot I2S format and hand it to the shared sink in one write,
* same rationale as web_radio_stream.cpp's writeFrame(): one
* i2s_channel_write() call per sample would be a needless source of
* jitter under sustained streaming. */
bool writePcm16Stereo(const std::int16_t* interleaved,
std::size_t frameCount)
{
constexpr std::size_t kMaxFramesPerCall = 1024U;
static std::int32_t out[kMaxFramesPerCall * 2U];
std::size_t offset = 0U;
while (offset < frameCount) {
const std::size_t batch =
(frameCount - offset) < kMaxFramesPerCall
? (frameCount - offset)
: kMaxFramesPerCall;
for (std::size_t i = 0U; i < batch; ++i) {
const std::int16_t left = interleaved[(offset + i) * 2U];
const std::int16_t right = interleaved[(offset + i) * 2U + 1U];
out[i * 2U] = static_cast<std::int32_t>(left) << 16;
out[i * 2U + 1U] = static_cast<std::int32_t>(right) << 16;
}
if (!esp32_i2s_sink::writeSamples(out, batch * 2U)) {
return false;
}
offset += batch;
}
return true;
}
} // namespace
net::PhoneStreamSink& sink() noexcept
{
static net::PhoneStreamSink instance{
.tryAcquire = &esp32_i2s_sink::tryAcquire,
.release = &esp32_i2s_sink::release,
.writePcm16Stereo = &writePcm16Stereo,
};
return instance;
}
} // namespace phone_stream
+26
View File
@@ -0,0 +1,26 @@
/**
* @file phone_stream.hpp
* @brief net::PhoneStreamSink implementation over the shared I2S sink.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "net/SetupWebServer.hpp"
namespace phone_stream {
/**
* @brief sink — the process-lifetime PhoneStreamSink instance.
*
* @dname sink
* @return Function-pointer table bound to esp32_i2s_sink, for
* net::HttpRouteContext::phoneStream / PUT /api/stream/phone.
* @pubstate none
*/
[[nodiscard]] net::PhoneStreamSink& sink() noexcept;
} // namespace phone_stream
+19 -66
View File
@@ -10,10 +10,9 @@
#include "web_radio_stream.hpp"
#include "board_pins.hpp"
#include "esp32_i2s_sink.hpp"
#include "webradio/WebRadioService.hpp"
#include "driver/i2s_std.h"
#include "esp_http_client.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
@@ -34,6 +33,8 @@ constexpr std::size_t kInputBufSize = 4096U; // >= 2x MAINBUF_SIZE (1940)
constexpr int kHttpTimeoutMs = 10000;
constexpr TickType_t kIdlePollDelay = pdMS_TO_TICKS(1000);
constexpr TickType_t kReconnectDelay = pdMS_TO_TICKS(5000);
/** How often to retry when a phone PCM stream currently owns the I2S sink. */
constexpr TickType_t kSinkBusyRetryDelay = pdMS_TO_TICKS(2000);
/** Raw MP3 bytes pending decode, refilled from the HTTP socket. */
struct InputBuffer {
@@ -42,53 +43,6 @@ struct InputBuffer {
std::uint8_t* readPtr = data;
};
[[nodiscard]] i2s_chan_handle_t openTxChannel()
{
i2s_chan_config_t chanCfg =
I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_SLAVE);
// Default (6 desc x 240 frames = 1440 frames = ~30 ms @ 48 kHz) leaves
// almost no headroom against network jitter in this single-task
// fetch+decode+play pipeline; widen it to ~120 ms so a brief HTTP
// stall doesn't immediately starve the I2S DMA and audibly crackle.
chanCfg.dma_desc_num = 12;
chanCfg.dma_frame_num = 480;
i2s_chan_handle_t txHandle = nullptr;
if (i2s_new_channel(&chanCfg, &txHandle, nullptr) != ESP_OK) {
ESP_LOGE(kTag, "i2s_new_channel failed");
return nullptr;
}
i2s_std_config_t stdCfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(kSampleRateHz),
// 32-bit slots match ADAU1701 SerialOutRegister1 (64 BCLKs/frame).
.slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(
I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO),
.gpio_cfg = {
.mclk = I2S_GPIO_UNUSED,
.bclk = static_cast<gpio_num_t>(board::pins::I2sBclk),
.ws = static_cast<gpio_num_t>(board::pins::I2sLrclk),
.dout = static_cast<gpio_num_t>(board::pins::I2sDataOut),
.din = I2S_GPIO_UNUSED,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false,
},
},
};
if (i2s_channel_init_std_mode(txHandle, &stdCfg) != ESP_OK
|| i2s_channel_enable(txHandle) != ESP_OK) {
ESP_LOGE(kTag, "I2S TX channel init/enable failed");
i2s_del_channel(txHandle);
return nullptr;
}
ESP_LOGI(kTag, "I2S slave TX started (BCLK=%d WS=%d DOUT=%d)",
board::pins::I2sBclk, board::pins::I2sLrclk,
board::pins::I2sDataOut);
return txHandle;
}
[[nodiscard]] esp_http_client_handle_t openStream(const std::string& url)
{
esp_http_client_config_t cfg{};
@@ -142,13 +96,12 @@ void refill(esp_http_client_handle_t client, InputBuffer& in)
}
/** Convert one decoded PCM frame to the ADAU's 32-bit-slot I2S format and
* hand the whole frame to the driver in a single write. One
* hand the whole frame to the shared sink in a single write. One
* i2s_channel_write() call per sample (the previous approach) meant up to
* 1152 separate driver calls per MP3 frame, each with its own locking/DMA
* bookkeeping overhead — a likely source of the reported stutter/crackle,
* independent of network jitter. */
void writeFrame(i2s_chan_handle_t tx, const std::int16_t* pcm,
int frameCount, int channels)
void writeFrame(const std::int16_t* pcm, int frameCount, int channels)
{
// MAX_NGRAN(2) * MAX_NSAMP(576) = 1152 samples/channel, stereo => 2304.
static std::int32_t out[MAX_NGRAN * MAX_NSAMP * 2];
@@ -161,11 +114,7 @@ void writeFrame(i2s_chan_handle_t tx, const std::int16_t* pcm,
out[i * 2] = static_cast<std::int32_t>(left) << 16;
out[i * 2 + 1] = static_cast<std::int32_t>(right) << 16;
}
std::size_t written = 0U;
(void)i2s_channel_write(tx, out,
static_cast<std::size_t>(sampleCount) * 2U
* sizeof(std::int32_t),
&written, portMAX_DELAY);
(void)esp32_i2s_sink::writeSamples(out, static_cast<std::size_t>(sampleCount) * 2U);
}
/**
@@ -173,9 +122,8 @@ void writeFrame(i2s_chan_handle_t tx, const std::int16_t* pcm,
* @return false when the stream has ended (caller should reconnect).
*/
[[nodiscard]] bool pumpOneFrame(esp_http_client_handle_t client,
HMP3Decoder decoder, i2s_chan_handle_t tx,
InputBuffer& in, std::int16_t* pcmOut,
bool& loggedFormat)
HMP3Decoder decoder, InputBuffer& in,
std::int16_t* pcmOut, bool& loggedFormat)
{
const std::size_t unread =
in.filled - static_cast<std::size_t>(in.readPtr - in.data);
@@ -220,14 +168,14 @@ void writeFrame(i2s_chan_handle_t tx, const std::int16_t* pcm,
: "");
}
const int frameCount = info.outputSamps / info.nChans;
writeFrame(tx, pcmOut, frameCount, info.nChans);
writeFrame(pcmOut, frameCount, info.nChans);
return true;
}
/** Stream until the config is disabled or the connection drops. */
void streamWhileEnabled(webradio::WebRadioService& service,
const std::string& url, HMP3Decoder decoder,
i2s_chan_handle_t tx, std::int16_t* pcmOut)
std::int16_t* pcmOut)
{
esp_http_client_handle_t client = openStream(url);
if (client == nullptr) {
@@ -238,7 +186,7 @@ void streamWhileEnabled(webradio::WebRadioService& service,
InputBuffer in;
bool loggedFormat = false;
while (service.config().enabled
&& pumpOneFrame(client, decoder, tx, in, pcmOut, loggedFormat)) {
&& pumpOneFrame(client, decoder, in, pcmOut, loggedFormat)) {
// keep pumping until disabled, the stream ends, or it drops
}
@@ -252,8 +200,7 @@ void run(void* arg)
{
auto* service = static_cast<webradio::WebRadioService*>(arg);
i2s_chan_handle_t tx = openTxChannel();
if (tx == nullptr) {
if (!esp32_i2s_sink::open()) {
vTaskDelete(nullptr);
return;
}
@@ -273,7 +220,13 @@ void run(void* arg)
vTaskDelay(kIdlePollDelay);
continue;
}
streamWhileEnabled(*service, cfg.url, decoder, tx, pcmOut);
if (!esp32_i2s_sink::tryAcquire()) {
// A phone PCM stream currently owns the shared I2S sink.
vTaskDelay(kSinkBusyRetryDelay);
continue;
}
streamWhileEnabled(*service, cfg.url, decoder, pcmOut);
esp32_i2s_sink::release();
}
}