decode_external.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /*
  2. * Squeezelite for esp32
  3. *
  4. * (c) Sebastien 2019
  5. * Philippe G. 2019, philippe_44@outlook.com
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. #include "platform_config.h"
  22. #include "squeezelite.h"
  23. #include "raop_sink.h"
  24. #include <math.h>
  25. #include "bt_app_sink.h"
  26. #define LOCK_O mutex_lock(outputbuf->mutex)
  27. #define UNLOCK_O mutex_unlock(outputbuf->mutex)
  28. #define LOCK_D mutex_lock(decode.mutex);
  29. #define UNLOCK_D mutex_unlock(decode.mutex);
  30. enum { DECODE_BT = 1, DECODE_RAOP };
  31. extern struct outputstate output;
  32. extern struct decodestate decode;
  33. extern struct buffer *outputbuf;
  34. // this is the only system-wide loglevel variable
  35. extern log_level loglevel;
  36. static bool enable_bt_sink;
  37. static bool enable_airplay;
  38. #define RAOP_OUTPUT_SIZE (RAOP_SAMPLE_RATE * 2 * 2 * 2 * 1.2)
  39. #define SYNC_WIN_RUN 32
  40. #define SYNC_WIN_CHECK 8
  41. #define SYNC_WIN_START 2
  42. static raop_event_t raop_state;
  43. static EXT_RAM_ATTR struct {
  44. bool enabled;
  45. int sum, count, win, errors[SYNC_WIN_RUN];
  46. s32_t len;
  47. u32_t start_time, playtime;
  48. } raop_sync;
  49. /****************************************************************************************
  50. * Common sink data handler
  51. */
  52. static void sink_data_handler(const uint8_t *data, uint32_t len)
  53. {
  54. size_t bytes, space;
  55. int wait = 5;
  56. // would be better to lock output, but really, it does not matter
  57. if (!output.external) {
  58. LOG_SDEBUG("Cannot use external sink while LMS is controlling player");
  59. return;
  60. }
  61. // there will always be room at some point
  62. while (len) {
  63. LOCK_O;
  64. bytes = min(_buf_space(outputbuf), _buf_cont_write(outputbuf));
  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 / BYTES_PER_FRAME * 2;
  73. while (n--) *optr++ = *iptr++ << 16;
  74. }
  75. #endif
  76. _buf_inc_writep(outputbuf, bytes);
  77. space = _buf_space(outputbuf);
  78. len -= bytes;
  79. data += bytes;
  80. UNLOCK_O;
  81. // allow i2s to empty the buffer if needed
  82. if (len && !space && wait--) usleep(20000);
  83. }
  84. if (!wait) {
  85. LOG_WARN("Waited too long, dropping frames");
  86. }
  87. }
  88. /****************************************************************************************
  89. * BT sink command handler
  90. */
  91. static bool bt_sink_cmd_handler(bt_sink_cmd_t cmd, va_list args)
  92. {
  93. // don't LOCK_O as there is always a chance that LMS takes control later anyway
  94. if (output.external != DECODE_BT && output.state > OUTPUT_STOPPED) {
  95. LOG_WARN("Cannot use BT sink while LMS/AirPlay is controlling player");
  96. return false;
  97. }
  98. LOCK_D;
  99. if (cmd != BT_SINK_VOLUME) LOCK_O;
  100. switch(cmd) {
  101. case BT_SINK_AUDIO_STARTED:
  102. output.next_sample_rate = output.current_sample_rate = va_arg(args, u32_t);
  103. output.external = DECODE_BT;
  104. output.state = OUTPUT_STOPPED;
  105. output.frames_played = 0;
  106. _buf_flush(outputbuf);
  107. if (decode.state != DECODE_STOPPED) decode.state = DECODE_ERROR;
  108. LOG_INFO("BT sink started");
  109. break;
  110. case BT_SINK_AUDIO_STOPPED:
  111. if (output.external == DECODE_BT) {
  112. if (output.state > OUTPUT_STOPPED) output.state = OUTPUT_STOPPED;
  113. output.stop_time = gettime_ms();
  114. LOG_INFO("BT sink stopped");
  115. }
  116. break;
  117. case BT_SINK_PLAY:
  118. output.state = OUTPUT_RUNNING;
  119. LOG_INFO("BT playing");
  120. break;
  121. case BT_SINK_STOP:
  122. _buf_flush(outputbuf);
  123. output.state = OUTPUT_STOPPED;
  124. output.stop_time = gettime_ms();
  125. LOG_INFO("BT stopped");
  126. break;
  127. case BT_SINK_PAUSE:
  128. output.stop_time = gettime_ms();
  129. LOG_INFO("BT paused, just silence");
  130. break;
  131. case BT_SINK_RATE:
  132. output.next_sample_rate = output.current_sample_rate = va_arg(args, u32_t);
  133. LOG_INFO("Setting BT sample rate %u", output.next_sample_rate);
  134. break;
  135. case BT_SINK_VOLUME: {
  136. u16_t volume = (u16_t) va_arg(args, u32_t);
  137. volume = 65536 * powf(volume / 128.0f, 3);
  138. set_volume(volume, volume);
  139. break;
  140. default:
  141. break;
  142. }
  143. }
  144. if (cmd != BT_SINK_VOLUME) UNLOCK_O;
  145. UNLOCK_D;
  146. return true;
  147. }
  148. /****************************************************************************************
  149. * raop sink data handler
  150. */
  151. static void raop_sink_data_handler(const uint8_t *data, uint32_t len, u32_t playtime) {
  152. raop_sync.playtime = playtime;
  153. raop_sync.len = len;
  154. sink_data_handler(data, len);
  155. }
  156. /****************************************************************************************
  157. * AirPlay sink command handler
  158. */
  159. static bool raop_sink_cmd_handler(raop_event_t event, va_list args)
  160. {
  161. // don't LOCK_O as there is always a chance that LMS takes control later anyway
  162. if (output.external != DECODE_RAOP && output.state > OUTPUT_STOPPED) {
  163. LOG_WARN("Cannot use Airplay sink while LMS/BT is controlling player");
  164. return false;
  165. }
  166. LOCK_D;
  167. if (event != RAOP_VOLUME) LOCK_O;
  168. // this is async, so player might have been deleted
  169. switch (event) {
  170. case RAOP_TIMING: {
  171. u32_t ms, now = gettime_ms();
  172. int error;
  173. if (!raop_sync.enabled || output.state < OUTPUT_RUNNING || output.frames_played_dmp < output.device_frames) break;
  174. // first must make sure we started on time
  175. if (raop_sync.win == SYNC_WIN_START) {
  176. // how many ms have we really played
  177. ms = now - output.updated + ((u64_t) (output.frames_played_dmp - output.device_frames) * 1000) / RAOP_SAMPLE_RATE;
  178. error = ms - (now - raop_sync.start_time);
  179. LOG_INFO("backend played %u, desired %u, (delta:%d)", ms, now - raop_sync.start_time, ms - (now - raop_sync.start_time));
  180. } else {
  181. u32_t level = _buf_used(outputbuf);
  182. // in how many ms will the most recent block play
  183. 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);
  184. // when outputbuf is empty, it means we have a network black-out or something
  185. error = level ? (raop_sync.playtime - now) - ms : 0;
  186. if (loglevel == lDEBUG || !level) {
  187. LOG_INFO("head local:%d, remote:%d (delta:%d)", ms, raop_sync.playtime - now, error);
  188. LOG_INFO("obuf:%u, sync_len:%u, devframes:%u, inproc:%u", _buf_used(outputbuf), raop_sync.len, output.device_frames, output.frames_in_process);
  189. }
  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. // move to normal mode if possible
  196. if (raop_sync.win == SYNC_WIN_START && raop_sync.count >= SYNC_WIN_START && abs(error) < 10) {
  197. raop_sync.win = SYNC_WIN_RUN;
  198. LOG_INFO("switching to slow sync mode %u", raop_sync.win);
  199. }
  200. // wait till e 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. // correct if needed
  203. if (error < 0) {
  204. output.skip_frames = -(error * RAOP_SAMPLE_RATE) / 1000;
  205. output.state = OUTPUT_SKIP_FRAMES;
  206. LOG_INFO("skipping %u frames (count:%d)", output.skip_frames, raop_sync.count);
  207. } else {
  208. output.pause_frames = (error * RAOP_SAMPLE_RATE) / 1000;
  209. output.state = OUTPUT_PAUSE_FRAMES;
  210. LOG_INFO("pausing for %u frames (count: %d)", output.pause_frames, raop_sync.count);
  211. }
  212. // reset sliding window
  213. raop_sync.sum = raop_sync.count = 0;
  214. memset(raop_sync.errors, 0, sizeof(raop_sync.errors));
  215. }
  216. break;
  217. }
  218. case RAOP_SETUP:
  219. // we need a fair bit of space for RTP process
  220. _buf_resize(outputbuf, RAOP_OUTPUT_SIZE);
  221. output.frames_played = 0;
  222. output.external = DECODE_RAOP;
  223. output.state = OUTPUT_STOPPED;
  224. if (decode.state != DECODE_STOPPED) decode.state = DECODE_ERROR;
  225. LOG_INFO("resizing buffer %u", outputbuf->size);
  226. break;
  227. case RAOP_STREAM:
  228. LOG_INFO("Stream", NULL);
  229. raop_state = event;
  230. raop_sync.win = SYNC_WIN_START;
  231. raop_sync.sum = raop_sync.count = 0 ;
  232. memset(raop_sync.errors, 0, sizeof(raop_sync.errors));
  233. raop_sync.enabled = !strcasestr(output.device, "BT");
  234. output.next_sample_rate = output.current_sample_rate = RAOP_SAMPLE_RATE;
  235. break;
  236. case RAOP_STOP:
  237. case RAOP_FLUSH:
  238. if (event == RAOP_FLUSH) { LOG_INFO("Flush", NULL); }
  239. else { LOG_INFO("Stop", NULL); }
  240. raop_state = event;
  241. _buf_flush(outputbuf);
  242. if (output.state > OUTPUT_STOPPED) output.state = OUTPUT_STOPPED;
  243. output.frames_played = 0;
  244. output.stop_time = gettime_ms();
  245. break;
  246. case RAOP_PLAY: {
  247. LOG_INFO("Play", NULL);
  248. if (raop_state != RAOP_PLAY) {
  249. output.state = OUTPUT_START_AT;
  250. output.start_at = va_arg(args, u32_t);
  251. raop_sync.start_time = output.start_at;
  252. LOG_INFO("Starting at %u (in %d ms)", output.start_at, output.start_at - gettime_ms());
  253. }
  254. raop_state = event;
  255. break;
  256. }
  257. case RAOP_VOLUME: {
  258. float volume = va_arg(args, double);
  259. LOG_INFO("Volume[0..1] %0.4f", volume);
  260. volume = 65536 * powf(volume, 3);
  261. set_volume((u16_t) volume, (u16_t) volume);
  262. break;
  263. }
  264. default:
  265. break;
  266. }
  267. if (event != RAOP_VOLUME) UNLOCK_O;
  268. UNLOCK_D;
  269. return true;
  270. }
  271. /****************************************************************************************
  272. * We provide the generic codec register option
  273. */
  274. void register_external(void) {
  275. char *p;
  276. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_bt_sink")) != NULL) {
  277. enable_bt_sink = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  278. free(p);
  279. }
  280. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_airplay")) != NULL) {
  281. enable_airplay = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  282. free(p);
  283. }
  284. if (!strcasestr(output.device, "BT ") ) {
  285. if(enable_bt_sink){
  286. bt_sink_init(bt_sink_cmd_handler, sink_data_handler);
  287. LOG_INFO("Initializing BT sink");
  288. }
  289. } else {
  290. LOG_WARN("Cannot be a BT sink and source");
  291. }
  292. if (enable_airplay){
  293. raop_sink_init(raop_sink_cmd_handler, raop_sink_data_handler);
  294. LOG_INFO("Initializing AirPlay sink");
  295. }
  296. }
  297. void deregister_external(void) {
  298. if (!strcasestr(output.device, "BT ") && enable_bt_sink) {
  299. bt_sink_deinit();
  300. LOG_INFO("Stopping BT sink");
  301. }
  302. if (enable_airplay){
  303. raop_sink_deinit();
  304. LOG_INFO("Stopping AirPlay sink");
  305. }
  306. }
  307. void decode_restore(int external) {
  308. switch (external) {
  309. case DECODE_BT:
  310. bt_disconnect();
  311. break;
  312. case DECODE_RAOP:
  313. raop_disconnect();
  314. raop_state = RAOP_STOP;
  315. break;
  316. }
  317. }