slimproto.c 28 KB

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