slimproto.c 27 KB

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