decode_external.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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_AIRPLAY_SINK
  23. #include "raop_sink.h"
  24. static bool enable_airplay;
  25. #define RAOP_OUTPUT_SIZE (((RAOP_SAMPLE_RATE * BYTES_PER_FRAME * 2 * 120) / 100) & ~BYTES_PER_FRAME)
  26. #define SYNC_WIN_SLOW 32
  27. #define SYNC_WIN_CHECK 8
  28. #define SYNC_WIN_FAST 2
  29. static raop_event_t raop_state;
  30. static EXT_RAM_ATTR struct {
  31. bool enabled;
  32. int sum, count, win, errors[SYNC_WIN_SLOW];
  33. s32_t len;
  34. u32_t start_time, playtime;
  35. } raop_sync;
  36. #endif
  37. static bool abort_sink ;
  38. #define LOCK_O mutex_lock(outputbuf->mutex)
  39. #define UNLOCK_O mutex_unlock(outputbuf->mutex)
  40. #define LOCK_D mutex_lock(decode.mutex);
  41. #define UNLOCK_D mutex_unlock(decode.mutex);
  42. enum { DECODE_BT = 1, DECODE_RAOP};
  43. extern struct outputstate output;
  44. extern struct decodestate decode;
  45. extern struct buffer *outputbuf;
  46. // this is the only system-wide loglevel variable
  47. extern log_level loglevel;
  48. /****************************************************************************************
  49. * Common sink data handler
  50. */
  51. static void sink_data_handler(const uint8_t *data, uint32_t len)
  52. {
  53. size_t bytes, space;
  54. int wait = 5;
  55. // would be better to lock output, but really, it does not matter
  56. if (!output.external) {
  57. LOG_SDEBUG("Cannot use external sink while LMS is controlling player");
  58. return;
  59. }
  60. LOCK_O;
  61. abort_sink = false;
  62. // there will always be room at some point
  63. while (len && wait && !abort_sink) {
  64. bytes = min(_buf_space(outputbuf), _buf_cont_write(outputbuf)) / (BYTES_PER_FRAME / 4);
  65. bytes = min(len, bytes);
  66. #if BYTES_PER_FRAME == 4
  67. memcpy(outputbuf->writep, data, bytes);
  68. #else
  69. {
  70. s16_t *iptr = (s16_t*) data;
  71. ISAMPLE_T *optr = (ISAMPLE_T *) outputbuf->writep;
  72. size_t n = bytes / 2;
  73. while (n--) *optr++ = *iptr++ << 16;
  74. }
  75. #endif
  76. _buf_inc_writep(outputbuf, bytes * BYTES_PER_FRAME / 4);
  77. space = _buf_space(outputbuf);
  78. len -= bytes;
  79. data += bytes;
  80. // allow i2s to empty the buffer if needed
  81. if (len && !space) {
  82. wait--;
  83. UNLOCK_O; usleep(50000); LOCK_O;
  84. }
  85. }
  86. UNLOCK_O;
  87. if (!wait) {
  88. LOG_WARN("Waited too long, dropping frames");
  89. }
  90. }
  91. /****************************************************************************************
  92. * BT sink command handler
  93. */
  94. #if CONFIG_BT_SINK
  95. static bool bt_sink_cmd_handler(bt_sink_cmd_t cmd, va_list args)
  96. {
  97. // don't LOCK_O as there is always a chance that LMS takes control later anyway
  98. if (output.external != DECODE_BT && output.state > OUTPUT_STOPPED) {
  99. LOG_WARN("Cannot use BT sink while LMS/AirPlay are controlling player");
  100. return false;
  101. }
  102. LOCK_D;
  103. if (cmd != BT_SINK_VOLUME) LOCK_O;
  104. switch(cmd) {
  105. case BT_SINK_AUDIO_STARTED:
  106. _buf_flush(outputbuf);
  107. _buf_limit(outputbuf, 0);
  108. output.next_sample_rate = output.current_sample_rate = va_arg(args, u32_t);
  109. output.external = DECODE_BT;
  110. output.state = OUTPUT_STOPPED;
  111. output.frames_played = 0;
  112. if (decode.state != DECODE_STOPPED) decode.state = DECODE_ERROR;
  113. LOG_INFO("BT sink started");
  114. break;
  115. case BT_SINK_AUDIO_STOPPED:
  116. if (output.external == DECODE_BT) {
  117. if (output.state > OUTPUT_STOPPED) output.state = OUTPUT_STOPPED;
  118. output.stop_time = gettime_ms();
  119. LOG_INFO("BT sink stopped");
  120. }
  121. break;
  122. case BT_SINK_PLAY:
  123. output.state = OUTPUT_RUNNING;
  124. LOG_INFO("BT play");
  125. break;
  126. case BT_SINK_STOP:
  127. _buf_flush(outputbuf);
  128. output.state = OUTPUT_STOPPED;
  129. output.stop_time = gettime_ms();
  130. abort_sink = true;
  131. LOG_INFO("BT stop");
  132. break;
  133. case BT_SINK_PAUSE:
  134. output.stop_time = gettime_ms();
  135. LOG_INFO("BT pause, just silence");
  136. break;
  137. case BT_SINK_RATE:
  138. output.next_sample_rate = output.current_sample_rate = va_arg(args, u32_t);
  139. LOG_INFO("Setting BT sample rate %u", output.next_sample_rate);
  140. break;
  141. case BT_SINK_VOLUME: {
  142. u32_t volume = va_arg(args, u32_t);
  143. volume = 65536 * powf(volume / 128.0f, 3);
  144. set_volume(volume, volume);
  145. break;
  146. default:
  147. break;
  148. }
  149. }
  150. if (cmd != BT_SINK_VOLUME) UNLOCK_O;
  151. UNLOCK_D;
  152. return true;
  153. }
  154. #endif
  155. /****************************************************************************************
  156. * raop sink data handler
  157. */
  158. #if CONFIG_AIRPLAY_SINK
  159. static void raop_sink_data_handler(const uint8_t *data, uint32_t len, u32_t playtime) {
  160. raop_sync.playtime = playtime;
  161. raop_sync.len = len;
  162. sink_data_handler(data, len);
  163. }
  164. /****************************************************************************************
  165. * AirPlay sink command handler
  166. */
  167. static bool raop_sink_cmd_handler(raop_event_t event, va_list args)
  168. {
  169. // don't LOCK_O as there is always a chance that LMS takes control later anyway
  170. if (output.external != DECODE_RAOP && output.state > OUTPUT_STOPPED) {
  171. LOG_WARN("Cannot use Airplay sink while LMS/BT are controlling player");
  172. return false;
  173. }
  174. LOCK_D;
  175. if (event != RAOP_VOLUME) LOCK_O;
  176. // this is async, so player might have been deleted
  177. switch (event) {
  178. case RAOP_TIMING: {
  179. if (!raop_sync.enabled || output.state != OUTPUT_RUNNING || output.frames_played_dmp < output.device_frames) break;
  180. u32_t ms, now = gettime_ms();
  181. u32_t level = _buf_used(outputbuf);
  182. int error;
  183. // in how many ms will the most recent block play
  184. 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);
  185. // when outputbuf is empty, it means we have a network black-out or something
  186. error = level ? (raop_sync.playtime - now) - ms : 0;
  187. if (loglevel == lDEBUG || !level) {
  188. LOG_INFO("head local:%d, remote:%d (delta:%d)", ms, raop_sync.playtime - now, error);
  189. LOG_INFO("obuf:%u, sync_len:%u, devframes:%u, inproc:%u", _buf_used(outputbuf), raop_sync.len, output.device_frames, output.frames_in_process);
  190. }
  191. // calculate sum, error and update sliding window
  192. raop_sync.errors[raop_sync.count++ % raop_sync.win] = error;
  193. raop_sync.sum += error;
  194. error = raop_sync.sum / min(raop_sync.count, raop_sync.win);
  195. // wait till we have enough data or there is a strong deviation
  196. if ((raop_sync.count >= raop_sync.win && abs(error) > 10) || (raop_sync.count >= SYNC_WIN_CHECK && abs(error) > 100)) {
  197. if (error < 0) {
  198. output.skip_frames = -(error * RAOP_SAMPLE_RATE) / 1000;
  199. output.state = OUTPUT_SKIP_FRAMES;
  200. LOG_INFO("skipping %u frames (count:%d)", output.skip_frames, raop_sync.count);
  201. } else {
  202. output.pause_frames = (error * RAOP_SAMPLE_RATE) / 1000;
  203. output.state = OUTPUT_PAUSE_FRAMES;
  204. LOG_INFO("pausing for %u frames (count: %d)", output.pause_frames, raop_sync.count);
  205. }
  206. raop_sync.sum = raop_sync.count = 0;
  207. memset(raop_sync.errors, 0, sizeof(raop_sync.errors));
  208. }
  209. // move to normal mode if possible
  210. if (raop_sync.win == 1) {
  211. raop_sync.win = SYNC_WIN_FAST;
  212. LOG_INFO("backend played %u, desired %u, (delta:%d)", ms, raop_sync.playtime - now, error);
  213. } else if (raop_sync.win == SYNC_WIN_FAST && raop_sync.count >= SYNC_WIN_FAST && abs(error) < 10) {
  214. raop_sync.win = SYNC_WIN_SLOW;
  215. LOG_INFO("switching to slow sync mode %u", raop_sync.win);
  216. }
  217. break;
  218. }
  219. case RAOP_SETUP: {
  220. uint8_t **buffer = va_arg(args, uint8_t**);
  221. size_t *size = va_arg(args, size_t*);
  222. // steal buffer tail from outputbuf but do not reallocate
  223. *size = _buf_limit(outputbuf, RAOP_OUTPUT_SIZE);
  224. *buffer = outputbuf->writep + RAOP_OUTPUT_SIZE;
  225. output.frames_played = 0;
  226. output.external = DECODE_RAOP;
  227. output.state = OUTPUT_STOPPED;
  228. if (decode.state != DECODE_STOPPED) decode.state = DECODE_ERROR;
  229. LOG_INFO("resizing buffer %u", outputbuf->size);
  230. break;
  231. }
  232. case RAOP_STREAM:
  233. LOG_INFO("Stream", NULL);
  234. raop_state = event;
  235. raop_sync.win = 1;
  236. raop_sync.sum = raop_sync.count = 0;
  237. memset(raop_sync.errors, 0, sizeof(raop_sync.errors));
  238. raop_sync.enabled = !strcasestr(output.device, "BT");
  239. output.next_sample_rate = output.current_sample_rate = RAOP_SAMPLE_RATE;
  240. break;
  241. case RAOP_STOP:
  242. case RAOP_FLUSH:
  243. LOG_INFO("%s", event == RAOP_FLUSH ? "Flush" : "Stop");
  244. _buf_flush(outputbuf);
  245. raop_state = event;
  246. if (output.state > OUTPUT_STOPPED) output.state = OUTPUT_STOPPED;
  247. abort_sink = true;
  248. output.frames_played = 0;
  249. output.stop_time = gettime_ms();
  250. break;
  251. case RAOP_PLAY: {
  252. LOG_INFO("Play", NULL);
  253. if (raop_state != RAOP_PLAY) {
  254. output.state = OUTPUT_START_AT;
  255. output.start_at = va_arg(args, u32_t);
  256. raop_sync.start_time = output.start_at;
  257. LOG_INFO("Starting at %u (in %d ms)", output.start_at, output.start_at - gettime_ms());
  258. }
  259. raop_state = event;
  260. break;
  261. }
  262. case RAOP_VOLUME: {
  263. float volume = va_arg(args, double);
  264. LOG_INFO("Volume[0..1] %0.4f", volume);
  265. volume = 65536 * powf(volume, 3);
  266. set_volume(volume, volume);
  267. break;
  268. }
  269. default:
  270. break;
  271. }
  272. if (event != RAOP_VOLUME) UNLOCK_O;
  273. UNLOCK_D;
  274. return true;
  275. }
  276. #endif
  277. /****************************************************************************************
  278. /****************************************************************************************
  279. * We provide the generic codec register option
  280. */
  281. #if defined(ESP_PLATFORM) && defined(CONFIG_BT_SINK)
  282. void bt_delay_start(TimerHandle_t xTimer) {
  283. xTimerDelete(xTimer, portMAX_DELAY);
  284. bt_sink_init(bt_sink_cmd_handler, sink_data_handler);
  285. LOG_INFO("Initializing BT sink");
  286. }
  287. void bt_delay_stop(TimerHandle_t xTimer) {
  288. xTimerDelete(xTimer, portMAX_DELAY);
  289. bt_sink_deinit();
  290. LOG_INFO("Stopping BT sink");
  291. }
  292. #endif
  293. void register_external(void) {
  294. char *p;
  295. #if CONFIG_BT_SINK
  296. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_bt_sink")) != NULL) {
  297. enable_bt_sink = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  298. free(p);
  299. }
  300. #endif
  301. #if CONFIG_AIRPLAY_SINK
  302. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_airplay")) != NULL) {
  303. enable_airplay = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  304. free(p);
  305. }
  306. #endif
  307. #if CONFIG_BT_SINK
  308. if (!strcasestr(output.device, "BT ") ) {
  309. if(enable_bt_sink){
  310. #ifdef ESP_PLATFORM
  311. // we need to delay the start because current task is in spiram
  312. TimerHandle_t timer = xTimerCreate("delay", 1, pdFALSE, NULL, bt_delay_start);
  313. xTimerStart(timer, portMAX_DELAY);
  314. #else
  315. bt_sink_init(bt_sink_cmd_handler, sink_data_handler);
  316. #endif
  317. }
  318. } else {
  319. LOG_WARN("Cannot be a BT sink and source");
  320. }
  321. #endif
  322. #if CONFIG_AIRPLAY_SINK
  323. if (enable_airplay){
  324. raop_sink_init(raop_sink_cmd_handler, raop_sink_data_handler);
  325. LOG_INFO("Initializing AirPlay sink");
  326. }
  327. #endif
  328. }
  329. void deregister_external(void) {
  330. #if CONFIG_BT_SINK
  331. if (!strcasestr(output.device, "BT ") && enable_bt_sink) {
  332. #ifdef ESP_PLATFORM
  333. // we need to delay the stop because current task is in spiram
  334. TimerHandle_t timer = xTimerCreate("delay", 1, pdFALSE, NULL, bt_delay_stop);
  335. xTimerStart(timer, portMAX_DELAY);
  336. #else
  337. bt_sink_deinit();
  338. #endif
  339. }
  340. #endif
  341. #if CONFIG_AIRPLAY_SINK
  342. if (enable_airplay){
  343. LOG_INFO("Stopping AirPlay sink");
  344. raop_sink_deinit();
  345. }
  346. #endif
  347. }
  348. void decode_restore(int external) {
  349. switch (external) {
  350. #if CONFIG_BT_SINK
  351. case DECODE_BT:
  352. bt_disconnect();
  353. break;
  354. #endif
  355. #if CONFIG_AIRPLAY_SINK
  356. case DECODE_RAOP:
  357. raop_disconnect();
  358. raop_state = RAOP_STOP;
  359. break;
  360. #endif
  361. }
  362. }