slimproto.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. /*
  2. * Squeezelite - lightweight headless squeezebox emulator
  3. *
  4. * (c) Adrian Smith 2012-2015, triode1@btinternet.com
  5. * Ralph Irving 2015-2017, ralph_irving@hotmail.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. * Additions (c) Paul Hermann, 2015-2017 under the same license terms
  21. * -Control of Raspberry pi GPIO for amplifier power
  22. * -Launch script on power status change from LMS
  23. */
  24. #include "squeezelite.h"
  25. #include "slimproto.h"
  26. static log_level loglevel;
  27. #define SQUEEZENETWORK "mysqueezebox.com:3483"
  28. #define PORT 3483
  29. #define MAXBUF 4096
  30. #if SL_LITTLE_ENDIAN
  31. #define LOCAL_PLAYER_IP 0x0100007f // 127.0.0.1
  32. #define LOCAL_PLAYER_PORT 0x9b0d // 3483
  33. #else
  34. #define LOCAL_PLAYER_IP 0x7f000001 // 127.0.0.1
  35. #define LOCAL_PLAYER_PORT 0x0d9b // 3483
  36. #endif
  37. static sockfd sock = -1;
  38. static in_addr_t slimproto_ip = 0;
  39. static u16_t slimproto_hport = 9000;
  40. static u16_t slimproto_cport = 9090;
  41. static u8_t player_id;
  42. extern struct buffer *streambuf;
  43. extern struct buffer *outputbuf;
  44. extern struct streamstate stream;
  45. extern struct outputstate output;
  46. extern struct decodestate decode;
  47. extern struct codec *codecs[];
  48. #if IR
  49. extern struct irstate ir;
  50. #endif
  51. event_event wake_e;
  52. #define LOCK_S mutex_lock(streambuf->mutex)
  53. #define UNLOCK_S mutex_unlock(streambuf->mutex)
  54. #define LOCK_O mutex_lock(outputbuf->mutex)
  55. #define UNLOCK_O mutex_unlock(outputbuf->mutex)
  56. #define LOCK_D mutex_lock(decode.mutex)
  57. #define UNLOCK_D mutex_unlock(decode.mutex)
  58. #if !EMBEDDED
  59. #define LOCK_P
  60. #define UNLOCK_P
  61. #endif
  62. #if IR
  63. #define LOCK_I mutex_lock(ir.mutex)
  64. #define UNLOCK_I mutex_unlock(ir.mutex)
  65. #endif
  66. static struct {
  67. u32_t updated;
  68. u32_t stream_start;
  69. u32_t stream_full;
  70. u32_t stream_size;
  71. u64_t stream_bytes;
  72. u32_t output_full;
  73. u32_t output_size;
  74. u32_t frames_played;
  75. u32_t device_frames;
  76. u32_t current_sample_rate;
  77. u32_t last;
  78. stream_state stream_state;
  79. } status;
  80. static int autostart;
  81. static bool sentSTMu, sentSTMo, sentSTMl;
  82. static u32_t new_server;
  83. static char *new_server_cap;
  84. #define PLAYER_NAME_LEN 64
  85. static char player_name[PLAYER_NAME_LEN + 1] = "";
  86. static const char *name_file = NULL;
  87. void slimproto_send_packet(u8_t *packet, size_t len) {
  88. u8_t *ptr = packet;
  89. unsigned try = 0;
  90. ssize_t n;
  91. while (len) {
  92. n = send(sock, ptr, len, MSG_NOSIGNAL);
  93. if (n <= 0) {
  94. if (n < 0 && last_error() == ERROR_WOULDBLOCK && try < 10) {
  95. LOG_DEBUG("retrying (%d) writing to socket", ++try);
  96. usleep(1000);
  97. continue;
  98. }
  99. LOG_INFO("failed writing to socket: %s", strerror(last_error()));
  100. return;
  101. }
  102. ptr += n;
  103. len -= n;
  104. }
  105. }
  106. static void sendHELO(bool reconnect, const char *fixed_cap, const char *var_cap, u8_t mac[6]) {
  107. #ifndef BASE_CAP
  108. #define BASE_CAP "Model=squeezelite,AccuratePlayPoints=1,HasDigitalOut=1,HasPolarityInversion=1,Balance=1,Firmware=" VERSION
  109. #endif
  110. #define SSL_CAP "CanHTTPS=1"
  111. const char *base_cap;
  112. struct HELO_packet pkt;
  113. #if USE_SSL
  114. #if !LINKALL && !NO_SSLSYM
  115. if (ssl_loaded) base_cap = SSL_CAP "," BASE_CAP;
  116. else base_cap = BASE_CAP;
  117. #endif
  118. base_cap = SSL_CAP "," BASE_CAP;
  119. #else
  120. base_cap = BASE_CAP;
  121. #endif
  122. if (!reconnect) player_id = PLAYER_ID;
  123. memset(&pkt, 0, sizeof(pkt));
  124. memcpy(&pkt.opcode, "HELO", 4);
  125. pkt.length = htonl(sizeof(struct HELO_packet) - 8 + strlen(base_cap) + strlen(fixed_cap) + strlen(var_cap));
  126. pkt.deviceid = player_id;
  127. pkt.revision = 0;
  128. packn(&pkt.wlan_channellist, reconnect ? 0x4000 : 0x0000);
  129. packN(&pkt.bytes_received_H, (u64_t)status.stream_bytes >> 32);
  130. packN(&pkt.bytes_received_L, (u64_t)status.stream_bytes & 0xffffffff);
  131. memcpy(pkt.mac, mac, 6);
  132. LOG_INFO("mac: %02x:%02x:%02x:%02x:%02x:%02x", pkt.mac[0], pkt.mac[1], pkt.mac[2], pkt.mac[3], pkt.mac[4], pkt.mac[5]);
  133. LOG_INFO("cap: %s%s%s", base_cap, fixed_cap, var_cap);
  134. LOCK_P;
  135. send_packet((u8_t *)&pkt, sizeof(pkt));
  136. send_packet((u8_t *)base_cap, strlen(base_cap));
  137. send_packet((u8_t *)fixed_cap, strlen(fixed_cap));
  138. send_packet((u8_t *)var_cap, strlen(var_cap));
  139. UNLOCK_P;
  140. }
  141. static void sendSTAT(const char *event, u32_t server_timestamp) {
  142. struct STAT_packet pkt;
  143. u32_t now = gettime_ms();
  144. u32_t ms_played;
  145. if (status.current_sample_rate && status.frames_played && status.frames_played > status.device_frames) {
  146. ms_played = (u32_t)(((u64_t)(status.frames_played - status.device_frames) * (u64_t)1000) / (u64_t)status.current_sample_rate);
  147. if (now > status.updated) ms_played += (now - status.updated);
  148. LOG_SDEBUG("ms_played: %u (frames_played: %u device_frames: %u)", ms_played, status.frames_played, status.device_frames);
  149. } else if (status.frames_played && now > status.stream_start) {
  150. ms_played = now - status.stream_start;
  151. LOG_SDEBUG("ms_played: %u using elapsed time (frames_played: %u device_frames: %u)", ms_played, status.frames_played, status.device_frames);
  152. } else {
  153. LOG_SDEBUG("ms_played: 0");
  154. ms_played = 0;
  155. }
  156. memset(&pkt, 0, sizeof(struct STAT_packet));
  157. memcpy(&pkt.opcode, "STAT", 4);
  158. pkt.length = htonl(sizeof(struct STAT_packet) - 8);
  159. memcpy(&pkt.event, event, 4);
  160. // num_crlf
  161. // mas_initialized; mas_mode;
  162. packN(&pkt.stream_buffer_fullness, status.stream_full);
  163. packN(&pkt.stream_buffer_size, status.stream_size);
  164. packN(&pkt.bytes_received_H, (u64_t)status.stream_bytes >> 32);
  165. packN(&pkt.bytes_received_L, (u64_t)status.stream_bytes & 0xffffffff);
  166. #if EMBEDDED
  167. packn(&pkt.signal_strength, get_RSSI());
  168. packn(&pkt.voltage, (get_battery() << 4) | get_plugged());
  169. #else
  170. pkt.signal_strength = 0xffff;
  171. #endif
  172. packN(&pkt.jiffies, now);
  173. packN(&pkt.output_buffer_size, status.output_size);
  174. packN(&pkt.output_buffer_fullness, status.output_full);
  175. packN(&pkt.elapsed_seconds, ms_played / 1000);
  176. packN(&pkt.elapsed_milliseconds, ms_played);
  177. pkt.server_timestamp = server_timestamp; // keep this is server format - don't unpack/pack
  178. // error_code;
  179. LOG_DEBUG("STAT: %s", event);
  180. if (loglevel == lSDEBUG) {
  181. LOG_SDEBUG("received bytesL: %u streambuf: %u outputbuf: %u calc elapsed: %u real elapsed: %u (diff: %d) device: %u delay: %d",
  182. (u32_t)status.stream_bytes, status.stream_full, status.output_full, ms_played, now - status.stream_start,
  183. ms_played - now + status.stream_start, status.device_frames * 1000 / status.current_sample_rate, now - status.updated);
  184. }
  185. LOCK_P;
  186. send_packet((u8_t *)&pkt, sizeof(pkt));
  187. UNLOCK_P;
  188. }
  189. static void sendDSCO(disconnect_code disconnect) {
  190. struct DSCO_packet pkt;
  191. memset(&pkt, 0, sizeof(pkt));
  192. memcpy(&pkt.opcode, "DSCO", 4);
  193. pkt.length = htonl(sizeof(pkt) - 8);
  194. pkt.reason = disconnect & 0xFF;
  195. LOG_DEBUG("DSCO: %d", disconnect);
  196. LOCK_P;
  197. send_packet((u8_t *)&pkt, sizeof(pkt));
  198. UNLOCK_P;
  199. }
  200. static void sendRESP(const char *header, size_t len) {
  201. struct RESP_header pkt_header;
  202. memset(&pkt_header, 0, sizeof(pkt_header));
  203. memcpy(&pkt_header.opcode, "RESP", 4);
  204. pkt_header.length = htonl(sizeof(pkt_header) + len - 8);
  205. LOG_DEBUG("RESP");
  206. LOCK_P;
  207. send_packet((u8_t *)&pkt_header, sizeof(pkt_header));
  208. send_packet((u8_t *)header, len);
  209. UNLOCK_P;
  210. }
  211. static void sendMETA(const char *meta, size_t len) {
  212. struct META_header pkt_header;
  213. memset(&pkt_header, 0, sizeof(pkt_header));
  214. memcpy(&pkt_header.opcode, "META", 4);
  215. pkt_header.length = htonl(sizeof(pkt_header) + len - 8);
  216. LOG_DEBUG("META");
  217. LOCK_P;
  218. send_packet((u8_t *)&pkt_header, sizeof(pkt_header));
  219. send_packet((u8_t *)meta, len);
  220. UNLOCK_P;
  221. }
  222. static void sendSETDName(const char *name) {
  223. struct SETD_header pkt_header;
  224. memset(&pkt_header, 0, sizeof(pkt_header));
  225. memcpy(&pkt_header.opcode, "SETD", 4);
  226. pkt_header.id = 0; // id 0 is playername S:P:Squeezebox2
  227. pkt_header.length = htonl(sizeof(pkt_header) + strlen(name) + 1 - 8);
  228. LOG_DEBUG("set playername: %s", name);
  229. LOCK_P;
  230. send_packet((u8_t *)&pkt_header, sizeof(pkt_header));
  231. send_packet((u8_t *)name, strlen(name) + 1);
  232. UNLOCK_P;
  233. }
  234. #if IR
  235. void sendIR(u32_t code, u32_t ts) {
  236. struct IR_packet pkt;
  237. memset(&pkt, 0, sizeof(pkt));
  238. memcpy(&pkt.opcode, "IR ", 4);
  239. pkt.length = htonl(sizeof(pkt) - 8);
  240. packN(&pkt.jiffies, ts);
  241. pkt.ir_code = htonl(code);
  242. LOG_DEBUG("IR: ir code: 0x%x ts: %u", code, ts);
  243. LOCK_P;
  244. send_packet((u8_t *)&pkt, sizeof(pkt));
  245. UNLOCK_P;
  246. }
  247. #endif
  248. static void process_strm(u8_t *pkt, int len) {
  249. struct strm_packet *strm = (struct strm_packet *)pkt;
  250. LOG_DEBUG("strm command %c", strm->command);
  251. switch(strm->command) {
  252. case 't':
  253. sendSTAT("STMt", strm->replay_gain); // STMt replay_gain is no longer used to track latency, but support it
  254. break;
  255. case 'f':
  256. {
  257. decode_flush(false);
  258. bool flushed = false;
  259. if (!output.external) flushed |= output_flush_streaming();
  260. // we can have fully finished the current streaming, that's still a flush
  261. if (stream_disconnect() || flushed) sendSTAT("STMf", 0);
  262. buf_flush(streambuf);
  263. output.stop_time = gettime_ms();
  264. break;
  265. }
  266. case 'q':
  267. decode_flush(true);
  268. if (!output.external) output_flush();
  269. status.frames_played = 0;
  270. if (stream_disconnect() && strm->command == 'f') sendSTAT("STMf", 0);
  271. buf_flush(streambuf);
  272. output.stop_time = gettime_ms();
  273. break;
  274. case 'p':
  275. {
  276. unsigned interval = unpackN(&strm->replay_gain);
  277. LOCK_O;
  278. output.pause_frames = interval * status.current_sample_rate / 1000;
  279. if (interval) {
  280. output.state = OUTPUT_PAUSE_FRAMES;
  281. } else if (output.state != OUTPUT_OFF) {
  282. output.state = OUTPUT_STOPPED;
  283. output.stop_time = gettime_ms();
  284. }
  285. UNLOCK_O;
  286. if (!interval) sendSTAT("STMp", 0);
  287. LOG_DEBUG("pause interval: %u", interval);
  288. }
  289. break;
  290. case 'a':
  291. {
  292. unsigned interval = unpackN(&strm->replay_gain);
  293. LOCK_O;
  294. output.skip_frames = interval * status.current_sample_rate / 1000;
  295. output.state = OUTPUT_SKIP_FRAMES;
  296. UNLOCK_O;
  297. LOG_DEBUG("skip ahead interval: %u", interval);
  298. }
  299. break;
  300. case 'u':
  301. {
  302. unsigned jiffies = unpackN(&strm->replay_gain);
  303. LOCK_O;
  304. output.state = jiffies ? OUTPUT_START_AT : OUTPUT_RUNNING;
  305. output.start_at = jiffies;
  306. UNLOCK_O;
  307. LOG_DEBUG("unpause at: %u now: %u", jiffies, gettime_ms());
  308. sendSTAT("STMr", 0);
  309. }
  310. break;
  311. case 's':
  312. {
  313. unsigned header_len = len - sizeof(struct strm_packet);
  314. char *header = (char *)(pkt + sizeof(struct strm_packet));
  315. in_addr_t ip = (in_addr_t)strm->server_ip; // keep in network byte order
  316. u16_t port = strm->server_port; // keep in network byte order
  317. if (ip == 0) ip = slimproto_ip;
  318. LOG_DEBUG("strm s autostart: %c transition period: %u transition type: %u codec: %c",
  319. strm->autostart, strm->transition_period, strm->transition_type - '0', strm->format);
  320. autostart = strm->autostart - '0';
  321. sendSTAT("STMf", 0);
  322. if (header_len > MAX_HEADER -1) {
  323. LOG_WARN("header too long: %u", header_len);
  324. break;
  325. }
  326. if (strm->format != '?') {
  327. codec_open(strm->format, strm->pcm_sample_size, strm->pcm_sample_rate, strm->pcm_channels, strm->pcm_endianness);
  328. } else if (autostart >= 2) {
  329. // extension to slimproto to allow server to detect codec from response header and send back in codc message
  330. LOG_DEBUG("streaming unknown codec");
  331. } else {
  332. LOG_WARN("unknown codec requires autostart >= 2");
  333. break;
  334. }
  335. if (ip == LOCAL_PLAYER_IP && port == LOCAL_PLAYER_PORT) {
  336. // extension to slimproto for LocalPlayer - header is filename not http header, don't expect cont
  337. stream_file(header, header_len, strm->threshold * 1024);
  338. autostart -= 2;
  339. } else {
  340. stream_sock(ip, port, strm->flags & 0x20,
  341. strm->format == 'o' || strm->format == 'u' || (strm->format == 'f' && strm->pcm_sample_size == 'o'),
  342. header, header_len, strm->threshold * 1024, autostart >= 2);
  343. }
  344. sendSTAT("STMc", 0);
  345. sentSTMu = sentSTMo = sentSTMl = false;
  346. #if EMBEDDED
  347. // not protected so that restore can call synchronously sink handlers
  348. if (output.external) decode_restore(output.external);
  349. LOCK_O;
  350. output.external = 0;
  351. _buf_limit(outputbuf, 0);
  352. #else
  353. LOCK_O;
  354. #endif
  355. output.threshold = strm->output_threshold;
  356. output.next_replay_gain = unpackN(&strm->replay_gain);
  357. output.fade_mode = strm->transition_type - '0';
  358. output.fade_secs = strm->transition_period;
  359. output.invert = (strm->flags & 0x03) == 0x03;
  360. output.channels = (strm->flags & 0x0c) >> 2;
  361. UNLOCK_O;
  362. LOG_DEBUG("set fade: %u, channels: %u, invert: %u", output.fade_mode, output.channels, output.invert);
  363. }
  364. break;
  365. default:
  366. LOG_WARN("unhandled strm %c", strm->command);
  367. break;
  368. }
  369. }
  370. static void process_cont(u8_t *pkt, int len) {
  371. struct cont_packet *cont = (struct cont_packet *)pkt;
  372. cont->metaint = unpackN(&cont->metaint);
  373. LOG_DEBUG("cont metaint: %u loop: %u", cont->metaint, cont->loop);
  374. if (autostart > 1) {
  375. autostart -= 2;
  376. LOCK_S;
  377. if (stream.state == STREAMING_WAIT) {
  378. stream.state = STREAMING_BUFFERING;
  379. stream.meta_interval = stream.meta_next = cont->metaint;
  380. }
  381. UNLOCK_S;
  382. wake_controller();
  383. }
  384. }
  385. static void process_codc(u8_t *pkt, int len) {
  386. struct codc_packet *codc = (struct codc_packet *)pkt;
  387. LOG_DEBUG("codc: %c", codc->format);
  388. codec_open(codc->format, codc->pcm_sample_size, codc->pcm_sample_rate, codc->pcm_channels, codc->pcm_endianness);
  389. }
  390. static void process_aude(u8_t *pkt, int len) {
  391. struct aude_packet *aude = (struct aude_packet *)pkt;
  392. LOG_DEBUG("enable spdif: %d dac: %d", aude->enable_spdif, aude->enable_dac);
  393. #if EMBEDDED
  394. powering(aude->enable_spdif),
  395. #endif
  396. LOCK_O;
  397. if (!aude->enable_spdif && output.state != OUTPUT_OFF) {
  398. output.state = OUTPUT_OFF;
  399. }
  400. if (aude->enable_spdif && output.state == OUTPUT_OFF && !output.idle_to) {
  401. output.state = OUTPUT_STOPPED;
  402. output.stop_time = gettime_ms();
  403. }
  404. UNLOCK_O;
  405. }
  406. static void process_audg(u8_t *pkt, int len) {
  407. struct audg_packet *audg = (struct audg_packet *)pkt;
  408. audg->gainL = unpackN(&audg->gainL);
  409. audg->gainR = unpackN(&audg->gainR);
  410. LOG_DEBUG("audg gainL: %u gainR: %u adjust: %u", audg->gainL, audg->gainR, audg->adjust);
  411. set_volume(audg->adjust ? audg->gainL : FIXED_ONE, audg->adjust ? audg->gainR : FIXED_ONE);
  412. }
  413. static void process_dsco(u8_t *pkt, int len) {
  414. LOG_INFO("got DSCO, switching from id %u to 12", (int) player_id);
  415. player_id = 12;
  416. }
  417. static void process_setd(u8_t *pkt, int len) {
  418. struct setd_packet *setd = (struct setd_packet *)pkt;
  419. // handle player name query and change
  420. if (setd->id == 0) {
  421. if (len == 5) {
  422. if (strlen(player_name)) {
  423. sendSETDName(player_name);
  424. }
  425. } else if (len > 5) {
  426. strncpy(player_name, setd->data, PLAYER_NAME_LEN);
  427. player_name[PLAYER_NAME_LEN] = '\0';
  428. LOG_INFO("set name: %s", setd->data);
  429. // confirm change to server
  430. sendSETDName(setd->data);
  431. #if EMBEDDED
  432. set_name(player_name);
  433. #endif
  434. // write name to name_file if -N option set
  435. if (name_file) {
  436. FILE *fp = fopen(name_file, "w");
  437. if (fp) {
  438. LOG_INFO("storing name in %s", name_file);
  439. fputs(player_name, fp);
  440. fclose(fp);
  441. } else {
  442. LOG_WARN("unable to store new name in %s", name_file);
  443. }
  444. }
  445. }
  446. }
  447. }
  448. #define SYNC_CAP ",SyncgroupID="
  449. #define SYNC_CAP_LEN 13
  450. static void process_serv(u8_t *pkt, int len) {
  451. struct serv_packet *serv = (struct serv_packet *)pkt;
  452. unsigned slimproto_port = 0;
  453. char squeezeserver[] = SQUEEZENETWORK;
  454. if(pkt[4] == 0 && pkt[5] == 0 && pkt[6] == 0 && pkt[7] == 1) {
  455. server_addr(squeezeserver, &new_server, &slimproto_port);
  456. } else {
  457. new_server = serv->server_ip;
  458. }
  459. LOG_INFO("switch server");
  460. if (len - sizeof(struct serv_packet) == 10) {
  461. if (!new_server_cap) {
  462. new_server_cap = malloc(SYNC_CAP_LEN + 10 + 1);
  463. }
  464. new_server_cap[0] = '\0';
  465. strcat(new_server_cap, SYNC_CAP);
  466. strncat(new_server_cap, (const char *)(pkt + sizeof(struct serv_packet)), 10);
  467. } else {
  468. if (new_server_cap) {
  469. free(new_server_cap);
  470. new_server_cap = NULL;
  471. }
  472. }
  473. }
  474. struct handler {
  475. char opcode[5];
  476. void (*handler)(u8_t *, int);
  477. };
  478. static struct handler handlers[] = {
  479. { "strm", process_strm },
  480. { "cont", process_cont },
  481. { "codc", process_codc },
  482. { "aude", process_aude },
  483. { "audg", process_audg },
  484. { "setd", process_setd },
  485. { "serv", process_serv },
  486. { "dsco", process_dsco },
  487. { "", NULL },
  488. };
  489. static void process(u8_t *pack, int len) {
  490. struct handler *h = handlers;
  491. while (h->handler && strncmp((char *)pack, h->opcode, 4)) { h++; }
  492. if (h->handler) {
  493. LOG_DEBUG("%s", h->opcode);
  494. h->handler(pack, len);
  495. } else if (!slimp_handler || !(*slimp_handler)(pack, len)) {
  496. pack[4] = '\0';
  497. LOG_WARN("unhandled %s", (char *)pack);
  498. }
  499. }
  500. static bool running;
  501. static void slimproto_run() {
  502. static u8_t EXT_BSS buffer[MAXBUF];
  503. int expect = 0;
  504. int got = 0;
  505. u32_t now;
  506. static u32_t last = 0;
  507. event_handle ehandles[2];
  508. int timeouts = 0;
  509. set_readwake_handles(ehandles, sock, wake_e);
  510. while (running && !new_server) {
  511. bool wake = false;
  512. event_type ev;
  513. if ((ev = wait_readwake(ehandles, 1000)) != EVENT_TIMEOUT) {
  514. if (ev == EVENT_READ) {
  515. if (expect > 0) {
  516. int n = recv(sock, buffer + got, expect, 0);
  517. if (n <= 0) {
  518. if (n < 0 && last_error() == ERROR_WOULDBLOCK) {
  519. continue;
  520. }
  521. LOG_INFO("error reading from socket: %s", n ? strerror(last_error()) : "closed");
  522. return;
  523. }
  524. expect -= n;
  525. got += n;
  526. if (expect == 0) {
  527. process(buffer, got);
  528. got = 0;
  529. }
  530. } else if (expect == 0) {
  531. int n = recv(sock, buffer + got, 2 - got, 0);
  532. if (n <= 0) {
  533. if (n < 0 && last_error() == ERROR_WOULDBLOCK) {
  534. continue;
  535. }
  536. LOG_INFO("error reading from socket: %s", n ? strerror(last_error()) : "closed");
  537. return;
  538. }
  539. got += n;
  540. if (got == 2) {
  541. expect = buffer[0] << 8 | buffer[1]; // length pack 'n'
  542. got = 0;
  543. if (expect > MAXBUF) {
  544. LOG_ERROR("FATAL: slimproto packet too big: %d > %d", expect, MAXBUF);
  545. return;
  546. }
  547. }
  548. } else {
  549. LOG_ERROR("FATAL: negative expect");
  550. return;
  551. }
  552. }
  553. if (ev == EVENT_WAKE) {
  554. wake = true;
  555. }
  556. timeouts = 0;
  557. } else if (++timeouts > 35) {
  558. // expect message from server every 5 seconds, but 30 seconds on mysb.com so timeout after 35 seconds
  559. LOG_INFO("No messages from server - connection dead");
  560. return;
  561. }
  562. // update playback state when woken or every 100ms
  563. now = gettime_ms();
  564. if (wake || now - last > 100 || last > now) {
  565. bool _sendSTMs = false;
  566. bool _sendDSCO = false;
  567. bool _sendRESP = false;
  568. bool _sendMETA = false;
  569. bool _sendSTMd = false;
  570. bool _sendSTMt = false;
  571. bool _sendSTMl = false;
  572. bool _sendSTMu = false;
  573. bool _sendSTMo = false;
  574. bool _sendSTMn = false;
  575. bool _stream_disconnect = false;
  576. bool _start_output = false;
  577. decode_state _decode_state;
  578. disconnect_code disconnect_code;
  579. static char EXT_BSS header[MAX_HEADER];
  580. size_t header_len = 0;
  581. #if IR
  582. bool _sendIR = false;
  583. u32_t ir_code, ir_ts;
  584. #endif
  585. last = now;
  586. LOCK_S;
  587. status.stream_full = _buf_used(streambuf);
  588. status.stream_size = streambuf->size;
  589. status.stream_bytes = stream.bytes;
  590. status.stream_state = stream.state;
  591. if (stream.state == DISCONNECT) {
  592. disconnect_code = stream.disconnect;
  593. stream.state = STOPPED;
  594. _sendDSCO = true;
  595. }
  596. if (!stream.sent_headers &&
  597. (stream.state == STREAMING_HTTP || stream.state == STREAMING_WAIT || stream.state == STREAMING_BUFFERING)) {
  598. header_len = stream.header_len;
  599. memcpy(header, stream.header, header_len);
  600. _sendRESP = true;
  601. stream.sent_headers = true;
  602. }
  603. if (stream.meta_send) {
  604. header_len = stream.header_len;
  605. memcpy(header, stream.header, header_len);
  606. _sendMETA = true;
  607. stream.meta_send = false;
  608. }
  609. UNLOCK_S;
  610. LOCK_D;
  611. if ((status.stream_state == STREAMING_HTTP || status.stream_state == STREAMING_FILE ||
  612. (status.stream_state == DISCONNECT && stream.disconnect == DISCONNECT_OK)) &&
  613. !sentSTMl && decode.state == DECODE_READY) {
  614. if (autostart == 0) {
  615. decode.state = DECODE_RUNNING;
  616. _sendSTMl = true;
  617. sentSTMl = true;
  618. } else if (autostart == 1) {
  619. decode.state = DECODE_RUNNING;
  620. _start_output = true;
  621. }
  622. // autostart 2 and 3 require cont to be received first
  623. }
  624. if (decode.state == DECODE_COMPLETE || decode.state == DECODE_ERROR) {
  625. if (decode.state == DECODE_COMPLETE) _sendSTMd = true;
  626. if (decode.state == DECODE_ERROR) _sendSTMn = true;
  627. decode.state = DECODE_STOPPED;
  628. if (status.stream_state == STREAMING_HTTP || status.stream_state == STREAMING_FILE) {
  629. _stream_disconnect = true;
  630. }
  631. }
  632. _decode_state = decode.state;
  633. UNLOCK_D;
  634. LOCK_O;
  635. if (!output.external) {
  636. status.output_full = _buf_used(outputbuf);
  637. status.output_size = outputbuf->size;
  638. status.frames_played = output.frames_played_dmp;
  639. status.current_sample_rate = output.current_sample_rate;
  640. status.updated = output.updated;
  641. status.device_frames = output.device_frames;
  642. if (output.track_started) {
  643. _sendSTMs = true;
  644. output.track_started = false;
  645. status.stream_start = output.track_start_time;
  646. }
  647. #if PORTAUDIO
  648. if (output.pa_reopen) {
  649. _pa_open();
  650. output.pa_reopen = false;
  651. }
  652. #endif
  653. if (_start_output && (output.state == OUTPUT_STOPPED || output.state == OUTPUT_OFF)) {
  654. output.state = OUTPUT_BUFFER;
  655. }
  656. if (output.state == OUTPUT_RUNNING && !sentSTMu && status.output_full == 0 && status.stream_state <= DISCONNECT &&
  657. _decode_state == DECODE_STOPPED) {
  658. _sendSTMu = true;
  659. sentSTMu = true;
  660. LOG_DEBUG("output underrun");
  661. output.state = OUTPUT_STOPPED;
  662. output.stop_time = now;
  663. }
  664. if (output.state == OUTPUT_RUNNING && !sentSTMo && status.output_full == 0 && status.stream_state == STREAMING_HTTP) {
  665. _sendSTMo = true;
  666. sentSTMo = true;
  667. }
  668. }
  669. if (output.state == OUTPUT_STOPPED && output.idle_to && (now - output.stop_time > output.idle_to)) {
  670. output.state = OUTPUT_OFF;
  671. LOG_DEBUG("output timeout");
  672. }
  673. if (output.state == OUTPUT_RUNNING && now - status.last > 1000) {
  674. _sendSTMt = true;
  675. status.last = now;
  676. }
  677. UNLOCK_O;
  678. #if IR
  679. LOCK_I;
  680. if (ir.code) {
  681. _sendIR = true;
  682. ir_code = ir.code;
  683. ir_ts = ir.ts;
  684. ir.code = 0;
  685. }
  686. UNLOCK_I;
  687. #endif
  688. if (_stream_disconnect) stream_disconnect();
  689. // send packets once locks released as packet sending can block
  690. if (_sendDSCO) sendDSCO(disconnect_code);
  691. if (_sendSTMs) sendSTAT("STMs", 0);
  692. if (_sendSTMd) sendSTAT("STMd", 0);
  693. if (_sendSTMt) sendSTAT("STMt", 0);
  694. if (_sendSTMl) sendSTAT("STMl", 0);
  695. if (_sendSTMu) sendSTAT("STMu", 0);
  696. if (_sendSTMo) sendSTAT("STMo", 0);
  697. if (_sendSTMn) sendSTAT("STMn", 0);
  698. if (_sendRESP) sendRESP(header, header_len);
  699. if (_sendMETA) sendMETA(header, header_len);
  700. #if IR
  701. if (_sendIR) sendIR(ir_code, ir_ts);
  702. #endif
  703. if (*slimp_loop) (*slimp_loop)();
  704. }
  705. }
  706. }
  707. // called from other threads to wake state machine above
  708. void wake_controller(void) {
  709. wake_signal(wake_e);
  710. }
  711. in_addr_t discover_server(char *default_server, int max) {
  712. struct sockaddr_in d;
  713. struct sockaddr_in s;
  714. char buf[32], port_d[] = "JSON", clip_d[] = "CLIP";
  715. struct pollfd pollinfo;
  716. unsigned port;
  717. u8_t len;
  718. int disc_sock = socket(AF_INET, SOCK_DGRAM, 0);
  719. socklen_t enable = 1;
  720. setsockopt(disc_sock, SOL_SOCKET, SO_BROADCAST, (const void *)&enable, sizeof(enable));
  721. len = sprintf(buf,"e%s%c%s", port_d, '\0', clip_d) + 1;
  722. memset(&d, 0, sizeof(d));
  723. d.sin_family = AF_INET;
  724. d.sin_port = htons(PORT);
  725. d.sin_addr.s_addr = htonl(INADDR_BROADCAST);
  726. pollinfo.fd = disc_sock;
  727. pollinfo.events = POLLIN;
  728. do {
  729. LOG_INFO("sending discovery %u", max);
  730. memset(&s, 0, sizeof(s));
  731. if (sendto(disc_sock, buf, len, 0, (struct sockaddr *)&d, sizeof(d)) < 0) {
  732. LOG_INFO("error sending discovery");
  733. }
  734. if (poll(&pollinfo, 1, 5000) == 1) {
  735. char readbuf[64], *p;
  736. socklen_t slen = sizeof(s);
  737. memset(readbuf, 0, sizeof(readbuf));
  738. recvfrom(disc_sock, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&s, &slen);
  739. LOG_INFO("got response from: %s:%d", inet_ntoa(s.sin_addr), ntohs(s.sin_port));
  740. if ((p = strstr(readbuf, port_d)) != NULL) {
  741. p += strlen(port_d);
  742. slimproto_hport = atoi(p + 1);
  743. }
  744. if ((p = strstr(readbuf, clip_d)) != NULL) {
  745. p += strlen(clip_d);
  746. slimproto_cport = atoi(p + 1);
  747. }
  748. }
  749. if (default_server) {
  750. server_addr(default_server, &s.sin_addr.s_addr, &port);
  751. }
  752. } while (s.sin_addr.s_addr == 0 && running && (!max || --max));
  753. closesocket(disc_sock);
  754. return s.sin_addr.s_addr;
  755. }
  756. #define FIXED_CAP_LEN 256
  757. #define VAR_CAP_LEN 128
  758. void slimproto(log_level level, char *server, u8_t mac[6], const char *name, const char *namefile, const char *modelname, int maxSampleRate) {
  759. struct sockaddr_in serv_addr;
  760. static char fixed_cap[FIXED_CAP_LEN], var_cap[VAR_CAP_LEN] = "";
  761. bool reconnect = false;
  762. unsigned failed_connect = 0;
  763. unsigned slimproto_port = 0;
  764. in_addr_t previous_server = 0;
  765. int i;
  766. memset(&status, 0, sizeof(status));
  767. wake_create(wake_e);
  768. loglevel = level;
  769. running = true;
  770. if (server) {
  771. server_addr(server, &slimproto_ip, &slimproto_port);
  772. }
  773. if (!slimproto_ip) {
  774. #if EMBEDDED
  775. // on first attempt, try really hard to connect before exiting (and only exit if we are not on another sink)
  776. slimproto_ip = discover_server(server, MAX_SERVER_RETRIES * 5);
  777. if (!slimproto_ip && !output.external) return;
  778. #else
  779. slimproto_ip = discover_server(server, 0);
  780. #endif
  781. }
  782. if (!slimproto_port) {
  783. slimproto_port = PORT;
  784. }
  785. if (name) {
  786. strncpy(player_name, name, PLAYER_NAME_LEN);
  787. player_name[PLAYER_NAME_LEN] = '\0';
  788. }
  789. if (namefile) {
  790. FILE *fp;
  791. name_file = namefile;
  792. fp = fopen(namefile, "r");
  793. if (fp) {
  794. if (!fgets(player_name, PLAYER_NAME_LEN, fp)) {
  795. player_name[PLAYER_NAME_LEN] = '\0';
  796. } else {
  797. // strip any \n from fgets response
  798. int len = strlen(player_name);
  799. if (len > 0 && player_name[len - 1] == '\n') {
  800. player_name[len - 1] = '\0';
  801. }
  802. LOG_INFO("retrieved name %s from %s", player_name, name_file);
  803. }
  804. fclose(fp);
  805. }
  806. }
  807. if (!running) return;
  808. LOCK_O;
  809. snprintf(fixed_cap, FIXED_CAP_LEN, ",ModelName=%s,MaxSampleRate=%u", modelname ? modelname : MODEL_NAME_STRING,
  810. #if RESAMPLE || RESAMPLE16
  811. ((maxSampleRate > 0) ? maxSampleRate : output.supported_rates[0]));
  812. #else
  813. ((maxSampleRate > 0 && maxSampleRate < output.supported_rates[0]) ? maxSampleRate : output.supported_rates[0]));
  814. #endif
  815. for (i = 0; i < MAX_CODECS; i++) {
  816. if (codecs[i] && codecs[i]->id && strlen(fixed_cap) < FIXED_CAP_LEN - 10) {
  817. strcat(fixed_cap, ",");
  818. strcat(fixed_cap, codecs[i]->types);
  819. }
  820. }
  821. UNLOCK_O;
  822. memset(&serv_addr, 0, sizeof(serv_addr));
  823. serv_addr.sin_family = AF_INET;
  824. serv_addr.sin_addr.s_addr = slimproto_ip;
  825. serv_addr.sin_port = htons(slimproto_port);
  826. LOG_INFO("connecting to %s:%d", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  827. new_server = 0;
  828. while (running) {
  829. if (new_server) {
  830. previous_server = slimproto_ip;
  831. slimproto_ip = serv_addr.sin_addr.s_addr = new_server;
  832. LOG_INFO("switching server to %s:%d", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  833. new_server = 0;
  834. reconnect = false;
  835. }
  836. sock = socket(AF_INET, SOCK_STREAM, 0);
  837. set_nonblock(sock);
  838. set_nosigpipe(sock);
  839. if (connect_timeout(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr), 5) != 0) {
  840. if (previous_server) {
  841. slimproto_ip = serv_addr.sin_addr.s_addr = previous_server;
  842. LOG_INFO("new server not reachable, reverting to previous server %s:%d", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  843. } else {
  844. LOG_INFO("unable to connect to server %u", failed_connect);
  845. sleep(5);
  846. }
  847. #if EMBEDDED
  848. // in embedded we give up after a while no matter what
  849. if (++failed_connect > MAX_SERVER_RETRIES && !server) {
  850. slimproto_ip = serv_addr.sin_addr.s_addr = discover_server(NULL, MAX_SERVER_RETRIES);
  851. if (!slimproto_ip && !output.external) return;
  852. } else if (reconnect && MAX_SERVER_RETRIES && failed_connect > 5 * MAX_SERVER_RETRIES && !output.external) return;
  853. #else
  854. // rediscover server if it was not set at startup or exit
  855. if (!server && ++failed_connect > 5) {
  856. slimproto_ip = serv_addr.sin_addr.s_addr = discover_server(NULL, 0);
  857. }
  858. #endif
  859. } else {
  860. struct sockaddr_in our_addr;
  861. socklen_t len;
  862. LOG_INFO("connected");
  863. var_cap[0] = '\0';
  864. failed_connect = 0;
  865. // check if this is a local player now we are connected & signal to server via 'loc' format
  866. // this requires LocalPlayer server plugin to enable direct file access
  867. len = sizeof(our_addr);
  868. getsockname(sock, (struct sockaddr *) &our_addr, &len);
  869. if (our_addr.sin_addr.s_addr == serv_addr.sin_addr.s_addr) {
  870. LOG_INFO("local player");
  871. strcat(var_cap, ",loc");
  872. }
  873. // add on any capablity to be sent to the new server
  874. if (new_server_cap) {
  875. strcat(var_cap, new_server_cap);
  876. free(new_server_cap);
  877. new_server_cap = NULL;
  878. }
  879. sendHELO(reconnect, fixed_cap, var_cap, mac);
  880. #if EMBEDDED
  881. if (server_notify) (*server_notify)(slimproto_ip, slimproto_hport, slimproto_cport);
  882. #endif
  883. slimproto_run();
  884. if (!reconnect) {
  885. reconnect = true;
  886. }
  887. usleep(100000);
  888. }
  889. previous_server = 0;
  890. closesocket(sock);
  891. }
  892. }
  893. void slimproto_stop(void) {
  894. LOG_INFO("slimproto stop");
  895. running = false;
  896. }