Shim.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. // try a command that will tell us if the sink is available */
  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", 104);
  165. cJSON_AddStringToObject(response, "statusString", "ERROR-NOT-IMPLEMENTED");
  166. cJSON_AddNumberToObject(response, "spotifyError", 501);
  167. httpd_resp_set_status(request, "501 Not Implemented");
  168. CSPOT_LOG(info, "sink is busy, can't accept request");
  169. }
  170. char *responseStr = cJSON_PrintUnformatted(response);
  171. cJSON_Delete(response);
  172. httpd_resp_set_hdr(request, "Content-type", "application/json");
  173. esp_err_t rc = httpd_resp_send(request, responseStr, strlen(responseStr));
  174. free(responseStr);
  175. return rc;
  176. }
  177. void cspotPlayer::eventHandler(std::unique_ptr<cspot::SpircHandler::Event> event) {
  178. switch (event->eventType) {
  179. case cspot::SpircHandler::EventType::PLAYBACK_START: {
  180. centralAudioBuffer->clearBuffer();
  181. // we are not playing anymore
  182. trackStatus = TRACK_INIT;
  183. // memorize position for when track's beginning will be detected
  184. startOffset = std::get<int>(event->data);
  185. // Spotify servers do not send volume at connection
  186. spirc->setRemoteVolume(volume);
  187. cmdHandler(CSPOT_START, 44100);
  188. CSPOT_LOG(info, "(re)start playing");
  189. break;
  190. }
  191. case cspot::SpircHandler::EventType::PLAY_PAUSE: {
  192. bool pause = std::get<bool>(event->data);
  193. cmdHandler(pause ? CSPOT_PAUSE : CSPOT_PLAY);
  194. chunker->isPaused = pause;
  195. break;
  196. }
  197. case cspot::SpircHandler::EventType::TRACK_INFO: {
  198. auto trackInfo = std::get<cspot::CDNTrackStream::TrackInfo>(event->data);
  199. cmdHandler(CSPOT_TRACK_INFO, trackInfo.duration, startOffset, trackInfo.artist.c_str(),
  200. trackInfo.album.c_str(), trackInfo.name.c_str(), trackInfo.imageUrl.c_str());
  201. spirc->updatePositionMs(startOffset);
  202. startOffset = 0;
  203. break;
  204. }
  205. case cspot::SpircHandler::EventType::NEXT:
  206. case cspot::SpircHandler::EventType::PREV:
  207. case cspot::SpircHandler::EventType::FLUSH: {
  208. // FLUSH is sent when there is no next, just clean everything
  209. centralAudioBuffer->clearBuffer();
  210. cmdHandler(CSPOT_FLUSH);
  211. break;
  212. }
  213. case cspot::SpircHandler::EventType::DISC:
  214. centralAudioBuffer->clearBuffer();
  215. cmdHandler(CSPOT_DISC);
  216. chunker->teardown();
  217. break;
  218. case cspot::SpircHandler::EventType::SEEK: {
  219. centralAudioBuffer->clearBuffer();
  220. cmdHandler(CSPOT_SEEK, std::get<int>(event->data));
  221. break;
  222. }
  223. case cspot::SpircHandler::EventType::DEPLETED:
  224. trackStatus = TRACK_END;
  225. CSPOT_LOG(info, "playlist ended, no track left to play");
  226. break;
  227. case cspot::SpircHandler::EventType::VOLUME:
  228. volume = std::get<int>(event->data);
  229. cmdHandler(CSPOT_VOLUME, volume);
  230. break;
  231. default:
  232. break;
  233. }
  234. }
  235. void cspotPlayer::trackHandler(void) {
  236. // this is just informative
  237. auto trackInfo = spirc->getTrackPlayer()->getCurrentTrackInfo();
  238. uint32_t remains;
  239. cmdHandler(CSPOT_QUERY_REMAINING, &remains);
  240. CSPOT_LOG(info, "next track <%s> will play in %d ms", trackInfo.name.c_str(), remains);
  241. // inform sink of track beginning
  242. trackStatus = TRACK_NOTIFY;
  243. cmdHandler(CSPOT_TRACK_MARK);
  244. }
  245. void cspotPlayer::command(cspot_event_t event) {
  246. if (!spirc) return;
  247. // switch...case consume a ton of extra .rodata
  248. switch (event) {
  249. // nextSong/previousSong come back through cspot::event as a FLUSH
  250. case CSPOT_PREV:
  251. spirc->previousSong();
  252. break;
  253. case CSPOT_NEXT:
  254. spirc->nextSong();
  255. break;
  256. // setPause comes back through cspot::event with PLAY/PAUSE
  257. case CSPOT_TOGGLE:
  258. spirc->setPause(!chunker->isPaused);
  259. break;
  260. case CSPOT_STOP:
  261. case CSPOT_PAUSE:
  262. spirc->setPause(true);
  263. break;
  264. case CSPOT_PLAY:
  265. spirc->setPause(false);
  266. break;
  267. // calling spirc->disconnect() might have been logical but it does not
  268. // generate any cspot::event, so we need to manually force exiting player
  269. // loop through chunker which will eventually do the disconnect
  270. case CSPOT_DISC:
  271. cmdHandler(CSPOT_DISC);
  272. chunker->teardown();
  273. break;
  274. // spirc->setRemoteVolume does not generate a cspot::event so call cmdHandler
  275. case CSPOT_VOLUME_UP:
  276. volume += (UINT16_MAX / 50);
  277. volume = std::min(volume, UINT16_MAX);
  278. cmdHandler(CSPOT_VOLUME, volume);
  279. spirc->setRemoteVolume(volume);
  280. break;
  281. case CSPOT_VOLUME_DOWN:
  282. volume -= (UINT16_MAX / 50);
  283. volume = std::max(volume, 0);
  284. cmdHandler(CSPOT_VOLUME, volume);
  285. spirc->setRemoteVolume(volume);
  286. break;
  287. default:
  288. break;
  289. }
  290. }
  291. void cspotPlayer::runTask() {
  292. httpd_uri_t request = {
  293. .uri = "/spotify_info",
  294. .method = HTTP_GET,
  295. .handler = ::handleGET,
  296. .user_ctx = NULL,
  297. };
  298. // register GET and POST handler for built-in server
  299. httpd_register_uri_handler(serverHandle, &request);
  300. request.method = HTTP_POST;
  301. request.handler = ::handlePOST;
  302. httpd_register_uri_handler(serverHandle, &request);
  303. // construct blob for that player
  304. blob = std::make_unique<cspot::LoginBlob>(name);
  305. // Register mdns service, for spotify to find us
  306. bell::MDNSService::registerService( blob->getDeviceName(), "_spotify-connect", "_tcp", "", serverPort,
  307. { {"VERSION", "1.0"}, {"CPath", "/spotify_info"}, {"Stack", "SP"} });
  308. static int count = 0;
  309. // gone with the wind...
  310. while (1) {
  311. clientConnected.wait();
  312. CSPOT_LOG(info, "Spotify client connected for %s", name.c_str());
  313. centralAudioBuffer = std::make_shared<bell::CentralAudioBuffer>(32);
  314. auto ctx = cspot::Context::createFromBlob(blob);
  315. if (bitrate == 320) ctx->config.audioFormat = AudioFormat_OGG_VORBIS_320;
  316. else if (bitrate == 96) ctx->config.audioFormat = AudioFormat_OGG_VORBIS_96;
  317. else ctx->config.audioFormat = AudioFormat_OGG_VORBIS_160;
  318. ctx->session->connectWithRandomAp();
  319. auto token = ctx->session->authenticate(blob);
  320. // Auth successful
  321. if (token.size() > 0) {
  322. spirc = std::make_unique<cspot::SpircHandler>(ctx);
  323. // set call back to calculate a hash on trackId
  324. spirc->getTrackPlayer()->setDataCallback(
  325. [this](uint8_t* data, size_t bytes, std::string_view trackId, size_t sequence) {
  326. return centralAudioBuffer->writePCM(data, bytes, sequence);
  327. });
  328. // set event (PLAY, VOLUME...) handler
  329. spirc->setEventHandler(
  330. [this](std::unique_ptr<cspot::SpircHandler::Event> event) {
  331. eventHandler(std::move(event));
  332. });
  333. // Start handling mercury messages
  334. ctx->session->startTask();
  335. // Create a player, pass the tack handler
  336. chunker = std::make_unique<chunkManager>(centralAudioBuffer,
  337. [this](void) {
  338. return trackHandler();
  339. },
  340. [this](const uint8_t* data, size_t bytes) {
  341. return dataHandler(data, bytes);
  342. });
  343. // set volume at connection
  344. cmdHandler(CSPOT_VOLUME, volume);
  345. // exit when player has stopped (received a DISC)
  346. while (chunker->isRunning) {
  347. ctx->session->handlePacket();
  348. // low-accuracy polling events
  349. if (trackStatus == TRACK_NOTIFY) {
  350. // inform Spotify that next track has started (don't need to be super accurate)
  351. uint32_t started;
  352. cmdHandler(CSPOT_QUERY_STARTED, &started);
  353. if (started) {
  354. CSPOT_LOG(info, "next track's audio has reached DAC");
  355. spirc->notifyAudioReachedPlayback();
  356. trackStatus = TRACK_STREAM;
  357. }
  358. } else if (trackStatus == TRACK_END) {
  359. // wait for end of last track
  360. uint32_t remains;
  361. cmdHandler(CSPOT_QUERY_REMAINING, &remains);
  362. if (!remains) {
  363. CSPOT_LOG(info, "last track finished");
  364. trackStatus = TRACK_INIT;
  365. cmdHandler(CSPOT_STOP);
  366. spirc->setPause(true);
  367. }
  368. }
  369. }
  370. spirc->disconnect();
  371. spirc.reset();
  372. CSPOT_LOG(info, "disconnecting player %s", name.c_str());
  373. }
  374. // we want to release memory ASAP and fore sure
  375. centralAudioBuffer.reset();
  376. ctx.reset();
  377. token.clear();
  378. // update volume when we disconnect
  379. cJSON *config = config_alloc_get_cjson("cspot_config");
  380. cJSON_DeleteItemFromObject(config, "volume");
  381. cJSON_AddNumberToObject(config, "volume", volume);
  382. config_set_cjson_str_and_free("cspot_config", config);
  383. }
  384. }
  385. /****************************************************************************************
  386. * API to create and start a cspot instance
  387. */
  388. 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) {
  389. bell::setDefaultLogger();
  390. player = new cspotPlayer(name, server, port, cmd_cb, data_cb);
  391. player->startTask();
  392. return (cspot_s*) player;
  393. }
  394. /****************************************************************************************
  395. * Commands sent by local buttons/actions
  396. */
  397. bool cspot_cmd(struct cspot_s* ctx, cspot_event_t event, void *param) {
  398. player->command(event);
  399. return true;
  400. }