slimproto.c 27 KB

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