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