slimproto.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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 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. case 'q':
  257. decode_flush();
  258. if (!output.external) output_flush();
  259. status.frames_played = 0;
  260. if (stream_disconnect() && strm->command == 'f') sendSTAT("STMf", 0);
  261. buf_flush(streambuf);
  262. output.stop_time = gettime_ms();
  263. break;
  264. case 'p':
  265. {
  266. unsigned interval = unpackN(&strm->replay_gain);
  267. LOCK_O;
  268. output.pause_frames = interval * status.current_sample_rate / 1000;
  269. if (interval) {
  270. output.state = OUTPUT_PAUSE_FRAMES;
  271. } else if (output.state != OUTPUT_OFF) {
  272. output.state = OUTPUT_STOPPED;
  273. output.stop_time = gettime_ms();
  274. }
  275. UNLOCK_O;
  276. if (!interval) sendSTAT("STMp", 0);
  277. LOG_DEBUG("pause interval: %u", interval);
  278. }
  279. break;
  280. case 'a':
  281. {
  282. unsigned interval = unpackN(&strm->replay_gain);
  283. LOCK_O;
  284. output.skip_frames = interval * status.current_sample_rate / 1000;
  285. output.state = OUTPUT_SKIP_FRAMES;
  286. UNLOCK_O;
  287. LOG_DEBUG("skip ahead interval: %u", interval);
  288. }
  289. break;
  290. case 'u':
  291. {
  292. unsigned jiffies = unpackN(&strm->replay_gain);
  293. LOCK_O;
  294. output.state = jiffies ? OUTPUT_START_AT : OUTPUT_RUNNING;
  295. output.start_at = jiffies;
  296. UNLOCK_O;
  297. LOG_DEBUG("unpause at: %u now: %u", jiffies, gettime_ms());
  298. sendSTAT("STMr", 0);
  299. }
  300. break;
  301. case 's':
  302. {
  303. unsigned header_len = len - sizeof(struct strm_packet);
  304. char *header = (char *)(pkt + sizeof(struct strm_packet));
  305. in_addr_t ip = (in_addr_t)strm->server_ip; // keep in network byte order
  306. u16_t port = strm->server_port; // keep in network byte order
  307. if (ip == 0) ip = slimproto_ip;
  308. LOG_DEBUG("strm s autostart: %c transition period: %u transition type: %u codec: %c",
  309. strm->autostart, strm->transition_period, strm->transition_type - '0', strm->format);
  310. autostart = strm->autostart - '0';
  311. sendSTAT("STMf", 0);
  312. if (header_len > MAX_HEADER -1) {
  313. LOG_WARN("header too long: %u", header_len);
  314. break;
  315. }
  316. if (strm->format != '?') {
  317. codec_open(strm->format, strm->pcm_sample_size, strm->pcm_sample_rate, strm->pcm_channels, strm->pcm_endianness);
  318. } else if (autostart >= 2) {
  319. // extension to slimproto to allow server to detect codec from response header and send back in codc message
  320. LOG_DEBUG("streaming unknown codec");
  321. } else {
  322. LOG_WARN("unknown codec requires autostart >= 2");
  323. break;
  324. }
  325. if (ip == LOCAL_PLAYER_IP && port == LOCAL_PLAYER_PORT) {
  326. // extension to slimproto for LocalPlayer - header is filename not http header, don't expect cont
  327. stream_file(header, header_len, strm->threshold * 1024);
  328. autostart -= 2;
  329. } else {
  330. stream_sock(ip, port, header, header_len, strm->threshold * 1024, autostart >= 2);
  331. }
  332. sendSTAT("STMc", 0);
  333. sentSTMu = sentSTMo = sentSTMl = false;
  334. LOCK_O;
  335. #if EMBEDDED
  336. if (output.external) decode_restore(output.external);
  337. output.external = 0;
  338. _buf_resize(outputbuf, output.init_size);
  339. #endif
  340. output.threshold = strm->output_threshold;
  341. output.next_replay_gain = unpackN(&strm->replay_gain);
  342. output.fade_mode = strm->transition_type - '0';
  343. output.fade_secs = strm->transition_period;
  344. output.invert = (strm->flags & 0x03) == 0x03;
  345. output.channels = (strm->flags & 0x0c) >> 2;
  346. LOG_DEBUG("set fade: %u, channels: %u, invert: %u", output.fade_mode, output.channels, output.invert);
  347. UNLOCK_O;
  348. }
  349. break;
  350. default:
  351. LOG_WARN("unhandled strm %c", strm->command);
  352. break;
  353. }
  354. }
  355. static void process_cont(u8_t *pkt, int len) {
  356. struct cont_packet *cont = (struct cont_packet *)pkt;
  357. cont->metaint = unpackN(&cont->metaint);
  358. LOG_DEBUG("cont metaint: %u loop: %u", cont->metaint, cont->loop);
  359. if (autostart > 1) {
  360. autostart -= 2;
  361. LOCK_S;
  362. if (stream.state == STREAMING_WAIT) {
  363. stream.state = STREAMING_BUFFERING;
  364. stream.meta_interval = stream.meta_next = cont->metaint;
  365. }
  366. UNLOCK_S;
  367. wake_controller();
  368. }
  369. }
  370. static void process_codc(u8_t *pkt, int len) {
  371. struct codc_packet *codc = (struct codc_packet *)pkt;
  372. LOG_DEBUG("codc: %c", codc->format);
  373. codec_open(codc->format, codc->pcm_sample_size, codc->pcm_sample_rate, codc->pcm_channels, codc->pcm_endianness);
  374. }
  375. static void process_aude(u8_t *pkt, int len) {
  376. struct aude_packet *aude = (struct aude_packet *)pkt;
  377. LOG_DEBUG("enable spdif: %d dac: %d", aude->enable_spdif, aude->enable_dac);
  378. LOCK_O;
  379. if (!aude->enable_spdif && output.state != OUTPUT_OFF) {
  380. output.state = OUTPUT_OFF;
  381. }
  382. if (aude->enable_spdif && output.state == OUTPUT_OFF && !output.idle_to) {
  383. output.state = OUTPUT_STOPPED;
  384. output.stop_time = gettime_ms();
  385. }
  386. UNLOCK_O;
  387. }
  388. static void process_audg(u8_t *pkt, int len) {
  389. struct audg_packet *audg = (struct audg_packet *)pkt;
  390. audg->gainL = unpackN(&audg->gainL);
  391. audg->gainR = unpackN(&audg->gainR);
  392. LOG_DEBUG("audg gainL: %u gainR: %u adjust: %u", audg->gainL, audg->gainR, audg->adjust);
  393. set_volume(audg->adjust ? audg->gainL : FIXED_ONE, audg->adjust ? audg->gainR : FIXED_ONE);
  394. }
  395. static void process_dsco(u8_t *pkt, int len) {
  396. LOG_INFO("got DSCO, switching from id %u to 12", (int) player_id);
  397. player_id = 12;
  398. }
  399. static void process_setd(u8_t *pkt, int len) {
  400. struct setd_packet *setd = (struct setd_packet *)pkt;
  401. // handle player name query and change
  402. if (setd->id == 0) {
  403. if (len == 5) {
  404. if (strlen(player_name)) {
  405. sendSETDName(player_name);
  406. }
  407. } else if (len > 5) {
  408. strncpy(player_name, setd->data, PLAYER_NAME_LEN);
  409. player_name[PLAYER_NAME_LEN] = '\0';
  410. LOG_INFO("set name: %s", setd->data);
  411. // confirm change to server
  412. sendSETDName(setd->data);
  413. // write name to name_file if -N option set
  414. if (name_file) {
  415. FILE *fp = fopen(name_file, "w");
  416. if (fp) {
  417. LOG_INFO("storing name in %s", name_file);
  418. fputs(player_name, fp);
  419. fclose(fp);
  420. } else {
  421. LOG_WARN("unable to store new name in %s", name_file);
  422. }
  423. }
  424. }
  425. }
  426. }
  427. #define SYNC_CAP ",SyncgroupID="
  428. #define SYNC_CAP_LEN 13
  429. static void process_serv(u8_t *pkt, int len) {
  430. struct serv_packet *serv = (struct serv_packet *)pkt;
  431. unsigned slimproto_port = 0;
  432. char squeezeserver[] = SQUEEZENETWORK;
  433. if(pkt[4] == 0 && pkt[5] == 0 && pkt[6] == 0 && pkt[7] == 1) {
  434. server_addr(squeezeserver, &new_server, &slimproto_port);
  435. } else {
  436. new_server = serv->server_ip;
  437. }
  438. LOG_INFO("switch server");
  439. if (len - sizeof(struct serv_packet) == 10) {
  440. if (!new_server_cap) {
  441. new_server_cap = malloc(SYNC_CAP_LEN + 10 + 1);
  442. }
  443. new_server_cap[0] = '\0';
  444. strcat(new_server_cap, SYNC_CAP);
  445. strncat(new_server_cap, (const char *)(pkt + sizeof(struct serv_packet)), 10);
  446. } else {
  447. if (new_server_cap) {
  448. free(new_server_cap);
  449. new_server_cap = NULL;
  450. }
  451. }
  452. }
  453. struct handler {
  454. char opcode[5];
  455. void (*handler)(u8_t *, int);
  456. };
  457. static struct handler handlers[] = {
  458. { "strm", process_strm },
  459. { "cont", process_cont },
  460. { "codc", process_codc },
  461. { "aude", process_aude },
  462. { "audg", process_audg },
  463. { "setd", process_setd },
  464. { "serv", process_serv },
  465. { "dsco", process_dsco },
  466. { "", NULL },
  467. };
  468. static void process(u8_t *pack, int len) {
  469. struct handler *h = handlers;
  470. while (h->handler && strncmp((char *)pack, h->opcode, 4)) { h++; }
  471. if (h->handler) {
  472. LOG_DEBUG("%s", h->opcode);
  473. h->handler(pack, len);
  474. } else if (!slimp_handler || !(*slimp_handler)(pack, len)) {
  475. pack[4] = '\0';
  476. LOG_WARN("unhandled %s", (char *)pack);
  477. }
  478. }
  479. static bool running;
  480. static void slimproto_run() {
  481. static u8_t EXT_BSS buffer[MAXBUF];
  482. int expect = 0;
  483. int got = 0;
  484. u32_t now;
  485. static u32_t last = 0;
  486. event_handle ehandles[2];
  487. int timeouts = 0;
  488. set_readwake_handles(ehandles, sock, wake_e);
  489. while (running && !new_server) {
  490. bool wake = false;
  491. event_type ev;
  492. if ((ev = wait_readwake(ehandles, 1000)) != EVENT_TIMEOUT) {
  493. if (ev == EVENT_READ) {
  494. if (expect > 0) {
  495. int n = recv(sock, buffer + got, expect, 0);
  496. if (n <= 0) {
  497. if (n < 0 && last_error() == ERROR_WOULDBLOCK) {
  498. continue;
  499. }
  500. LOG_INFO("error reading from socket: %s", n ? strerror(last_error()) : "closed");
  501. return;
  502. }
  503. expect -= n;
  504. got += n;
  505. if (expect == 0) {
  506. process(buffer, got);
  507. got = 0;
  508. }
  509. } else if (expect == 0) {
  510. int n = recv(sock, buffer + got, 2 - got, 0);
  511. if (n <= 0) {
  512. if (n < 0 && last_error() == ERROR_WOULDBLOCK) {
  513. continue;
  514. }
  515. LOG_INFO("error reading from socket: %s", n ? strerror(last_error()) : "closed");
  516. return;
  517. }
  518. got += n;
  519. if (got == 2) {
  520. expect = buffer[0] << 8 | buffer[1]; // length pack 'n'
  521. got = 0;
  522. if (expect > MAXBUF) {
  523. LOG_ERROR("FATAL: slimproto packet too big: %d > %d", expect, MAXBUF);
  524. return;
  525. }
  526. }
  527. } else {
  528. LOG_ERROR("FATAL: negative expect");
  529. return;
  530. }
  531. }
  532. if (ev == EVENT_WAKE) {
  533. wake = true;
  534. }
  535. timeouts = 0;
  536. } else if (++timeouts > 35) {
  537. // expect message from server every 5 seconds, but 30 seconds on mysb.com so timeout after 35 seconds
  538. LOG_INFO("No messages from server - connection dead");
  539. return;
  540. }
  541. // update playback state when woken or every 100ms
  542. now = gettime_ms();
  543. if (wake || now - last > 100 || last > now) {
  544. bool _sendSTMs = false;
  545. bool _sendDSCO = false;
  546. bool _sendRESP = false;
  547. bool _sendMETA = false;
  548. bool _sendSTMd = false;
  549. bool _sendSTMt = false;
  550. bool _sendSTMl = false;
  551. bool _sendSTMu = false;
  552. bool _sendSTMo = false;
  553. bool _sendSTMn = false;
  554. bool _stream_disconnect = false;
  555. bool _start_output = false;
  556. decode_state _decode_state;
  557. disconnect_code disconnect_code;
  558. static char EXT_BSS header[MAX_HEADER];
  559. size_t header_len = 0;
  560. #if IR
  561. bool _sendIR = false;
  562. u32_t ir_code, ir_ts;
  563. #endif
  564. last = now;
  565. LOCK_S;
  566. status.stream_full = _buf_used(streambuf);
  567. status.stream_size = streambuf->size;
  568. status.stream_bytes = stream.bytes;
  569. status.stream_state = stream.state;
  570. if (stream.state == DISCONNECT) {
  571. disconnect_code = stream.disconnect;
  572. stream.state = STOPPED;
  573. _sendDSCO = true;
  574. }
  575. if (!stream.sent_headers &&
  576. (stream.state == STREAMING_HTTP || stream.state == STREAMING_WAIT || stream.state == STREAMING_BUFFERING)) {
  577. header_len = stream.header_len;
  578. memcpy(header, stream.header, header_len);
  579. _sendRESP = true;
  580. stream.sent_headers = true;
  581. }
  582. if (stream.meta_send) {
  583. header_len = stream.header_len;
  584. memcpy(header, stream.header, header_len);
  585. _sendMETA = true;
  586. stream.meta_send = false;
  587. }
  588. UNLOCK_S;
  589. LOCK_D;
  590. if ((status.stream_state == STREAMING_HTTP || status.stream_state == STREAMING_FILE ||
  591. (status.stream_state == DISCONNECT && stream.disconnect == DISCONNECT_OK)) &&
  592. !sentSTMl && decode.state == DECODE_READY) {
  593. if (autostart == 0) {
  594. decode.state = DECODE_RUNNING;
  595. _sendSTMl = true;
  596. sentSTMl = true;
  597. } else if (autostart == 1) {
  598. decode.state = DECODE_RUNNING;
  599. _start_output = true;
  600. }
  601. // autostart 2 and 3 require cont to be received first
  602. }
  603. if (decode.state == DECODE_COMPLETE || decode.state == DECODE_ERROR) {
  604. if (decode.state == DECODE_COMPLETE) _sendSTMd = true;
  605. if (decode.state == DECODE_ERROR) _sendSTMn = true;
  606. decode.state = DECODE_STOPPED;
  607. if (status.stream_state == STREAMING_HTTP || status.stream_state == STREAMING_FILE) {
  608. _stream_disconnect = true;
  609. }
  610. }
  611. _decode_state = decode.state;
  612. UNLOCK_D;
  613. LOCK_O;
  614. if (!output.external) {
  615. status.output_full = _buf_used(outputbuf);
  616. status.output_size = outputbuf->size;
  617. status.frames_played = output.frames_played_dmp;
  618. status.current_sample_rate = output.current_sample_rate;
  619. status.updated = output.updated;
  620. status.device_frames = output.device_frames;
  621. if (output.track_started) {
  622. _sendSTMs = true;
  623. output.track_started = false;
  624. status.stream_start = output.track_start_time;
  625. }
  626. #if PORTAUDIO
  627. if (output.pa_reopen) {
  628. _pa_open();
  629. output.pa_reopen = false;
  630. }
  631. #endif
  632. if (_start_output && (output.state == OUTPUT_STOPPED || output.state == OUTPUT_OFF)) {
  633. output.state = OUTPUT_BUFFER;
  634. }
  635. if (output.state == OUTPUT_RUNNING && !sentSTMu && status.output_full == 0 && status.stream_state <= DISCONNECT &&
  636. _decode_state == DECODE_STOPPED) {
  637. _sendSTMu = true;
  638. sentSTMu = true;
  639. LOG_DEBUG("output underrun");
  640. output.state = OUTPUT_STOPPED;
  641. output.stop_time = now;
  642. }
  643. if (output.state == OUTPUT_RUNNING && !sentSTMo && status.output_full == 0 && status.stream_state == STREAMING_HTTP) {
  644. _sendSTMo = true;
  645. sentSTMo = true;
  646. }
  647. }
  648. if (output.state == OUTPUT_STOPPED && output.idle_to && (now - output.stop_time > output.idle_to)) {
  649. output.state = OUTPUT_OFF;
  650. LOG_DEBUG("output timeout");
  651. }
  652. if (output.state == OUTPUT_RUNNING && now - status.last > 1000) {
  653. _sendSTMt = true;
  654. status.last = now;
  655. }
  656. UNLOCK_O;
  657. #if IR
  658. LOCK_I;
  659. if (ir.code) {
  660. _sendIR = true;
  661. ir_code = ir.code;
  662. ir_ts = ir.ts;
  663. ir.code = 0;
  664. }
  665. UNLOCK_I;
  666. #endif
  667. if (_stream_disconnect) stream_disconnect();
  668. // send packets once locks released as packet sending can block
  669. if (_sendDSCO) sendDSCO(disconnect_code);
  670. if (_sendSTMs) sendSTAT("STMs", 0);
  671. if (_sendSTMd) sendSTAT("STMd", 0);
  672. if (_sendSTMt) sendSTAT("STMt", 0);
  673. if (_sendSTMl) sendSTAT("STMl", 0);
  674. if (_sendSTMu) sendSTAT("STMu", 0);
  675. if (_sendSTMo) sendSTAT("STMo", 0);
  676. if (_sendSTMn) sendSTAT("STMn", 0);
  677. if (_sendRESP) sendRESP(header, header_len);
  678. if (_sendMETA) sendMETA(header, header_len);
  679. #if IR
  680. if (_sendIR) sendIR(ir_code, ir_ts);
  681. #endif
  682. if (*slimp_loop) (*slimp_loop)();
  683. }
  684. }
  685. }
  686. // called from other threads to wake state machine above
  687. void wake_controller(void) {
  688. wake_signal(wake_e);
  689. }
  690. in_addr_t discover_server(char *default_server, int max) {
  691. struct sockaddr_in d;
  692. struct sockaddr_in s;
  693. char buf[32], port_d[] = "JSON", clip_d[] = "CLIP";
  694. struct pollfd pollinfo;
  695. unsigned port;
  696. u8_t len;
  697. int disc_sock = socket(AF_INET, SOCK_DGRAM, 0);
  698. socklen_t enable = 1;
  699. setsockopt(disc_sock, SOL_SOCKET, SO_BROADCAST, (const void *)&enable, sizeof(enable));
  700. len = sprintf(buf,"e%s%c%s", port_d, '\0', clip_d) + 1;
  701. memset(&d, 0, sizeof(d));
  702. d.sin_family = AF_INET;
  703. d.sin_port = htons(PORT);
  704. d.sin_addr.s_addr = htonl(INADDR_BROADCAST);
  705. pollinfo.fd = disc_sock;
  706. pollinfo.events = POLLIN;
  707. do {
  708. LOG_INFO("sending discovery");
  709. memset(&s, 0, sizeof(s));
  710. if (sendto(disc_sock, buf, len, 0, (struct sockaddr *)&d, sizeof(d)) < 0) {
  711. LOG_INFO("error sending discovery");
  712. }
  713. if (poll(&pollinfo, 1, 5000) == 1) {
  714. char readbuf[64], *p;
  715. socklen_t slen = sizeof(s);
  716. memset(readbuf, 0, sizeof(readbuf));
  717. recvfrom(disc_sock, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&s, &slen);
  718. LOG_INFO("got response from: %s:%d", inet_ntoa(s.sin_addr), ntohs(s.sin_port));
  719. if ((p = strstr(readbuf, port_d)) != NULL) {
  720. p += strlen(port_d);
  721. slimproto_hport = atoi(p + 1);
  722. }
  723. if ((p = strstr(readbuf, clip_d)) != NULL) {
  724. p += strlen(clip_d);
  725. slimproto_cport = atoi(p + 1);
  726. }
  727. }
  728. if (default_server) {
  729. server_addr(default_server, &s.sin_addr.s_addr, &port);
  730. }
  731. } while (s.sin_addr.s_addr == 0 && running && (!max || --max));
  732. closesocket(disc_sock);
  733. return s.sin_addr.s_addr;
  734. }
  735. #define FIXED_CAP_LEN 256
  736. #define VAR_CAP_LEN 128
  737. void slimproto(log_level level, char *server, u8_t mac[6], const char *name, const char *namefile, const char *modelname, int maxSampleRate) {
  738. struct sockaddr_in serv_addr;
  739. static char fixed_cap[FIXED_CAP_LEN], var_cap[VAR_CAP_LEN] = "";
  740. bool reconnect = false;
  741. unsigned failed_connect = 0;
  742. unsigned slimproto_port = 0;
  743. in_addr_t previous_server = 0;
  744. int i;
  745. memset(&status, 0, sizeof(status));
  746. wake_create(wake_e);
  747. loglevel = level;
  748. running = true;
  749. if (server) {
  750. server_addr(server, &slimproto_ip, &slimproto_port);
  751. }
  752. if (!slimproto_ip) {
  753. slimproto_ip = discover_server(server, 0);
  754. }
  755. if (!slimproto_port) {
  756. slimproto_port = PORT;
  757. }
  758. if (name) {
  759. strncpy(player_name, name, PLAYER_NAME_LEN);
  760. player_name[PLAYER_NAME_LEN] = '\0';
  761. }
  762. if (namefile) {
  763. FILE *fp;
  764. name_file = namefile;
  765. fp = fopen(namefile, "r");
  766. if (fp) {
  767. if (!fgets(player_name, PLAYER_NAME_LEN, fp)) {
  768. player_name[PLAYER_NAME_LEN] = '\0';
  769. } else {
  770. // strip any \n from fgets response
  771. int len = strlen(player_name);
  772. if (len > 0 && player_name[len - 1] == '\n') {
  773. player_name[len - 1] = '\0';
  774. }
  775. LOG_INFO("retrieved name %s from %s", player_name, name_file);
  776. }
  777. fclose(fp);
  778. }
  779. }
  780. if (!running) return;
  781. LOCK_O;
  782. snprintf(fixed_cap, FIXED_CAP_LEN, ",ModelName=%s,MaxSampleRate=%u", modelname ? modelname : MODEL_NAME_STRING,
  783. ((maxSampleRate > 0) ? maxSampleRate : output.supported_rates[0]));
  784. for (i = 0; i < MAX_CODECS; i++) {
  785. if (codecs[i] && codecs[i]->id && strlen(fixed_cap) < FIXED_CAP_LEN - 10) {
  786. strcat(fixed_cap, ",");
  787. strcat(fixed_cap, codecs[i]->types);
  788. }
  789. }
  790. UNLOCK_O;
  791. memset(&serv_addr, 0, sizeof(serv_addr));
  792. serv_addr.sin_family = AF_INET;
  793. serv_addr.sin_addr.s_addr = slimproto_ip;
  794. serv_addr.sin_port = htons(slimproto_port);
  795. LOG_INFO("connecting to %s:%d", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  796. new_server = 0;
  797. while (running) {
  798. if (new_server) {
  799. previous_server = slimproto_ip;
  800. slimproto_ip = serv_addr.sin_addr.s_addr = new_server;
  801. LOG_INFO("switching server to %s:%d", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  802. new_server = 0;
  803. reconnect = false;
  804. }
  805. sock = socket(AF_INET, SOCK_STREAM, 0);
  806. set_nonblock(sock);
  807. set_nosigpipe(sock);
  808. if (connect_timeout(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr), 5) != 0) {
  809. if (previous_server) {
  810. slimproto_ip = serv_addr.sin_addr.s_addr = previous_server;
  811. LOG_INFO("new server not reachable, reverting to previous server %s:%d", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  812. } else {
  813. LOG_INFO("unable to connect to server %u", failed_connect);
  814. sleep(5);
  815. }
  816. #if EMBEDDED
  817. // in embedded we give up after a while no matter what
  818. if (++failed_connect > 5 && !server) {
  819. slimproto_ip = serv_addr.sin_addr.s_addr = discover_server(NULL, MAX_SERVER_RETRIES);
  820. if (!slimproto_ip) return;
  821. } else if (reconnect && MAX_SERVER_RETRIES && failed_connect > 5 * MAX_SERVER_RETRIES) return;
  822. #else
  823. // rediscover server if it was not set at startup or exit
  824. if (!server && ++failed_connect > 5) {
  825. slimproto_ip = serv_addr.sin_addr.s_addr = discover_server(NULL, 0);
  826. }
  827. #endif
  828. } else {
  829. struct sockaddr_in our_addr;
  830. socklen_t len;
  831. LOG_INFO("connected");
  832. var_cap[0] = '\0';
  833. failed_connect = 0;
  834. // check if this is a local player now we are connected & signal to server via 'loc' format
  835. // this requires LocalPlayer server plugin to enable direct file access
  836. len = sizeof(our_addr);
  837. getsockname(sock, (struct sockaddr *) &our_addr, &len);
  838. if (our_addr.sin_addr.s_addr == serv_addr.sin_addr.s_addr) {
  839. LOG_INFO("local player");
  840. strcat(var_cap, ",loc");
  841. }
  842. // add on any capablity to be sent to the new server
  843. if (new_server_cap) {
  844. strcat(var_cap, new_server_cap);
  845. free(new_server_cap);
  846. new_server_cap = NULL;
  847. }
  848. sendHELO(reconnect, fixed_cap, var_cap, mac);
  849. #if EMBEDDED
  850. if (server_notify) (*server_notify)(slimproto_ip, slimproto_hport, slimproto_cport);
  851. #endif
  852. slimproto_run();
  853. if (!reconnect) {
  854. reconnect = true;
  855. }
  856. usleep(100000);
  857. }
  858. previous_server = 0;
  859. closesocket(sock);
  860. }
  861. }
  862. void slimproto_stop(void) {
  863. LOG_INFO("slimproto stop");
  864. running = false;
  865. }