slimproto.c 28 KB

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