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");
136 if(!(pid = xfork())) {
138 ev_signal_atfork(ev);
143 signal(SIGPIPE, SIG_DFL);
145 execlp("valgrind", "valgrind", SPEAKER, "--config", configfile,
146 debugging ? "--debug" : "--no-debug",
147 log_default == &log_syslog ? "--syslog" : "--no-syslog",
150 execlp(SPEAKER, SPEAKER, "--config", configfile,
151 debugging ? "--debug" : "--no-debug",
152 log_default == &log_syslog ? "--syslog" : "--no-syslog",
155 fatal(errno, "error invoking %s", SPEAKER);
157 ev_child(ev, pid, 0, speaker_terminated, 0);
161 /* Wait for the speaker to be ready */
162 speaker_recv(speaker_fd, &sm);
163 nonblock(speaker_fd);
164 ev_fd(ev, ev_read, speaker_fd, speaker_readable, 0, "speaker read");
167 void speaker_reload(void) {
168 struct speaker_message sm;
170 memset(&sm, 0, sizeof sm);
172 speaker_send(speaker_fd, &sm);
175 /* timeout for play retry */
176 static int play_again(ev_source *ev,
177 const struct timeval attribute((unused)) *now,
178 void attribute((unused)) *u) {
184 /* try calling play() again after @offset@ seconds */
185 static void retry_play(ev_source *ev, int offset) {
188 D(("retry_play(%d)", offset));
191 ev_timeout(ev, 0, &w, play_again, 0);
194 /* Called when the currently playing track finishes playing. This
195 * might be because the player finished or because the speaker process
197 static void finished(ev_source *ev) {
198 D(("finished playing=%p", (void *)playing));
201 if(playing->state != playing_scratched)
202 notify_not_scratched(playing->track, playing->submitter);
203 switch(playing->state) {
205 eventlog("completed", playing->track, (char *)0);
207 case playing_scratched:
208 eventlog("scratched", playing->track, playing->scratched, (char *)0);
211 eventlog("failed", playing->track, wstat(playing->wstat), (char *)0);
216 queue_played(playing);
218 forget_player_pid(playing->id);
220 if(ev) retry_play(ev, config->gap);
223 /* Called when a player terminates. */
224 static int player_finished(ev_source *ev,
227 const struct rusage attribute((unused)) *rusage,
229 struct queue_entry *q = u;
231 D(("player_finished pid=%lu status=%#x",
232 (unsigned long)pid, (unsigned)status));
233 /* Record that this PID is dead. If we killed the track we might know this
234 * already, but also it might have exited or crashed. Either way we don't
235 * want to end up signalling it. */
236 if(pid == find_player_pid(q->id))
237 forget_player_pid(q->id);
239 case playing_unplayed:
241 /* If this was a pre-prepared track then either it failed or we
242 * deliberately stopped it because it was removed from the queue or moved
243 * down it. So leave it state alone for future use. */
246 /* We actually started playing this track. */
248 if(q->state != playing_scratched)
249 q->state = playing_failed;
251 q->state = playing_ok;
254 /* Regardless we always report and record the status and do cleanup for
257 error(0, "player for %s %s", q->track, wstat(status));
258 if(q->type & DISORDER_PLAYER_PREFORK)
259 play_cleanup(q->pl, q->data);
261 /* If this actually was the current track, and does not use the speaker
262 * process, then it must have finished. For raw-output players we will get a
263 * separate notification from the speaker process. */
265 && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
270 /* Find the player for Q */
271 static int find_player(const struct queue_entry *q) {
274 for(n = 0; n < config->player.n; ++n)
275 if(fnmatch(config->player.s[n].s[0], q->track, 0) == 0)
277 if(n >= config->player.n)
283 /* Return values from start() */
284 #define START_OK 0 /**< @brief Succeeded. */
285 #define START_HARDFAIL 1 /**< @brief Track is broken. */
286 #define START_SOFTFAIL 2 /**< @brief Track OK, system (temporarily?) broken */
288 /** @brief Play or prepare @p q
289 * @param ev Event loop
290 * @param q Track to play/prepare
291 * @param prepare_only If true, only prepares track
292 * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
294 static int start(ev_source *ev,
295 struct queue_entry *q,
300 struct speaker_message sm;
303 ao_sample_format format;
307 const char *waitdevice = 0;
308 const char *const *optv;
310 struct sockaddr_un addr;
313 memset(&sm, 0, sizeof sm);
314 D(("start %s %d", q->id, prepare_only));
315 if(find_player_pid(q->id) > 0) {
316 if(prepare_only) return START_OK;
317 /* We have already prepared this track so we just need to tell the speaker
318 * process to start actually playing the queued up audio data */
319 strcpy(sm.id, q->id);
321 speaker_send(speaker_fd, &sm);
322 D(("sent SM_PLAY for %s", sm.id));
325 /* Find the player plugin. */
326 if((n = find_player(q)) < 0) return START_HARDFAIL;
327 if(!(q->pl = open_plugin(config->player.s[n].s[1], 0)))
328 return START_HARDFAIL;
329 q->type = play_get_type(q->pl);
330 /* Can't prepare non-raw tracks. */
332 && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
334 /* Call the prefork function. */
335 p = trackdb_rawpath(q->track);
336 if(q->type & DISORDER_PLAYER_PREFORK)
337 if(!(q->data = play_prefork(q->pl, p))) {
338 error(0, "prefork function for %s failed", q->track);
339 return START_HARDFAIL;
341 /* Use the second arg as the tag if available (it's probably a command name),
342 * otherwise the module name. */
344 lfd = logfd(ev, (config->player.s[n].s[2]
345 ? config->player.s[n].s[2] : config->player.s[n].s[1]));
348 optc = config->player.s[n].n - 2;
349 optv = (void *)&config->player.s[n].s[2];
350 while(optc > 0 && optv[0][0] == '-') {
351 if(!strcmp(optv[0], "--")) {
356 if(!strcmp(optv[0], "--wait-for-device")
357 || !strncmp(optv[0], "--wait-for-device=", 18)) {
358 if((waitdevice = strchr(optv[0], '='))) {
361 waitdevice = ""; /* use default */
365 error(0, "unknown option %s", optv[0]);
366 return START_HARDFAIL;
369 switch(pid = fork()) {
372 ev_signal_atfork(ev);
373 signal(SIGPIPE, SIG_DFL);
377 xclose(lfd); /* tidy up */
380 if((q->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
381 /* "Raw" format players always have their output send down a pipe
382 * to the disorder-normalize process. This will connect to the
383 * speaker process to actually play the audio data.
385 /* np will be the pipe to disorder-normalize */
386 if(socketpair(PF_UNIX, SOCK_STREAM, 0, np) < 0)
387 fatal(errno, "error calling socketpair");
388 xshutdown(np[0], SHUT_WR); /* normalize reads from np[0] */
389 xshutdown(np[1], SHUT_RD); /* decoder writes to np[1] */
392 /* Start disorder-normalize */
393 if(!(npid = xfork())) {
395 /* Connect to the speaker process */
396 memset(&addr, 0, sizeof addr);
397 addr.sun_family = AF_UNIX;
398 snprintf(addr.sun_path, sizeof addr.sun_path,
399 "%s/speaker", config->home);
400 sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
401 if(connect(sfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
402 fatal(errno, "connecting to %s", addr.sun_path);
404 if(write(sfd, &l, sizeof l) < 0
405 || write(sfd, q->id, l) < 0)
406 fatal(errno, "writing to %s", addr.sun_path);
415 /* Ask the speaker to actually start playing the track; we do it here
416 * so it's definitely after ack. */
418 strcpy(sm.id, q->id);
420 speaker_send(speaker_fd, &sm);
421 D(("sent SM_PLAY for %s", sm.id));
423 /* TODO stderr shouldn't be redirected for disorder-normalize
424 * (but it should be for play_track() */
425 execlp("disorder-normalize", "disorder-normalize",
426 log_default == &log_syslog ? "--syslog" : "--no-syslog",
428 fatal(errno, "executing disorder-normalize");
429 /* end of the innermost fork */
432 /* end of the middle fork */
434 /* Wait for the middle fork to finish */
435 while(waitpid(npid, &n, 0) < 0 && errno == EINTR)
437 /* Pass the file descriptor to the driver in an environment
439 snprintf(buffer, sizeof buffer, "DISORDER_RAW_FD=%d", np[1]);
440 if(putenv(buffer) < 0)
441 fatal(errno, "error calling putenv");
442 /* Close all the FDs we don't need */
448 n = ao_driver_id(waitdevice);
450 fatal(0, "invalid libao driver: %s", optv[0]);
452 n = ao_default_driver_id();
453 /* Make up a format. */
454 memset(&format, 0, sizeof format);
458 format.byte_format = AO_FMT_NATIVE;
461 ts.tv_nsec = 100000000; /* 0.1s */
462 while((device = ao_open_live(n, &format, 0)) == 0 && retries-- > 0)
473 error(errno, "error calling fork");
474 if(q->type & DISORDER_PLAYER_PREFORK)
475 play_cleanup(q->pl, q->data); /* else would leak */
478 return START_SOFTFAIL;
480 store_player_pid(q->id, pid);
484 ev_child(ev, pid, 0, player_finished, q);
485 D(("player subprocess ID %lu", (unsigned long)pid));
489 int prepare(ev_source *ev,
490 struct queue_entry *q) {
493 /* Find the player plugin */
494 if(find_player_pid(q->id) > 0) return 0; /* Already going. */
495 if((n = find_player(q)) < 0) return -1; /* No player */
496 q->pl = open_plugin(config->player.s[n].s[1], 0); /* No player */
497 q->type = play_get_type(q->pl);
498 if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
499 return 0; /* Not a raw player */
500 return start(ev, q, 1/*prepare_only*/); /* Prepare it */
503 void abandon(ev_source attribute((unused)) *ev,
504 struct queue_entry *q) {
505 struct speaker_message sm;
506 pid_t pid = find_player_pid(q->id);
508 if(pid < 0) return; /* Not prepared. */
509 if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
510 return; /* Not a raw player. */
511 /* Terminate the player. */
512 kill(-pid, config->signal);
513 forget_player_pid(q->id);
514 /* Cancel the track. */
515 memset(&sm, 0, sizeof sm);
517 strcpy(sm.id, q->id);
518 speaker_send(speaker_fd, &sm);
521 int add_random_track(void) {
522 struct queue_entry *q;
527 /* If random play is not enabled then do nothing. */
528 if(shutting_down || !random_is_enabled())
530 /* Count how big the queue is */
531 for(q = qhead.next; q != &qhead; q = q->next)
533 /* Add random tracks until the queue is at the right size */
534 while(qlen < config->queue_pad) {
535 /* Try to pick a random track */
536 if(!(p = trackdb_random(16))) {
540 /* Add it to the end of the queue. */
541 q = queue_add(p, 0, WHERE_END);
542 q->state = playing_random;
543 D(("picked %p (%s) at random", (void *)q, q->track));
546 /* Commit the queue */
551 /* try to play a track */
552 void play(ev_source *ev) {
553 struct queue_entry *q;
554 int random_enabled = random_is_enabled();
556 D(("play playing=%p", (void *)playing));
557 if(shutting_down || playing || !playing_is_enabled()) return;
558 /* If the queue is empty then add a random track. */
559 if(qhead.next == &qhead) {
562 if(add_random_track()) {
563 /* On error, try again in 10s. */
567 /* Now there must be at least one track in the queue. */
570 /* If random play is disabled but the track is a random one then don't play
571 * it. play() will be called again when random play is re-enabled. */
572 if(!random_enabled && q->state == playing_random)
574 D(("taken %p (%s) from queue", (void *)q, q->track));
575 /* Try to start playing. */
576 switch(start(ev, q, 0/*!prepare_only*/)) {
578 if(q == qhead.next) {
579 queue_remove(q, 0); /* Abandon this track. */
583 if(qhead.next == &qhead)
584 /* Queue is empty, wait a bit before trying something else (so we don't
585 * sit there looping madly in the presence of persistent problem). Note
586 * that we might not reliably get a random track lookahead in this case,
587 * but if we get here then really there are bigger problems. */
590 /* More in queue, try again now. */
594 /* Try same track again in a bit. */
598 if(q == qhead.next) {
603 time(&playing->played);
604 playing->state = playing_started;
605 notify_play(playing->track, playing->submitter);
606 eventlog("playing", playing->track,
607 playing->submitter ? playing->submitter : (const char *)0,
609 /* Maybe add a random track. */
611 /* If there is another track in the queue prepare it now. This could
612 * potentially be a just-added random track. */
613 if(qhead.next != &qhead)
614 prepare(ev, qhead.next);
619 int playing_is_enabled(void) {
620 const char *s = trackdb_get_global("playing");
622 return !s || !strcmp(s, "yes");
625 void enable_playing(const char *who, ev_source *ev) {
626 trackdb_set_global("playing", "yes", who);
627 /* Add a random track if necessary. */
632 void disable_playing(const char *who) {
633 trackdb_set_global("playing", "no", who);
636 int random_is_enabled(void) {
637 const char *s = trackdb_get_global("random-play");
639 return !s || !strcmp(s, "yes");
642 void enable_random(const char *who, ev_source *ev) {
643 trackdb_set_global("random-play", "yes", who);
648 void disable_random(const char *who) {
649 trackdb_set_global("random-play", "no", who);
652 void scratch(const char *who, const char *id) {
653 struct queue_entry *q;
654 struct speaker_message sm;
657 D(("scratch playing=%p state=%d id=%s playing->id=%s",
659 playing ? playing->state : 0,
661 playing ? playing->id : "(none)"));
663 && (playing->state == playing_started
664 || playing->state == playing_paused)
666 || !strcmp(id, playing->id))) {
667 playing->state = playing_scratched;
668 playing->scratched = who ? xstrdup(who) : 0;
669 if((pid = find_player_pid(playing->id)) > 0) {
670 D(("kill -%d %lu", config->signal, (unsigned long)pid));
671 kill(-pid, config->signal);
672 forget_player_pid(playing->id);
674 error(0, "could not find PID for %s", playing->id);
675 if((playing->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
676 memset(&sm, 0, sizeof sm);
678 strcpy(sm.id, playing->id);
679 speaker_send(speaker_fd, &sm);
680 D(("sending SM_CANCEL for %s", playing->id));
682 /* put a scratch track onto the front of the queue (but don't
683 * bother if playing is disabled) */
684 if(playing_is_enabled() && config->scratch.n) {
685 int r = rand() * (double)config->scratch.n / (RAND_MAX + 1.0);
686 q = queue_add(config->scratch.s[r], who, WHERE_START);
687 q->state = playing_isscratch;
689 notify_scratch(playing->track, playing->submitter, who,
690 time(0) - playing->played);
694 void quitting(ev_source *ev) {
695 struct queue_entry *q;
698 /* Don't start anything new */
700 /* Shut down the current player */
702 if((pid = find_player_pid(playing->id)) > 0) {
703 kill(-pid, config->signal);
704 forget_player_pid(playing->id);
706 error(0, "could not find PID for %s", playing->id);
707 playing->state = playing_quitting;
710 /* Zap any other players */
711 for(q = qhead.next; q != &qhead; q = q->next)
712 if((pid = find_player_pid(q->id)) > 0) {
713 D(("kill -%d %lu", config->signal, (unsigned long)pid));
714 kill(-pid, config->signal);
715 forget_player_pid(q->id);
717 error(0, "could not find PID for %s", q->id);
718 /* Don't need the speaker any more */
719 ev_fd_cancel(ev, ev_read, speaker_fd);
723 int pause_playing(const char *who) {
724 struct speaker_message sm;
727 /* Can't pause if already paused or if nothing playing. */
728 if(!playing || paused) return 0;
729 switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
730 case DISORDER_PLAYER_STANDALONE:
731 if(!(playing->type & DISORDER_PLAYER_PAUSES)) {
733 error(0, "cannot pause because player is not powerful enough");
736 if(play_pause(playing->pl, &played, playing->data)) {
737 error(0, "player indicates it cannot pause");
740 time(&playing->lastpaused);
741 playing->uptopause = played;
742 playing->lastresumed = 0;
744 case DISORDER_PLAYER_RAW:
745 memset(&sm, 0, sizeof sm);
747 speaker_send(speaker_fd, &sm);
750 if(who) info("paused by %s", who);
751 notify_pause(playing->track, who);
753 if(playing->state == playing_started)
754 playing->state = playing_paused;
755 eventlog("state", "pause", (char *)0);
759 void resume_playing(const char *who) {
760 struct speaker_message sm;
765 switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
766 case DISORDER_PLAYER_STANDALONE:
767 if(!playing->type & DISORDER_PLAYER_PAUSES) {
769 /* Shouldn't happen */
772 play_resume(playing->pl, playing->data);
773 time(&playing->lastresumed);
775 case DISORDER_PLAYER_RAW:
776 memset(&sm, 0, sizeof sm);
778 speaker_send(speaker_fd, &sm);
781 if(who) info("resumed by %s", who);
782 notify_resume(playing->track, who);
783 if(playing->state == playing_paused)
784 playing->state = playing_started;
785 eventlog("state", "resume", (char *)0);