2
0

Shim.cpp 16 KB

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