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