slimproto.c 27 KB

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