2
0

slimproto.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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 slimproto_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,Balance=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(strm->command == 'q');
  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. #if EMBEDDED
  335. // not protected so that restore can call synchronously sink handlers
  336. if (output.external) decode_restore(output.external);
  337. LOCK_O;
  338. output.external = 0;
  339. _buf_limit(outputbuf, 0);
  340. #else
  341. LOCK_O;
  342. #endif
  343. output.threshold = strm->output_threshold;
  344. output.next_replay_gain = unpackN(&strm->replay_gain);
  345. output.fade_mode = strm->transition_type - '0';
  346. output.fade_secs = strm->transition_period;
  347. output.invert = (strm->flags & 0x03) == 0x03;
  348. output.channels = (strm->flags & 0x0c) >> 2;
  349. LOG_DEBUG("set fade: %u, channels: %u, invert: %u", output.fade_mode, output.channels, output.invert);
  350. UNLOCK_O;
  351. }
  352. break;
  353. default:
  354. LOG_WARN("unhandled strm %c", strm->command);
  355. break;
  356. }
  357. }
  358. static void process_cont(u8_t *pkt, int len) {
  359. struct cont_packet *cont = (struct cont_packet *)pkt;
  360. cont->metaint = unpackN(&cont->metaint);
  361. LOG_DEBUG("cont metaint: %u loop: %u", cont->metaint, cont->loop);
  362. if (autostart > 1) {
  363. autostart -= 2;
  364. LOCK_S;
  365. if (stream.state == STREAMING_WAIT) {
  366. stream.state = STREAMING_BUFFERING;
  367. stream.meta_interval = stream.meta_next = cont->metaint;
  368. }
  369. UNLOCK_S;
  370. wake_controller();
  371. }
  372. }
  373. static void process_codc(u8_t *pkt, int len) {
  374. struct codc_packet *codc = (struct codc_packet *)pkt;
  375. LOG_DEBUG("codc: %c", codc->format);
  376. codec_open(codc->format, codc->pcm_sample_size, codc->pcm_sample_rate, codc->pcm_channels, codc->pcm_endianness);
  377. }
  378. static void process_aude(u8_t *pkt, int len) {
  379. struct aude_packet *aude = (struct aude_packet *)pkt;
  380. LOG_DEBUG("enable spdif: %d dac: %d", aude->enable_spdif, aude->enable_dac);
  381. #if EMBEDDED
  382. powering(aude->enable_spdif),
  383. #endif
  384. LOCK_O;
  385. if (!aude->enable_spdif && output.state != OUTPUT_OFF) {
  386. output.state = OUTPUT_OFF;
  387. }
  388. if (aude->enable_spdif && output.state == OUTPUT_OFF && !output.idle_to) {
  389. output.state = OUTPUT_STOPPED;
  390. output.stop_time = gettime_ms();
  391. }
  392. UNLOCK_O;
  393. }
  394. static void process_audg(u8_t *pkt, int len) {
  395. struct audg_packet *audg = (struct audg_packet *)pkt;
  396. audg->gainL = unpackN(&audg->gainL);
  397. audg->gainR = unpackN(&audg->gainR);
  398. LOG_DEBUG("audg gainL: %u gainR: %u adjust: %u", audg->gainL, audg->gainR, audg->adjust);
  399. set_volume(audg->adjust ? audg->gainL : FIXED_ONE, audg->adjust ? audg->gainR : FIXED_ONE);
  400. }
  401. static void process_dsco(u8_t *pkt, int len) {
  402. LOG_INFO("got DSCO, switching from id %u to 12", (int) player_id);
  403. player_id = 12;
  404. }
  405. static void process_setd(u8_t *pkt, int len) {
  406. struct setd_packet *setd = (struct setd_packet *)pkt;
  407. // handle player name query and change
  408. if (setd->id == 0) {
  409. if (len == 5) {
  410. if (strlen(player_name)) {
  411. sendSETDName(player_name);
  412. }
  413. } else if (len > 5) {
  414. strncpy(player_name, setd->data, PLAYER_NAME_LEN);
  415. player_name[PLAYER_NAME_LEN] = '\0';
  416. LOG_INFO("set name: %s", setd->data);
  417. // confirm change to server
  418. sendSETDName(setd->data);
  419. #if EMBEDDED
  420. set_name(player_name);
  421. #endif
  422. // write name to name_file if -N option set
  423. if (name_file) {
  424. FILE *fp = fopen(name_file, "w");
  425. if (fp) {
  426. LOG_INFO("storing name in %s", name_file);
  427. fputs(player_name, fp);
  428. fclose(fp);
  429. } else {
  430. LOG_WARN("unable to store new name in %s", name_file);
  431. }
  432. }
  433. }
  434. }
  435. }
  436. #define SYNC_CAP ",SyncgroupID="
  437. #define SYNC_CAP_LEN 13
  438. static void process_serv(u8_t *pkt, int len) {
  439. struct serv_packet *serv = (struct serv_packet *)pkt;
  440. unsigned slimproto_port = 0;
  441. char squeezeserver[] = SQUEEZENETWORK;
  442. if(pkt[4] == 0 && pkt[5] == 0 && pkt[6] == 0 && pkt[7] == 1) {
  443. server_addr(squeezeserver, &new_server, &slimproto_port);
  444. } else {
  445. new_server = serv->server_ip;
  446. }
  447. LOG_INFO("switch server");
  448. if (len - sizeof(struct serv_packet) == 10) {
  449. if (!new_server_cap) {
  450. new_server_cap = malloc(SYNC_CAP_LEN + 10 + 1);
  451. }
  452. new_server_cap[0] = '\0';
  453. strcat(new_server_cap, SYNC_CAP);
  454. strncat(new_server_cap, (const char *)(pkt + sizeof(struct serv_packet)), 10);
  455. } else {
  456. if (new_server_cap) {
  457. free(new_server_cap);
  458. new_server_cap = NULL;
  459. }
  460. }
  461. }
  462. struct handler {
  463. char opcode[5];
  464. void (*handler)(u8_t *, int);
  465. };
  466. static struct handler handlers[] = {
  467. { "strm", process_strm },
  468. { "cont", process_cont },
  469. { "codc", process_codc },
  470. { "aude", process_aude },
  471. { "audg", process_audg },
  472. { "setd", process_setd },
  473. { "serv", process_serv },
  474. { "dsco", process_dsco },
  475. { "", NULL },
  476. };
  477. static void process(u8_t *pack, int len) {
  478. struct handler *h = handlers;
  479. while (h->handler && strncmp((char *)pack, h->opcode, 4)) { h++; }
  480. if (h->handler) {
  481. LOG_DEBUG("%s", h->opcode);
  482. h->handler(pack, len);
  483. } else if (!slimp_handler || !(*slimp_handler)(pack, len)) {
  484. pack[4] = '\0';
  485. LOG_WARN("unhandled %s", (char *)pack);
  486. }
  487. }
  488. static bool running;
  489. static void slimproto_run() {
  490. static u8_t EXT_BSS buffer[MAXBUF];
  491. int expect = 0;
  492. int got = 0;
  493. u32_t now;
  494. static u32_t last = 0;
  495. event_handle ehandles[2];
  496. int timeouts = 0;
  497. set_readwake_handles(ehandles, sock, wake_e);
  498. while (running && !new_server) {
  499. bool wake = false;
  500. event_type ev;
  501. if ((ev = wait_readwake(ehandles, 1000)) != EVENT_TIMEOUT) {
  502. if (ev == EVENT_READ) {
  503. if (expect > 0) {
  504. int n = recv(sock, buffer + got, expect, 0);
  505. if (n <= 0) {
  506. if (n < 0 && last_error() == ERROR_WOULDBLOCK) {
  507. continue;
  508. }
  509. LOG_INFO("error reading from socket: %s", n ? strerror(last_error()) : "closed");
  510. return;
  511. }
  512. expect -= n;
  513. got += n;
  514. if (expect == 0) {
  515. process(buffer, got);
  516. got = 0;
  517. }
  518. } else if (expect == 0) {
  519. int n = recv(sock, buffer + got, 2 - got, 0);
  520. if (n <= 0) {
  521. if (n < 0 && last_error() == ERROR_WOULDBLOCK) {
  522. continue;
  523. }
  524. LOG_INFO("error reading from socket: %s", n ? strerror(last_error()) : "closed");
  525. return;
  526. }
  527. got += n;
  528. if (got == 2) {
  529. expect = buffer[0] << 8 | buffer[1]; // length pack 'n'
  530. got = 0;
  531. if (expect > MAXBUF) {
  532. LOG_ERROR("FATAL: slimproto packet too big: %d > %d", expect, MAXBUF);
  533. return;
  534. }
  535. }
  536. } else {
  537. LOG_ERROR("FATAL: negative expect");
  538. return;
  539. }
  540. }
  541. if (ev == EVENT_WAKE) {
  542. wake = true;
  543. }
  544. timeouts = 0;
  545. } else if (++timeouts > 35) {
  546. // expect message from server every 5 seconds, but 30 seconds on mysb.com so timeout after 35 seconds
  547. LOG_INFO("No messages from server - connection dead");
  548. return;
  549. }
  550. // update playback state when woken or every 100ms
  551. now = gettime_ms();
  552. if (wake || now - last > 100 || last > now) {
  553. bool _sendSTMs = false;
  554. bool _sendDSCO = false;
  555. bool _sendRESP = false;
  556. bool _sendMETA = false;
  557. bool _sendSTMd = false;
  558. bool _sendSTMt = false;
  559. bool _sendSTMl = false;
  560. bool _sendSTMu = false;
  561. bool _sendSTMo = false;
  562. bool _sendSTMn = false;
  563. bool _stream_disconnect = false;
  564. bool _start_output = false;
  565. decode_state _decode_state;
  566. disconnect_code disconnect_code;
  567. static char EXT_BSS header[MAX_HEADER];
  568. size_t header_len = 0;
  569. #if IR
  570. bool _sendIR = false;
  571. u32_t ir_code, ir_ts;
  572. #endif
  573. last = now;
  574. LOCK_S;
  575. status.stream_full = _buf_used(streambuf);
  576. status.stream_size = streambuf->size;
  577. status.stream_bytes = stream.bytes;
  578. status.stream_state = stream.state;
  579. if (stream.state == DISCONNECT) {
  580. disconnect_code = stream.disconnect;
  581. stream.state = STOPPED;
  582. _sendDSCO = true;
  583. }
  584. if (!stream.sent_headers &&
  585. (stream.state == STREAMING_HTTP || stream.state == STREAMING_WAIT || stream.state == STREAMING_BUFFERING)) {
  586. header_len = stream.header_len;
  587. memcpy(header, stream.header, header_len);
  588. _sendRESP = true;
  589. stream.sent_headers = true;
  590. }
  591. if (stream.meta_send) {
  592. header_len = stream.header_len;
  593. memcpy(header, stream.header, header_len);
  594. _sendMETA = true;
  595. stream.meta_send = false;
  596. }
  597. UNLOCK_S;
  598. LOCK_D;
  599. if ((status.stream_state == STREAMING_HTTP || status.stream_state == STREAMING_FILE ||
  600. (status.stream_state == DISCONNECT && stream.disconnect == DISCONNECT_OK)) &&
  601. !sentSTMl && decode.state == DECODE_READY) {
  602. if (autostart == 0) {
  603. decode.state = DECODE_RUNNING;
  604. _sendSTMl = true;
  605. sentSTMl = true;
  606. } else if (autostart == 1) {
  607. decode.state = DECODE_RUNNING;
  608. _start_output = true;
  609. }
  610. // autostart 2 and 3 require cont to be received first
  611. }
  612. if (decode.state == DECODE_COMPLETE || decode.state == DECODE_ERROR) {
  613. if (decode.state == DECODE_COMPLETE) _sendSTMd = true;
  614. if (decode.state == DECODE_ERROR) _sendSTMn = true;
  615. decode.state = DECODE_STOPPED;
  616. if (status.stream_state == STREAMING_HTTP || status.stream_state == STREAMING_FILE) {
  617. _stream_disconnect = true;
  618. }
  619. }
  620. _decode_state = decode.state;
  621. UNLOCK_D;
  622. LOCK_O;
  623. if (!output.external) {
  624. status.output_full = _buf_used(outputbuf);
  625. status.output_size = outputbuf->size;
  626. status.frames_played = output.frames_played_dmp;
  627. status.current_sample_rate = output.current_sample_rate;
  628. status.updated = output.updated;
  629. status.device_frames = output.device_frames;
  630. if (output.track_started) {
  631. _sendSTMs = true;
  632. output.track_started = false;
  633. status.stream_start = output.track_start_time;
  634. }
  635. #if PORTAUDIO
  636. if (output.pa_reopen) {
  637. _pa_open();
  638. output.pa_reopen = false;
  639. }
  640. #endif
  641. if (_start_output && (output.state == OUTPUT_STOPPED || output.state == OUTPUT_OFF)) {
  642. output.state = OUTPUT_BUFFER;
  643. }
  644. if (output.state == OUTPUT_RUNNING && !sentSTMu && status.output_full == 0 && status.stream_state <= DISCONNECT &&
  645. _decode_state == DECODE_STOPPED) {
  646. _sendSTMu = true;
  647. sentSTMu = true;
  648. LOG_DEBUG("output underrun");
  649. output.state = OUTPUT_STOPPED;
  650. output.stop_time = now;
  651. }
  652. if (output.state == OUTPUT_RUNNING && !sentSTMo && status.output_full == 0 && status.stream_state == STREAMING_HTTP) {
  653. _sendSTMo = true;
  654. sentSTMo = true;
  655. }
  656. }
  657. if (output.state == OUTPUT_STOPPED && output.idle_to && (now - output.stop_time > output.idle_to)) {
  658. output.state = OUTPUT_OFF;
  659. LOG_DEBUG("output timeout");
  660. }
  661. if (output.state == OUTPUT_RUNNING && now - status.last > 1000) {
  662. _sendSTMt = true;
  663. status.last = now;
  664. }
  665. UNLOCK_O;
  666. #if IR
  667. LOCK_I;
  668. if (ir.code) {
  669. _sendIR = true;
  670. ir_code = ir.code;
  671. ir_ts = ir.ts;
  672. ir.code = 0;
  673. }
  674. UNLOCK_I;
  675. #endif
  676. if (_stream_disconnect) stream_disconnect();
  677. // send packets once locks released as packet sending can block
  678. if (_sendDSCO) sendDSCO(disconnect_code);
  679. if (_sendSTMs) sendSTAT("STMs", 0);
  680. if (_sendSTMd) sendSTAT("STMd", 0);
  681. if (_sendSTMt) sendSTAT("STMt", 0);
  682. if (_sendSTMl) sendSTAT("STMl", 0);
  683. if (_sendSTMu) sendSTAT("STMu", 0);
  684. if (_sendSTMo) sendSTAT("STMo", 0);
  685. if (_sendSTMn) sendSTAT("STMn", 0);
  686. if (_sendRESP) sendRESP(header, header_len);
  687. if (_sendMETA) sendMETA(header, header_len);
  688. #if IR
  689. if (_sendIR) sendIR(ir_code, ir_ts);
  690. #endif
  691. if (*slimp_loop) (*slimp_loop)();
  692. }
  693. }
  694. }
  695. // called from other threads to wake state machine above
  696. void wake_controller(void) {
  697. wake_signal(wake_e);
  698. }
  699. in_addr_t discover_server(char *default_server, int max) {
  700. struct sockaddr_in d;
  701. struct sockaddr_in s;
  702. char buf[32], port_d[] = "JSON", clip_d[] = "CLIP";
  703. struct pollfd pollinfo;
  704. unsigned port;
  705. u8_t len;
  706. int disc_sock = socket(AF_INET, SOCK_DGRAM, 0);
  707. socklen_t enable = 1;
  708. setsockopt(disc_sock, SOL_SOCKET, SO_BROADCAST, (const void *)&enable, sizeof(enable));
  709. len = sprintf(buf,"e%s%c%s", port_d, '\0', clip_d) + 1;
  710. memset(&d, 0, sizeof(d));
  711. d.sin_family = AF_INET;
  712. d.sin_port = htons(PORT);
  713. d.sin_addr.s_addr = htonl(INADDR_BROADCAST);
  714. pollinfo.fd = disc_sock;
  715. pollinfo.events = POLLIN;
  716. do {
  717. LOG_INFO("sending discovery %u", max);
  718. memset(&s, 0, sizeof(s));
  719. if (sendto(disc_sock, buf, len, 0, (struct sockaddr *)&d, sizeof(d)) < 0) {
  720. LOG_INFO("error sending discovery");
  721. }
  722. if (poll(&pollinfo, 1, 5000) == 1) {
  723. char readbuf[64], *p;
  724. socklen_t slen = sizeof(s);
  725. memset(readbuf, 0, sizeof(readbuf));
  726. recvfrom(disc_sock, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&s, &slen);
  727. LOG_INFO("got response from: %s:%d", inet_ntoa(s.sin_addr), ntohs(s.sin_port));
  728. if ((p = strstr(readbuf, port_d)) != NULL) {
  729. p += strlen(port_d);
  730. slimproto_hport = atoi(p + 1);
  731. }
  732. if ((p = strstr(readbuf, clip_d)) != NULL) {
  733. p += strlen(clip_d);
  734. slimproto_cport = atoi(p + 1);
  735. }
  736. }
  737. if (default_server) {
  738. server_addr(default_server, &s.sin_addr.s_addr, &port);
  739. }
  740. } while (s.sin_addr.s_addr == 0 && running && (!max || --max));
  741. closesocket(disc_sock);
  742. return s.sin_addr.s_addr;
  743. }
  744. #define FIXED_CAP_LEN 256
  745. #define VAR_CAP_LEN 128
  746. void slimproto(log_level level, char *server, u8_t mac[6], const char *name, const char *namefile, const char *modelname, int maxSampleRate) {
  747. struct sockaddr_in serv_addr;
  748. static char fixed_cap[FIXED_CAP_LEN], var_cap[VAR_CAP_LEN] = "";
  749. bool reconnect = false;
  750. unsigned failed_connect = 0;
  751. unsigned slimproto_port = 0;
  752. in_addr_t previous_server = 0;
  753. int i;
  754. memset(&status, 0, sizeof(status));
  755. wake_create(wake_e);
  756. loglevel = level;
  757. running = true;
  758. if (server) {
  759. server_addr(server, &slimproto_ip, &slimproto_port);
  760. }
  761. if (!slimproto_ip) {
  762. #if EMBEDDED
  763. // on first attempt, try really hard to connect before exiting (and only exit if we are not on another sink)
  764. slimproto_ip = discover_server(server, MAX_SERVER_RETRIES * 5);
  765. if (!slimproto_ip && !output.external) return;
  766. #else
  767. slimproto_ip = discover_server(server, 0);
  768. #endif
  769. }
  770. if (!slimproto_port) {
  771. slimproto_port = PORT;
  772. }
  773. if (name) {
  774. strncpy(player_name, name, PLAYER_NAME_LEN);
  775. player_name[PLAYER_NAME_LEN] = '\0';
  776. }
  777. if (namefile) {
  778. FILE *fp;
  779. name_file = namefile;
  780. fp = fopen(namefile, "r");
  781. if (fp) {
  782. if (!fgets(player_name, PLAYER_NAME_LEN, fp)) {
  783. player_name[PLAYER_NAME_LEN] = '\0';
  784. } else {
  785. // strip any \n from fgets response
  786. int len = strlen(player_name);
  787. if (len > 0 && player_name[len - 1] == '\n') {
  788. player_name[len - 1] = '\0';
  789. }
  790. LOG_INFO("retrieved name %s from %s", player_name, name_file);
  791. }
  792. fclose(fp);
  793. }
  794. }
  795. if (!running) return;
  796. LOCK_O;
  797. snprintf(fixed_cap, FIXED_CAP_LEN, ",ModelName=%s,MaxSampleRate=%u", modelname ? modelname : MODEL_NAME_STRING,
  798. #if RESAMPLE || RESAMPLE16
  799. ((maxSampleRate > 0) ? maxSampleRate : output.supported_rates[0]));
  800. #else
  801. ((maxSampleRate > 0 && maxSampleRate < output.supported_rates[0]) ? maxSampleRate : output.supported_rates[0]));
  802. #endif
  803. for (i = 0; i < MAX_CODECS; i++) {
  804. if (codecs[i] && codecs[i]->id && strlen(fixed_cap) < FIXED_CAP_LEN - 10) {
  805. strcat(fixed_cap, ",");
  806. strcat(fixed_cap, codecs[i]->types);
  807. }
  808. }
  809. UNLOCK_O;
  810. memset(&serv_addr, 0, sizeof(serv_addr));
  811. serv_addr.sin_family = AF_INET;
  812. serv_addr.sin_addr.s_addr = slimproto_ip;
  813. serv_addr.sin_port = htons(slimproto_port);
  814. LOG_INFO("connecting to %s:%d", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  815. new_server = 0;
  816. while (running) {
  817. if (new_server) {
  818. previous_server = slimproto_ip;
  819. slimproto_ip = serv_addr.sin_addr.s_addr = new_server;
  820. LOG_INFO("switching server to %s:%d", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  821. new_server = 0;
  822. reconnect = false;
  823. }
  824. sock = socket(AF_INET, SOCK_STREAM, 0);
  825. set_nonblock(sock);
  826. set_nosigpipe(sock);
  827. if (connect_timeout(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr), 5) != 0) {
  828. if (previous_server) {
  829. slimproto_ip = serv_addr.sin_addr.s_addr = previous_server;
  830. LOG_INFO("new server not reachable, reverting to previous server %s:%d", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
  831. } else {
  832. LOG_INFO("unable to connect to server %u", failed_connect);
  833. sleep(5);
  834. }
  835. #if EMBEDDED
  836. // in embedded we give up after a while no matter what
  837. if (++failed_connect > MAX_SERVER_RETRIES && !server) {
  838. slimproto_ip = serv_addr.sin_addr.s_addr = discover_server(NULL, MAX_SERVER_RETRIES);
  839. if (!slimproto_ip) return;
  840. } else if (reconnect && MAX_SERVER_RETRIES && failed_connect > 5 * MAX_SERVER_RETRIES) return;
  841. #else
  842. // rediscover server if it was not set at startup or exit
  843. if (!server && ++failed_connect > 5) {
  844. slimproto_ip = serv_addr.sin_addr.s_addr = discover_server(NULL, 0);
  845. }
  846. #endif
  847. } else {
  848. struct sockaddr_in our_addr;
  849. socklen_t len;
  850. LOG_INFO("connected");
  851. var_cap[0] = '\0';
  852. failed_connect = 0;
  853. // check if this is a local player now we are connected & signal to server via 'loc' format
  854. // this requires LocalPlayer server plugin to enable direct file access
  855. len = sizeof(our_addr);
  856. getsockname(sock, (struct sockaddr *) &our_addr, &len);
  857. if (our_addr.sin_addr.s_addr == serv_addr.sin_addr.s_addr) {
  858. LOG_INFO("local player");
  859. strcat(var_cap, ",loc");
  860. }
  861. // add on any capablity to be sent to the new server
  862. if (new_server_cap) {
  863. strcat(var_cap, new_server_cap);
  864. free(new_server_cap);
  865. new_server_cap = NULL;
  866. }
  867. sendHELO(reconnect, fixed_cap, var_cap, mac);
  868. #if EMBEDDED
  869. if (server_notify) (*server_notify)(slimproto_ip, slimproto_hport, slimproto_cport);
  870. #endif
  871. slimproto_run();
  872. if (!reconnect) {
  873. reconnect = true;
  874. }
  875. usleep(100000);
  876. }
  877. previous_server = 0;
  878. closesocket(sock);
  879. }
  880. }
  881. void slimproto_stop(void) {
  882. LOG_INFO("slimproto stop");
  883. running = false;
  884. }