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
);
368 if (read(sfd
, &l
, 1) < 0)
369 fatal(errno
, "reading ack from %s", addr
.sun_path
);
376 /* Ask the speaker to actually start playing the track; we do it here
377 * so it's definitely after ack. */
379 strcpy(sm
.id
, q
->id
);
381 speaker_send(speaker_fd
, &sm
);
382 D(("sent SM_PLAY for %s", sm
.id
));
384 /* TODO stderr shouldn't be redirected for disorder-normalize
385 * (but it should be for play_track() */
386 execlp("disorder-normalize", "disorder-normalize",
387 log_default
== &log_syslog ?
"--syslog" : "--no-syslog",
388 "--config", configfile
,
390 fatal(errno
, "executing disorder-normalize");
391 /* end of the innermost fork */
394 /* end of the middle fork */
396 /* Wait for the middle fork to finish */
397 while(waitpid(npid
, &n
, 0) < 0 && errno
== EINTR
)
399 /* Pass the file descriptor to the driver in an environment
401 snprintf(buffer
, sizeof buffer
, "DISORDER_RAW_FD=%d", np
[1]);
402 if(putenv(buffer
) < 0)
403 fatal(errno
, "error calling putenv");
404 /* Close all the FDs we don't need */
410 n
= ao_driver_id(waitdevice
);
412 fatal(0, "invalid libao driver: %s", optv
[0]);
414 n
= ao_default_driver_id();
415 /* Make up a format. */
416 memset(&format
, 0, sizeof format
);
420 format
.byte_format
= AO_FMT_NATIVE
;
423 ts
.tv_nsec
= 100000000; /* 0.1s */
424 while((device
= ao_open_live(n
, &format
, 0)) == 0 && retries
-- > 0)
435 error(errno
, "error calling fork");
436 if(q
->type
& DISORDER_PLAYER_PREFORK
)
437 play_cleanup(q
->pl
, q
->data
); /* else would leak */
440 return START_SOFTFAIL
;
442 store_player_pid(q
->id
, pid
);
447 ev_child(ev
, pid
, 0, player_finished
, q
);
448 D(("player subprocess ID %lu", (unsigned long)pid
));
452 int prepare(ev_source
*ev
,
453 struct queue_entry
*q
) {
456 /* Find the player plugin */
457 if(find_player_pid(q
->id
) > 0) return 0; /* Already going. */
458 if((n
= find_player(q
)) < 0) return -1; /* No player */
459 q
->pl
= open_plugin(config
->player
.s
[n
].s
[1], 0); /* No player */
460 q
->type
= play_get_type(q
->pl
);
461 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
462 return 0; /* Not a raw player */
463 return start(ev
, q
, 1/*prepare_only*/); /* Prepare it */
466 void abandon(ev_source
attribute((unused
)) *ev
,
467 struct queue_entry
*q
) {
468 struct speaker_message sm
;
469 pid_t pid
= find_player_pid(q
->id
);
471 if(pid
< 0) return; /* Not prepared. */
472 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
473 return; /* Not a raw player. */
474 /* Terminate the player. */
475 kill(-pid
, config
->signal
);
476 forget_player_pid(q
->id
);
477 /* Cancel the track. */
478 memset(&sm
, 0, sizeof sm
);
480 strcpy(sm
.id
, q
->id
);
481 speaker_send(speaker_fd
, &sm
);
484 /** @brief Called with a new random track
485 * @param ev Event loop
486 * @param track Track name
488 static void chosen_random_track(ev_source
*ev
,
490 struct queue_entry
*q
;
494 /* Add the track to the queue */
495 q
= queue_add(track
, 0, WHERE_END
, origin_random
);
496 D(("picked %p (%s) at random", (void *)q
, q
->track
));
498 /* Maybe a track can now be played */
502 /** @brief Maybe add a randomly chosen track
503 * @param ev Event loop
505 void add_random_track(ev_source
*ev
) {
506 struct queue_entry
*q
;
509 /* If random play is not enabled then do nothing. */
510 if(shutting_down
|| !random_is_enabled())
512 /* Count how big the queue is */
513 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
515 /* If it's smaller than the desired size then add a track */
516 if(qlen
< config
->queue_pad
)
517 trackdb_request_random(ev
, chosen_random_track
);
520 /* try to play a track */
521 void play(ev_source
*ev
) {
522 struct queue_entry
*q
;
523 int random_enabled
= random_is_enabled();
525 D(("play playing=%p", (void *)playing
));
526 if(shutting_down
|| playing
|| !playing_is_enabled()) return;
527 /* See if there's anything to play */
528 if(qhead
.next
== &qhead
) {
529 /* Queue is empty. We could just wait around since there are periodic
530 * attempts to add a random track anyway. However they are rarer than
531 * attempts to force a track so we initiate one now. */
532 add_random_track(ev
);
535 /* There must be at least one track in the queue. */
537 /* If random play is disabled but the track is a non-adopted random one
538 * then don't play it. play() will be called again when random play is
540 if(!random_enabled
&& q
->origin
== origin_random
)
542 D(("taken %p (%s) from queue", (void *)q
, q
->track
));
543 /* Try to start playing. */
544 switch(start(ev
, q
, 0/*!prepare_only*/)) {
546 if(q
== qhead
.next
) {
547 queue_remove(q
, 0); /* Abandon this track. */
551 /* Oh well, try the next one */
555 /* We'll try the same track again shortly. */
558 if(q
== qhead
.next
) {
563 time(&playing
->played
);
564 playing
->state
= playing_started
;
565 notify_play(playing
->track
, playing
->submitter
);
566 eventlog("playing", playing
->track
,
567 playing
->submitter ? playing
->submitter
: (const char *)0,
569 /* Maybe add a random track. */
570 add_random_track(ev
);
571 /* If there is another track in the queue prepare it now. This could
572 * potentially be a just-added random track. */
573 if(qhead
.next
!= &qhead
)
574 prepare(ev
, qhead
.next
);
579 int playing_is_enabled(void) {
580 const char *s
= trackdb_get_global("playing");
582 return !s
|| !strcmp(s
, "yes");
585 void enable_playing(const char *who
, ev_source
*ev
) {
586 trackdb_set_global("playing", "yes", who
);
587 /* Add a random track if necessary. */
588 add_random_track(ev
);
592 void disable_playing(const char *who
) {
593 trackdb_set_global("playing", "no", who
);
596 int random_is_enabled(void) {
597 const char *s
= trackdb_get_global("random-play");
599 return !s
|| !strcmp(s
, "yes");
602 void enable_random(const char *who
, ev_source
*ev
) {
603 trackdb_set_global("random-play", "yes", who
);
604 add_random_track(ev
);
608 void disable_random(const char *who
) {
609 trackdb_set_global("random-play", "no", who
);
612 void scratch(const char *who
, const char *id
) {
613 struct queue_entry
*q
;
614 struct speaker_message sm
;
617 D(("scratch playing=%p state=%d id=%s playing->id=%s",
619 playing ? playing
->state
: 0,
621 playing ? playing
->id
: "(none)"));
623 && (playing
->state
== playing_started
624 || playing
->state
== playing_paused
)
626 || !strcmp(id
, playing
->id
))) {
627 playing
->state
= playing_scratched
;
628 playing
->scratched
= who ?
xstrdup(who
) : 0;
629 if((pid
= find_player_pid(playing
->id
)) > 0) {
630 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
631 kill(-pid
, config
->signal
);
632 forget_player_pid(playing
->id
);
634 error(0, "could not find PID for %s", playing
->id
);
635 if((playing
->type
& DISORDER_PLAYER_TYPEMASK
) == DISORDER_PLAYER_RAW
) {
636 memset(&sm
, 0, sizeof sm
);
638 strcpy(sm
.id
, playing
->id
);
639 speaker_send(speaker_fd
, &sm
);
640 D(("sending SM_CANCEL for %s", playing
->id
));
642 /* put a scratch track onto the front of the queue (but don't
643 * bother if playing is disabled) */
644 if(playing_is_enabled() && config
->scratch
.n
) {
645 int r
= rand() * (double)config
->scratch
.n
/ (RAND_MAX
+ 1.0);
646 q
= queue_add(config
->scratch
.s
[r
], who
, WHERE_START
, origin_scratch
);
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);