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
21 #include "disorder-server.h"
24 #define SPEAKER "disorder-speaker"
26 struct queue_entry
*playing
;
29 static void finished(ev_source
*ev
);
31 static int speaker_fd
= -1;
32 static hash
*player_pids
;
33 static int shutting_down
;
35 static void store_player_pid(const char *id
, pid_t pid
) {
36 if(!player_pids
) player_pids
= hash_new(sizeof (pid_t
));
37 hash_add(player_pids
, id
, &pid
, HASH_INSERT_OR_REPLACE
);
40 static pid_t
find_player_pid(const char *id
) {
43 if(player_pids
&& (pidp
= hash_find(player_pids
, id
))) return *pidp
;
47 static void forget_player_pid(const char *id
) {
48 if(player_pids
) hash_remove(player_pids
, id
);
51 /* called when speaker process terminates */
52 static int speaker_terminated(ev_source
attribute((unused
)) *ev
,
53 pid_t
attribute((unused
)) pid
,
54 int attribute((unused
)) status
,
55 const struct rusage
attribute((unused
)) *rusage
,
56 void attribute((unused
)) *u
) {
57 fatal(0, "speaker subprocess %s",
61 /* called when speaker process has something to say */
62 static int speaker_readable(ev_source
*ev
, int fd
,
63 void attribute((unused
)) *u
) {
64 struct speaker_message sm
;
65 int ret
= speaker_recv(fd
, &sm
);
67 if(ret
< 0) return 0; /* EAGAIN */
69 ev_fd_cancel(ev
, ev_read
, fd
);
74 /* track ID is paused, DATA seconds played */
75 D(("SM_PAUSED %s %ld", sm
.id
, sm
.data
));
76 playing
->sofar
= sm
.data
;
78 case SM_FINISHED
: /* scratched the playing track */
79 case SM_STILLBORN
: /* scratched too early */
80 case SM_UNKNOWN
: /* scratched WAY too early */
81 if(playing
&& !strcmp(sm
.id
, playing
->id
))
85 /* track ID is playing, DATA seconds played */
86 D(("SM_PLAYING %s %ld", sm
.id
, sm
.data
));
87 playing
->sofar
= sm
.data
;
90 error(0, "unknown message type %d", sm
.type
);
95 void speaker_setup(ev_source
*ev
) {
98 struct speaker_message sm
;
100 if(socketpair(PF_UNIX
, SOCK_DGRAM
, 0, sp
) < 0)
101 fatal(errno
, "error calling socketpair");
102 if(!(pid
= xfork())) {
104 ev_signal_atfork(ev
);
109 signal(SIGPIPE
, SIG_DFL
);
111 execlp("valgrind", "valgrind", SPEAKER
, "--config", configfile
,
112 debugging ?
"--debug" : "--no-debug",
113 log_default
== &log_syslog ?
"--syslog" : "--no-syslog",
116 execlp(SPEAKER
, SPEAKER
, "--config", configfile
,
117 debugging ?
"--debug" : "--no-debug",
118 log_default
== &log_syslog ?
"--syslog" : "--no-syslog",
121 fatal(errno
, "error invoking %s", SPEAKER
);
123 ev_child(ev
, pid
, 0, speaker_terminated
, 0);
127 /* Wait for the speaker to be ready */
128 speaker_recv(speaker_fd
, &sm
);
129 nonblock(speaker_fd
);
130 ev_fd(ev
, ev_read
, speaker_fd
, speaker_readable
, 0, "speaker read");
133 void speaker_reload(void) {
134 struct speaker_message sm
;
136 memset(&sm
, 0, sizeof sm
);
138 speaker_send(speaker_fd
, &sm
);
141 /* Called when the currently playing track finishes playing. This
142 * might be because the player finished or because the speaker process
144 static void finished(ev_source
*ev
) {
145 D(("finished playing=%p", (void *)playing
));
148 if(playing
->state
!= playing_scratched
)
149 notify_not_scratched(playing
->track
, playing
->submitter
);
150 switch(playing
->state
) {
152 eventlog("completed", playing
->track
, (char *)0);
154 case playing_scratched
:
155 eventlog("scratched", playing
->track
, playing
->scratched
, (char *)0);
158 eventlog("failed", playing
->track
, wstat(playing
->wstat
), (char *)0);
163 queue_played(playing
);
165 forget_player_pid(playing
->id
);
167 /* Try to play something else */
168 /* TODO re-support config->gap? */
173 /* Called when a player terminates. */
174 static int player_finished(ev_source
*ev
,
177 const struct rusage
attribute((unused
)) *rusage
,
179 struct queue_entry
*q
= u
;
181 D(("player_finished pid=%lu status=%#x",
182 (unsigned long)pid
, (unsigned)status
));
183 /* Record that this PID is dead. If we killed the track we might know this
184 * already, but also it might have exited or crashed. Either way we don't
185 * want to end up signalling it. */
186 if(pid
== find_player_pid(q
->id
))
187 forget_player_pid(q
->id
);
189 case playing_unplayed
:
191 /* If this was a pre-prepared track then either it failed or we
192 * deliberately stopped it because it was removed from the queue or moved
193 * down it. So leave it state alone for future use. */
196 /* We actually started playing this track. */
198 if(q
->state
!= playing_scratched
)
199 q
->state
= playing_failed
;
201 q
->state
= playing_ok
;
204 /* Regardless we always report and record the status and do cleanup for
207 error(0, "player for %s %s", q
->track
, wstat(status
));
208 if(q
->type
& DISORDER_PLAYER_PREFORK
)
209 play_cleanup(q
->pl
, q
->data
);
211 /* If this actually was the current track, and does not use the speaker
212 * process, then it must have finished. For raw-output players we will get a
213 * separate notification from the speaker process. */
215 && (q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
220 /* Find the player for Q */
221 static int find_player(const struct queue_entry
*q
) {
224 for(n
= 0; n
< config
->player
.n
; ++n
)
225 if(fnmatch(config
->player
.s
[n
].s
[0], q
->track
, 0) == 0)
227 if(n
>= config
->player
.n
)
233 /* Return values from start() */
234 #define START_OK 0 /**< @brief Succeeded. */
235 #define START_HARDFAIL 1 /**< @brief Track is broken. */
236 #define START_SOFTFAIL 2 /**< @brief Track OK, system (temporarily?) broken */
238 /** @brief Play or prepare @p q
239 * @param ev Event loop
240 * @param q Track to play/prepare
241 * @param prepare_only If true, only prepares track
242 * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
244 static int start(ev_source
*ev
,
245 struct queue_entry
*q
,
250 struct speaker_message sm
;
253 ao_sample_format format
;
257 const char *waitdevice
= 0;
258 const char *const *optv
;
260 struct sockaddr_un addr
;
263 memset(&sm
, 0, sizeof sm
);
264 D(("start %s %d", q
->id
, prepare_only
));
266 /* The track is alraedy prepared */
268 /* We want to run it, since it's prepared the answer is to tell the
269 * speaker to set it off */
270 strcpy(sm
.id
, q
->id
);
272 speaker_send(speaker_fd
, &sm
);
273 D(("sent SM_PLAY for %s", sm
.id
));
277 /* Find the player plugin. */
278 if((n
= find_player(q
)) < 0) return START_HARDFAIL
;
279 if(!(q
->pl
= open_plugin(config
->player
.s
[n
].s
[1], 0)))
280 return START_HARDFAIL
;
281 q
->type
= play_get_type(q
->pl
);
282 /* Can't prepare non-raw tracks. */
284 && (q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
286 /* Call the prefork function. */
287 p
= trackdb_rawpath(q
->track
);
288 if(q
->type
& DISORDER_PLAYER_PREFORK
)
289 if(!(q
->data
= play_prefork(q
->pl
, p
))) {
290 error(0, "prefork function for %s failed", q
->track
);
291 return START_HARDFAIL
;
293 /* Use the second arg as the tag if available (it's probably a command name),
294 * otherwise the module name. */
296 lfd
= logfd(ev
, (config
->player
.s
[n
].s
[2]
297 ? config
->player
.s
[n
].s
[2] : config
->player
.s
[n
].s
[1]));
300 optc
= config
->player
.s
[n
].n
- 2;
301 optv
= (void *)&config
->player
.s
[n
].s
[2];
302 while(optc
> 0 && optv
[0][0] == '-') {
303 if(!strcmp(optv
[0], "--")) {
308 if(!strcmp(optv
[0], "--wait-for-device")
309 || !strncmp(optv
[0], "--wait-for-device=", 18)) {
310 if((waitdevice
= strchr(optv
[0], '='))) {
313 waitdevice
= ""; /* use default */
317 error(0, "unknown option %s", optv
[0]);
318 return START_HARDFAIL
;
321 switch(pid
= fork()) {
324 progname
= "disorderd-fork";
325 ev_signal_atfork(ev
);
326 signal(SIGPIPE
, SIG_DFL
);
330 xclose(lfd
); /* tidy up */
333 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) == DISORDER_PLAYER_RAW
) {
334 /* "Raw" format players always have their output send down a pipe
335 * to the disorder-normalize process. This will connect to the
336 * speaker process to actually play the audio data.
338 /* np will be the pipe to disorder-normalize */
339 if(socketpair(PF_UNIX
, SOCK_STREAM
, 0, np
) < 0)
340 fatal(errno
, "error calling socketpair");
341 /* Beware of the Leopard! On OS X 10.5.x, the order of the shutdown
342 * calls here DOES MATTER. If you do the SHUT_WR first then the SHUT_RD
343 * fails with "Socket is not connected". I think this is a bug but
344 * provided implementors either don't care about the order or all agree
345 * about the order, choosing the reliable order is an adequate
347 xshutdown(np
[1], SHUT_RD
); /* decoder writes to np[1] */
348 xshutdown(np
[0], SHUT_WR
); /* normalize reads from np[0] */
351 /* Start disorder-normalize */
352 if(!(npid
= xfork())) {
354 /* Connect to the speaker process */
355 memset(&addr
, 0, sizeof addr
);
356 addr
.sun_family
= AF_UNIX
;
357 snprintf(addr
.sun_path
, sizeof addr
.sun_path
,
358 "%s/speaker/socket", config
->home
);
359 sfd
= xsocket(PF_UNIX
, SOCK_STREAM
, 0);
360 if(connect(sfd
, (const struct sockaddr
*)&addr
, sizeof addr
) < 0)
361 fatal(errno
, "connecting to %s", addr
.sun_path
);
363 if(write(sfd
, &l
, sizeof l
) < 0
364 || write(sfd
, q
->id
, l
) < 0)
365 fatal(errno
, "writing to %s", addr
.sun_path
);
374 /* Ask the speaker to actually start playing the track; we do it here
375 * so it's definitely after ack. */
377 strcpy(sm
.id
, q
->id
);
379 speaker_send(speaker_fd
, &sm
);
380 D(("sent SM_PLAY for %s", sm
.id
));
382 /* TODO stderr shouldn't be redirected for disorder-normalize
383 * (but it should be for play_track() */
384 execlp("disorder-normalize", "disorder-normalize",
385 log_default
== &log_syslog ?
"--syslog" : "--no-syslog",
386 "--config", configfile
,
388 fatal(errno
, "executing disorder-normalize");
389 /* end of the innermost fork */
392 /* end of the middle fork */
394 /* Wait for the middle fork to finish */
395 while(waitpid(npid
, &n
, 0) < 0 && errno
== EINTR
)
397 /* Pass the file descriptor to the driver in an environment
399 snprintf(buffer
, sizeof buffer
, "DISORDER_RAW_FD=%d", np
[1]);
400 if(putenv(buffer
) < 0)
401 fatal(errno
, "error calling putenv");
402 /* Close all the FDs we don't need */
408 n
= ao_driver_id(waitdevice
);
410 fatal(0, "invalid libao driver: %s", optv
[0]);
412 n
= ao_default_driver_id();
413 /* Make up a format. */
414 memset(&format
, 0, sizeof format
);
418 format
.byte_format
= AO_FMT_NATIVE
;
421 ts
.tv_nsec
= 100000000; /* 0.1s */
422 while((device
= ao_open_live(n
, &format
, 0)) == 0 && retries
-- > 0)
433 error(errno
, "error calling fork");
434 if(q
->type
& DISORDER_PLAYER_PREFORK
)
435 play_cleanup(q
->pl
, q
->data
); /* else would leak */
438 return START_SOFTFAIL
;
440 store_player_pid(q
->id
, pid
);
445 ev_child(ev
, pid
, 0, player_finished
, q
);
446 D(("player subprocess ID %lu", (unsigned long)pid
));
450 int prepare(ev_source
*ev
,
451 struct queue_entry
*q
) {
454 /* Find the player plugin */
455 if(find_player_pid(q
->id
) > 0) return 0; /* Already going. */
456 if((n
= find_player(q
)) < 0) return -1; /* No player */
457 q
->pl
= open_plugin(config
->player
.s
[n
].s
[1], 0); /* No player */
458 q
->type
= play_get_type(q
->pl
);
459 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
460 return 0; /* Not a raw player */
461 return start(ev
, q
, 1/*prepare_only*/); /* Prepare it */
464 void abandon(ev_source
attribute((unused
)) *ev
,
465 struct queue_entry
*q
) {
466 struct speaker_message sm
;
467 pid_t pid
= find_player_pid(q
->id
);
469 if(pid
< 0) return; /* Not prepared. */
470 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
471 return; /* Not a raw player. */
472 /* Terminate the player. */
473 kill(-pid
, config
->signal
);
474 forget_player_pid(q
->id
);
475 /* Cancel the track. */
476 memset(&sm
, 0, sizeof sm
);
478 strcpy(sm
.id
, q
->id
);
479 speaker_send(speaker_fd
, &sm
);
482 /** @brief Called with a new random track
483 * @param track Track name
485 static void chosen_random_track(ev_source
*ev
,
487 struct queue_entry
*q
;
491 /* Add the track to the queue */
492 q
= queue_add(track
, 0, WHERE_END
);
493 q
->state
= playing_random
;
494 D(("picked %p (%s) at random", (void *)q
, q
->track
));
496 /* Maybe a track can now be played */
500 /** @brief Maybe add a randomly chosen track
501 * @param ev Event loop
503 void add_random_track(ev_source
*ev
) {
504 struct queue_entry
*q
;
507 /* If random play is not enabled then do nothing. */
508 if(shutting_down
|| !random_is_enabled())
510 /* Count how big the queue is */
511 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
513 /* If it's smaller than the desired size then add a track */
514 if(qlen
< config
->queue_pad
)
515 trackdb_request_random(ev
, chosen_random_track
);
518 /* try to play a track */
519 void play(ev_source
*ev
) {
520 struct queue_entry
*q
;
521 int random_enabled
= random_is_enabled();
523 D(("play playing=%p", (void *)playing
));
524 if(shutting_down
|| playing
|| !playing_is_enabled()) return;
525 /* See if there's anything to play */
526 if(qhead
.next
== &qhead
) {
527 /* Queue is empty. We could just wait around since there are periodic
528 * attempts to add a random track anyway. However they are rarer than
529 * attempts to force a track so we initiate one now. */
530 add_random_track(ev
);
533 /* There must be at least one track in the queue. */
535 /* If random play is disabled but the track is a random one then don't play
536 * it. play() will be called again when random play is re-enabled. */
537 if(!random_enabled
&& q
->state
== playing_random
)
539 D(("taken %p (%s) from queue", (void *)q
, q
->track
));
540 /* Try to start playing. */
541 switch(start(ev
, q
, 0/*!prepare_only*/)) {
543 if(q
== qhead
.next
) {
544 queue_remove(q
, 0); /* Abandon this track. */
548 /* Oh well, try the next one */
552 /* We'll try the same track again shortly. */
555 if(q
== qhead
.next
) {
560 time(&playing
->played
);
561 playing
->state
= playing_started
;
562 notify_play(playing
->track
, playing
->submitter
);
563 eventlog("playing", playing
->track
,
564 playing
->submitter ? playing
->submitter
: (const char *)0,
566 /* Maybe add a random track. */
567 add_random_track(ev
);
568 /* If there is another track in the queue prepare it now. This could
569 * potentially be a just-added random track. */
570 if(qhead
.next
!= &qhead
)
571 prepare(ev
, qhead
.next
);
576 int playing_is_enabled(void) {
577 const char *s
= trackdb_get_global("playing");
579 return !s
|| !strcmp(s
, "yes");
582 void enable_playing(const char *who
, ev_source
*ev
) {
583 trackdb_set_global("playing", "yes", who
);
584 /* Add a random track if necessary. */
585 add_random_track(ev
);
589 void disable_playing(const char *who
) {
590 trackdb_set_global("playing", "no", who
);
593 int random_is_enabled(void) {
594 const char *s
= trackdb_get_global("random-play");
596 return !s
|| !strcmp(s
, "yes");
599 void enable_random(const char *who
, ev_source
*ev
) {
600 trackdb_set_global("random-play", "yes", who
);
601 add_random_track(ev
);
605 void disable_random(const char *who
) {
606 trackdb_set_global("random-play", "no", who
);
609 void scratch(const char *who
, const char *id
) {
610 struct queue_entry
*q
;
611 struct speaker_message sm
;
614 D(("scratch playing=%p state=%d id=%s playing->id=%s",
616 playing ? playing
->state
: 0,
618 playing ? playing
->id
: "(none)"));
620 && (playing
->state
== playing_started
621 || playing
->state
== playing_paused
)
623 || !strcmp(id
, playing
->id
))) {
624 playing
->state
= playing_scratched
;
625 playing
->scratched
= who ?
xstrdup(who
) : 0;
626 if((pid
= find_player_pid(playing
->id
)) > 0) {
627 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
628 kill(-pid
, config
->signal
);
629 forget_player_pid(playing
->id
);
631 error(0, "could not find PID for %s", playing
->id
);
632 if((playing
->type
& DISORDER_PLAYER_TYPEMASK
) == DISORDER_PLAYER_RAW
) {
633 memset(&sm
, 0, sizeof sm
);
635 strcpy(sm
.id
, playing
->id
);
636 speaker_send(speaker_fd
, &sm
);
637 D(("sending SM_CANCEL for %s", playing
->id
));
639 /* put a scratch track onto the front of the queue (but don't
640 * bother if playing is disabled) */
641 if(playing_is_enabled() && config
->scratch
.n
) {
642 int r
= rand() * (double)config
->scratch
.n
/ (RAND_MAX
+ 1.0);
643 q
= queue_add(config
->scratch
.s
[r
], who
, WHERE_START
);
644 q
->state
= playing_isscratch
;
646 notify_scratch(playing
->track
, playing
->submitter
, who
,
647 time(0) - playing
->played
);
651 void quitting(ev_source
*ev
) {
652 struct queue_entry
*q
;
655 /* Don't start anything new */
657 /* Shut down the current player */
659 if((pid
= find_player_pid(playing
->id
)) > 0) {
660 kill(-pid
, config
->signal
);
661 forget_player_pid(playing
->id
);
663 error(0, "could not find PID for %s", playing
->id
);
664 playing
->state
= playing_quitting
;
667 /* Zap any other players */
668 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
669 if((pid
= find_player_pid(q
->id
)) > 0) {
670 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
671 kill(-pid
, config
->signal
);
672 forget_player_pid(q
->id
);
674 error(0, "could not find PID for %s", q
->id
);
675 /* Don't need the speaker any more */
676 ev_fd_cancel(ev
, ev_read
, speaker_fd
);
680 int pause_playing(const char *who
) {
681 struct speaker_message sm
;
684 /* Can't pause if already paused or if nothing playing. */
685 if(!playing
|| paused
) return 0;
686 switch(playing
->type
& DISORDER_PLAYER_TYPEMASK
) {
687 case DISORDER_PLAYER_STANDALONE
:
688 if(!(playing
->type
& DISORDER_PLAYER_PAUSES
)) {
690 error(0, "cannot pause because player is not powerful enough");
693 if(play_pause(playing
->pl
, &played
, playing
->data
)) {
694 error(0, "player indicates it cannot pause");
697 time(&playing
->lastpaused
);
698 playing
->uptopause
= played
;
699 playing
->lastresumed
= 0;
701 case DISORDER_PLAYER_RAW
:
702 memset(&sm
, 0, sizeof sm
);
704 speaker_send(speaker_fd
, &sm
);
707 if(who
) info("paused by %s", who
);
708 notify_pause(playing
->track
, who
);
710 if(playing
->state
== playing_started
)
711 playing
->state
= playing_paused
;
712 eventlog("state", "pause", (char *)0);
716 void resume_playing(const char *who
) {
717 struct speaker_message sm
;
722 switch(playing
->type
& DISORDER_PLAYER_TYPEMASK
) {
723 case DISORDER_PLAYER_STANDALONE
:
724 if(!playing
->type
& DISORDER_PLAYER_PAUSES
) {
726 /* Shouldn't happen */
729 play_resume(playing
->pl
, playing
->data
);
730 time(&playing
->lastresumed
);
732 case DISORDER_PLAYER_RAW
:
733 memset(&sm
, 0, sizeof sm
);
735 speaker_send(speaker_fd
, &sm
);
738 if(who
) info("resumed by %s", who
);
739 notify_resume(playing
->track
, who
);
740 if(playing
->state
== playing_paused
)
741 playing
->state
= playing_started
;
742 eventlog("state", "resume", (char *)0);