slimproto.c 28 KB

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