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 track Track name
483 static void chosen_random_track(ev_source
*ev
,
485 struct queue_entry
*q
;
489 /* Add the track to the queue */
490 q
= queue_add(track
, 0, WHERE_END
);
491 q
->state
= playing_random
;
492 D(("picked %p (%s) at random", (void *)q
, q
->track
));
494 /* Maybe a track can now be played */
498 /** @brief Maybe add a randomly chosen track
499 * @param ev Event loop
501 void add_random_track(ev_source
*ev
) {
502 struct queue_entry
*q
;
505 /* If random play is not enabled then do nothing. */
506 if(shutting_down
|| !random_is_enabled())
508 /* Count how big the queue is */
509 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
511 /* If it's smaller than the desired size then add a track */
512 if(qlen
< config
->queue_pad
)
513 trackdb_request_random(ev
, chosen_random_track
);
516 /* try to play a track */
517 void play(ev_source
*ev
) {
518 struct queue_entry
*q
;
519 int random_enabled
= random_is_enabled();
521 D(("play playing=%p", (void *)playing
));
522 if(shutting_down
|| playing
|| !playing_is_enabled()) return;
523 /* See if there's anything to play */
524 if(qhead
.next
== &qhead
) {
525 /* Queue is empty. We could just wait around since there are periodic
526 * attempts to add a random track anyway. However they are rarer than
527 * attempts to force a track so we initiate one now. */
528 add_random_track(ev
);
531 /* There must be at least one track in the queue. */
533 /* If random play is disabled but the track is a random one then don't play
534 * it. play() will be called again when random play is re-enabled. */
535 if(!random_enabled
&& q
->state
== playing_random
)
537 D(("taken %p (%s) from queue", (void *)q
, q
->track
));
538 /* Try to start playing. */
539 switch(start(ev
, q
, 0/*!prepare_only*/)) {
541 if(q
== qhead
.next
) {
542 queue_remove(q
, 0); /* Abandon this track. */
546 /* Oh well, try the next one */
550 /* We'll try the same track again shortly. */
553 if(q
== qhead
.next
) {
558 time(&playing
->played
);
559 playing
->state
= playing_started
;
560 notify_play(playing
->track
, playing
->submitter
);
561 eventlog("playing", playing
->track
,
562 playing
->submitter ? playing
->submitter
: (const char *)0,
564 /* Maybe add a random track. */
565 add_random_track(ev
);
566 /* If there is another track in the queue prepare it now. This could
567 * potentially be a just-added random track. */
568 if(qhead
.next
!= &qhead
)
569 prepare(ev
, qhead
.next
);
574 int playing_is_enabled(void) {
575 const char *s
= trackdb_get_global("playing");
577 return !s
|| !strcmp(s
, "yes");
580 void enable_playing(const char *who
, ev_source
*ev
) {
581 trackdb_set_global("playing", "yes", who
);
582 /* Add a random track if necessary. */
583 add_random_track(ev
);
587 void disable_playing(const char *who
) {
588 trackdb_set_global("playing", "no", who
);
591 int random_is_enabled(void) {
592 const char *s
= trackdb_get_global("random-play");
594 return !s
|| !strcmp(s
, "yes");
597 void enable_random(const char *who
, ev_source
*ev
) {
598 trackdb_set_global("random-play", "yes", who
);
599 add_random_track(ev
);
603 void disable_random(const char *who
) {
604 trackdb_set_global("random-play", "no", who
);
607 void scratch(const char *who
, const char *id
) {
608 struct queue_entry
*q
;
609 struct speaker_message sm
;
612 D(("scratch playing=%p state=%d id=%s playing->id=%s",
614 playing ? playing
->state
: 0,
616 playing ? playing
->id
: "(none)"));
618 && (playing
->state
== playing_started
619 || playing
->state
== playing_paused
)
621 || !strcmp(id
, playing
->id
))) {
622 playing
->state
= playing_scratched
;
623 playing
->scratched
= who ?
xstrdup(who
) : 0;
624 if((pid
= find_player_pid(playing
->id
)) > 0) {
625 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
626 kill(-pid
, config
->signal
);
627 forget_player_pid(playing
->id
);
629 error(0, "could not find PID for %s", playing
->id
);
630 if((playing
->type
& DISORDER_PLAYER_TYPEMASK
) == DISORDER_PLAYER_RAW
) {
631 memset(&sm
, 0, sizeof sm
);
633 strcpy(sm
.id
, playing
->id
);
634 speaker_send(speaker_fd
, &sm
);
635 D(("sending SM_CANCEL for %s", playing
->id
));
637 /* put a scratch track onto the front of the queue (but don't
638 * bother if playing is disabled) */
639 if(playing_is_enabled() && config
->scratch
.n
) {
640 int r
= rand() * (double)config
->scratch
.n
/ (RAND_MAX
+ 1.0);
641 q
= queue_add(config
->scratch
.s
[r
], who
, WHERE_START
);
642 q
->state
= playing_isscratch
;
644 notify_scratch(playing
->track
, playing
->submitter
, who
,
645 time(0) - playing
->played
);
649 void quitting(ev_source
*ev
) {
650 struct queue_entry
*q
;
653 /* Don't start anything new */
655 /* Shut down the current player */
657 if((pid
= find_player_pid(playing
->id
)) > 0) {
658 kill(-pid
, config
->signal
);
659 forget_player_pid(playing
->id
);
661 error(0, "could not find PID for %s", playing
->id
);
662 playing
->state
= playing_quitting
;
665 /* Zap any other players */
666 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
667 if((pid
= find_player_pid(q
->id
)) > 0) {
668 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
669 kill(-pid
, config
->signal
);
670 forget_player_pid(q
->id
);
672 error(0, "could not find PID for %s", q
->id
);
673 /* Don't need the speaker any more */
674 ev_fd_cancel(ev
, ev_read
, speaker_fd
);
678 int pause_playing(const char *who
) {
679 struct speaker_message sm
;
682 /* Can't pause if already paused or if nothing playing. */
683 if(!playing
|| paused
) return 0;
684 switch(playing
->type
& DISORDER_PLAYER_TYPEMASK
) {
685 case DISORDER_PLAYER_STANDALONE
:
686 if(!(playing
->type
& DISORDER_PLAYER_PAUSES
)) {
688 error(0, "cannot pause because player is not powerful enough");
691 if(play_pause(playing
->pl
, &played
, playing
->data
)) {
692 error(0, "player indicates it cannot pause");
695 time(&playing
->lastpaused
);
696 playing
->uptopause
= played
;
697 playing
->lastresumed
= 0;
699 case DISORDER_PLAYER_RAW
:
700 memset(&sm
, 0, sizeof sm
);
702 speaker_send(speaker_fd
, &sm
);
705 if(who
) info("paused by %s", who
);
706 notify_pause(playing
->track
, who
);
708 if(playing
->state
== playing_started
)
709 playing
->state
= playing_paused
;
710 eventlog("state", "pause", (char *)0);
714 void resume_playing(const char *who
) {
715 struct speaker_message sm
;
720 switch(playing
->type
& DISORDER_PLAYER_TYPEMASK
) {
721 case DISORDER_PLAYER_STANDALONE
:
722 if(!playing
->type
& DISORDER_PLAYER_PAUSES
) {
724 /* Shouldn't happen */
727 play_resume(playing
->pl
, playing
->data
);
728 time(&playing
->lastresumed
);
730 case DISORDER_PLAYER_RAW
:
731 memset(&sm
, 0, sizeof sm
);
733 speaker_send(speaker_fd
, &sm
);
736 if(who
) info("resumed by %s", who
);
737 notify_resume(playing
->track
, who
);
738 if(playing
->state
== playing_paused
)
739 playing
->state
= playing_started
;
740 eventlog("state", "resume", (char *)0);