2 * This file is part of DisOrder.
3 * Copyright (C) 2004-2008 Richard Kettlewell
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
24 #include <sys/types.h>
33 #include <sys/socket.h>
44 #include "configuration.h"
46 #include "server-queue.h"
55 #include "speaker-protocol.h"
60 #define SPEAKER "disorder-speaker"
62 struct queue_entry *playing;
65 static void finished(ev_source *ev);
67 static int speaker_fd = -1;
68 static hash *player_pids;
69 static int shutting_down;
71 static void store_player_pid(const char *id, pid_t pid) {
72 if(!player_pids) player_pids = hash_new(sizeof (pid_t));
73 hash_add(player_pids, id, &pid, HASH_INSERT_OR_REPLACE);
76 static pid_t find_player_pid(const char *id) {
79 if(player_pids && (pidp = hash_find(player_pids, id))) return *pidp;
83 static void forget_player_pid(const char *id) {
84 if(player_pids) hash_remove(player_pids, id);
87 /* called when speaker process terminates */
88 static int speaker_terminated(ev_source attribute((unused)) *ev,
89 pid_t attribute((unused)) pid,
90 int attribute((unused)) status,
91 const struct rusage attribute((unused)) *rusage,
92 void attribute((unused)) *u) {
93 fatal(0, "speaker subprocess %s",
97 /* called when speaker process has something to say */
98 static int speaker_readable(ev_source *ev, int fd,
99 void attribute((unused)) *u) {
100 struct speaker_message sm;
101 int ret = speaker_recv(fd, &sm);
103 if(ret < 0) return 0; /* EAGAIN */
105 ev_fd_cancel(ev, ev_read, fd);
110 /* track ID is paused, DATA seconds played */
111 D(("SM_PAUSED %s %ld", sm.id, sm.data));
112 playing->sofar = sm.data;
114 case SM_FINISHED: /* scratched the playing track */
115 case SM_STILLBORN: /* scratched too early */
116 case SM_UNKNOWN: /* scratched WAY too early */
117 if(playing && !strcmp(sm.id, playing->id))
121 /* track ID is playing, DATA seconds played */
122 D(("SM_PLAYING %s %ld", sm.id, sm.data));
123 playing->sofar = sm.data;
126 error(0, "unknown message type %d", sm.type);
131 void speaker_setup(ev_source *ev) {
134 struct speaker_message sm;
136 if(socketpair(PF_UNIX, SOCK_DGRAM, 0, sp) < 0)
137 fatal(errno, "error calling socketpair");
138 if(!(pid = xfork())) {
140 ev_signal_atfork(ev);
145 signal(SIGPIPE, SIG_DFL);
147 execlp("valgrind", "valgrind", SPEAKER, "--config", configfile,
148 debugging ? "--debug" : "--no-debug",
149 log_default == &log_syslog ? "--syslog" : "--no-syslog",
152 execlp(SPEAKER, SPEAKER, "--config", configfile,
153 debugging ? "--debug" : "--no-debug",
154 log_default == &log_syslog ? "--syslog" : "--no-syslog",
157 fatal(errno, "error invoking %s", SPEAKER);
159 ev_child(ev, pid, 0, speaker_terminated, 0);
163 /* Wait for the speaker to be ready */
164 speaker_recv(speaker_fd, &sm);
165 nonblock(speaker_fd);
166 ev_fd(ev, ev_read, speaker_fd, speaker_readable, 0, "speaker read");
169 void speaker_reload(void) {
170 struct speaker_message sm;
172 memset(&sm, 0, sizeof sm);
174 speaker_send(speaker_fd, &sm);
177 /* Called when the currently playing track finishes playing. This
178 * might be because the player finished or because the speaker process
180 static void finished(ev_source *ev) {
181 D(("finished playing=%p", (void *)playing));
184 if(playing->state != playing_scratched)
185 notify_not_scratched(playing->track, playing->submitter);
186 switch(playing->state) {
188 eventlog("completed", playing->track, (char *)0);
190 case playing_scratched:
191 eventlog("scratched", playing->track, playing->scratched, (char *)0);
194 eventlog("failed", playing->track, wstat(playing->wstat), (char *)0);
199 queue_played(playing);
201 forget_player_pid(playing->id);
203 /* Try to play something else */
204 /* TODO re-support config->gap? */
209 /* Called when a player terminates. */
210 static int player_finished(ev_source *ev,
213 const struct rusage attribute((unused)) *rusage,
215 struct queue_entry *q = u;
217 D(("player_finished pid=%lu status=%#x",
218 (unsigned long)pid, (unsigned)status));
219 /* Record that this PID is dead. If we killed the track we might know this
220 * already, but also it might have exited or crashed. Either way we don't
221 * want to end up signalling it. */
222 if(pid == find_player_pid(q->id))
223 forget_player_pid(q->id);
225 case playing_unplayed:
227 /* If this was a pre-prepared track then either it failed or we
228 * deliberately stopped it because it was removed from the queue or moved
229 * down it. So leave it state alone for future use. */
232 /* We actually started playing this track. */
234 if(q->state != playing_scratched)
235 q->state = playing_failed;
237 q->state = playing_ok;
240 /* Regardless we always report and record the status and do cleanup for
243 error(0, "player for %s %s", q->track, wstat(status));
244 if(q->type & DISORDER_PLAYER_PREFORK)
245 play_cleanup(q->pl, q->data);
247 /* If this actually was the current track, and does not use the speaker
248 * process, then it must have finished. For raw-output players we will get a
249 * separate notification from the speaker process. */
251 && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
256 /* Find the player for Q */
257 static int find_player(const struct queue_entry *q) {
260 for(n = 0; n < config->player.n; ++n)
261 if(fnmatch(config->player.s[n].s[0], q->track, 0) == 0)
263 if(n >= config->player.n)
269 /* Return values from start() */
270 #define START_OK 0 /**< @brief Succeeded. */
271 #define START_HARDFAIL 1 /**< @brief Track is broken. */
272 #define START_SOFTFAIL 2 /**< @brief Track OK, system (temporarily?) broken */
274 /** @brief Play or prepare @p q
275 * @param ev Event loop
276 * @param q Track to play/prepare
277 * @param prepare_only If true, only prepares track
278 * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
280 static int start(ev_source *ev,
281 struct queue_entry *q,
286 struct speaker_message sm;
289 ao_sample_format format;
293 const char *waitdevice = 0;
294 const char *const *optv;
296 struct sockaddr_un addr;
299 memset(&sm, 0, sizeof sm);
300 D(("start %s %d", q->id, prepare_only));
302 /* The track is alraedy prepared */
304 /* We want to run it, since it's prepared the answer is to tell the
305 * speaker to set it off */
306 strcpy(sm.id, q->id);
308 speaker_send(speaker_fd, &sm);
309 D(("sent SM_PLAY for %s", sm.id));
313 /* Find the player plugin. */
314 if((n = find_player(q)) < 0) return START_HARDFAIL;
315 if(!(q->pl = open_plugin(config->player.s[n].s[1], 0)))
316 return START_HARDFAIL;
317 q->type = play_get_type(q->pl);
318 /* Can't prepare non-raw tracks. */
320 && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
322 /* Call the prefork function. */
323 p = trackdb_rawpath(q->track);
324 if(q->type & DISORDER_PLAYER_PREFORK)
325 if(!(q->data = play_prefork(q->pl, p))) {
326 error(0, "prefork function for %s failed", q->track);
327 return START_HARDFAIL;
329 /* Use the second arg as the tag if available (it's probably a command name),
330 * otherwise the module name. */
332 lfd = logfd(ev, (config->player.s[n].s[2]
333 ? config->player.s[n].s[2] : config->player.s[n].s[1]));
336 optc = config->player.s[n].n - 2;
337 optv = (void *)&config->player.s[n].s[2];
338 while(optc > 0 && optv[0][0] == '-') {
339 if(!strcmp(optv[0], "--")) {
344 if(!strcmp(optv[0], "--wait-for-device")
345 || !strncmp(optv[0], "--wait-for-device=", 18)) {
346 if((waitdevice = strchr(optv[0], '='))) {
349 waitdevice = ""; /* use default */
353 error(0, "unknown option %s", optv[0]);
354 return START_HARDFAIL;
357 switch(pid = fork()) {
360 progname = "disorderd-fork";
361 ev_signal_atfork(ev);
362 signal(SIGPIPE, SIG_DFL);
366 xclose(lfd); /* tidy up */
369 if((q->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
370 /* "Raw" format players always have their output send down a pipe
371 * to the disorder-normalize process. This will connect to the
372 * speaker process to actually play the audio data.
374 /* np will be the pipe to disorder-normalize */
375 if(socketpair(PF_UNIX, SOCK_STREAM, 0, np) < 0)
376 fatal(errno, "error calling socketpair");
377 /* Beware of the Leopard! On OS X 10.5.x, the order of the shutdown
378 * calls here DOES MATTER. If you do the SHUT_WR first then the SHUT_RD
379 * fails with "Socket is not connected". I think this is a bug but
380 * provided implementors either don't care about the order or all agree
381 * about the order, choosing the reliable order is an adequate
383 xshutdown(np[1], SHUT_RD); /* decoder writes to np[1] */
384 xshutdown(np[0], SHUT_WR); /* normalize reads from np[0] */
387 /* Start disorder-normalize */
388 if(!(npid = xfork())) {
390 /* Connect to the speaker process */
391 memset(&addr, 0, sizeof addr);
392 addr.sun_family = AF_UNIX;
393 snprintf(addr.sun_path, sizeof addr.sun_path,
394 "%s/speaker/socket", config->home);
395 sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
396 if(connect(sfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
397 fatal(errno, "connecting to %s", addr.sun_path);
399 if(write(sfd, &l, sizeof l) < 0
400 || write(sfd, q->id, l) < 0)
401 fatal(errno, "writing to %s", addr.sun_path);
410 /* Ask the speaker to actually start playing the track; we do it here
411 * so it's definitely after ack. */
413 strcpy(sm.id, q->id);
415 speaker_send(speaker_fd, &sm);
416 D(("sent SM_PLAY for %s", sm.id));
418 /* TODO stderr shouldn't be redirected for disorder-normalize
419 * (but it should be for play_track() */
420 execlp("disorder-normalize", "disorder-normalize",
421 log_default == &log_syslog ? "--syslog" : "--no-syslog",
422 "--config", configfile,
424 fatal(errno, "executing disorder-normalize");
425 /* end of the innermost fork */
428 /* end of the middle fork */
430 /* Wait for the middle fork to finish */
431 while(waitpid(npid, &n, 0) < 0 && errno == EINTR)
433 /* Pass the file descriptor to the driver in an environment
435 snprintf(buffer, sizeof buffer, "DISORDER_RAW_FD=%d", np[1]);
436 if(putenv(buffer) < 0)
437 fatal(errno, "error calling putenv");
438 /* Close all the FDs we don't need */
444 n = ao_driver_id(waitdevice);
446 fatal(0, "invalid libao driver: %s", optv[0]);
448 n = ao_default_driver_id();
449 /* Make up a format. */
450 memset(&format, 0, sizeof format);
454 format.byte_format = AO_FMT_NATIVE;
457 ts.tv_nsec = 100000000; /* 0.1s */
458 while((device = ao_open_live(n, &format, 0)) == 0 && retries-- > 0)
469 error(errno, "error calling fork");
470 if(q->type & DISORDER_PLAYER_PREFORK)
471 play_cleanup(q->pl, q->data); /* else would leak */
474 return START_SOFTFAIL;
476 store_player_pid(q->id, pid);
481 ev_child(ev, pid, 0, player_finished, q);
482 D(("player subprocess ID %lu", (unsigned long)pid));
486 int prepare(ev_source *ev,
487 struct queue_entry *q) {
490 /* Find the player plugin */
491 if(find_player_pid(q->id) > 0) return 0; /* Already going. */
492 if((n = find_player(q)) < 0) return -1; /* No player */
493 q->pl = open_plugin(config->player.s[n].s[1], 0); /* No player */
494 q->type = play_get_type(q->pl);
495 if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
496 return 0; /* Not a raw player */
497 return start(ev, q, 1/*prepare_only*/); /* Prepare it */
500 void abandon(ev_source attribute((unused)) *ev,
501 struct queue_entry *q) {
502 struct speaker_message sm;
503 pid_t pid = find_player_pid(q->id);
505 if(pid < 0) return; /* Not prepared. */
506 if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
507 return; /* Not a raw player. */
508 /* Terminate the player. */
509 kill(-pid, config->signal);
510 forget_player_pid(q->id);
511 /* Cancel the track. */
512 memset(&sm, 0, sizeof sm);
514 strcpy(sm.id, q->id);
515 speaker_send(speaker_fd, &sm);
518 /** @brief Called with a new random track
519 * @param track Track name
521 static void chosen_random_track(ev_source *ev,
523 struct queue_entry *q;
527 /* Add the track to the queue */
528 q = queue_add(track, 0, WHERE_END);
529 q->state = playing_random;
530 D(("picked %p (%s) at random", (void *)q, q->track));
532 /* Maybe a track can now be played */
536 /** @brief Maybe add a randomly chosen track
537 * @param ev Event loop
539 void add_random_track(ev_source *ev) {
540 struct queue_entry *q;
543 /* If random play is not enabled then do nothing. */
544 if(shutting_down || !random_is_enabled())
546 /* Count how big the queue is */
547 for(q = qhead.next; q != &qhead; q = q->next)
549 /* If it's smaller than the desired size then add a track */
550 if(qlen < config->queue_pad)
551 trackdb_request_random(ev, chosen_random_track);
554 /* try to play a track */
555 void play(ev_source *ev) {
556 struct queue_entry *q;
557 int random_enabled = random_is_enabled();
559 D(("play playing=%p", (void *)playing));
560 if(shutting_down || playing || !playing_is_enabled()) return;
561 /* See if there's anything to play */
562 if(qhead.next == &qhead) {
563 /* Queue is empty. We could just wait around since there are periodic
564 * attempts to add a random track anyway. However they are rarer than
565 * attempts to force a track so we initiate one now. */
566 add_random_track(ev);
569 /* There must be at least one track in the queue. */
571 /* If random play is disabled but the track is a random one then don't play
572 * it. play() will be called again when random play is re-enabled. */
573 if(!random_enabled && q->state == playing_random)
575 D(("taken %p (%s) from queue", (void *)q, q->track));
576 /* Try to start playing. */
577 switch(start(ev, q, 0/*!prepare_only*/)) {
579 if(q == qhead.next) {
580 queue_remove(q, 0); /* Abandon this track. */
584 /* Oh well, try the next one */
588 /* We'll try the same track again shortly. */
591 if(q == qhead.next) {
596 time(&playing->played);
597 playing->state = playing_started;
598 notify_play(playing->track, playing->submitter);
599 eventlog("playing", playing->track,
600 playing->submitter ? playing->submitter : (const char *)0,
602 /* Maybe add a random track. */
603 add_random_track(ev);
604 /* If there is another track in the queue prepare it now. This could
605 * potentially be a just-added random track. */
606 if(qhead.next != &qhead)
607 prepare(ev, qhead.next);
612 int playing_is_enabled(void) {
613 const char *s = trackdb_get_global("playing");
615 return !s || !strcmp(s, "yes");
618 void enable_playing(const char *who, ev_source *ev) {
619 trackdb_set_global("playing", "yes", who);
620 /* Add a random track if necessary. */
621 add_random_track(ev);
625 void disable_playing(const char *who) {
626 trackdb_set_global("playing", "no", who);
629 int random_is_enabled(void) {
630 const char *s = trackdb_get_global("random-play");
632 return !s || !strcmp(s, "yes");
635 void enable_random(const char *who, ev_source *ev) {
636 trackdb_set_global("random-play", "yes", who);
637 add_random_track(ev);
641 void disable_random(const char *who) {
642 trackdb_set_global("random-play", "no", who);
645 void scratch(const char *who, const char *id) {
646 struct queue_entry *q;
647 struct speaker_message sm;
650 D(("scratch playing=%p state=%d id=%s playing->id=%s",
652 playing ? playing->state : 0,
654 playing ? playing->id : "(none)"));
656 && (playing->state == playing_started
657 || playing->state == playing_paused)
659 || !strcmp(id, playing->id))) {
660 playing->state = playing_scratched;
661 playing->scratched = who ? xstrdup(who) : 0;
662 if((pid = find_player_pid(playing->id)) > 0) {
663 D(("kill -%d %lu", config->signal, (unsigned long)pid));
664 kill(-pid, config->signal);
665 forget_player_pid(playing->id);
667 error(0, "could not find PID for %s", playing->id);
668 if((playing->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
669 memset(&sm, 0, sizeof sm);
671 strcpy(sm.id, playing->id);
672 speaker_send(speaker_fd, &sm);
673 D(("sending SM_CANCEL for %s", playing->id));
675 /* put a scratch track onto the front of the queue (but don't
676 * bother if playing is disabled) */
677 if(playing_is_enabled() && config->scratch.n) {
678 int r = rand() * (double)config->scratch.n / (RAND_MAX + 1.0);
679 q = queue_add(config->scratch.s[r], who, WHERE_START);
680 q->state = playing_isscratch;
682 notify_scratch(playing->track, playing->submitter, who,
683 time(0) - playing->played);
687 void quitting(ev_source *ev) {
688 struct queue_entry *q;
691 /* Don't start anything new */
693 /* Shut down the current player */
695 if((pid = find_player_pid(playing->id)) > 0) {
696 kill(-pid, config->signal);
697 forget_player_pid(playing->id);
699 error(0, "could not find PID for %s", playing->id);
700 playing->state = playing_quitting;
703 /* Zap any other players */
704 for(q = qhead.next; q != &qhead; q = q->next)
705 if((pid = find_player_pid(q->id)) > 0) {
706 D(("kill -%d %lu", config->signal, (unsigned long)pid));
707 kill(-pid, config->signal);
708 forget_player_pid(q->id);
710 error(0, "could not find PID for %s", q->id);
711 /* Don't need the speaker any more */
712 ev_fd_cancel(ev, ev_read, speaker_fd);
716 int pause_playing(const char *who) {
717 struct speaker_message sm;
720 /* Can't pause if already paused or if nothing playing. */
721 if(!playing || paused) return 0;
722 switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
723 case DISORDER_PLAYER_STANDALONE:
724 if(!(playing->type & DISORDER_PLAYER_PAUSES)) {
726 error(0, "cannot pause because player is not powerful enough");
729 if(play_pause(playing->pl, &played, playing->data)) {
730 error(0, "player indicates it cannot pause");
733 time(&playing->lastpaused);
734 playing->uptopause = played;
735 playing->lastresumed = 0;
737 case DISORDER_PLAYER_RAW:
738 memset(&sm, 0, sizeof sm);
740 speaker_send(speaker_fd, &sm);
743 if(who) info("paused by %s", who);
744 notify_pause(playing->track, who);
746 if(playing->state == playing_started)
747 playing->state = playing_paused;
748 eventlog("state", "pause", (char *)0);
752 void resume_playing(const char *who) {
753 struct speaker_message sm;
758 switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
759 case DISORDER_PLAYER_STANDALONE:
760 if(!playing->type & DISORDER_PLAYER_PAUSES) {
762 /* Shouldn't happen */
765 play_resume(playing->pl, playing->data);
766 time(&playing->lastresumed);
768 case DISORDER_PLAYER_RAW:
769 memset(&sm, 0, sizeof sm);
771 speaker_send(speaker_fd, &sm);
774 if(who) info("resumed by %s", who);
775 notify_resume(playing->track, who);
776 if(playing->state == playing_paused)
777 playing->state = playing_started;
778 eventlog("state", "resume", (char *)0);