Files
aes67-ESP32-P4/components/spotify/spotify.cpp
T
bsncubed 4a38254660 Step 7.5b3b: Spotify audio on AES67
- spotify_init(pcm_cb, event_cb): cspot's data callback hands 44.1 kHz
  stereo s16 PCM to the player and returns what was taken; the player's
  blocking ring write paces decoding to playback speed.
- Events: FLUSH/SEEK/PLAYBACK_START empty the ring (skip/seek sound at
  once); PLAY_PAUSE pauses output (silence, buffer kept, no underrun);
  VOLUME logged (applied in b4).
- player: Spotify via its own audio_out converter (44.1 -> 48 kHz);
  source_state playing / paused / buffering.
- Verified from a Mac: music on the AES67 stream (10 s: 0 gaps, no
  silent packets, RMS -9.6 dBFS, peak 0.0 dBFS), buffer 4.0 s full,
  0 underruns, pause/play/skip/seek events.
  Seen: first 3 connects "Can't connect to spotify servers", 4th worked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:41:49 +10:00

286 lines
9.9 KiB
C++

#include "spotify.h"
#include <atomic>
#include <cstring>
#include <exception>
#include <map>
#include <memory>
#include <string>
#include "BellLogger.h"
#include "CSpotContext.h"
#include "LoginBlob.h"
#include "SpircHandler.h"
#include "TrackPlayer.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "mdns.h"
extern "C" {
#include "aes67_cfg.h"
#include "aes67_web.h"
}
#define BODY_MAX 8192
static const char *TAG = "spotify";
static std::shared_ptr<cspot::LoginBlob> s_blob;
static std::atomic<bool> s_got_blob{false};
static std::atomic<const char *> s_state{"disabled"};
static std::atomic<uint64_t> s_pcm_bytes{0};
static spotify_pcm_cb_t s_pcm_cb;
static spotify_event_cb_t s_event_cb;
const char *spotify_state(void)
{
return s_state.load();
}
/* ----- cspot/bell logging -> esp_log (UART + syslog) ----- */
// cspot logs through bell::bellGlobalLogger; without one, CSPOT_LOG dereferences NULL.
class EspLogger : public bell::AbstractLogger {
static void out(esp_log_level_t lvl, const std::string &file, int line, const std::string &sub,
const char *fmt, va_list ap)
{
char msg[256];
vsnprintf(msg, sizeof(msg), fmt, ap);
// CDN URLs carry signed tokens: keep them out of the log (syslog may leave the box).
char *q = strstr(msg, "?__token__=");
if (q) {
strcpy(q, "?__token__=...");
}
size_t slash = file.find_last_of('/');
const char *base = file.c_str() + (slash == std::string::npos ? 0 : slash + 1);
ESP_LOG_LEVEL(lvl, sub.empty() ? "cspot" : sub.c_str(), "%s:%d: %s", base, line, msg);
}
public:
void debug(std::string file, int line, std::string sub, const char *fmt, ...) override
{
va_list ap;
va_start(ap, fmt);
out(ESP_LOG_DEBUG, file, line, sub, fmt, ap);
va_end(ap);
}
void info(std::string file, int line, std::string sub, const char *fmt, ...) override
{
va_list ap;
va_start(ap, fmt);
out(ESP_LOG_INFO, file, line, sub, fmt, ap);
va_end(ap);
}
void error(std::string file, int line, std::string sub, const char *fmt, ...) override
{
va_list ap;
va_start(ap, fmt);
out(ESP_LOG_ERROR, file, line, sub, fmt, ap);
va_end(ap);
}
};
/* ----- zeroconf (Spotify Connect discovery) on our httpd ----- */
static esp_err_t info_get(httpd_req_t *req)
{
std::string json = s_blob->buildZeroconfInfo();
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, json.data(), json.size());
}
static std::string url_decode(const char *s, size_t n)
{
std::string out;
for (size_t i = 0; i < n; i++) {
if (s[i] == '+') {
out += ' ';
} else if (s[i] == '%' && i + 2 < n && isxdigit((unsigned char)s[i + 1]) && isxdigit((unsigned char)s[i + 2])) {
char hex[3] = { s[i + 1], s[i + 2], 0 };
out += (char)strtol(hex, nullptr, 16);
i += 2;
} else {
out += s[i];
}
}
return out;
}
// The Spotify app posts its login blob (action=addUser&userName=...&blob=...&clientKey=...).
static esp_err_t info_post(httpd_req_t *req)
{
if (req->content_len == 0 || req->content_len > BODY_MAX) {
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad body");
}
std::string body(req->content_len, '\0');
size_t got = 0;
while (got < body.size()) {
int r = httpd_req_recv(req, body.data() + got, body.size() - got);
if (r <= 0) {
return ESP_FAIL;
}
got += r;
}
std::map<std::string, std::string> query;
size_t pos = 0;
while (pos < body.size()) {
size_t amp = body.find('&', pos), end = amp == std::string::npos ? body.size() : amp;
size_t eq = body.find('=', pos);
if (eq != std::string::npos && eq < end) {
query[url_decode(&body[pos], eq - pos)] = url_decode(&body[eq + 1], end - eq - 1);
}
pos = end + 1;
}
ESP_LOGI(TAG, "zeroconf %s from \"%s\"", query["action"].c_str(), query["userName"].c_str());
s_blob->loadZeroconfQuery(query);
s_got_blob = true;
static const char ok[] = "{\"status\":101,\"spotifyError\":0,\"statusString\":\"ERROR-OK\"}";
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, ok, sizeof(ok) - 1);
}
/* ----- session ----- */
static const char *event_name(cspot::SpircHandler::EventType t)
{
using E = cspot::SpircHandler::EventType;
switch (t) {
case E::PLAY_PAUSE: return "PLAY_PAUSE";
case E::VOLUME: return "VOLUME";
case E::TRACK_INFO: return "TRACK_INFO";
case E::DISC: return "DISC";
case E::NEXT: return "NEXT";
case E::PREV: return "PREV";
case E::SEEK: return "SEEK";
case E::DEPLETED: return "DEPLETED";
case E::FLUSH: return "FLUSH";
case E::PLAYBACK_START: return "PLAYBACK_START";
}
return "?";
}
static void session(void)
{
cJSON *src = cfg_get("source");
std::string client_id = cJSON_GetObjectItemCaseSensitive(src, "spotify_client_id")->valuestring;
std::string client_secret = cJSON_GetObjectItemCaseSensitive(src, "spotify_client_secret")->valuestring;
int bitrate = (int)cJSON_GetObjectItemCaseSensitive(src, "spotify_bitrate")->valuedouble;
cJSON_Delete(src);
auto ctx = cspot::Context::createFromBlob(s_blob);
ctx->config.clientId = client_id;
ctx->config.clientSecret = client_secret;
ctx->config.audioFormat = bitrate >= 320 ? AudioFormat_OGG_VORBIS_320
: bitrate >= 160 ? AudioFormat_OGG_VORBIS_160 : AudioFormat_OGG_VORBIS_96;
s_state = "connecting";
ctx->session->connectWithRandomAp();
auto token = ctx->session->authenticate(s_blob);
if (token.empty()) {
s_state = "login failed";
ESP_LOGE(TAG, "login failed (check the client ID/secret and that the account is Premium)");
return;
}
ctx->session->startTask();
auto handler = std::make_shared<cspot::SpircHandler>(ctx);
handler->subscribeToMercury();
// PCM (44.1 kHz stereo s16) to the player; returning fewer bytes makes cspot retry the rest,
// so the player's blocking write paces decoding to playback speed.
handler->getTrackPlayer()->setDataCallback([](uint8_t *data, size_t len, std::string_view id) -> size_t {
size_t frames = len / 4;
size_t taken = s_pcm_cb ? s_pcm_cb(reinterpret_cast<const int16_t *>(data), frames) : frames;
s_pcm_bytes += taken * 4;
return taken * 4;
});
handler->setEventHandler([](std::unique_ptr<cspot::SpircHandler::Event> ev) {
using E = cspot::SpircHandler::EventType;
switch (ev->eventType) {
case E::TRACK_INFO: {
auto &ti = std::get<cspot::TrackInfo>(ev->data);
ESP_LOGI(TAG, "track: %s - %s (%lu ms)", ti.artist.c_str(), ti.name.c_str(), (unsigned long)ti.duration);
return;
}
case E::PLAY_PAUSE:
if (s_event_cb) {
s_event_cb(std::get<bool>(ev->data) ? SPOTIFY_EV_PAUSE : SPOTIFY_EV_PLAY, 0);
}
break;
case E::FLUSH:
case E::SEEK:
case E::PLAYBACK_START:
if (s_event_cb) {
s_event_cb(SPOTIFY_EV_FLUSH, 0);
if (ev->eventType == E::PLAYBACK_START) {
s_event_cb(SPOTIFY_EV_PLAY, 0);
}
}
break;
case E::VOLUME:
if (s_event_cb) {
s_event_cb(SPOTIFY_EV_VOLUME, std::get<int>(ev->data));
}
break;
default:
break;
}
ESP_LOGI(TAG, "event %s", event_name(ev->eventType));
});
s_state = "connected";
ESP_LOGI(TAG, "connected as %s", ctx->config.username.c_str());
while (true) {
ctx->session->handlePacket();
}
}
static void spotify_task(void *arg)
{
while (true) {
s_state = "waiting for Spotify app";
while (!s_got_blob) {
vTaskDelay(pdMS_TO_TICKS(500));
}
s_got_blob = false;
try {
session();
} catch (const std::exception &e) {
s_state = "error";
ESP_LOGE(TAG, "session ended: %s", e.what());
}
vTaskDelay(pdMS_TO_TICKS(2000));
}
}
extern "C" esp_err_t spotify_init(spotify_pcm_cb_t pcm, spotify_event_cb_t event)
{
s_pcm_cb = pcm;
s_event_cb = event;
if (!bell::bellGlobalLogger) {
bell::bellGlobalLogger = new EspLogger();
}
cJSON *src = cfg_get("source");
std::string mode = cJSON_GetObjectItemCaseSensitive(src, "mode")->valuestring;
std::string name = cJSON_GetObjectItemCaseSensitive(src, "spotify_name")->valuestring;
bool creds = cJSON_GetObjectItemCaseSensitive(src, "spotify_client_id")->valuestring[0] &&
cJSON_GetObjectItemCaseSensitive(src, "spotify_client_secret")->valuestring[0];
cJSON_Delete(src);
if (mode != "spotify" && mode != "auto") {
s_state = "disabled (source mode)";
return ESP_OK;
}
if (!creds) {
s_state = "no client credentials";
ESP_LOGW(TAG, "not started: set the Spotify client ID and secret (web UI, Source)");
return ESP_OK;
}
s_blob = std::make_shared<cspot::LoginBlob>(name);
static const httpd_uri_t get = { .uri = "/spotify_info", .method = HTTP_GET, .handler = info_get, .user_ctx = nullptr };
static const httpd_uri_t post = { .uri = "/spotify_info", .method = HTTP_POST, .handler = info_post, .user_ctx = nullptr };
web_register_uri(&get);
web_register_uri(&post);
mdns_txt_item_t txt[] = { { "VERSION", "1.0" }, { "CPath", "/spotify_info" }, { "Stack", "SP" } };
esp_err_t err = mdns_service_add(name.c_str(), "_spotify-connect", "_tcp", 80, txt, 3);
ESP_LOGI(TAG, "Spotify Connect \"%s\" advertised (%s)", name.c_str(), esp_err_to_name(err));
return xTaskCreate(spotify_task, "spotify", 32 * 1024, nullptr, 5, nullptr) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}