#include "spotify.h" #include #include #include #include #include #include #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 s_blob; static std::atomic s_got_blob{false}; static std::atomic s_state{"disabled"}; static std::atomic 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 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(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(data), frames) : frames; s_pcm_bytes += taken * 4; return taken * 4; }); handler->setEventHandler([](std::unique_ptr ev) { using E = cspot::SpircHandler::EventType; switch (ev->eventType) { case E::TRACK_INFO: { auto &ti = std::get(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(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(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(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; }