slimproto.c 26 KB

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