decode_external.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*
  2. * Squeezelite for esp32
  3. *
  4. * (c) Sebastien 2019
  5. * Philippe G. 2019, philippe_44@outlook.com
  6. *
  7. * This software is released under the MIT License.
  8. * https://opensource.org/licenses/MIT
  9. *
  10. */
  11. #include <math.h>
  12. #ifdef ESP_PLATFORM
  13. #include "freertos/FreeRTOS.h"
  14. #include "freertos/timers.h"
  15. #endif
  16. #include "platform_config.h"
  17. #include "squeezelite.h"
  18. #if CONFIG_BT_SINK
  19. #include "bt_app_sink.h"
  20. static bool enable_bt_sink;
  21. #endif
  22. #if CONFIG_CSPOT_SINK
  23. #include "cspot_sink.h"
  24. static bool enable_cspot;
  25. #endif
  26. #if CONFIG_AIRPLAY_SINK
  27. #include "raop_sink.h"
  28. static bool enable_airplay;
  29. #define RAOP_OUTPUT_SIZE (((RAOP_SAMPLE_RATE * BYTES_PER_FRAME * 2 * 120) / 100) & ~BYTES_PER_FRAME)
  30. #define SYNC_WIN_SLOW 32
  31. #define SYNC_WIN_CHECK 8
  32. #define SYNC_WIN_FAST 2
  33. static raop_event_t raop_state;
  34. static EXT_RAM_ATTR struct {
  35. bool enabled;
  36. int sum, count, win, errors[SYNC_WIN_SLOW];
  37. s32_t len;
  38. u32_t start_time, playtime;
  39. } raop_sync;
  40. #endif
  41. static bool abort_sink ;
  42. #define LOCK_O mutex_lock(outputbuf->mutex)
  43. #define UNLOCK_O mutex_unlock(outputbuf->mutex)
  44. #define LOCK_D mutex_lock(decode.mutex);
  45. #define UNLOCK_D mutex_unlock(decode.mutex);
  46. enum { DECODE_BT = 1, DECODE_RAOP, DECODE_CSPOT };
  47. extern struct outputstate output;
  48. extern struct decodestate decode;
  49. extern struct buffer *outputbuf;
  50. // this is the only system-wide loglevel variable
  51. extern log_level loglevel;
  52. /****************************************************************************************
  53. * Common sink data handler
  54. */
  55. static void sink_data_handler(const uint8_t *data, uint32_t len)
  56. {
  57. size_t bytes, space;
  58. int wait = 5;
  59. // would be better to lock output, but really, it does not matter
  60. if (!output.external) {
  61. LOG_SDEBUG("Cannot use external sink while LMS is controlling player");
  62. return;
  63. }
  64. LOCK_O;
  65. abort_sink = false;
  66. // there will always be room at some point
  67. while (len && wait && !abort_sink) {
  68. bytes = min(_buf_space(outputbuf), _buf_cont_write(outputbuf)) / (BYTES_PER_FRAME / 4);
  69. bytes = min(len, bytes);
  70. #if BYTES_PER_FRAME == 4
  71. memcpy(outputbuf->writep, data, bytes);
  72. #else
  73. {
  74. s16_t *iptr = (s16_t*) data;
  75. ISAMPLE_T *optr = (ISAMPLE_T *) outputbuf->writep;
  76. size_t n = bytes / 2;
  77. while (n--) *optr++ = *iptr++ << 16;
  78. }
  79. #endif
  80. _buf_inc_writep(outputbuf, bytes * BYTES_PER_FRAME / 4);
  81. space = _buf_space(outputbuf);
  82. len -= bytes;
  83. data += bytes;
  84. // allow i2s to empty the buffer if needed
  85. if (len && !space) {
  86. wait--;
  87. UNLOCK_O; usleep(50000); LOCK_O;
  88. }
  89. }
  90. UNLOCK_O;
  91. if (!wait) {
  92. LOG_WARN("Waited too long, dropping frames");
  93. }
  94. }
  95. /****************************************************************************************
  96. * BT sink command handler
  97. */
  98. #if CONFIG_BT_SINK
  99. static bool bt_sink_cmd_handler(bt_sink_cmd_t cmd, va_list args)
  100. {
  101. // don't LOCK_O as there is always a chance that LMS takes control later anyway
  102. if (output.external != DECODE_BT && output.state > OUTPUT_STOPPED) {
  103. LOG_WARN("Cannot use BT sink while LMS/AirPlay/CSpot are controlling player");
  104. return false;
  105. }
  106. LOCK_D;
  107. if (cmd != BT_SINK_VOLUME) LOCK_O;
  108. switch(cmd) {
  109. case BT_SINK_AUDIO_STARTED:
  110. _buf_flush(outputbuf);
  111. _buf_limit(outputbuf, 0);
  112. output.next_sample_rate = output.current_sample_rate = va_arg(args, u32_t);
  113. output.external = DECODE_BT;
  114. output.state = OUTPUT_STOPPED;
  115. output.frames_played = 0;
  116. if (decode.state != DECODE_STOPPED) decode.state = DECODE_ERROR;
  117. LOG_INFO("BT sink started");
  118. break;
  119. case BT_SINK_AUDIO_STOPPED:
  120. if (output.external == DECODE_BT) {
  121. if (output.state > OUTPUT_STOPPED) output.state = OUTPUT_STOPPED;
  122. output.external = 0;
  123. output.stop_time = gettime_ms();
  124. LOG_INFO("BT sink stopped");
  125. }
  126. break;
  127. case BT_SINK_PLAY:
  128. output.state = OUTPUT_RUNNING;
  129. LOG_INFO("BT play");
  130. break;
  131. case BT_SINK_STOP:
  132. _buf_flush(outputbuf);
  133. output.state = OUTPUT_STOPPED;
  134. output.stop_time = gettime_ms();
  135. abort_sink = true;
  136. LOG_INFO("BT stop");
  137. break;
  138. case BT_SINK_PAUSE:
  139. output.stop_time = gettime_ms();
  140. LOG_INFO("BT pause, just silence");
  141. break;
  142. case BT_SINK_RATE:
  143. output.next_sample_rate = output.current_sample_rate = va_arg(args, u32_t);
  144. LOG_INFO("Setting BT sample rate %u", output.next_sample_rate);
  145. break;
  146. case BT_SINK_VOLUME: {
  147. u32_t volume = va_arg(args, u32_t);
  148. volume = 65536 * powf(volume / 128.0f, 3);
  149. set_volume(volume, volume);
  150. break;
  151. default:
  152. break;
  153. }
  154. }
  155. if (cmd != BT_SINK_VOLUME) UNLOCK_O;
  156. UNLOCK_D;
  157. return true;
  158. }
  159. #endif
  160. /****************************************************************************************
  161. * raop sink data handler
  162. */
  163. #if CONFIG_AIRPLAY_SINK
  164. static void raop_sink_data_handler(const uint8_t *data, uint32_t len, u32_t playtime) {
  165. raop_sync.playtime = playtime;
  166. raop_sync.len = len;
  167. sink_data_handler(data, len);
  168. }
  169. /****************************************************************************************
  170. * AirPlay sink command handler
  171. */
  172. static bool raop_sink_cmd_handler(raop_event_t event, va_list args)
  173. {
  174. // don't LOCK_O as there is always a chance that LMS takes control later anyway
  175. if (output.external != DECODE_RAOP && output.state > OUTPUT_STOPPED) {
  176. LOG_WARN("Cannot use Airplay sink while LMS/BT/CSpot are controlling player");
  177. return false;
  178. }
  179. LOCK_D;
  180. if (event != RAOP_VOLUME) LOCK_O;
  181. // this is async, so player might have been deleted
  182. switch (event) {
  183. case RAOP_TIMING: {
  184. if (!raop_sync.enabled || output.state != OUTPUT_RUNNING || output.frames_played_dmp < output.device_frames) break;
  185. u32_t ms, now = gettime_ms();
  186. u32_t level = _buf_used(outputbuf);
  187. int error;
  188. // in how many ms will the most recent block play
  189. ms = (((s32_t)(level - raop_sync.len) / BYTES_PER_FRAME + output.device_frames + output.frames_in_process) * 10) / (RAOP_SAMPLE_RATE / 100) - (s32_t) (now - output.updated);
  190. // when outputbuf is empty, it means we have a network black-out or something
  191. error = level ? (raop_sync.playtime - now) - ms : 0;
  192. if (loglevel == lDEBUG || !level) {
  193. LOG_INFO("head local:%d, remote:%d (delta:%d)", ms, raop_sync.playtime - now, error);
  194. LOG_INFO("obuf:%u, sync_len:%u, devframes:%u, inproc:%u", _buf_used(outputbuf), raop_sync.len, output.device_frames, output.frames_in_process);
  195. }
  196. // calculate sum, error and update sliding window
  197. raop_sync.errors[raop_sync.count++ % raop_sync.win] = error;
  198. raop_sync.sum += error;
  199. error = raop_sync.sum / min(raop_sync.count, raop_sync.win);
  200. // wait till we have enough data or there is a strong deviation
  201. if ((raop_sync.count >= raop_sync.win && abs(error) > 10) || (raop_sync.count >= SYNC_WIN_CHECK && abs(error) > 100)) {
  202. if (error < 0) {
  203. output.skip_frames = -(error * RAOP_SAMPLE_RATE) / 1000;
  204. output.state = OUTPUT_SKIP_FRAMES;
  205. LOG_INFO("skipping %u frames (count:%d)", output.skip_frames, raop_sync.count);
  206. } else {
  207. output.pause_frames = (error * RAOP_SAMPLE_RATE) / 1000;
  208. output.state = OUTPUT_PAUSE_FRAMES;
  209. LOG_INFO("pausing for %u frames (count: %d)", output.pause_frames, raop_sync.count);
  210. }
  211. raop_sync.sum = raop_sync.count = 0;
  212. memset(raop_sync.errors, 0, sizeof(raop_sync.errors));
  213. }
  214. // move to normal mode if possible
  215. if (raop_sync.win == 1) {
  216. raop_sync.win = SYNC_WIN_FAST;
  217. LOG_INFO("backend played %u, desired %u, (delta:%d)", ms, raop_sync.playtime - now, error);
  218. } else if (raop_sync.win == SYNC_WIN_FAST && raop_sync.count >= SYNC_WIN_FAST && abs(error) < 10) {
  219. raop_sync.win = SYNC_WIN_SLOW;
  220. LOG_INFO("switching to slow sync mode %u", raop_sync.win);
  221. }
  222. break;
  223. }
  224. case RAOP_SETUP: {
  225. uint8_t **buffer = va_arg(args, uint8_t**);
  226. size_t *size = va_arg(args, size_t*);
  227. // steal buffer tail from outputbuf but do not reallocate
  228. *size = _buf_limit(outputbuf, RAOP_OUTPUT_SIZE);
  229. *buffer = outputbuf->writep + RAOP_OUTPUT_SIZE;
  230. output.frames_played = 0;
  231. output.external = DECODE_RAOP;
  232. output.state = OUTPUT_STOPPED;
  233. if (decode.state != DECODE_STOPPED) decode.state = DECODE_ERROR;
  234. LOG_INFO("resizing buffer %u", outputbuf->size);
  235. break;
  236. }
  237. case RAOP_STREAM:
  238. LOG_INFO("Stream", NULL);
  239. raop_state = event;
  240. raop_sync.win = 1;
  241. raop_sync.sum = raop_sync.count = 0;
  242. memset(raop_sync.errors, 0, sizeof(raop_sync.errors));
  243. raop_sync.enabled = !strcasestr(output.device, "BT");
  244. output.next_sample_rate = output.current_sample_rate = RAOP_SAMPLE_RATE;
  245. break;
  246. case RAOP_STOP:
  247. output.external = 0;
  248. __attribute__ ((fallthrough));
  249. case RAOP_FLUSH:
  250. LOG_INFO("%s", event == RAOP_FLUSH ? "Flush" : "Stop");
  251. _buf_flush(outputbuf);
  252. raop_state = event;
  253. if (output.state > OUTPUT_STOPPED) output.state = OUTPUT_STOPPED;
  254. abort_sink = true;
  255. output.frames_played = 0;
  256. output.stop_time = gettime_ms();
  257. break;
  258. case RAOP_PLAY: {
  259. LOG_INFO("Play", NULL);
  260. if (raop_state != RAOP_PLAY) {
  261. output.state = OUTPUT_START_AT;
  262. output.start_at = va_arg(args, u32_t);
  263. raop_sync.start_time = output.start_at;
  264. LOG_INFO("Starting at %u (in %d ms)", output.start_at, output.start_at - gettime_ms());
  265. }
  266. raop_state = event;
  267. break;
  268. }
  269. case RAOP_VOLUME: {
  270. float volume = va_arg(args, double);
  271. LOG_INFO("Volume[0..1] %0.4f", volume);
  272. volume = 65536 * powf(volume, 3);
  273. set_volume(volume, volume);
  274. break;
  275. }
  276. default:
  277. break;
  278. }
  279. if (event != RAOP_VOLUME) UNLOCK_O;
  280. UNLOCK_D;
  281. return true;
  282. }
  283. #endif
  284. /****************************************************************************************
  285. * cspot sink command handler
  286. */
  287. #if CONFIG_CSPOT_SINK
  288. static bool cspot_cmd_handler(cspot_event_t cmd, va_list args)
  289. {
  290. // don't LOCK_O as there is always a chance that LMS takes control later anyway
  291. if (output.external != DECODE_CSPOT && output.state > OUTPUT_STOPPED) {
  292. LOG_WARN("Cannot use CSpot sink while LMS/BT/Airplay are controlling player");
  293. return false;
  294. }
  295. LOCK_D;
  296. if (cmd != CSPOT_VOLUME) LOCK_O;
  297. switch(cmd) {
  298. case CSPOT_SETUP:
  299. output.current_sample_rate = output.next_sample_rate = va_arg(args, u32_t);
  300. output.external = DECODE_CSPOT;
  301. output.frames_played = 0;
  302. output.state = OUTPUT_STOPPED;
  303. _buf_flush(outputbuf);
  304. _buf_limit(outputbuf, 0);
  305. if (decode.state != DECODE_STOPPED) decode.state = DECODE_ERROR;
  306. LOG_INFO("CSpot connected");
  307. break;
  308. case CSPOT_DISC:
  309. _buf_flush(outputbuf);
  310. abort_sink = true;
  311. output.external = 0;
  312. output.state = OUTPUT_STOPPED;
  313. output.stop_time = gettime_ms();
  314. LOG_INFO("CSpot disconnected");
  315. break;
  316. case CSPOT_TRACK:
  317. LOG_INFO("CSpot sink new track rate %d", output.next_sample_rate);
  318. break;
  319. case CSPOT_PLAY:
  320. output.state = OUTPUT_RUNNING;
  321. LOG_INFO("CSpot play");
  322. break;
  323. case CSPOT_SEEK:
  324. //TODO: can it be merged with flush (shall we stop)
  325. _buf_flush(outputbuf);
  326. abort_sink = true;
  327. LOG_INFO("CSpot seek by %d", va_arg(args, int));
  328. break;
  329. case CSPOT_FLUSH:
  330. _buf_flush(outputbuf);
  331. abort_sink = true;
  332. __attribute__ ((fallthrough));
  333. case CSPOT_PAUSE:
  334. output.state = OUTPUT_STOPPED;
  335. output.stop_time = gettime_ms();
  336. LOG_INFO("CSpot pause/flush");
  337. break;
  338. case CSPOT_VOLUME: {
  339. u32_t volume = va_arg(args, u32_t);
  340. LOG_INFO("CSpot volume %u", volume);
  341. //volume = 65536 * powf(volume / 32768.0f, 3);
  342. // TODO spotify seems to volume normalize crazy high
  343. volume = 4096 * powf(volume / 32768.0f, 3);
  344. set_volume(volume, volume);
  345. break;
  346. default:
  347. break;
  348. }
  349. }
  350. if (cmd != CSPOT_VOLUME) UNLOCK_O;
  351. UNLOCK_D;
  352. return true;
  353. }
  354. #endif
  355. /****************************************************************************************
  356. * We provide the generic codec register option
  357. */
  358. #if defined(ESP_PLATFORM) && defined(CONFIG_BT_SINK)
  359. void bt_delay_start(TimerHandle_t xTimer) {
  360. xTimerDelete(xTimer, portMAX_DELAY);
  361. bt_sink_init(bt_sink_cmd_handler, sink_data_handler);
  362. LOG_INFO("Initializing BT sink");
  363. }
  364. void bt_delay_stop(TimerHandle_t xTimer) {
  365. xTimerDelete(xTimer, portMAX_DELAY);
  366. bt_sink_deinit();
  367. LOG_INFO("Stopping BT sink");
  368. }
  369. #endif
  370. void register_external(void) {
  371. char *p;
  372. #if CONFIG_BT_SINK
  373. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_bt_sink")) != NULL) {
  374. enable_bt_sink = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  375. free(p);
  376. }
  377. #endif
  378. #if CONFIG_AIRPLAY_SINK
  379. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_airplay")) != NULL) {
  380. enable_airplay = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  381. free(p);
  382. }
  383. #endif
  384. #if CONFIG_CSPOT_SINK
  385. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_cspot")) != NULL) {
  386. enable_cspot = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  387. free(p);
  388. }
  389. #endif
  390. #if CONFIG_BT_SINK
  391. if (!strcasestr(output.device, "BT ") ) {
  392. if(enable_bt_sink){
  393. #ifdef ESP_PLATFORM
  394. // we need to delay the start because current task is in spiram
  395. TimerHandle_t timer = xTimerCreate("delay", 1, pdFALSE, NULL, bt_delay_start);
  396. xTimerStart(timer, portMAX_DELAY);
  397. #else
  398. bt_sink_init(bt_sink_cmd_handler, sink_data_handler);
  399. #endif
  400. }
  401. } else {
  402. LOG_WARN("Cannot be a BT sink and source");
  403. }
  404. #endif
  405. #if CONFIG_AIRPLAY_SINK
  406. if (enable_airplay){
  407. raop_sink_init(raop_sink_cmd_handler, raop_sink_data_handler);
  408. LOG_INFO("Initializing AirPlay sink");
  409. }
  410. #endif
  411. #if CONFIG_CSPOT_SINK
  412. if (enable_cspot){
  413. cspot_sink_init(cspot_cmd_handler, sink_data_handler);
  414. LOG_INFO("Initializing CSpot sink");
  415. }
  416. #endif
  417. }
  418. void deregister_external(void) {
  419. #if CONFIG_BT_SINK
  420. if (!strcasestr(output.device, "BT ") && enable_bt_sink) {
  421. #ifdef ESP_PLATFORM
  422. // we need to delay the stop because current task is in spiram
  423. TimerHandle_t timer = xTimerCreate("delay", 1, pdFALSE, NULL, bt_delay_stop);
  424. xTimerStart(timer, portMAX_DELAY);
  425. #else
  426. bt_sink_deinit();
  427. #endif
  428. }
  429. #endif
  430. #if CONFIG_AIRPLAY_SINK
  431. if (enable_airplay){
  432. LOG_INFO("Stopping AirPlay sink");
  433. raop_sink_deinit();
  434. }
  435. #endif
  436. #if CONFIG_CSPOT_SINK
  437. if (enable_cspot){
  438. LOG_INFO("Stopping CSpot sink");
  439. cspot_sink_deinit();
  440. }
  441. #endif
  442. }
  443. void decode_restore(int external) {
  444. switch (external) {
  445. #if CONFIG_BT_SINK
  446. case DECODE_BT:
  447. bt_disconnect();
  448. break;
  449. #endif
  450. #if CONFIG_AIRPLAY_SINK
  451. case DECODE_RAOP:
  452. raop_disconnect();
  453. raop_state = RAOP_STOP;
  454. break;
  455. #endif
  456. #if CONFIG_CSPOT_SINK
  457. case DECODE_CSPOT:
  458. cspot_disconnect();
  459. break;
  460. #endif
  461. }
  462. }