2 * This file is part of DisOrder.
3 * Copyright (C) 2004, 2005, 2006, 2007 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"
54 #include "speaker-protocol.h"
59 #define SPEAKER "disorder-speaker"
61 struct queue_entry *playing;
64 static void finished(ev_source *ev);
66 static int speaker_fd = -1;
67 static hash *player_pids;
68 static int shutting_down;
70 static void store_player_pid(const char *id, pid_t pid) {
71 if(!player_pids) player_pids = hash_new(sizeof (pid_t));
72 hash_add(player_pids, id, &pid, HASH_INSERT_OR_REPLACE);
75 static pid_t find_player_pid(const char *id) {
78 if(player_pids && (pidp = hash_find(player_pids, id))) return *pidp;
82 static void forget_player_pid(const char *id) {
83 if(player_pids) hash_remove(player_pids, id);
86 /* called when speaker process terminates */
87 static int speaker_terminated(ev_source attribute((unused)) *ev,
88 pid_t attribute((unused)) pid,
89 int attribute((unused)) status,
90 const struct rusage attribute((unused)) *rusage,
91 void attribute((unused)) *u) {
92 fatal(0, "speaker subprocess %s",
96 /* called when speaker process has something to say */
97 static int speaker_readable(ev_source *ev, int fd,
98 void attribute((unused)) *u) {
99 struct speaker_message sm;
100 int ret = speaker_recv(fd, &sm);
102 if(ret < 0) return 0; /* EAGAIN */
104 ev_fd_cancel(ev, ev_read, fd);
109 /* track ID is paused, DATA seconds played */
110 D(("SM_PAUSED %s %ld", sm.id, sm.data));
111 playing->sofar = sm.data;
114 /* the playing track finished */
115 D(("SM_FINISHED %s", sm.id));
119 /* track ID is playing, DATA seconds played */
120 D(("SM_PLAYING %s %ld", sm.id, sm.data));
121 playing->sofar = sm.data;
124 error(0, "unknown message type %d", sm.type);
129 void speaker_setup(ev_source *ev) {
132 struct speaker_message sm;
134 if(socketpair(PF_UNIX, SOCK_DGRAM, 0, sp) < 0)
135 fatal(errno, "error calling socketpair");
137 lfd = logfd(ev, SPEAKER);
140 if(!(pid = xfork())) {
142 ev_signal_atfork(ev);
151 signal(SIGPIPE, SIG_DFL);
153 execlp("valgrind", "valgrind", SPEAKER, "--config", configfile,
154 debugging ? "--debug" : "--no-debug",
155 log_default == &log_syslog ? "--syslog" : "--no-syslog",
158 execlp(SPEAKER, SPEAKER, "--config", configfile,
159 debugging ? "--debug" : "--no-debug",
160 log_default == &log_syslog ? "--syslog" : "--no-syslog",
163 fatal(errno, "error invoking %s", SPEAKER);
165 ev_child(ev, pid, 0, speaker_terminated, 0);
169 /* Wait for the speaker to be ready */
170 speaker_recv(speaker_fd, &sm);
171 nonblock(speaker_fd);
172 ev_fd(ev, ev_read, speaker_fd, speaker_readable, 0, "speaker read");
175 void speaker_reload(void) {
176 struct speaker_message sm;
178 memset(&sm, 0, sizeof sm);
180 speaker_send(speaker_fd, &sm);
183 /* timeout for play retry */
184 static int play_again(ev_source *ev,
185 const struct timeval attribute((unused)) *now,
186 void attribute((unused)) *u) {
192 /* try calling play() again after @offset@ seconds */
193 static void retry_play(ev_source *ev, int offset) {
196 D(("retry_play(%d)", offset));
199 ev_timeout(ev, 0, &w, play_again, 0);
202 /* Called when the currently playing track finishes playing. This
203 * might be because the player finished or because the speaker process
205 static void finished(ev_source *ev) {
206 D(("finished playing=%p", (void *)playing));
209 if(playing->state != playing_scratched)
210 notify_not_scratched(playing->track, playing->submitter);
211 switch(playing->state) {
213 eventlog("completed", playing->track, (char *)0);
215 case playing_scratched:
216 eventlog("scratched", playing->track, playing->scratched, (char *)0);
219 eventlog("failed", playing->track, wstat(playing->wstat), (char *)0);
224 queue_played(playing);
226 forget_player_pid(playing->id);
228 if(ev) retry_play(ev, config->gap);
231 /* Called when a player terminates. */
232 static int player_finished(ev_source *ev,
235 const struct rusage attribute((unused)) *rusage,
237 struct queue_entry *q = u;
239 D(("player_finished pid=%lu status=%#x",
240 (unsigned long)pid, (unsigned)status));
241 /* Record that this PID is dead. If we killed the track we might know this
242 * already, but also it might have exited or crashed. Either way we don't
243 * want to end up signalling it. */
244 if(pid == find_player_pid(q->id))
245 forget_player_pid(q->id);
247 case playing_unplayed:
249 /* If this was a pre-prepared track then either it failed or we
250 * deliberately stopped it because it was removed from the queue or moved
251 * down it. So leave it state alone for future use. */
254 /* We actually started playing this track. */
256 if(q->state != playing_scratched)
257 q->state = playing_failed;
259 q->state = playing_ok;
262 /* Regardless we always report and record the status and do cleanup for
265 error(0, "player for %s %s", q->track, wstat(status));
266 if(q->type & DISORDER_PLAYER_PREFORK)
267 play_cleanup(q->pl, q->data);
269 /* If this actually was the current track, and does not use the speaker
270 * process, then it must have finished. For raw-output players we will get a
271 * separate notification from the speaker process. */
273 && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
278 /* Find the player for Q */
279 static int find_player(const struct queue_entry *q) {
282 for(n = 0; n < config->player.n; ++n)
283 if(fnmatch(config->player.s[n].s[0], q->track, 0) == 0)
285 if(n >= config->player.n)
291 /* Return values from start() */
292 #define START_OK 0 /**< @brief Succeeded. */
293 #define START_HARDFAIL 1 /**< @brief Track is broken. */
294 #define START_SOFTFAIL 2 /**< @brief Track OK, system (temporarily?) broken */
296 /** @brief Play or prepare @p q
297 * @param ev Event loop
298 * @param q Track to play/prepare
299 * @param prepare_only If true, only prepares track
300 * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
302 static int start(ev_source *ev,
303 struct queue_entry *q,
308 struct speaker_message sm;
311 ao_sample_format format;
315 const char *waitdevice = 0;
316 const char *const *optv;
318 struct sockaddr_un addr;
321 memset(&sm, 0, sizeof sm);
322 D(("start %s %d", q->id, prepare_only));
323 if(find_player_pid(q->id) > 0) {
324 if(prepare_only) return START_OK;
325 /* We have already prepared this track so we just need to tell the speaker
326 * process to start actually playing the queued up audio data */
327 strcpy(sm.id, q->id);
329 speaker_send(speaker_fd, &sm);
330 D(("sent SM_PLAY for %s", sm.id));
333 /* Find the player plugin. */
334 if((n = find_player(q)) < 0) return START_HARDFAIL;
335 if(!(q->pl = open_plugin(config->player.s[n].s[1], 0)))
336 return START_HARDFAIL;
337 q->type = play_get_type(q->pl);
338 /* Can't prepare non-raw tracks. */
340 && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
342 /* Call the prefork function. */
343 p = trackdb_rawpath(q->track);
344 if(q->type & DISORDER_PLAYER_PREFORK)
345 if(!(q->data = play_prefork(q->pl, p))) {
346 error(0, "prefork function for %s failed", q->track);
347 return START_HARDFAIL;
349 /* Use the second arg as the tag if available (it's probably a command name),
350 * otherwise the module name. */
352 lfd = logfd(ev, (config->player.s[n].s[2]
353 ? config->player.s[n].s[2] : config->player.s[n].s[1]));
356 optc = config->player.s[n].n - 2;
357 optv = (void *)&config->player.s[n].s[2];
358 while(optc > 0 && optv[0][0] == '-') {
359 if(!strcmp(optv[0], "--")) {
364 if(!strcmp(optv[0], "--wait-for-device")
365 || !strncmp(optv[0], "--wait-for-device=", 18)) {
366 if((waitdevice = strchr(optv[0], '='))) {
369 waitdevice = ""; /* use default */
373 error(0, "unknown option %s", optv[0]);
374 return START_HARDFAIL;
377 switch(pid = fork()) {
380 ev_signal_atfork(ev);
381 signal(SIGPIPE, SIG_DFL);
385 xclose(lfd); /* tidy up */
388 if((q->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
389 /* "Raw" format players always have their output send down a pipe
390 * to the disorder-normalize process. This will connect to the
391 * speaker process to actually play the audio data.
393 /* np will be the pipe to disorder-normalize */
394 if(socketpair(PF_UNIX, SOCK_STREAM, 0, np) < 0)
395 fatal(errno, "error calling socketpair");
396 xshutdown(np[0], SHUT_WR); /* normalize reads from np[0] */
397 xshutdown(np[1], SHUT_RD); /* decoder writes to np[1] */
400 /* Start disorder-normalize */
401 if(!(npid = xfork())) {
403 /* Connect to the speaker process */
404 memset(&addr, 0, sizeof addr);
405 addr.sun_family = AF_UNIX;
406 snprintf(addr.sun_path, sizeof addr.sun_path,
407 "%s/speaker", config->home);
408 sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
409 if(connect(sfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
410 fatal(errno, "connecting to %s", addr.sun_path);
412 if(write(sfd, &l, sizeof l) < 0
413 || write(sfd, q->id, l) < 0)
414 fatal(errno, "writing to %s", addr.sun_path);
423 /* Ask the speaker to actually start playing the track; we do it here
424 * so it's definitely after ack. */
426 strcpy(sm.id, q->id);
428 speaker_send(speaker_fd, &sm);
429 D(("sent SM_PLAY for %s", sm.id));
431 execlp("disorder-normalize", "disorder-normalize",
432 log_default == &log_syslog ? "--syslog" : "--no-syslog",
434 fatal(errno, "executing disorder-normalize");
435 /* end of the innermost fork */
438 /* end of the middle fork */
440 /* Wait for the middle fork to finish */
441 while(waitpid(npid, &n, 0) < 0 && errno == EINTR)
443 /* Pass the file descriptor to the driver in an environment
445 snprintf(buffer, sizeof buffer, "DISORDER_RAW_FD=%d", np[1]);
446 if(putenv(buffer) < 0)
447 fatal(errno, "error calling putenv");
448 /* Close all the FDs we don't need */
454 n = ao_driver_id(waitdevice);
456 fatal(0, "invalid libao driver: %s", optv[0]);
458 n = ao_default_driver_id();
459 /* Make up a format. */
460 memset(&format, 0, sizeof format);
464 format.byte_format = AO_FMT_NATIVE;
467 ts.tv_nsec = 100000000; /* 0.1s */
468 while((device = ao_open_live(n, &format, 0)) == 0 && retries-- > 0)
479 error(errno, "error calling fork");
480 if(q->type & DISORDER_PLAYER_PREFORK)
481 play_cleanup(q->pl, q->data); /* else would leak */
484 return START_SOFTFAIL;
486 store_player_pid(q->id, pid);
490 ev_child(ev, pid, 0, player_finished, q);
491 D(("player subprocess ID %lu", (unsigned long)pid));
495 int prepare(ev_source *ev,
496 struct queue_entry *q) {
499 /* Find the player plugin */
500 if(find_player_pid(q->id) > 0) return 0; /* Already going. */
501 if((n = find_player(q)) < 0) return -1; /* No player */
502 q->pl = open_plugin(config->player.s[n].s[1], 0); /* No player */
503 q->type = play_get_type(q->pl);
504 if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
505 return 0; /* Not a raw player */
506 return start(ev, q, 1/*prepare_only*/); /* Prepare it */
509 void abandon(ev_source attribute((unused)) *ev,
510 struct queue_entry *q) {
511 struct speaker_message sm;
512 pid_t pid = find_player_pid(q->id);
514 if(pid < 0) return; /* Not prepared. */
515 if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
516 return; /* Not a raw player. */
517 /* Terminate the player. */
518 kill(-pid, config->signal);
519 forget_player_pid(q->id);
520 /* Cancel the track. */
521 memset(&sm, 0, sizeof sm);
523 strcpy(sm.id, q->id);
524 speaker_send(speaker_fd, &sm);
527 int add_random_track(void) {
528 struct queue_entry *q;
533 /* If random play is not enabled then do nothing. */
534 if(shutting_down || !random_is_enabled())
536 /* Count how big the queue is */
537 for(q = qhead.next; q != &qhead; q = q->next)
539 /* Add random tracks until the queue is at the right size */
540 while(qlen < config->queue_pad) {
541 /* Try to pick a random track */
542 if(!(p = trackdb_random(16))) {
546 /* Add it to the end of the queue. */
547 q = queue_add(p, 0, WHERE_END);
548 q->state = playing_random;
549 D(("picked %p (%s) at random", (void *)q, q->track));
552 /* Commit the queue */
557 /* try to play a track */
558 void play(ev_source *ev) {
559 struct queue_entry *q;
560 int random_enabled = random_is_enabled();
562 D(("play playing=%p", (void *)playing));
563 if(shutting_down || playing || !playing_is_enabled()) return;
564 /* If the queue is empty then add a random track. */
565 if(qhead.next == &qhead) {
568 if(add_random_track()) {
569 /* On error, try again in 10s. */
573 /* Now there must be at least one track in the queue. */
576 /* If random play is disabled but the track is a random one then don't play
577 * it. play() will be called again when random play is re-enabled. */
578 if(!random_enabled && q->state == playing_random)
580 D(("taken %p (%s) from queue", (void *)q, q->track));
581 /* Try to start playing. */
582 switch(start(ev, q, 0/*!prepare_only*/)) {
584 if(q == qhead.next) {
585 queue_remove(q, 0); /* Abandon this track. */
589 if(qhead.next == &qhead)
590 /* Queue is empty, wait a bit before trying something else (so we don't
591 * sit there looping madly in the presence of persistent problem). Note
592 * that we might not reliably get a random track lookahead in this case,
593 * but if we get here then really there are bigger problems. */
596 /* More in queue, try again now. */
600 /* Try same track again in a bit. */
604 if(q == qhead.next) {
609 time(&playing->played);
610 playing->state = playing_started;
611 notify_play(playing->track, playing->submitter);
612 eventlog("playing", playing->track,
613 playing->submitter ? playing->submitter : (const char *)0,
615 /* Maybe add a random track. */
617 /* If there is another track in the queue prepare it now. This could
618 * potentially be a just-added random track. */
619 if(qhead.next != &qhead)
620 prepare(ev, qhead.next);
625 int playing_is_enabled(void) {
626 const char *s = trackdb_get_global("playing");
628 return !s || !strcmp(s, "yes");
631 void enable_playing(const char *who, ev_source *ev) {
632 trackdb_set_global("playing", "yes", who);
633 /* Add a random track if necessary. */
638 void disable_playing(const char *who) {
639 trackdb_set_global("playing", "no", who);
642 int random_is_enabled(void) {
643 const char *s = trackdb_get_global("random-play");
645 return !s || !strcmp(s, "yes");
648 void enable_random(const char *who, ev_source *ev) {
649 trackdb_set_global("random-play", "yes", who);
654 void disable_random(const char *who) {
655 trackdb_set_global("random-play", "no", who);
658 void scratch(const char *who, const char *id) {
659 struct queue_entry *q;
660 struct speaker_message sm;
663 D(("scratch playing=%p state=%d id=%s playing->id=%s",
665 playing ? playing->state : 0,
667 playing ? playing->id : "(none)"));
669 && (playing->state == playing_started
670 || playing->state == playing_paused)
672 || !strcmp(id, playing->id))) {
673 playing->state = playing_scratched;
674 playing->scratched = who ? xstrdup(who) : 0;
675 if((pid = find_player_pid(playing->id)) > 0) {
676 D(("kill -%d %lu", config->signal, (unsigned long)pid));
677 kill(-pid, config->signal);
678 forget_player_pid(playing->id);
680 error(0, "could not find PID for %s", playing->id);
681 if((playing->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
682 memset(&sm, 0, sizeof sm);
684 strcpy(sm.id, playing->id);
685 speaker_send(speaker_fd, &sm);
686 D(("sending SM_CANCEL for %s", playing->id));
688 /* put a scratch track onto the front of the queue (but don't
689 * bother if playing is disabled) */
690 if(playing_is_enabled() && config->scratch.n) {
691 int r = rand() * (double)config->scratch.n / (RAND_MAX + 1.0);
692 q = queue_add(config->scratch.s[r], who, WHERE_START);
693 q->state = playing_isscratch;
695 notify_scratch(playing->track, playing->submitter, who,
696 time(0) - playing->played);
700 void quitting(ev_source *ev) {
701 struct queue_entry *q;
704 /* Don't start anything new */
706 /* Shut down the current player */
708 if((pid = find_player_pid(playing->id)) > 0) {
709 kill(-pid, config->signal);
710 forget_player_pid(playing->id);
712 error(0, "could not find PID for %s", playing->id);
713 playing->state = playing_quitting;
716 /* Zap any other players */
717 for(q = qhead.next; q != &qhead; q = q->next)
718 if((pid = find_player_pid(q->id)) > 0) {
719 D(("kill -%d %lu", config->signal, (unsigned long)pid));
720 kill(-pid, config->signal);
721 forget_player_pid(q->id);
723 error(0, "could not find PID for %s", q->id);
724 /* Don't need the speaker any more */
725 ev_fd_cancel(ev, ev_read, speaker_fd);
729 int pause_playing(const char *who) {
730 struct speaker_message sm;
733 /* Can't pause if already paused or if nothing playing. */
734 if(!playing || paused) return 0;
735 switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
736 case DISORDER_PLAYER_STANDALONE:
737 if(!(playing->type & DISORDER_PLAYER_PAUSES)) {
739 error(0, "cannot pause because player is not powerful enough");
742 if(play_pause(playing->pl, &played, playing->data)) {
743 error(0, "player indicates it cannot pause");
746 time(&playing->lastpaused);
747 playing->uptopause = played;
748 playing->lastresumed = 0;
750 case DISORDER_PLAYER_RAW:
751 memset(&sm, 0, sizeof sm);
753 speaker_send(speaker_fd, &sm);
756 if(who) info("paused by %s", who);
757 notify_pause(playing->track, who);
759 if(playing->state == playing_started)
760 playing->state = playing_paused;
761 eventlog("state", "pause", (char *)0);
765 void resume_playing(const char *who) {
766 struct speaker_message sm;
771 switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
772 case DISORDER_PLAYER_STANDALONE:
773 if(!playing->type & DISORDER_PLAYER_PAUSES) {
775 /* Shouldn't happen */
778 play_resume(playing->pl, playing->data);
779 time(&playing->lastresumed);
781 case DISORDER_PLAYER_RAW:
782 memset(&sm, 0, sizeof sm);
784 speaker_send(speaker_fd, &sm);
787 if(who) info("resumed by %s", who);
788 notify_resume(playing->track, who);
789 if(playing->state == playing_paused)
790 playing->state = playing_started;
791 eventlog("state", "resume", (char *)0);