Shim.cpp 17 KB

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