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/>.
19 #include "disorder-server.h"
22 #define SPEAKER "disorder-speaker"
24 struct queue_entry
*playing
;
27 static void finished(ev_source
*ev
);
29 static int speaker_fd
= -1;
30 static hash
*player_pids
;
31 static int shutting_down
;
33 static void store_player_pid(const char *id
, pid_t pid
) {
34 if(!player_pids
) player_pids
= hash_new(sizeof (pid_t
));
35 hash_add(player_pids
, id
, &pid
, HASH_INSERT_OR_REPLACE
);
38 static pid_t
find_player_pid(const char *id
) {
41 if(player_pids
&& (pidp
= hash_find(player_pids
, id
))) return *pidp
;
45 static void forget_player_pid(const char *id
) {
46 if(player_pids
) hash_remove(player_pids
, id
);
49 /* called when speaker process terminates */
50 static int speaker_terminated(ev_source
attribute((unused
)) *ev
,
51 pid_t
attribute((unused
)) pid
,
52 int attribute((unused
)) status
,
53 const struct rusage
attribute((unused
)) *rusage
,
54 void attribute((unused
)) *u
) {
55 fatal(0, "speaker subprocess %s",
59 /* called when speaker process has something to say */
60 static int speaker_readable(ev_source
*ev
, int fd
,
61 void attribute((unused
)) *u
) {
62 struct speaker_message sm
;
63 int ret
= speaker_recv(fd
, &sm
);
65 if(ret
< 0) return 0; /* EAGAIN */
67 ev_fd_cancel(ev
, ev_read
, fd
);
72 /* track ID is paused, DATA seconds played */
73 D(("SM_PAUSED %s %ld", sm
.id
, sm
.data
));
74 playing
->sofar
= sm
.data
;
76 case SM_FINISHED
: /* scratched the playing track */
77 case SM_STILLBORN
: /* scratched too early */
78 case SM_UNKNOWN
: /* scratched WAY too early */
79 if(playing
&& !strcmp(sm
.id
, playing
->id
))
83 /* track ID is playing, DATA seconds played */
84 D(("SM_PLAYING %s %ld", sm
.id
, sm
.data
));
85 playing
->sofar
= sm
.data
;
88 error(0, "unknown message type %d", sm
.type
);
93 void speaker_setup(ev_source
*ev
) {
96 struct speaker_message sm
;
98 if(socketpair(PF_UNIX
, SOCK_DGRAM
, 0, sp
) < 0)
99 fatal(errno
, "error calling socketpair");
100 if(!(pid
= xfork())) {
102 ev_signal_atfork(ev
);
107 signal(SIGPIPE
, SIG_DFL
);
109 execlp("valgrind", "valgrind", SPEAKER
, "--config", configfile
,
110 debugging ?
"--debug" : "--no-debug",
111 log_default
== &log_syslog ?
"--syslog" : "--no-syslog",
114 execlp(SPEAKER
, SPEAKER
, "--config", configfile
,
115 debugging ?
"--debug" : "--no-debug",
116 log_default
== &log_syslog ?
"--syslog" : "--no-syslog",
119 fatal(errno
, "error invoking %s", SPEAKER
);
121 ev_child(ev
, pid
, 0, speaker_terminated
, 0);
125 /* Wait for the speaker to be ready */
126 speaker_recv(speaker_fd
, &sm
);
127 nonblock(speaker_fd
);
128 ev_fd(ev
, ev_read
, speaker_fd
, speaker_readable
, 0, "speaker read");
131 void speaker_reload(void) {
132 struct speaker_message sm
;
134 memset(&sm
, 0, sizeof sm
);
136 speaker_send(speaker_fd
, &sm
);
139 /* Called when the currently playing track finishes playing. This
140 * might be because the player finished or because the speaker process
142 static void finished(ev_source
*ev
) {
143 D(("finished playing=%p", (void *)playing
));
146 if(playing
->state
!= playing_scratched
)
147 notify_not_scratched(playing
->track
, playing
->submitter
);
148 switch(playing
->state
) {
150 eventlog("completed", playing
->track
, (char *)0);
152 case playing_scratched
:
153 eventlog("scratched", playing
->track
, playing
->scratched
, (char *)0);
156 eventlog("failed", playing
->track
, wstat(playing
->wstat
), (char *)0);
161 queue_played(playing
);
163 forget_player_pid(playing
->id
);
165 /* Try to play something else */
166 /* TODO re-support config->gap? */
171 /* Called when a player terminates. */
172 static int player_finished(ev_source
*ev
,
175 const struct rusage
attribute((unused
)) *rusage
,
177 struct queue_entry
*q
= u
;
179 D(("player_finished pid=%lu status=%#x",
180 (unsigned long)pid
, (unsigned)status
));
181 /* Record that this PID is dead. If we killed the track we might know this
182 * already, but also it might have exited or crashed. Either way we don't
183 * want to end up signalling it. */
184 if(pid
== find_player_pid(q
->id
))
185 forget_player_pid(q
->id
);
187 case playing_unplayed
:
189 /* If this was a pre-prepared track then either it failed or we
190 * deliberately stopped it because it was removed from the queue or moved
191 * down it. So leave it state alone for future use. */
194 /* We actually started playing this track. */
196 if(q
->state
!= playing_scratched
)
197 q
->state
= playing_failed
;
199 q
->state
= playing_ok
;
202 /* Regardless we always report and record the status and do cleanup for
205 error(0, "player for %s %s", q
->track
, wstat(status
));
206 if(q
->type
& DISORDER_PLAYER_PREFORK
)
207 play_cleanup(q
->pl
, q
->data
);
209 /* If this actually was the current track, and does not use the speaker
210 * process, then it must have finished. For raw-output players we will get a
211 * separate notification from the speaker process. */
213 && (q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
218 /* Find the player for Q */
219 static int find_player(const struct queue_entry
*q
) {
222 for(n
= 0; n
< config
->player
.n
; ++n
)
223 if(fnmatch(config
->player
.s
[n
].s
[0], q
->track
, 0) == 0)
225 if(n
>= config
->player
.n
)
231 /* Return values from start() */
232 #define START_OK 0 /**< @brief Succeeded. */
233 #define START_HARDFAIL 1 /**< @brief Track is broken. */
234 #define START_SOFTFAIL 2 /**< @brief Track OK, system (temporarily?) broken */
236 /** @brief Play or prepare @p q
237 * @param ev Event loop
238 * @param q Track to play/prepare
239 * @param prepare_only If true, only prepares track
240 * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
242 static int start(ev_source
*ev
,
243 struct queue_entry
*q
,
248 struct speaker_message sm
;
251 ao_sample_format format
;
255 const char *waitdevice
= 0;
256 const char *const *optv
;
258 struct sockaddr_un addr
;
261 memset(&sm
, 0, sizeof sm
);
262 D(("start %s %d", q
->id
, prepare_only
));
264 /* The track is alraedy prepared */
266 /* We want to run it, since it's prepared the answer is to tell the
267 * speaker to set it off */
268 strcpy(sm
.id
, q
->id
);
270 speaker_send(speaker_fd
, &sm
);
271 D(("sent SM_PLAY for %s", sm
.id
));
275 /* Find the player plugin. */
276 if((n
= find_player(q
)) < 0) return START_HARDFAIL
;
277 if(!(q
->pl
= open_plugin(config
->player
.s
[n
].s
[1], 0)))
278 return START_HARDFAIL
;
279 q
->type
= play_get_type(q
->pl
);
280 /* Can't prepare non-raw tracks. */
282 && (q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
284 /* Call the prefork function. */
285 p
= trackdb_rawpath(q
->track
);
286 if(q
->type
& DISORDER_PLAYER_PREFORK
)
287 if(!(q
->data
= play_prefork(q
->pl
, p
))) {
288 error(0, "prefork function for %s failed", q
->track
);
289 return START_HARDFAIL
;
291 /* Use the second arg as the tag if available (it's probably a command name),
292 * otherwise the module name. */
294 lfd
= logfd(ev
, (config
->player
.s
[n
].s
[2]
295 ? config
->player
.s
[n
].s
[2] : config
->player
.s
[n
].s
[1]));
298 optc
= config
->player
.s
[n
].n
- 2;
299 optv
= (void *)&config
->player
.s
[n
].s
[2];
300 while(optc
> 0 && optv
[0][0] == '-') {
301 if(!strcmp(optv
[0], "--")) {
306 if(!strcmp(optv
[0], "--wait-for-device")
307 || !strncmp(optv
[0], "--wait-for-device=", 18)) {
308 if((waitdevice
= strchr(optv
[0], '='))) {
311 waitdevice
= ""; /* use default */
315 error(0, "unknown option %s", optv
[0]);
316 return START_HARDFAIL
;
319 switch(pid
= fork()) {
322 progname
= "disorderd-fork";
323 ev_signal_atfork(ev
);
324 signal(SIGPIPE
, SIG_DFL
);
328 xclose(lfd
); /* tidy up */
331 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) == DISORDER_PLAYER_RAW
) {
332 /* "Raw" format players always have their output send down a pipe
333 * to the disorder-normalize process. This will connect to the
334 * speaker process to actually play the audio data.
336 /* np will be the pipe to disorder-normalize */
337 if(socketpair(PF_UNIX
, SOCK_STREAM
, 0, np
) < 0)
338 fatal(errno
, "error calling socketpair");
339 /* Beware of the Leopard! On OS X 10.5.x, the order of the shutdown
340 * calls here DOES MATTER. If you do the SHUT_WR first then the SHUT_RD
341 * fails with "Socket is not connected". I think this is a bug but
342 * provided implementors either don't care about the order or all agree
343 * about the order, choosing the reliable order is an adequate
345 xshutdown(np
[1], SHUT_RD
); /* decoder writes to np[1] */
346 xshutdown(np
[0], SHUT_WR
); /* normalize reads from np[0] */
349 /* Start disorder-normalize */
350 if(!(npid
= xfork())) {
352 /* Connect to the speaker process */
353 memset(&addr
, 0, sizeof addr
);
354 addr
.sun_family
= AF_UNIX
;
355 snprintf(addr
.sun_path
, sizeof addr
.sun_path
,
356 "%s/speaker/socket", config
->home
);
357 sfd
= xsocket(PF_UNIX
, SOCK_STREAM
, 0);
358 if(connect(sfd
, (const struct sockaddr
*)&addr
, sizeof addr
) < 0)
359 fatal(errno
, "connecting to %s", addr
.sun_path
);
361 if(write(sfd
, &l
, sizeof l
) < 0
362 || write(sfd
, q
->id
, l
) < 0)
363 fatal(errno
, "writing to %s", addr
.sun_path
);
372 /* Ask the speaker to actually start playing the track; we do it here
373 * so it's definitely after ack. */
375 strcpy(sm
.id
, q
->id
);
377 speaker_send(speaker_fd
, &sm
);
378 D(("sent SM_PLAY for %s", sm
.id
));
380 /* TODO stderr shouldn't be redirected for disorder-normalize
381 * (but it should be for play_track() */
382 execlp("disorder-normalize", "disorder-normalize",
383 log_default
== &log_syslog ?
"--syslog" : "--no-syslog",
384 "--config", configfile
,
386 fatal(errno
, "executing disorder-normalize");
387 /* end of the innermost fork */
390 /* end of the middle fork */
392 /* Wait for the middle fork to finish */
393 while(waitpid(npid
, &n
, 0) < 0 && errno
== EINTR
)
395 /* Pass the file descriptor to the driver in an environment
397 snprintf(buffer
, sizeof buffer
, "DISORDER_RAW_FD=%d", np
[1]);
398 if(putenv(buffer
) < 0)
399 fatal(errno
, "error calling putenv");
400 /* Close all the FDs we don't need */
406 n
= ao_driver_id(waitdevice
);
408 fatal(0, "invalid libao driver: %s", optv
[0]);
410 n
= ao_default_driver_id();
411 /* Make up a format. */
412 memset(&format
, 0, sizeof format
);
416 format
.byte_format
= AO_FMT_NATIVE
;
419 ts
.tv_nsec
= 100000000; /* 0.1s */
420 while((device
= ao_open_live(n
, &format
, 0)) == 0 && retries
-- > 0)
431 error(errno
, "error calling fork");
432 if(q
->type
& DISORDER_PLAYER_PREFORK
)
433 play_cleanup(q
->pl
, q
->data
); /* else would leak */
436 return START_SOFTFAIL
;
438 store_player_pid(q
->id
, pid
);
443 ev_child(ev
, pid
, 0, player_finished
, q
);
444 D(("player subprocess ID %lu", (unsigned long)pid
));
448 int prepare(ev_source
*ev
,
449 struct queue_entry
*q
) {
452 /* Find the player plugin */
453 if(find_player_pid(q
->id
) > 0) return 0; /* Already going. */
454 if((n
= find_player(q
)) < 0) return -1; /* No player */
455 q
->pl
= open_plugin(config
->player
.s
[n
].s
[1], 0); /* No player */
456 q
->type
= play_get_type(q
->pl
);
457 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
458 return 0; /* Not a raw player */
459 return start(ev
, q
, 1/*prepare_only*/); /* Prepare it */
462 void abandon(ev_source
attribute((unused
)) *ev
,
463 struct queue_entry
*q
) {
464 struct speaker_message sm
;
465 pid_t pid
= find_player_pid(q
->id
);
467 if(pid
< 0) return; /* Not prepared. */
468 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
469 return; /* Not a raw player. */
470 /* Terminate the player. */
471 kill(-pid
, config
->signal
);
472 forget_player_pid(q
->id
);
473 /* Cancel the track. */
474 memset(&sm
, 0, sizeof sm
);
476 strcpy(sm
.id
, q
->id
);
477 speaker_send(speaker_fd
, &sm
);
480 /** @brief Called with a new random track
481 * @param ev Event loop
482 * @param track Track name
484 static void chosen_random_track(ev_source
*ev
,
486 struct queue_entry
*q
;
490 /* Add the track to the queue */
491 q
= queue_add(track
, 0, WHERE_END
);
492 q
->state
= playing_random
;
493 D(("picked %p (%s) at random", (void *)q
, q
->track
));
495 /* Maybe a track can now be played */
499 /** @brief Maybe add a randomly chosen track
500 * @param ev Event loop
502 void add_random_track(ev_source
*ev
) {
503 struct queue_entry
*q
;
506 /* If random play is not enabled then do nothing. */
507 if(shutting_down
|| !random_is_enabled())
509 /* Count how big the queue is */
510 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
512 /* If it's smaller than the desired size then add a track */
513 if(qlen
< config
->queue_pad
)
514 trackdb_request_random(ev
, chosen_random_track
);
517 /* try to play a track */
518 void play(ev_source
*ev
) {
519 struct queue_entry
*q
;
520 int random_enabled
= random_is_enabled();
522 D(("play playing=%p", (void *)playing
));
523 if(shutting_down
|| playing
|| !playing_is_enabled()) return;
524 /* See if there's anything to play */
525 if(qhead
.next
== &qhead
) {
526 /* Queue is empty. We could just wait around since there are periodic
527 * attempts to add a random track anyway. However they are rarer than
528 * attempts to force a track so we initiate one now. */
529 add_random_track(ev
);
532 /* There must be at least one track in the queue. */
534 /* If random play is disabled but the track is a random one then don't play
535 * it. play() will be called again when random play is re-enabled. */
536 if(!random_enabled
&& q
->state
== playing_random
)
538 D(("taken %p (%s) from queue", (void *)q
, q
->track
));
539 /* Try to start playing. */
540 switch(start(ev
, q
, 0/*!prepare_only*/)) {
542 if(q
== qhead
.next
) {
543 queue_remove(q
, 0); /* Abandon this track. */
547 /* Oh well, try the next one */
551 /* We'll try the same track again shortly. */
554 if(q
== qhead
.next
) {
559 time(&playing
->played
);
560 playing
->state
= playing_started
;
561 notify_play(playing
->track
, playing
->submitter
);
562 eventlog("playing", playing
->track
,
563 playing
->submitter ? playing
->submitter
: (const char *)0,
565 /* Maybe add a random track. */
566 add_random_track(ev
);
567 /* If there is another track in the queue prepare it now. This could
568 * potentially be a just-added random track. */
569 if(qhead
.next
!= &qhead
)
570 prepare(ev
, qhead
.next
);
575 int playing_is_enabled(void) {
576 const char *s
= trackdb_get_global("playing");
578 return !s
|| !strcmp(s
, "yes");
581 void enable_playing(const char *who
, ev_source
*ev
) {
582 trackdb_set_global("playing", "yes", who
);
583 /* Add a random track if necessary. */
584 add_random_track(ev
);
588 void disable_playing(const char *who
) {
589 trackdb_set_global("playing", "no", who
);
592 int random_is_enabled(void) {
593 const char *s
= trackdb_get_global("random-play");
595 return !s
|| !strcmp(s
, "yes");
598 void enable_random(const char *who
, ev_source
*ev
) {
599 trackdb_set_global("random-play", "yes", who
);
600 add_random_track(ev
);
604 void disable_random(const char *who
) {
605 trackdb_set_global("random-play", "no", who
);
608 void scratch(const char *who
, const char *id
) {
609 struct queue_entry
*q
;
610 struct speaker_message sm
;
613 D(("scratch playing=%p state=%d id=%s playing->id=%s",
615 playing ? playing
->state
: 0,
617 playing ? playing
->id
: "(none)"));
619 && (playing
->state
== playing_started
620 || playing
->state
== playing_paused
)
622 || !strcmp(id
, playing
->id
))) {
623 playing
->state
= playing_scratched
;
624 playing
->scratched
= who ?
xstrdup(who
) : 0;
625 if((pid
= find_player_pid(playing
->id
)) > 0) {
626 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
627 kill(-pid
, config
->signal
);
628 forget_player_pid(playing
->id
);
630 error(0, "could not find PID for %s", playing
->id
);
631 if((playing
->type
& DISORDER_PLAYER_TYPEMASK
) == DISORDER_PLAYER_RAW
) {
632 memset(&sm
, 0, sizeof sm
);
634 strcpy(sm
.id
, playing
->id
);
635 speaker_send(speaker_fd
, &sm
);
636 D(("sending SM_CANCEL for %s", playing
->id
));
638 /* put a scratch track onto the front of the queue (but don't
639 * bother if playing is disabled) */
640 if(playing_is_enabled() && config
->scratch
.n
) {
641 int r
= rand() * (double)config
->scratch
.n
/ (RAND_MAX
+ 1.0);
642 q
= queue_add(config
->scratch
.s
[r
], who
, WHERE_START
);
643 q
->state
= playing_isscratch
;
645 notify_scratch(playing
->track
, playing
->submitter
, who
,
646 time(0) - playing
->played
);
650 void quitting(ev_source
*ev
) {
651 struct queue_entry
*q
;
654 /* Don't start anything new */
656 /* Shut down the current player */
658 if((pid
= find_player_pid(playing
->id
)) > 0) {
659 kill(-pid
, config
->signal
);
660 forget_player_pid(playing
->id
);
662 error(0, "could not find PID for %s", playing
->id
);
663 playing
->state
= playing_quitting
;
666 /* Zap any other players */
667 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
668 if((pid
= find_player_pid(q
->id
)) > 0) {
669 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
670 kill(-pid
, config
->signal
);
671 forget_player_pid(q
->id
);
673 error(0, "could not find PID for %s", q
->id
);
674 /* Don't need the speaker any more */
675 ev_fd_cancel(ev
, ev_read
, speaker_fd
);
679 int pause_playing(const char *who
) {
680 struct speaker_message sm
;
683 /* Can't pause if already paused or if nothing playing. */
684 if(!playing
|| paused
) return 0;
685 switch(playing
->type
& DISORDER_PLAYER_TYPEMASK
) {
686 case DISORDER_PLAYER_STANDALONE
:
687 if(!(playing
->type
& DISORDER_PLAYER_PAUSES
)) {
689 error(0, "cannot pause because player is not powerful enough");
692 if(play_pause(playing
->pl
, &played
, playing
->data
)) {
693 error(0, "player indicates it cannot pause");
696 time(&playing
->lastpaused
);
697 playing
->uptopause
= played
;
698 playing
->lastresumed
= 0;
700 case DISORDER_PLAYER_RAW
:
701 memset(&sm
, 0, sizeof sm
);
703 speaker_send(speaker_fd
, &sm
);
706 if(who
) info("paused by %s", who
);
707 notify_pause(playing
->track
, who
);
709 if(playing
->state
== playing_started
)
710 playing
->state
= playing_paused
;
711 eventlog("state", "pause", (char *)0);
715 void resume_playing(const char *who
) {
716 struct speaker_message sm
;
721 switch(playing
->type
& DISORDER_PLAYER_TYPEMASK
) {
722 case DISORDER_PLAYER_STANDALONE
:
723 if(!playing
->type
& DISORDER_PLAYER_PAUSES
) {
725 /* Shouldn't happen */
728 play_resume(playing
->pl
, playing
->data
);
729 time(&playing
->lastresumed
);
731 case DISORDER_PLAYER_RAW
:
732 memset(&sm
, 0, sizeof sm
);
734 speaker_send(speaker_fd
, &sm
);
737 if(who
) info("resumed by %s", who
);
738 notify_resume(playing
->track
, who
);
739 if(playing
->state
== playing_paused
)
740 playing
->state
= playing_started
;
741 eventlog("state", "resume", (char *)0);