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 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU 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, see <http://www.gnu.org/licenses/>.
18 /** @file server/play.c
19 * @brief Playing tracks
22 #include "disorder-server.h"
25 #define SPEAKER "disorder-speaker"
27 struct queue_entry *playing;
30 static void finished(ev_source *ev);
32 static int speaker_fd = -1;
33 static hash *player_pids;
34 static int shutting_down;
36 static void store_player_pid(const char *id, pid_t pid) {
37 if(!player_pids) player_pids = hash_new(sizeof (pid_t));
38 hash_add(player_pids, id, &pid, HASH_INSERT_OR_REPLACE);
41 static pid_t find_player_pid(const char *id) {
44 if(player_pids && (pidp = hash_find(player_pids, id))) return *pidp;
48 static void forget_player_pid(const char *id) {
49 if(player_pids) hash_remove(player_pids, id);
52 /* called when speaker process terminates */
53 static int speaker_terminated(ev_source attribute((unused)) *ev,
54 pid_t attribute((unused)) pid,
55 int attribute((unused)) status,
56 const struct rusage attribute((unused)) *rusage,
57 void attribute((unused)) *u) {
58 fatal(0, "speaker subprocess %s",
62 /* called when speaker process has something to say */
63 static int speaker_readable(ev_source *ev, int fd,
64 void attribute((unused)) *u) {
65 struct speaker_message sm;
66 int ret = speaker_recv(fd, &sm);
68 if(ret < 0) return 0; /* EAGAIN */
70 ev_fd_cancel(ev, ev_read, fd);
75 /* track ID is paused, DATA seconds played */
76 D(("SM_PAUSED %s %ld", sm.id, sm.data));
77 playing->sofar = sm.data;
79 case SM_FINISHED: /* scratched the playing track */
80 case SM_STILLBORN: /* scratched too early */
81 case SM_UNKNOWN: /* scratched WAY too early */
82 if(playing && !strcmp(sm.id, playing->id))
86 /* track ID is playing, DATA seconds played */
87 D(("SM_PLAYING %s %ld", sm.id, sm.data));
88 playing->sofar = sm.data;
91 error(0, "unknown message type %d", sm.type);
96 void speaker_setup(ev_source *ev) {
99 struct speaker_message sm;
101 if(socketpair(PF_UNIX, SOCK_DGRAM, 0, sp) < 0)
102 fatal(errno, "error calling socketpair");
103 if(!(pid = xfork())) {
105 ev_signal_atfork(ev);
110 signal(SIGPIPE, SIG_DFL);
112 execlp("valgrind", "valgrind", SPEAKER, "--config", configfile,
113 debugging ? "--debug" : "--no-debug",
114 log_default == &log_syslog ? "--syslog" : "--no-syslog",
117 execlp(SPEAKER, SPEAKER, "--config", configfile,
118 debugging ? "--debug" : "--no-debug",
119 log_default == &log_syslog ? "--syslog" : "--no-syslog",
122 fatal(errno, "error invoking %s", SPEAKER);
124 ev_child(ev, pid, 0, speaker_terminated, 0);
128 /* Wait for the speaker to be ready */
129 speaker_recv(speaker_fd, &sm);
130 nonblock(speaker_fd);
131 ev_fd(ev, ev_read, speaker_fd, speaker_readable, 0, "speaker read");
134 void speaker_reload(void) {
135 struct speaker_message sm;
137 memset(&sm, 0, sizeof sm);
139 speaker_send(speaker_fd, &sm);
142 /* Called when the currently playing track finishes playing. This
143 * might be because the player finished or because the speaker process
145 static void finished(ev_source *ev) {
146 D(("finished playing=%p", (void *)playing));
149 if(playing->state != playing_scratched)
150 notify_not_scratched(playing->track, playing->submitter);
151 switch(playing->state) {
153 eventlog("completed", playing->track, (char *)0);
155 case playing_scratched:
156 eventlog("scratched", playing->track, playing->scratched, (char *)0);
159 eventlog("failed", playing->track, wstat(playing->wstat), (char *)0);
164 queue_played(playing);
166 forget_player_pid(playing->id);
168 /* Try to play something else */
169 /* TODO re-support config->gap? */
174 /* Called when a player terminates. */
175 static int player_finished(ev_source *ev,
178 const struct rusage attribute((unused)) *rusage,
180 struct queue_entry *q = u;
182 D(("player_finished pid=%lu status=%#x",
183 (unsigned long)pid, (unsigned)status));
184 /* Record that this PID is dead. If we killed the track we might know this
185 * already, but also it might have exited or crashed. Either way we don't
186 * want to end up signalling it. */
187 if(pid == find_player_pid(q->id))
188 forget_player_pid(q->id);
190 case playing_unplayed:
192 /* If this was a pre-prepared track then either it failed or we
193 * deliberately stopped it because it was removed from the queue or moved
194 * down it. So leave it state alone for future use. */
197 /* We actually started playing this track. */
199 if(q->state != playing_scratched)
200 q->state = playing_failed;
202 q->state = playing_ok;
205 /* Regardless we always report and record the status and do cleanup for
208 error(0, "player for %s %s", q->track, wstat(status));
209 if(q->type & DISORDER_PLAYER_PREFORK)
210 play_cleanup(q->pl, q->data);
212 /* If this actually was the current track, and does not use the speaker
213 * process, then it must have finished. For raw-output players we will get a
214 * separate notification from the speaker process. */
216 && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
221 /* Find the player for Q */
222 static int find_player(const struct queue_entry *q) {
225 for(n = 0; n < config->player.n; ++n)
226 if(fnmatch(config->player.s[n].s[0], q->track, 0) == 0)
228 if(n >= config->player.n)
234 /* Return values from start() */
235 #define START_OK 0 /**< @brief Succeeded. */
236 #define START_HARDFAIL 1 /**< @brief Track is broken. */
237 #define START_SOFTFAIL 2 /**< @brief Track OK, system (temporarily?) broken */
239 /** @brief Play or prepare @p q
240 * @param ev Event loop
241 * @param q Track to play/prepare
242 * @param prepare_only If true, only prepares track
243 * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
245 static int start(ev_source *ev,
246 struct queue_entry *q,
251 struct speaker_message sm;
254 ao_sample_format format;
258 const char *waitdevice = 0;
259 const char *const *optv;
261 struct sockaddr_un addr;
264 memset(&sm, 0, sizeof sm);
265 D(("start %s %d", q->id, prepare_only));
267 /* The track is alraedy prepared */
269 /* We want to run it, since it's prepared the answer is to tell the
270 * speaker to set it off */
271 strcpy(sm.id, q->id);
273 speaker_send(speaker_fd, &sm);
274 D(("sent SM_PLAY for %s", sm.id));
278 /* Find the player plugin. */
279 if((n = find_player(q)) < 0) return START_HARDFAIL;
280 if(!(q->pl = open_plugin(config->player.s[n].s[1], 0)))
281 return START_HARDFAIL;
282 q->type = play_get_type(q->pl);
283 /* Can't prepare non-raw tracks. */
285 && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
287 /* Call the prefork function. */
288 p = trackdb_rawpath(q->track);
289 if(q->type & DISORDER_PLAYER_PREFORK)
290 if(!(q->data = play_prefork(q->pl, p))) {
291 error(0, "prefork function for %s failed", q->track);
292 return START_HARDFAIL;
294 /* Use the second arg as the tag if available (it's probably a command name),
295 * otherwise the module name. */
297 lfd = logfd(ev, (config->player.s[n].s[2]
298 ? config->player.s[n].s[2] : config->player.s[n].s[1]));
301 optc = config->player.s[n].n - 2;
302 optv = (void *)&config->player.s[n].s[2];
303 while(optc > 0 && optv[0][0] == '-') {
304 if(!strcmp(optv[0], "--")) {
309 if(!strcmp(optv[0], "--wait-for-device")
310 || !strncmp(optv[0], "--wait-for-device=", 18)) {
311 if((waitdevice = strchr(optv[0], '='))) {
314 waitdevice = ""; /* use default */
318 error(0, "unknown option %s", optv[0]);
319 return START_HARDFAIL;
322 switch(pid = fork()) {
325 progname = "disorderd-fork";
326 ev_signal_atfork(ev);
327 signal(SIGPIPE, SIG_DFL);
331 xclose(lfd); /* tidy up */
334 if((q->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
335 /* "Raw" format players always have their output send down a pipe
336 * to the disorder-normalize process. This will connect to the
337 * speaker process to actually play the audio data.
339 /* np will be the pipe to disorder-normalize */
340 if(socketpair(PF_UNIX, SOCK_STREAM, 0, np) < 0)
341 fatal(errno, "error calling socketpair");
342 /* Beware of the Leopard! On OS X 10.5.x, the order of the shutdown
343 * calls here DOES MATTER. If you do the SHUT_WR first then the SHUT_RD
344 * fails with "Socket is not connected". I think this is a bug but
345 * provided implementors either don't care about the order or all agree
346 * about the order, choosing the reliable order is an adequate
348 xshutdown(np[1], SHUT_RD); /* decoder writes to np[1] */
349 xshutdown(np[0], SHUT_WR); /* normalize reads from np[0] */
352 /* Start disorder-normalize */
353 if(!(npid = xfork())) {
355 /* Connect to the speaker process */
356 memset(&addr, 0, sizeof addr);
357 addr.sun_family = AF_UNIX;
358 snprintf(addr.sun_path, sizeof addr.sun_path,
359 "%s/speaker/socket", config->home);
360 sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
361 if(connect(sfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
362 fatal(errno, "connecting to %s", addr.sun_path);
364 if(write(sfd, &l, sizeof l) < 0
365 || write(sfd, q->id, l) < 0)
366 fatal(errno, "writing to %s", addr.sun_path);
375 /* Ask the speaker to actually start playing the track; we do it here
376 * so it's definitely after ack. */
378 strcpy(sm.id, q->id);
380 speaker_send(speaker_fd, &sm);
381 D(("sent SM_PLAY for %s", sm.id));
383 /* TODO stderr shouldn't be redirected for disorder-normalize
384 * (but it should be for play_track() */
385 execlp("disorder-normalize", "disorder-normalize",
386 log_default == &log_syslog ? "--syslog" : "--no-syslog",
387 "--config", configfile,
389 fatal(errno, "executing disorder-normalize");
390 /* end of the innermost fork */
393 /* end of the middle fork */
395 /* Wait for the middle fork to finish */
396 while(waitpid(npid, &n, 0) < 0 && errno == EINTR)
398 /* Pass the file descriptor to the driver in an environment
400 snprintf(buffer, sizeof buffer, "DISORDER_RAW_FD=%d", np[1]);
401 if(putenv(buffer) < 0)
402 fatal(errno, "error calling putenv");
403 /* Close all the FDs we don't need */
409 n = ao_driver_id(waitdevice);
411 fatal(0, "invalid libao driver: %s", optv[0]);
413 n = ao_default_driver_id();
414 /* Make up a format. */
415 memset(&format, 0, sizeof format);
419 format.byte_format = AO_FMT_NATIVE;
422 ts.tv_nsec = 100000000; /* 0.1s */
423 while((device = ao_open_live(n, &format, 0)) == 0 && retries-- > 0)
434 error(errno, "error calling fork");
435 if(q->type & DISORDER_PLAYER_PREFORK)
436 play_cleanup(q->pl, q->data); /* else would leak */
439 return START_SOFTFAIL;
441 store_player_pid(q->id, pid);
446 ev_child(ev, pid, 0, player_finished, q);
447 D(("player subprocess ID %lu", (unsigned long)pid));
451 int prepare(ev_source *ev,
452 struct queue_entry *q) {
455 /* Find the player plugin */
456 if(find_player_pid(q->id) > 0) return 0; /* Already going. */
457 if((n = find_player(q)) < 0) return -1; /* No player */
458 q->pl = open_plugin(config->player.s[n].s[1], 0); /* No player */
459 q->type = play_get_type(q->pl);
460 if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
461 return 0; /* Not a raw player */
462 return start(ev, q, 1/*prepare_only*/); /* Prepare it */
465 void abandon(ev_source attribute((unused)) *ev,
466 struct queue_entry *q) {
467 struct speaker_message sm;
468 pid_t pid = find_player_pid(q->id);
470 if(pid < 0) return; /* Not prepared. */
471 if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
472 return; /* Not a raw player. */
473 /* Terminate the player. */
474 kill(-pid, config->signal);
475 forget_player_pid(q->id);
476 /* Cancel the track. */
477 memset(&sm, 0, sizeof sm);
479 strcpy(sm.id, q->id);
480 speaker_send(speaker_fd, &sm);
483 /** @brief Called with a new random track
484 * @param ev Event loop
485 * @param track Track name
487 static void chosen_random_track(ev_source *ev,
489 struct queue_entry *q;
493 /* Add the track to the queue */
494 q = queue_add(track, 0, WHERE_END, origin_random);
495 D(("picked %p (%s) at random", (void *)q, q->track));
497 /* Maybe a track can now be played */
501 /** @brief Maybe add a randomly chosen track
502 * @param ev Event loop
504 void add_random_track(ev_source *ev) {
505 struct queue_entry *q;
508 /* If random play is not enabled then do nothing. */
509 if(shutting_down || !random_is_enabled())
511 /* Count how big the queue is */
512 for(q = qhead.next; q != &qhead; q = q->next)
514 /* If it's smaller than the desired size then add a track */
515 if(qlen < config->queue_pad)
516 trackdb_request_random(ev, chosen_random_track);
519 /* try to play a track */
520 void play(ev_source *ev) {
521 struct queue_entry *q;
522 int random_enabled = random_is_enabled();
524 D(("play playing=%p", (void *)playing));
525 if(shutting_down || playing || !playing_is_enabled()) return;
526 /* See if there's anything to play */
527 if(qhead.next == &qhead) {
528 /* Queue is empty. We could just wait around since there are periodic
529 * attempts to add a random track anyway. However they are rarer than
530 * attempts to force a track so we initiate one now. */
531 add_random_track(ev);
534 /* There must be at least one track in the queue. */
536 /* If random play is disabled but the track is a non-adopted random one
537 * then don't play it. play() will be called again when random play is
539 if(!random_enabled && q->origin == origin_random)
541 D(("taken %p (%s) from queue", (void *)q, q->track));
542 /* Try to start playing. */
543 switch(start(ev, q, 0/*!prepare_only*/)) {
545 if(q == qhead.next) {
546 queue_remove(q, 0); /* Abandon this track. */
550 /* Oh well, try the next one */
554 /* We'll try the same track again shortly. */
557 if(q == qhead.next) {
562 time(&playing->played);
563 playing->state = playing_started;
564 notify_play(playing->track, playing->submitter);
565 eventlog("playing", playing->track,
566 playing->submitter ? playing->submitter : (const char *)0,
568 /* Maybe add a random track. */
569 add_random_track(ev);
570 /* If there is another track in the queue prepare it now. This could
571 * potentially be a just-added random track. */
572 if(qhead.next != &qhead)
573 prepare(ev, qhead.next);
578 int playing_is_enabled(void) {
579 const char *s = trackdb_get_global("playing");
581 return !s || !strcmp(s, "yes");
584 void enable_playing(const char *who, ev_source *ev) {
585 trackdb_set_global("playing", "yes", who);
586 /* Add a random track if necessary. */
587 add_random_track(ev);
591 void disable_playing(const char *who) {
592 trackdb_set_global("playing", "no", who);
595 int random_is_enabled(void) {
596 const char *s = trackdb_get_global("random-play");
598 return !s || !strcmp(s, "yes");
601 void enable_random(const char *who, ev_source *ev) {
602 trackdb_set_global("random-play", "yes", who);
603 add_random_track(ev);
607 void disable_random(const char *who) {
608 trackdb_set_global("random-play", "no", who);
611 void scratch(const char *who, const char *id) {
612 struct queue_entry *q;
613 struct speaker_message sm;
616 D(("scratch playing=%p state=%d id=%s playing->id=%s",
618 playing ? playing->state : 0,
620 playing ? playing->id : "(none)"));
622 && (playing->state == playing_started
623 || playing->state == playing_paused)
625 || !strcmp(id, playing->id))) {
626 playing->state = playing_scratched;
627 playing->scratched = who ? xstrdup(who) : 0;
628 if((pid = find_player_pid(playing->id)) > 0) {
629 D(("kill -%d %lu", config->signal, (unsigned long)pid));
630 kill(-pid, config->signal);
631 forget_player_pid(playing->id);
633 error(0, "could not find PID for %s", playing->id);
634 if((playing->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
635 memset(&sm, 0, sizeof sm);
637 strcpy(sm.id, playing->id);
638 speaker_send(speaker_fd, &sm);
639 D(("sending SM_CANCEL for %s", playing->id));
641 /* put a scratch track onto the front of the queue (but don't
642 * bother if playing is disabled) */
643 if(playing_is_enabled() && config->scratch.n) {
644 int r = rand() * (double)config->scratch.n / (RAND_MAX + 1.0);
645 q = queue_add(config->scratch.s[r], who, WHERE_START, origin_scratch);
646 q->state = playing_isscratch;
648 notify_scratch(playing->track, playing->submitter, who,
649 time(0) - playing->played);
653 void quitting(ev_source *ev) {
654 struct queue_entry *q;
657 /* Don't start anything new */
659 /* Shut down the current player */
661 if((pid = find_player_pid(playing->id)) > 0) {
662 kill(-pid, config->signal);
663 forget_player_pid(playing->id);
665 error(0, "could not find PID for %s", playing->id);
666 playing->state = playing_quitting;
669 /* Zap any other players */
670 for(q = qhead.next; q != &qhead; q = q->next)
671 if((pid = find_player_pid(q->id)) > 0) {
672 D(("kill -%d %lu", config->signal, (unsigned long)pid));
673 kill(-pid, config->signal);
674 forget_player_pid(q->id);
676 error(0, "could not find PID for %s", q->id);
677 /* Don't need the speaker any more */
678 ev_fd_cancel(ev, ev_read, speaker_fd);
682 int pause_playing(const char *who) {
683 struct speaker_message sm;
686 /* Can't pause if already paused or if nothing playing. */
687 if(!playing || paused) return 0;
688 switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
689 case DISORDER_PLAYER_STANDALONE:
690 if(!(playing->type & DISORDER_PLAYER_PAUSES)) {
692 error(0, "cannot pause because player is not powerful enough");
695 if(play_pause(playing->pl, &played, playing->data)) {
696 error(0, "player indicates it cannot pause");
699 time(&playing->lastpaused);
700 playing->uptopause = played;
701 playing->lastresumed = 0;
703 case DISORDER_PLAYER_RAW:
704 memset(&sm, 0, sizeof sm);
706 speaker_send(speaker_fd, &sm);
709 if(who) info("paused by %s", who);
710 notify_pause(playing->track, who);
712 if(playing->state == playing_started)
713 playing->state = playing_paused;
714 eventlog("state", "pause", (char *)0);
718 void resume_playing(const char *who) {
719 struct speaker_message sm;
724 switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
725 case DISORDER_PLAYER_STANDALONE:
726 if(!playing->type & DISORDER_PLAYER_PAUSES) {
728 /* Shouldn't happen */
731 play_resume(playing->pl, playing->data);
732 time(&playing->lastresumed);
734 case DISORDER_PLAYER_RAW:
735 memset(&sm, 0, sizeof sm);
737 speaker_send(speaker_fd, &sm);
740 if(who) info("resumed by %s", who);
741 notify_resume(playing->track, who);
742 if(playing->state == playing_paused)
743 playing->state = playing_started;
744 eventlog("state", "resume", (char *)0);