slimproto.c 28 KB

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