decode_external.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 <platform_bt_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. u32_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. LOG_INFO("BT sink stopped");
  114. }
  115. break;
  116. case BT_SINK_PLAY:
  117. output.state = OUTPUT_RUNNING;
  118. LOG_INFO("BT sink playing");
  119. break;
  120. case BT_SINK_STOP:
  121. _buf_flush(outputbuf);
  122. output.state = OUTPUT_STOPPED;
  123. output.stop_time = gettime_ms();
  124. LOG_INFO("BT sink stopped");
  125. break;
  126. case BT_SINK_PAUSE:
  127. LOG_INFO("BT sink paused, just silence");
  128. break;
  129. case BT_SINK_RATE:
  130. output.next_sample_rate = output.current_sample_rate = va_arg(args, u32_t);
  131. LOG_INFO("Setting BT sample rate %u", output.next_sample_rate);
  132. break;
  133. case BT_SINK_VOLUME: {
  134. u16_t volume = (u16_t) va_arg(args, u32_t);
  135. volume = 65536 * powf(volume / 128.0f, 3);
  136. set_volume(volume, volume);
  137. break;
  138. default:
  139. break;
  140. }
  141. }
  142. if (cmd != BT_SINK_VOLUME) UNLOCK_O;
  143. UNLOCK_D;
  144. return true;
  145. }
  146. /****************************************************************************************
  147. * raop sink data handler
  148. */
  149. static void raop_sink_data_handler(const uint8_t *data, uint32_t len, u32_t playtime) {
  150. raop_sync.playtime = playtime;
  151. raop_sync.len = len;
  152. sink_data_handler(data, len);
  153. }
  154. /****************************************************************************************
  155. * AirPlay sink command handler
  156. */
  157. static bool raop_sink_cmd_handler(raop_event_t event, va_list args)
  158. {
  159. // don't LOCK_O as there is always a chance that LMS takes control later anyway
  160. if (output.external != DECODE_RAOP && output.state > OUTPUT_STOPPED) {
  161. LOG_WARN("Cannot use Airplay sink while LMS/BT is controlling player");
  162. return false;
  163. }
  164. LOCK_D;
  165. if (event != RAOP_VOLUME) LOCK_O;
  166. // this is async, so player might have been deleted
  167. switch (event) {
  168. case RAOP_TIMING: {
  169. u32_t ms, now = gettime_ms();
  170. int error;
  171. if (!raop_sync.enabled || output.state < OUTPUT_RUNNING || output.frames_played_dmp < output.device_frames) break;
  172. // first must make sure we started on time
  173. if (raop_sync.win == SYNC_WIN_START) {
  174. // how many ms have we really played
  175. ms = now - output.updated + ((u64_t) (output.frames_played_dmp - output.device_frames) * 1000) / RAOP_SAMPLE_RATE;
  176. error = ms - (now - raop_sync.start_time);
  177. LOG_INFO("backend played %u, desired %u, (delta:%d)", ms, now - raop_sync.start_time, ms - (now - raop_sync.start_time));
  178. } else {
  179. // in how many ms will the most recent block play
  180. ms = ((u64_t) ((_buf_used(outputbuf) - raop_sync.len) / BYTES_PER_FRAME + output.device_frames + output.frames_in_process) * 1000) / RAOP_SAMPLE_RATE - (now - output.updated);
  181. error = (raop_sync.playtime - now) - ms;
  182. // make sure impact of erroneous point is limited, but taken into account
  183. if (abs(error) > 1000) {
  184. LOG_INFO("limiting erroneous sync point %d", error);
  185. error = (error > 0) ? SYNC_WIN_RUN : -SYNC_WIN_RUN;
  186. }
  187. LOG_DEBUG("head local:%u, remote:%u (delta:%d)", ms, raop_sync.playtime - now, error);
  188. LOG_DEBUG("obuf:%u, sync_len:%u, devframes:%u, inproc:%u", _buf_used(outputbuf), raop_sync.len, output.device_frames, output.frames_in_process);
  189. }
  190. // calculate sum, error and update sliding window
  191. raop_sync.errors[raop_sync.count++ % raop_sync.win] = error;
  192. raop_sync.sum += error;
  193. error = raop_sync.sum / min(raop_sync.count, raop_sync.win);
  194. // move to normal mode if possible
  195. if (raop_sync.win == SYNC_WIN_START && raop_sync.count >= SYNC_WIN_START && abs(error) < 10) raop_sync.win = SYNC_WIN_RUN;
  196. // wait till e have enough data or there is a strong deviation
  197. if ((raop_sync.count >= raop_sync.win && abs(error) > 10) || (raop_sync.count >= SYNC_WIN_CHECK && abs(error) > 100)) {
  198. // correct if needed
  199. if (error < 0) {
  200. output.skip_frames = -(error * RAOP_SAMPLE_RATE) / 1000;
  201. output.state = OUTPUT_SKIP_FRAMES;
  202. LOG_INFO("skipping %u frames", output.skip_frames);
  203. } else {
  204. output.pause_frames = (error * RAOP_SAMPLE_RATE) / 1000;
  205. output.state = OUTPUT_PAUSE_FRAMES;
  206. LOG_INFO("pausing for %u frames", output.pause_frames);
  207. }
  208. // reset sliding window
  209. raop_sync.sum = raop_sync.count = 0;
  210. memset(raop_sync.errors, 0, sizeof(raop_sync.errors));
  211. }
  212. break;
  213. }
  214. case RAOP_SETUP:
  215. // we need a fair bit of space for RTP process
  216. _buf_resize(outputbuf, RAOP_OUTPUT_SIZE);
  217. output.frames_played = 0;
  218. output.external = DECODE_RAOP;
  219. output.state = OUTPUT_STOPPED;
  220. if (decode.state != DECODE_STOPPED) decode.state = DECODE_ERROR;
  221. LOG_INFO("resizing buffer %u", outputbuf->size);
  222. break;
  223. case RAOP_STREAM:
  224. LOG_INFO("Stream", NULL);
  225. raop_state = event;
  226. raop_sync.win = SYNC_WIN_START;
  227. raop_sync.sum = raop_sync.count = 0 ;
  228. memset(raop_sync.errors, 0, sizeof(raop_sync.errors));
  229. raop_sync.enabled = !strcasestr(output.device, "BT");
  230. output.next_sample_rate = output.current_sample_rate = RAOP_SAMPLE_RATE;
  231. break;
  232. case RAOP_STOP:
  233. case RAOP_FLUSH:
  234. if (event == RAOP_FLUSH) { LOG_INFO("Flush", NULL); }
  235. else { LOG_INFO("Stop", NULL); }
  236. raop_state = event;
  237. _buf_flush(outputbuf);
  238. if (output.state > OUTPUT_STOPPED) output.state = OUTPUT_STOPPED;
  239. output.frames_played = 0;
  240. output.stop_time = gettime_ms();
  241. break;
  242. case RAOP_PLAY: {
  243. LOG_INFO("Play", NULL);
  244. if (raop_state != RAOP_PLAY) {
  245. output.state = OUTPUT_START_AT;
  246. output.start_at = va_arg(args, u32_t);
  247. raop_sync.start_time = output.start_at;
  248. LOG_INFO("Starting at %u (in %d ms)", output.start_at, output.start_at - gettime_ms());
  249. }
  250. raop_state = event;
  251. break;
  252. }
  253. case RAOP_VOLUME: {
  254. float volume = va_arg(args, double);
  255. LOG_INFO("Volume[0..1] %0.4f", volume);
  256. volume = 65536 * powf(volume, 3);
  257. set_volume((u16_t) volume, (u16_t) volume);
  258. break;
  259. }
  260. default:
  261. break;
  262. }
  263. if (event != RAOP_VOLUME) UNLOCK_O;
  264. UNLOCK_D;
  265. return true;
  266. }
  267. /****************************************************************************************
  268. * We provide the generic codec register option
  269. */
  270. void register_external(void) {
  271. char *p;
  272. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_bt_sink")) != NULL) {
  273. enable_bt_sink = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  274. free(p);
  275. }
  276. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_airplay")) != NULL) {
  277. enable_airplay = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  278. free(p);
  279. }
  280. if (!strcasestr(output.device, "BT ") ) {
  281. if(enable_bt_sink){
  282. bt_sink_init(bt_sink_cmd_handler, sink_data_handler);
  283. LOG_INFO("Initializing BT sink");
  284. }
  285. } else {
  286. LOG_WARN("Cannot be a BT sink and source");
  287. }
  288. if (enable_airplay){
  289. raop_sink_init(raop_sink_cmd_handler, raop_sink_data_handler);
  290. LOG_INFO("Initializing AirPlay sink");
  291. }
  292. }
  293. void deregister_external(void) {
  294. if (!strcasestr(output.device, "BT ") && enable_bt_sink) {
  295. bt_sink_deinit();
  296. LOG_INFO("Stopping BT sink");
  297. }
  298. if (enable_airplay){
  299. raop_sink_deinit();
  300. LOG_INFO("Stopping AirPlay sink");
  301. }
  302. }
  303. void decode_restore(int external) {
  304. switch (external) {
  305. case DECODE_BT:
  306. bt_disconnect();
  307. break;
  308. case DECODE_RAOP:
  309. raop_disconnect();
  310. raop_state = RAOP_STOP;
  311. break;
  312. }
  313. }