decode_external.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 "config.h"
  22. #include "squeezelite.h"
  23. #include "bt_app_sink.h"
  24. #include "raop_sink.h"
  25. #include <math.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_SLOW 32
  40. #define SYNC_WIN_CHECK 8
  41. #define SYNC_WIN_FAST 2
  42. static raop_event_t raop_state;
  43. static EXT_RAM_ATTR struct {
  44. bool enabled, init;
  45. int sum, count, win, errors[SYNC_WIN_SLOW];
  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 apply sync
  158. */
  159. static void resync(int error) {
  160. if (error < 0) {
  161. output.skip_frames = -(error * RAOP_SAMPLE_RATE) / 1000;
  162. output.state = OUTPUT_SKIP_FRAMES;
  163. LOG_INFO("skipping %u frames (count:%d)", output.skip_frames, raop_sync.count);
  164. } else {
  165. output.pause_frames = (error * RAOP_SAMPLE_RATE) / 1000;
  166. output.state = OUTPUT_PAUSE_FRAMES;
  167. LOG_INFO("pausing for %u frames (count: %d)", output.pause_frames, raop_sync.count);
  168. }
  169. }
  170. /****************************************************************************************
  171. * AirPlay sink command handler
  172. */
  173. static bool raop_sink_cmd_handler(raop_event_t event, va_list args)
  174. {
  175. // don't LOCK_O as there is always a chance that LMS takes control later anyway
  176. if (output.external != DECODE_RAOP && output.state > OUTPUT_STOPPED) {
  177. LOG_WARN("Cannot use Airplay sink while LMS/BT is controlling player");
  178. return false;
  179. }
  180. LOCK_D;
  181. if (event != RAOP_VOLUME) LOCK_O;
  182. // this is async, so player might have been deleted
  183. switch (event) {
  184. case RAOP_TIMING: {
  185. u32_t ms, now = gettime_ms();
  186. int error;
  187. if (!raop_sync.enabled || output.state != OUTPUT_RUNNING || output.frames_played_dmp < output.device_frames) break;
  188. // do one (only one) time-based adjustement in case we started totally off)
  189. if (raop_sync.init) {
  190. // how many ms have we really played
  191. ms = now - output.updated + ((output.frames_played_dmp - output.device_frames) * 10) / (RAOP_SAMPLE_RATE / 100);
  192. error = ms - (now - raop_sync.start_time);
  193. resync(error);
  194. LOG_INFO("backend played %u, desired %u, (delta:%d)", ms, now - raop_sync.start_time, error);
  195. raop_sync.init = false;
  196. raop_sync.win = SYNC_WIN_FAST;
  197. raop_sync.sum = raop_sync.count = 0 ;
  198. memset(raop_sync.errors, 0, sizeof(raop_sync.errors));
  199. } else {
  200. u32_t level = _buf_used(outputbuf);
  201. // in how many ms will the most recent block play
  202. 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);
  203. // when outputbuf is empty, it means we have a network black-out or something
  204. error = level ? (raop_sync.playtime - now) - ms : 0;
  205. if (loglevel == lDEBUG || !level) {
  206. LOG_INFO("head local:%d, remote:%d (delta:%d)", ms, raop_sync.playtime - now, error);
  207. LOG_INFO("obuf:%u, sync_len:%u, devframes:%u, inproc:%u", _buf_used(outputbuf), raop_sync.len, output.device_frames, output.frames_in_process);
  208. }
  209. // calculate sum, error and update sliding window
  210. raop_sync.errors[raop_sync.count++ % raop_sync.win] = error;
  211. raop_sync.sum += error;
  212. error = raop_sync.sum / min(raop_sync.count, raop_sync.win);
  213. // move to normal mode if possible
  214. if (raop_sync.win == SYNC_WIN_FAST && raop_sync.count >= SYNC_WIN_FAST && abs(error) < 10) {
  215. raop_sync.win = SYNC_WIN_SLOW;
  216. LOG_INFO("switching to slow sync mode %u", raop_sync.win);
  217. }
  218. // wait till we have enough data or there is a strong deviation
  219. if ((raop_sync.count >= raop_sync.win && abs(error) > 10) || (raop_sync.count >= SYNC_WIN_CHECK && abs(error) > 100)) {
  220. resync(error);
  221. raop_sync.sum = raop_sync.count = 0;
  222. memset(raop_sync.errors, 0, sizeof(raop_sync.errors));
  223. }
  224. }
  225. break;
  226. }
  227. case RAOP_SETUP:
  228. // we need a fair bit of space for RTP process
  229. _buf_resize(outputbuf, 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. case RAOP_STREAM:
  237. LOG_INFO("Stream", NULL);
  238. raop_state = event;
  239. raop_sync.init = true;
  240. raop_sync.enabled = !strcasestr(output.device, "BT");
  241. output.next_sample_rate = output.current_sample_rate = RAOP_SAMPLE_RATE;
  242. break;
  243. case RAOP_STOP:
  244. case RAOP_FLUSH:
  245. if (event == RAOP_FLUSH) { LOG_INFO("Flush", NULL); }
  246. else { LOG_INFO("Stop", NULL); }
  247. raop_state = event;
  248. _buf_flush(outputbuf);
  249. if (output.state > OUTPUT_STOPPED) output.state = OUTPUT_STOPPED;
  250. output.frames_played = 0;
  251. output.stop_time = gettime_ms();
  252. break;
  253. case RAOP_PLAY: {
  254. LOG_INFO("Play", NULL);
  255. if (raop_state != RAOP_PLAY) {
  256. output.state = OUTPUT_START_AT;
  257. output.start_at = va_arg(args, u32_t);
  258. raop_sync.start_time = output.start_at;
  259. LOG_INFO("Starting at %u (in %d ms)", output.start_at, output.start_at - gettime_ms());
  260. }
  261. raop_state = event;
  262. break;
  263. }
  264. case RAOP_VOLUME: {
  265. float volume = va_arg(args, double);
  266. LOG_INFO("Volume[0..1] %0.4f", volume);
  267. volume = 65536 * powf(volume, 3);
  268. set_volume((u16_t) volume, (u16_t) volume);
  269. break;
  270. }
  271. default:
  272. break;
  273. }
  274. if (event != RAOP_VOLUME) UNLOCK_O;
  275. UNLOCK_D;
  276. return true;
  277. }
  278. /****************************************************************************************
  279. * We provide the generic codec register option
  280. */
  281. void register_external(void) {
  282. char *p;
  283. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_bt_sink")) != NULL) {
  284. enable_bt_sink = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  285. free(p);
  286. }
  287. if ((p = config_alloc_get(NVS_TYPE_STR, "enable_airplay")) != NULL) {
  288. enable_airplay = strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0;
  289. free(p);
  290. }
  291. if (!strcasestr(output.device, "BT ") ) {
  292. if(enable_bt_sink){
  293. bt_sink_init(bt_sink_cmd_handler, sink_data_handler);
  294. LOG_INFO("Initializing BT sink");
  295. }
  296. } else {
  297. LOG_WARN("Cannot be a BT sink and source");
  298. }
  299. if (enable_airplay){
  300. raop_sink_init(raop_sink_cmd_handler, raop_sink_data_handler);
  301. LOG_INFO("Initializing AirPlay sink");
  302. }
  303. }
  304. void deregister_external(void) {
  305. if (!strcasestr(output.device, "BT ") && enable_bt_sink) {
  306. bt_sink_deinit();
  307. LOG_INFO("Stopping BT sink");
  308. }
  309. if (enable_airplay){
  310. raop_sink_deinit();
  311. LOG_INFO("Stopping AirPlay sink");
  312. }
  313. }
  314. void decode_restore(int external) {
  315. switch (external) {
  316. case DECODE_BT:
  317. bt_disconnect();
  318. break;
  319. case DECODE_RAOP:
  320. raop_disconnect();
  321. raop_state = RAOP_STOP;
  322. break;
  323. }
  324. }