Shim.cpp 14 KB

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