Shim.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /*
  2. * This software is released under the MIT License.
  3. * https://opensource.org/licenses/MIT
  4. *
  5. */
  6. #include <string>
  7. #include <streambuf>
  8. #include <Session.h>
  9. #include <PlainConnection.h>
  10. #include <memory>
  11. #include <vector>
  12. #include <iostream>
  13. #include <inttypes.h>
  14. #include <fstream>
  15. #include <stdarg.h>
  16. #include <ApResolve.h>
  17. #include "MDNSService.h"
  18. #include "SpircHandler.h"
  19. #include "LoginBlob.h"
  20. #include "CentralAudioBuffer.h"
  21. #include "Logger.h"
  22. #include "Utils.h"
  23. #include "esp_http_server.h"
  24. #include "cspot_private.h"
  25. #include "cspot_sink.h"
  26. #include "platform_config.h"
  27. #include "tools.h"
  28. static class cspotPlayer *player;
  29. /****************************************************************************************
  30. * Chunk manager class (task)
  31. */
  32. class chunkManager : public bell::Task {
  33. public:
  34. std::atomic<bool> isRunning = true;
  35. std::atomic<bool> isPaused = true;
  36. std::atomic<bool> discard = true;
  37. chunkManager(std::shared_ptr<bell::CentralAudioBuffer> centralAudioBuffer, std::function<void()> trackHandler,
  38. std::function<void(const uint8_t*, size_t)> dataHandler);
  39. void teardown();
  40. private:
  41. std::shared_ptr<bell::CentralAudioBuffer> centralAudioBuffer;
  42. std::function<void()> trackHandler;
  43. std::function<void(const uint8_t*, size_t)> dataHandler;
  44. std::mutex runningMutex;
  45. void runTask() override;
  46. };
  47. chunkManager::chunkManager(std::shared_ptr<bell::CentralAudioBuffer> centralAudioBuffer,
  48. std::function<void()> trackHandler, std::function<void(const uint8_t*, size_t)> dataHandler)
  49. : bell::Task("chunker", 4 * 1024, 0, 0) {
  50. this->centralAudioBuffer = centralAudioBuffer;
  51. this->trackHandler = trackHandler;
  52. this->dataHandler = dataHandler;
  53. startTask();
  54. }
  55. void chunkManager::teardown() {
  56. isRunning = false;
  57. std::scoped_lock lock(runningMutex);
  58. }
  59. void chunkManager::runTask() {
  60. std::scoped_lock lock(runningMutex);
  61. size_t lastHash = 0;
  62. while (isRunning) {
  63. if (isPaused) {
  64. BELL_SLEEP_MS(100);
  65. continue;
  66. }
  67. auto chunk = centralAudioBuffer->readChunk();
  68. if (!chunk || chunk->pcmSize == 0) {
  69. BELL_SLEEP_MS(50);
  70. continue;
  71. }
  72. // receiving first chunk of new track from Spotify server
  73. if (lastHash != chunk->trackHash) {
  74. CSPOT_LOG(info, "hash update %x => %x", lastHash, chunk->trackHash);
  75. lastHash = chunk->trackHash;
  76. discard = false;
  77. trackHandler();
  78. }
  79. if (!discard) dataHandler(chunk->pcmData, chunk->pcmSize);
  80. }
  81. }
  82. /****************************************************************************************
  83. * Player's main class & task
  84. */
  85. class cspotPlayer : public bell::Task {
  86. private:
  87. std::string name;
  88. bell::WrappedSemaphore clientConnected;
  89. std::shared_ptr<bell::CentralAudioBuffer> centralAudioBuffer;
  90. int startOffset, volume = 0, bitrate = 160;
  91. httpd_handle_t serverHandle;
  92. int serverPort;
  93. cspot_cmd_cb_t cmdHandler;
  94. cspot_data_cb_t dataHandler;
  95. std::shared_ptr<cspot::LoginBlob> blob;
  96. std::unique_ptr<cspot::SpircHandler> spirc;
  97. std::unique_ptr<chunkManager> chunker;
  98. void eventHandler(std::unique_ptr<cspot::SpircHandler::Event> event);
  99. void trackHandler(void);
  100. void runTask();
  101. public:
  102. typedef enum {TRACK_INIT, TRACK_NOTIFY, TRACK_STREAM, TRACK_END} TrackStatus;
  103. std::atomic<TrackStatus> trackStatus = TRACK_INIT;
  104. cspotPlayer(const char*, httpd_handle_t, int, cspot_cmd_cb_t, cspot_data_cb_t);
  105. esp_err_t handleGET(httpd_req_t *request);
  106. esp_err_t handlePOST(httpd_req_t *request);
  107. void command(cspot_event_t event);
  108. };
  109. cspotPlayer::cspotPlayer(const char* name, httpd_handle_t server, int port, cspot_cmd_cb_t cmdHandler, cspot_data_cb_t dataHandler) :
  110. bell::Task("playerInstance", 32 * 1024, 0, 0),
  111. serverHandle(server), serverPort(port),
  112. cmdHandler(cmdHandler), dataHandler(dataHandler) {
  113. cJSON *item, *config = config_alloc_get_cjson("cspot_config");
  114. if ((item = cJSON_GetObjectItem(config, "volume")) != NULL) volume = item->valueint;
  115. if ((item = cJSON_GetObjectItem(config, "bitrate")) != NULL) bitrate = item->valueint;
  116. if ((item = cJSON_GetObjectItem(config, "deviceName") ) != NULL) this->name = item->valuestring;
  117. else this->name = name;
  118. cJSON_Delete(config);
  119. if (bitrate != 96 && bitrate != 160 && bitrate != 320) bitrate = 160;
  120. }
  121. extern "C" {
  122. static esp_err_t handleGET(httpd_req_t *request) {
  123. return player->handleGET(request);
  124. }
  125. static esp_err_t handlePOST(httpd_req_t *request) {
  126. return player->handlePOST(request);
  127. }
  128. }
  129. esp_err_t cspotPlayer::handleGET(httpd_req_t *request) {
  130. std::string body = this->blob->buildZeroconfInfo();
  131. if (body.size() == 0) {
  132. CSPOT_LOG(info, "cspot empty blob's body on GET");
  133. return ESP_ERR_HTTPD_INVALID_REQ;
  134. }
  135. httpd_resp_set_hdr(request, "Content-type", "application/json");
  136. httpd_resp_send(request, body.c_str(), body.size());
  137. return ESP_OK;
  138. }
  139. esp_err_t cspotPlayer::handlePOST(httpd_req_t *request) {
  140. cJSON* response= cJSON_CreateObject();
  141. //see https://developer.spotify.com/documentation/commercial-hardware/implementation/guides/zeroconf
  142. if (cmdHandler(CSPOT_BUSY)) {
  143. cJSON_AddNumberToObject(response, "status", 101);
  144. cJSON_AddStringToObject(response, "statusString", "OK");
  145. cJSON_AddNumberToObject(response, "spotifyError", 0);
  146. // get body if any (add '\0' at the end if used as string)
  147. if (request->content_len) {
  148. char* body = (char*) calloc(1, request->content_len + 1);
  149. int size = httpd_req_recv(request, body, request->content_len);
  150. // I know this is very crude and unsafe...
  151. url_decode(body);
  152. char *key = strtok(body, "&");
  153. std::map<std::string, std::string> queryMap;
  154. while (key) {
  155. char *value = strchr(key, '=');
  156. *value++ = '\0';
  157. queryMap[key] = value;
  158. key = strtok(NULL, "&");
  159. };
  160. free(body);
  161. // Pass user's credentials to the blob and give the token
  162. blob->loadZeroconfQuery(queryMap);
  163. clientConnected.give();
  164. }
  165. } else {
  166. cJSON_AddNumberToObject(response, "status", 202);
  167. cJSON_AddStringToObject(response, "statusString", "ERROR-LOGIN-FAILED");
  168. cJSON_AddNumberToObject(response, "spotifyError", 0);
  169. CSPOT_LOG(info, "sink is busy, can't accept request");
  170. }
  171. char *responseStr = cJSON_PrintUnformatted(response);
  172. cJSON_Delete(response);
  173. httpd_resp_set_hdr(request, "Content-type", "application/json");
  174. esp_err_t rc = httpd_resp_send(request, responseStr, strlen(responseStr));
  175. free(responseStr);
  176. return rc;
  177. }
  178. void cspotPlayer::eventHandler(std::unique_ptr<cspot::SpircHandler::Event> event) {
  179. switch (event->eventType) {
  180. case cspot::SpircHandler::EventType::PLAYBACK_START: {
  181. chunker->discard = true;
  182. centralAudioBuffer->clearBuffer();
  183. // we are not playing anymore
  184. trackStatus = TRACK_INIT;
  185. // memorize position for when track's beginning will be detected
  186. startOffset = std::get<int>(event->data);
  187. // Spotify servers do not send volume at connection
  188. spirc->setRemoteVolume(volume);
  189. cmdHandler(CSPOT_START, 44100);
  190. CSPOT_LOG(info, "(re)start playing");
  191. break;
  192. }
  193. case cspot::SpircHandler::EventType::PLAY_PAUSE: {
  194. bool pause = std::get<bool>(event->data);
  195. cmdHandler(pause ? CSPOT_PAUSE : CSPOT_PLAY);
  196. chunker->isPaused = pause;
  197. break;
  198. }
  199. case cspot::SpircHandler::EventType::TRACK_INFO: {
  200. auto trackInfo = std::get<cspot::CDNTrackStream::TrackInfo>(event->data);
  201. cmdHandler(CSPOT_TRACK_INFO, trackInfo.duration, startOffset, trackInfo.artist.c_str(),
  202. trackInfo.album.c_str(), trackInfo.name.c_str(), trackInfo.imageUrl.c_str());
  203. spirc->updatePositionMs(startOffset);
  204. startOffset = 0;
  205. break;
  206. }
  207. case cspot::SpircHandler::EventType::NEXT:
  208. case cspot::SpircHandler::EventType::PREV:
  209. case cspot::SpircHandler::EventType::FLUSH: {
  210. // FLUSH is sent when there is no next, just clean everything
  211. centralAudioBuffer->clearBuffer();
  212. cmdHandler(CSPOT_FLUSH);
  213. break;
  214. }
  215. case cspot::SpircHandler::EventType::DISC:
  216. centralAudioBuffer->clearBuffer();
  217. cmdHandler(CSPOT_DISC);
  218. chunker->teardown();
  219. break;
  220. case cspot::SpircHandler::EventType::SEEK: {
  221. centralAudioBuffer->clearBuffer();
  222. cmdHandler(CSPOT_SEEK, std::get<int>(event->data));
  223. break;
  224. }
  225. case cspot::SpircHandler::EventType::DEPLETED:
  226. trackStatus = TRACK_END;
  227. CSPOT_LOG(info, "playlist ended, no track left to play");
  228. break;
  229. case cspot::SpircHandler::EventType::VOLUME:
  230. volume = std::get<int>(event->data);
  231. cmdHandler(CSPOT_VOLUME, volume);
  232. break;
  233. default:
  234. break;
  235. }
  236. }
  237. void cspotPlayer::trackHandler(void) {
  238. // this is just informative
  239. auto trackInfo = spirc->getTrackPlayer()->getCurrentTrackInfo();
  240. uint32_t remains;
  241. cmdHandler(CSPOT_QUERY_REMAINING, &remains);
  242. CSPOT_LOG(info, "next track <%s> will play in %d ms", trackInfo.name.c_str(), remains);
  243. // inform sink of track beginning
  244. trackStatus = TRACK_NOTIFY;
  245. cmdHandler(CSPOT_TRACK_MARK);
  246. }
  247. void cspotPlayer::command(cspot_event_t event) {
  248. if (!spirc) return;
  249. // switch...case consume a ton of extra .rodata
  250. switch (event) {
  251. // nextSong/previousSong come back through cspot::event as a FLUSH
  252. case CSPOT_PREV:
  253. spirc->previousSong();
  254. break;
  255. case CSPOT_NEXT:
  256. spirc->nextSong();
  257. break;
  258. // setPause comes back through cspot::event with PLAY/PAUSE
  259. case CSPOT_TOGGLE:
  260. spirc->setPause(!chunker->isPaused);
  261. break;
  262. case CSPOT_STOP:
  263. case CSPOT_PAUSE:
  264. spirc->setPause(true);
  265. break;
  266. case CSPOT_PLAY:
  267. spirc->setPause(false);
  268. break;
  269. // calling spirc->disconnect() might have been logical but it does not
  270. // generate any cspot::event, so we need to manually force exiting player
  271. // loop through chunker which will eventually do the disconnect
  272. case CSPOT_DISC:
  273. cmdHandler(CSPOT_DISC);
  274. chunker->teardown();
  275. break;
  276. // spirc->setRemoteVolume does not generate a cspot::event so call cmdHandler
  277. case CSPOT_VOLUME_UP:
  278. volume += (UINT16_MAX / 50);
  279. volume = std::min(volume, UINT16_MAX);
  280. cmdHandler(CSPOT_VOLUME, volume);
  281. spirc->setRemoteVolume(volume);
  282. break;
  283. case CSPOT_VOLUME_DOWN:
  284. volume -= (UINT16_MAX / 50);
  285. volume = std::max(volume, 0);
  286. cmdHandler(CSPOT_VOLUME, volume);
  287. spirc->setRemoteVolume(volume);
  288. break;
  289. default:
  290. break;
  291. }
  292. }
  293. void cspotPlayer::runTask() {
  294. httpd_uri_t request = {
  295. .uri = "/spotify_info",
  296. .method = HTTP_GET,
  297. .handler = ::handleGET,
  298. .user_ctx = NULL,
  299. };
  300. // register GET and POST handler for built-in server
  301. httpd_register_uri_handler(serverHandle, &request);
  302. request.method = HTTP_POST;
  303. request.handler = ::handlePOST;
  304. httpd_register_uri_handler(serverHandle, &request);
  305. // construct blob for that player
  306. blob = std::make_unique<cspot::LoginBlob>(name);
  307. // Register mdns service, for spotify to find us
  308. bell::MDNSService::registerService( blob->getDeviceName(), "_spotify-connect", "_tcp", "", serverPort,
  309. { {"VERSION", "1.0"}, {"CPath", "/spotify_info"}, {"Stack", "SP"} });
  310. static int count = 0;
  311. // gone with the wind...
  312. while (1) {
  313. clientConnected.wait();
  314. CSPOT_LOG(info, "Spotify client connected for %s", name.c_str());
  315. centralAudioBuffer = std::make_shared<bell::CentralAudioBuffer>(32);
  316. auto ctx = cspot::Context::createFromBlob(blob);
  317. if (bitrate == 320) ctx->config.audioFormat = AudioFormat_OGG_VORBIS_320;
  318. else if (bitrate == 96) ctx->config.audioFormat = AudioFormat_OGG_VORBIS_96;
  319. else ctx->config.audioFormat = AudioFormat_OGG_VORBIS_160;
  320. ctx->session->connectWithRandomAp();
  321. auto token = ctx->session->authenticate(blob);
  322. // Auth successful
  323. if (token.size() > 0) {
  324. spirc = std::make_unique<cspot::SpircHandler>(ctx);
  325. // set call back to calculate a hash on trackId
  326. spirc->getTrackPlayer()->setDataCallback(
  327. [this](uint8_t* data, size_t bytes, std::string_view trackId, size_t sequence) {
  328. return centralAudioBuffer->writePCM(data, bytes, sequence);
  329. });
  330. // set event (PLAY, VOLUME...) handler
  331. spirc->setEventHandler(
  332. [this](std::unique_ptr<cspot::SpircHandler::Event> event) {
  333. eventHandler(std::move(event));
  334. });
  335. // Start handling mercury messages
  336. ctx->session->startTask();
  337. // Create a player, pass the tack handler
  338. chunker = std::make_unique<chunkManager>(centralAudioBuffer,
  339. [this](void) {
  340. return trackHandler();
  341. },
  342. [this](const uint8_t* data, size_t bytes) {
  343. return dataHandler(data, bytes);
  344. });
  345. // set volume at connection
  346. cmdHandler(CSPOT_VOLUME, volume);
  347. // exit when player has stopped (received a DISC)
  348. while (chunker->isRunning) {
  349. ctx->session->handlePacket();
  350. // low-accuracy polling events
  351. if (trackStatus == TRACK_NOTIFY) {
  352. // inform Spotify that next track has started (don't need to be super accurate)
  353. uint32_t started;
  354. cmdHandler(CSPOT_QUERY_STARTED, &started);
  355. if (started) {
  356. CSPOT_LOG(info, "next track's audio has reached DAC");
  357. spirc->notifyAudioReachedPlayback();
  358. trackStatus = TRACK_STREAM;
  359. }
  360. } else if (trackStatus == TRACK_END) {
  361. // wait for end of last track
  362. uint32_t remains;
  363. cmdHandler(CSPOT_QUERY_REMAINING, &remains);
  364. if (!remains) {
  365. CSPOT_LOG(info, "last track finished");
  366. trackStatus = TRACK_INIT;
  367. cmdHandler(CSPOT_STOP);
  368. spirc->setPause(true);
  369. }
  370. }
  371. }
  372. spirc->disconnect();
  373. spirc.reset();
  374. CSPOT_LOG(info, "disconnecting player %s", name.c_str());
  375. }
  376. // we want to release memory ASAP and for sure
  377. centralAudioBuffer.reset();
  378. ctx.reset();
  379. token.clear();
  380. // update volume when we disconnect
  381. cJSON *config = config_alloc_get_cjson("cspot_config");
  382. cJSON_DeleteItemFromObject(config, "volume");
  383. cJSON_AddNumberToObject(config, "volume", volume);
  384. config_set_cjson_str_and_free("cspot_config", config);
  385. }
  386. }
  387. /****************************************************************************************
  388. * API to create and start a cspot instance
  389. */
  390. struct cspot_s* cspot_create(const char *name, httpd_handle_t server, int port, cspot_cmd_cb_t cmd_cb, cspot_data_cb_t data_cb) {
  391. bell::setDefaultLogger();
  392. player = new cspotPlayer(name, server, port, cmd_cb, data_cb);
  393. player->startTask();
  394. return (cspot_s*) player;
  395. }
  396. /****************************************************************************************
  397. * Commands sent by local buttons/actions
  398. */
  399. bool cspot_cmd(struct cspot_s* ctx, cspot_event_t event, void *param) {
  400. player->command(event);
  401. return true;
  402. }