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
+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();
}
}