Add internet radio streaming with runtime API, modernize web UI, remove auto-tune/beep at boot

Streaming (main feature this session):
- New WebRadioConfig/WebRadioJson core types, ISecureStore-backed persistence
- New webradio::WebRadioService (thread-safe live config) + GET/POST /api/streaming
- web_radio_stream task now runtime-toggleable (no reboot), no hardcoded URL
- Content-Type diagnostic: warns clearly when a URL is a webpage, not an audio stream

Boot cleanup:
- Removed boot-time auto FM/DAB tune, auto-beep, and the (now-concluded) Si4684
  crystal IBIAS/CTUN empirical sweep from main.cpp — tuning/beep are on-demand
  via the existing REST API only

Web UI:
- Modernized styling (cards, gradients, toggle switches, light/dark theme)
- New Stream tab wired to /api/streaming

Fixes found via real idf.py build (not just clangd):
- Restored wrongly-removed si4684/Si4684Tuner.hpp include in main.cpp
- Fixed MP3Decode() argument types in web_radio_stream.cpp (unsigned char**/int*)

Quality-gate fixes:
- Host-test stub headers (esp_log.h, freertos/*) so TunerService.cpp's
  scanForStation logging/pacing compiles for station_service_test /
  integration_service_test instead of running stale binaries
- Added WifiScanner and WebRadioService manual sections; filled in missing
  Doxygen docs on BluetoothService, i2s_sdata_probe, test_firmware, Bt1035At
- Ignore clangd's .cache/ index directory

Also includes prior uncommitted work carried in the tree: Wi-Fi/Bluetooth
device scan REST API and UI (WifiScanner, BT scan), SigmaStudio TCP bridge,
and the current ADAU1701 SigmaStudio DSP program export.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-08 21:15:22 +02:00
co-authored by Claude Sonnet 5
parent 8a8523515d
commit 6f7b6dd12c
131 changed files with 20309 additions and 1702 deletions
+4 -1
View File
@@ -2,9 +2,12 @@ idf_component_register(
SRCS
"main.cpp"
"hardware_bootstrap.cpp"
"web_radio_stream.cpp"
"$<$<BOOL:${CONFIG_TEST_FIRMWARE}>:test_firmware.cpp>"
"$<$<BOOL:${CONFIG_I2S_SDATA_PROBE}>:i2s_sdata_probe.cpp>"
INCLUDE_DIRS "."
REQUIRES core net secure_store adau1701 si4684 tuner audio bt1035 bluetooth station integration ota eeprom24aa
REQUIRES core net secure_store adau1701 si4684 tuner audio bt1035 bluetooth station integration ota eeprom24aa webradio driver
PRIV_REQUIRES esp_timer esp_http_client
)
if(CONFIG_TEST_FIRMWARE)
+20
View File
@@ -0,0 +1,20 @@
menu "DigiRadio"
config TEST_FIRMWARE
bool "Run minimal test_firmware instead of app_main"
default n
help
Replaces normal boot with board/chip smoke tests (see test_firmware.cpp).
config I2S_SDATA_PROBE
bool "I2S SDATA capture probe (ADAU -> BT1035 data line)"
default n
help
One-shot boot-time capture: reconfigures board_pins::I2sDataOut (GPIO16)
as I2S slave RX (using the existing BCLK/LRCLK inputs) and logs whether
real, non-silent PCM content is present. Requires physically rewiring
GPIO16 from its old ESP32->ADAU MP1 net to the ADAU MP6->BT1035 PCM
input trace (or an equivalent test point) -- enabling this without the
rewire just reads whatever GPIO16 happens to be floating/connected to.
endmenu
+5 -2
View File
@@ -75,8 +75,6 @@ bt1035::Bt1035Driver gBt1035(
bt1035::Bt1035Pins{
.uartTx = board::pins::Bt1035UartTx,
.uartRx = board::pins::Bt1035UartRx,
.rtsGpio = board::pins::Bt1035Rts,
.ctsGpio = board::pins::Bt1035Cts,
.resetGpio = board::pins::Bt1035Reset,
.sysCtlGpio = board::pins::Bt1035SysCtl,
});
@@ -122,6 +120,11 @@ std::expected<void, HardwareBootError> HardwareBootstrap::boot()
if (auto audioResult = gAudioService.loadAndApply(); !audioResult) {
ESP_LOGW(kTag, "ADAU1701 profile apply failed");
}
if (auto radioMix = gAudioService.applyRadioFirstMix(false); !radioMix) {
ESP_LOGW(kTag, "ADAU1701 radio-first mix failed");
} else {
ESP_LOGI(kTag, "ADAU1701 Si4684 input routed (radio-first mix)");
}
if (auto btResult = gBt1035.boot(); !btResult) {
ESP_LOGE(kTag, "BT1035 boot failed");
+149
View File
@@ -0,0 +1,149 @@
/**
* @file i2s_sdata_probe.cpp
* @brief One-shot I2S slave RX capture to check for real audio on SDATA.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*/
#include "i2s_sdata_probe.hpp"
#include "board_pins.hpp"
#include "driver/i2s_std.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include <cstddef>
#include <cstdint>
namespace i2s_sdata_probe {
namespace {
constexpr char kTag[] = "i2s_sdata_probe";
constexpr int kSampleRateHz = 48000;
constexpr std::size_t kReadBufSamples = 512U;
// Top 24 bits carry ADAU audio data in a 32-bit slot (see former
// esp32_i2s_tone.cpp); a few % of full scale is already audible content.
constexpr std::int32_t kAudibleThreshold = 0x7FFFFFFF / 20; // ~5% FS
struct CaptureStats {
std::int32_t peak = 0;
std::uint32_t nonZeroSamples = 0U;
std::uint32_t totalSamples = 0U;
};
i2s_chan_handle_t openRxChannel()
{
i2s_chan_config_t chanCfg =
I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_SLAVE);
i2s_chan_handle_t rxHandle = nullptr;
if (i2s_new_channel(&chanCfg, nullptr, &rxHandle) != ESP_OK) {
ESP_LOGW(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=0x800 (64 BCLKs/frame),
// same format the removed esp32_i2s_tone.cpp used on the TX side.
.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 = I2S_GPIO_UNUSED,
.din = static_cast<gpio_num_t>(board::pins::I2sDataOut),
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false,
},
},
};
// Slave: BCLK/LRCLK driven by ADAU1701 master; no clock overrides needed.
if (i2s_channel_init_std_mode(rxHandle, &stdCfg) != ESP_OK
|| i2s_channel_enable(rxHandle) != ESP_OK) {
ESP_LOGW(kTag, "I2S RX channel init/enable failed");
i2s_del_channel(rxHandle);
return nullptr;
}
ESP_LOGI(kTag, "I2S slave RX started (BCLK=%d WS=%d DIN=%d)",
board::pins::I2sBclk, board::pins::I2sLrclk,
board::pins::I2sDataOut);
return rxHandle;
}
void accumulateSamples(const std::int32_t* buf, std::size_t count,
CaptureStats& stats)
{
for (std::size_t i = 0U; i < count; ++i) {
const std::int32_t value = buf[i];
const std::int32_t absValue = value < 0 ? -value : value;
if (absValue > stats.peak) {
stats.peak = absValue;
}
if (value != 0) {
++stats.nonZeroSamples;
}
}
stats.totalSamples += static_cast<std::uint32_t>(count);
}
CaptureStats sampleWindow(i2s_chan_handle_t rxHandle, int windowMs)
{
CaptureStats stats;
std::int32_t buf[kReadBufSamples];
const std::int64_t startUs = esp_timer_get_time();
const std::int64_t targetUs = static_cast<std::int64_t>(windowMs) * 1000;
while (esp_timer_get_time() - startUs < targetUs) {
std::size_t bytesRead = 0U;
const esp_err_t err = i2s_channel_read(rxHandle, buf, sizeof(buf),
&bytesRead, pdMS_TO_TICKS(50));
if (err != ESP_OK || bytesRead == 0U) {
continue;
}
accumulateSamples(buf, bytesRead / sizeof(std::int32_t), stats);
}
return stats;
}
const char* verdictFor(const CaptureStats& stats)
{
if (stats.totalSamples == 0U || stats.nonZeroSamples == 0U) {
return "SILENT — dead/zero line on GPIO16";
}
return stats.peak >= kAudibleThreshold
? "real audio-level content"
: "activity present but very low amplitude";
}
} // namespace
void captureAndLog(int windowMs)
{
i2s_chan_handle_t rxHandle = openRxChannel();
if (rxHandle == nullptr) {
return;
}
const CaptureStats stats = sampleWindow(rxHandle, windowMs);
i2s_channel_disable(rxHandle);
i2s_del_channel(rxHandle);
ESP_LOGI(kTag, "SDATA capture: %u samples, peak=%ld, nonzero=%u/%u -> %s",
static_cast<unsigned>(stats.totalSamples),
static_cast<long>(stats.peak),
static_cast<unsigned>(stats.nonZeroSamples),
static_cast<unsigned>(stats.totalSamples), verdictFor(stats));
}
} // namespace i2s_sdata_probe
+24
View File
@@ -0,0 +1,24 @@
/**
* @file i2s_sdata_probe.hpp
* @brief One-shot I2S slave RX capture to check for real audio on SDATA.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
namespace i2s_sdata_probe {
/**
* Capture I2S slave RX on board_pins BCLK/LRCLK/I2sDataOut for windowMs and
* log whether real, non-silent PCM content is present. Requires GPIO16
* (I2sDataOut) to be physically rewired from its old ESP32->ADAU MP1 net to
* the line under test (e.g. ADAU MP6 -> BT1035 PCM input).
*
* @param windowMs Capture duration in milliseconds.
*/
void captureAndLog(int windowMs);
} // namespace i2s_sdata_probe
+1
View File
@@ -15,3 +15,4 @@ dependencies:
# # All dependencies of `main` are public by default.
# public: true
espressif/mdns: '*'
chmorgan/esp-libhelix-mp3: ^1.0.3
+122 -6
View File
@@ -11,7 +11,9 @@
* @date 2026-07-06
*/
#include "board_pins.hpp"
#include "hardware_bootstrap.hpp"
#include "audio/AudioService.hpp"
#include "bluetooth/BluetoothService.hpp"
#include "integration/IntegrationService.hpp"
#include "net/NetBootstrap.hpp"
@@ -21,20 +23,104 @@
#include "si4684/Si4684Tuner.hpp"
#include "station/StationService.hpp"
#include "tuner/TunerService.hpp"
#include "web_radio_stream.hpp"
#include "webradio/WebRadioService.hpp"
#include "driver/pulse_cnt.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <cstdint>
#if CONFIG_TEST_FIRMWARE
#include "test_firmware.hpp"
#endif
#if CONFIG_I2S_SDATA_PROBE
#include "i2s_sdata_probe.hpp"
#endif
namespace {
constexpr char kTag[] = "digiradio";
constexpr TickType_t kHeartbeatPeriod = pdMS_TO_TICKS(5000);
/**
* @brief logGpioClockFrequency — one-shot edge-count frequency probe.
*
* Uses the ESP32-S3 PCNT peripheral to count rising edges on an input GPIO
* over a fixed window and log the resulting frequency, so BCLK/LRCLK on the
* ADAU1701 -> ESP32 I2S bus (board::pins::I2sBclk/I2sLrclk, shared clock
* domain with the ADAU -> BT1035 link, see docs/manual/ch-bt1035.tex) can be
* verified without an oscilloscope. Read-only: the PCNT channel only listens
* on the pad, so it does not conflict with the I2S peripheral also reading
* the same GPIO later (ESP32 GPIO matrix fans one input pad out to multiple
* peripherals). windowMs must stay short enough that expected edge count
* does not exceed the PCNT hardware limit (signed 16-bit, so < 32767).
*/
void logGpioClockFrequency(const char* label, int gpio, int windowMs)
{
pcnt_unit_config_t unitConfig{};
unitConfig.low_limit = -1;
unitConfig.high_limit = 30000;
pcnt_unit_handle_t unit = nullptr;
if (pcnt_new_unit(&unitConfig, &unit) != ESP_OK) {
ESP_LOGW(kTag, "%s clock probe: pcnt_new_unit failed", label);
return;
}
pcnt_chan_config_t chanConfig{};
chanConfig.edge_gpio_num = gpio;
chanConfig.level_gpio_num = -1;
pcnt_channel_handle_t chan = nullptr;
if (pcnt_new_channel(unit, &chanConfig, &chan) != ESP_OK) {
ESP_LOGW(kTag, "%s clock probe: pcnt_new_channel failed (GPIO%d)",
label, gpio);
pcnt_del_unit(unit);
return;
}
pcnt_channel_set_edge_action(chan, PCNT_CHANNEL_EDGE_ACTION_INCREASE,
PCNT_CHANNEL_EDGE_ACTION_HOLD);
pcnt_unit_enable(unit);
pcnt_unit_clear_count(unit);
pcnt_unit_start(unit);
// Busy-wait on esp_timer instead of vTaskDelay: at the default 100 Hz
// FreeRTOS tick rate, a short requested window (e.g. 5-10 ms for BCLK)
// rounds to the nearest 10 ms tick, which is a huge relative error at
// MHz-range signals. Measuring the *actual* elapsed time afterwards
// makes the frequency calculation correct regardless of overshoot.
const std::int64_t startUs = esp_timer_get_time();
const std::int64_t targetUs = static_cast<std::int64_t>(windowMs) * 1000;
while (esp_timer_get_time() - startUs < targetUs) {
// intentionally tight: window is a few ms to a few hundred ms,
// far under any watchdog timeout.
}
pcnt_unit_stop(unit);
const std::int64_t elapsedUs = esp_timer_get_time() - startUs;
int count = 0;
pcnt_unit_get_count(unit, &count);
pcnt_del_channel(chan);
pcnt_unit_disable(unit);
pcnt_del_unit(unit);
const long freqHz = elapsedUs > 0
? static_cast<long>((static_cast<std::int64_t>(count) * 1000000LL)
/ elapsedUs)
: 0;
const bool nearSaturation = count >= (unitConfig.high_limit * 9) / 10;
ESP_LOGI(kTag, "%s clock probe: GPIO%d = %ld edges / %lld us -> ~%ld Hz%s",
label, gpio, static_cast<long>(count),
static_cast<long long>(elapsedUs), freqHz,
nearSaturation ? " (near PCNT limit — window too long for this "
"clock, re-run with a shorter windowMs)"
: "");
}
void heartbeatTask(void* arg)
{
(void)arg;
@@ -65,6 +151,18 @@ extern "C" void app_main()
return;
}
ESP_LOGI(kTag, "==== ADAU1701 I2S clock probe (no scope needed) ====");
// 500 ms: at 44.1-48 kHz this stays under the 16-bit PCNT limit
// (~24000 counts) while keeping tick/overhead error under ~1%.
logGpioClockFrequency("LRCLK", board::pins::I2sLrclk, 500);
// 10 ms: BCLK is in the MHz range (Nx LRCLK), so the window must be
// short enough that expected edges stay under the PCNT limit.
logGpioClockFrequency("BCLK", board::pins::I2sBclk, 10);
#if CONFIG_I2S_SDATA_PROBE
i2s_sdata_probe::captureAndLog(500);
#endif
#if CONFIG_TEST_FIRMWARE
test_firmware::runTestFirmware();
return;
@@ -93,10 +191,12 @@ extern "C" void app_main()
}
static bluetooth::BluetoothService bluetoothService(
hardware::HardwareBootstrap::bt1035Driver());
hardware::HardwareBootstrap::bt1035Driver(), store);
static ota::OtaService otaService;
static webradio::WebRadioService webRadioService(store);
auto netResult = net::NetBootstrap::start(
store,
tunerService,
@@ -105,6 +205,7 @@ extern "C" void app_main()
stationService,
integration,
otaService,
webRadioService,
hardware::HardwareBootstrap::companionChipStatus(),
hardware::HardwareBootstrap::deviceIdentity());
if (!netResult) {
@@ -118,17 +219,32 @@ extern "C" void app_main()
ESP_LOGW(kTag, "OTA rollback confirm failed");
}
if (xTaskCreate(heartbeatTask, "heartbeat", 2048, nullptr, 5, nullptr)
if (xTaskCreate(heartbeatTask, "heartbeat", 4096, nullptr, 5, nullptr)
!= pdPASS) {
ESP_LOGE(kTag, "heartbeat task create failed");
return;
}
bluetoothService.startupReconnect();
if (xTaskCreate(web_radio_stream::run, "web_radio", 16384,
&webRadioService, 4, nullptr) != pdPASS) {
ESP_LOGW(kTag, "web radio stream task create failed");
}
if (net.state() == net::NetState::StaConnected) {
ESP_LOGI(kTag, "running in STA mode — open http://<device-ip>/");
} else {
const auto& identity = hardware::HardwareBootstrap::deviceIdentity();
ESP_LOGI(kTag,
"running in setup mode — join DigiRadio-setup, "
"open http://192.168.4.1/");
"running in STA mode — open http://%.*s.local/ "
"(or check serial for IP)",
static_cast<int>(identity.hostname().size()),
identity.hostname().data());
} else {
const auto& identity = hardware::HardwareBootstrap::deviceIdentity();
ESP_LOGI(kTag,
"running in setup mode — join %.*s, "
"open http://192.168.4.1/",
static_cast<int>(identity.softApSsid().size()),
identity.softApSsid().data());
}
}
+6 -5
View File
@@ -124,8 +124,6 @@ void runTestFirmware()
bt1035::Bt1035Pins{
.uartTx = board::pins::Bt1035UartTx,
.uartRx = board::pins::Bt1035UartRx,
.rtsGpio = board::pins::Bt1035Rts,
.ctsGpio = board::pins::Bt1035Cts,
.resetGpio = board::pins::Bt1035Reset,
.sysCtlGpio = board::pins::Bt1035SysCtl,
});
@@ -178,9 +176,12 @@ void runTestFirmware()
if (auto rsqResult = si4684.readFmRsq(); rsqResult) {
ESP_LOGI(kTag,
"FM RSQ: snr=%u, afc=%d, blend=%u, stere=%u, rssi=%d",
rsqResult->snr, rsqResult->afc, rsqResult->blend,
rsqResult->stere, rsqResult->rssi);
"FM RSQ: freq=%u kHz rssi=%d dBuV snr=%d dB valid=%d stereo=%d",
rsqResult->frequency ? rsqResult->frequency->value() : 0U,
static_cast<int>(rsqResult->rssiDbuV),
static_cast<int>(rsqResult->snrDb),
static_cast<int>(rsqResult->valid),
static_cast<int>(rsqResult->stereo));
} else {
logError("Si4684 read FM RSQ", static_cast<int>(rsqResult.error()));
}
+6
View File
@@ -11,6 +11,12 @@
namespace test_firmware {
/**
* Sequentially boots and smoke-tests each companion chip (ADAU1701,
* Si4684, BT1035) with serial log output, then halts. Entered from
* app_main() when CONFIG_TEST_FIRMWARE is enabled, instead of the
* normal boot path.
*/
void runTestFirmware();
} // namespace test_firmware
+263
View File
@@ -0,0 +1,263 @@
/**
* @file web_radio_stream.cpp
* @brief HTTP MP3 stream -> libhelix decode -> ADAU1701 I2S.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*/
#include "web_radio_stream.hpp"
#include "board_pins.hpp"
#include "webradio/WebRadioService.hpp"
#include "driver/i2s_std.h"
#include "esp_http_client.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "mp3dec.h"
#include <cstdint>
#include <cstring>
#include <string>
namespace web_radio_stream {
namespace {
constexpr char kTag[] = "web_radio";
constexpr int kSampleRateHz = 48000;
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);
/** Raw MP3 bytes pending decode, refilled from the HTTP socket. */
struct InputBuffer {
std::uint8_t data[kInputBufSize];
std::size_t filled = 0U;
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);
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{};
cfg.url = url.c_str();
cfg.timeout_ms = kHttpTimeoutMs;
esp_http_client_handle_t client = esp_http_client_init(&cfg);
if (client == nullptr) {
ESP_LOGE(kTag, "esp_http_client_init failed");
return nullptr;
}
if (esp_http_client_open(client, 0) != ESP_OK) {
ESP_LOGE(kTag, "esp_http_client_open failed: %s", url.c_str());
esp_http_client_cleanup(client);
return nullptr;
}
const int contentLength = esp_http_client_fetch_headers(client);
ESP_LOGI(kTag, "stream opened: %s (content-length=%d, status=%d)",
url.c_str(), contentLength,
esp_http_client_get_status_code(client));
char* contentType = nullptr;
if (esp_http_client_get_header(client, "Content-Type", &contentType)
== ESP_OK
&& contentType != nullptr
&& std::strncmp(contentType, "audio/", 6) != 0) {
ESP_LOGW(kTag,
"Content-Type '%s' is not audio/* -- this URL is probably "
"a website, not a direct MP3 stream link. Find the actual "
"stream endpoint (often ends in .mp3, or is listed as a "
"\"listen live\"/shoutcast/icecast URL on the station's "
"site) and set that instead.",
contentType);
}
return client;
}
/** Slide unread bytes to the front, then top up from the HTTP socket. */
void refill(esp_http_client_handle_t client, InputBuffer& in)
{
const std::size_t unread =
in.filled - static_cast<std::size_t>(in.readPtr - in.data);
std::memmove(in.data, in.readPtr, unread);
const int freeSpace = static_cast<int>(kInputBufSize - unread);
const int nRead = freeSpace > 0
? esp_http_client_read(client, reinterpret_cast<char*>(in.data)
+ unread,
freeSpace)
: 0;
in.filled = unread + (nRead > 0 ? static_cast<std::size_t>(nRead) : 0U);
in.readPtr = in.data;
}
/** Convert one decoded PCM frame to the ADAU's 32-bit-slot I2S format. */
void writeFrame(i2s_chan_handle_t tx, const std::int16_t* pcm,
int frameCount, int channels)
{
std::int32_t out[2];
for (int i = 0; i < frameCount; ++i) {
const std::int16_t left = pcm[i * channels];
const std::int16_t right = channels > 1 ? pcm[i * channels + 1] : left;
out[0] = static_cast<std::int32_t>(left) << 16;
out[1] = static_cast<std::int32_t>(right) << 16;
std::size_t written = 0U;
(void)i2s_channel_write(tx, out, sizeof(out), &written,
portMAX_DELAY);
}
}
/**
* One refill+decode+play cycle.
* @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)
{
const std::size_t unread =
in.filled - static_cast<std::size_t>(in.readPtr - in.data);
if (unread < MAINBUF_SIZE) {
refill(client, in);
}
const std::size_t available =
in.filled - static_cast<std::size_t>(in.readPtr - in.data);
if (available == 0U) {
return false;
}
const int offset =
MP3FindSyncWord(in.readPtr, static_cast<int>(available));
if (offset < 0) {
in.readPtr += available; // no sync word in this chunk, drop it
return true;
}
in.readPtr += offset;
unsigned char* decodePtr = in.readPtr;
int bytesLeft = static_cast<int>(available - static_cast<std::size_t>(offset));
const int err =
MP3Decode(decoder, &decodePtr, &bytesLeft, pcmOut, 0);
in.readPtr = decodePtr;
if (err != ERR_MP3_NONE) {
if (err == ERR_MP3_MAINDATA_UNDERFLOW) {
return true; // needs more bytes; try again next cycle
}
ESP_LOGW(kTag, "MP3 decode error %d, resyncing", err);
return true;
}
MP3FrameInfo info{};
MP3GetLastFrameInfo(decoder, &info);
if (!loggedFormat) {
loggedFormat = true;
ESP_LOGI(kTag, "stream format: %d Hz, %d ch, %d bps%s", info.samprate,
info.nChans, info.bitsPerSample,
info.samprate != kSampleRateHz
? " (WARNING: != 48000 Hz, no resampler -> pitch off)"
: "");
}
const int frameCount = info.outputSamps / info.nChans;
writeFrame(tx, 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)
{
esp_http_client_handle_t client = openStream(url);
if (client == nullptr) {
vTaskDelay(kReconnectDelay);
return;
}
InputBuffer in;
bool loggedFormat = false;
while (service.config().enabled
&& pumpOneFrame(client, decoder, tx, in, pcmOut, loggedFormat)) {
// keep pumping until disabled, the stream ends, or it drops
}
esp_http_client_close(client);
esp_http_client_cleanup(client);
}
} // namespace
void run(void* arg)
{
auto* service = static_cast<webradio::WebRadioService*>(arg);
i2s_chan_handle_t tx = openTxChannel();
if (tx == nullptr) {
vTaskDelete(nullptr);
return;
}
HMP3Decoder decoder = MP3InitDecoder();
if (decoder == nullptr) {
ESP_LOGE(kTag, "MP3InitDecoder failed");
vTaskDelete(nullptr);
return;
}
static std::int16_t pcmOut[MAX_NCHAN * MAX_NGRAN * MAX_NSAMP];
while (true) {
const core::WebRadioConfig cfg = service->config();
if (!cfg.enabled) {
vTaskDelay(kIdlePollDelay);
continue;
}
streamWhileEnabled(*service, cfg.url, decoder, tx, pcmOut);
}
}
} // namespace web_radio_stream
+31
View File
@@ -0,0 +1,31 @@
/**
* @file web_radio_stream.hpp
* @brief HTTP MP3 stream -> libhelix decode -> ADAU1701 I2S.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
namespace webradio {
class WebRadioService;
} // namespace webradio
namespace web_radio_stream {
/**
* Task entry point: polls webradio::WebRadioService for the enabled flag
* and URL, connects when enabled, decodes MP3 to PCM with libhelix-mp3,
* and writes it to the ADAU1701 over I2S slave TX (board_pins
* BCLK/LRCLK/I2sDataOut). Idles when disabled, reconnects on stream drop,
* and re-reads the config on every frame so a UI/API toggle takes effect
* without a reboot. Loops forever — run it in its own FreeRTOS task with
* arg pointing at a live WebRadioService.
*
* @param arg webradio::WebRadioService* — must outlive this task.
*/
void run(void* arg);
} // namespace web_radio_stream