2 * This file is part of DisOrder.
3 * Copyright (C) 2004, 2005, 2006, 2007 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
24 #include <sys/types.h>
33 #include <sys/socket.h>
44 #include "configuration.h"
53 #include "speaker-protocol.h"
58 #define SPEAKER "disorder-speaker"
60 struct queue_entry
*playing
;
63 static void finished(ev_source
*ev
);
65 static int speaker_fd
= -1;
66 static hash
*player_pids
;
67 static int shutting_down
;
69 static void store_player_pid(const char *id
, pid_t pid
) {
70 if(!player_pids
) player_pids
= hash_new(sizeof (pid_t
));
71 hash_add(player_pids
, id
, &pid
, HASH_INSERT_OR_REPLACE
);
74 static pid_t
find_player_pid(const char *id
) {
77 if(player_pids
&& (pidp
= hash_find(player_pids
, id
))) return *pidp
;
81 static void forget_player_pid(const char *id
) {
82 if(player_pids
) hash_remove(player_pids
, id
);
85 /* called when speaker process terminates */
86 static int speaker_terminated(ev_source
attribute((unused
)) *ev
,
87 pid_t
attribute((unused
)) pid
,
88 int attribute((unused
)) status
,
89 const struct rusage
attribute((unused
)) *rusage
,
90 void attribute((unused
)) *u
) {
91 fatal(0, "speaker subprocess %s",
95 /* called when speaker process has something to say */
96 static int speaker_readable(ev_source
*ev
, int fd
,
97 void attribute((unused
)) *u
) {
98 struct speaker_message sm
;
99 int ret
= speaker_recv(fd
, &sm
);
101 if(ret
< 0) return 0; /* EAGAIN */
103 ev_fd_cancel(ev
, ev_read
, fd
);
108 /* track ID is paused, DATA seconds played */
109 D(("SM_PAUSED %s %ld", sm
.id
, sm
.data
));
110 playing
->sofar
= sm
.data
;
113 /* the playing track finished */
114 D(("SM_FINISHED %s", sm
.id
));
118 /* track ID is playing, DATA seconds played */
119 D(("SM_PLAYING %s %ld", sm
.id
, sm
.data
));
120 playing
->sofar
= sm
.data
;
123 error(0, "unknown message type %d", sm
.type
);
128 void speaker_setup(ev_source
*ev
) {
131 struct speaker_message sm
;
133 if(socketpair(PF_UNIX
, SOCK_DGRAM
, 0, sp
) < 0)
134 fatal(errno
, "error calling socketpair");
136 lfd
= logfd(ev
, SPEAKER
);
139 if(!(pid
= xfork())) {
141 ev_signal_atfork(ev
);
150 signal(SIGPIPE
, SIG_DFL
);
152 execlp("valgrind", "valgrind", SPEAKER
, "--config", configfile
,
153 debugging ?
"--debug" : "--no-debug", (char *)0);
155 execlp(SPEAKER
, SPEAKER
, "--config", configfile
,
156 debugging ?
"--debug" : "--no-debug", (char *)0);
158 fatal(errno
, "error invoking %s", SPEAKER
);
160 ev_child(ev
, pid
, 0, speaker_terminated
, 0);
164 /* Wait for the speaker to be ready */
165 speaker_recv(speaker_fd
, &sm
);
166 nonblock(speaker_fd
);
167 ev_fd(ev
, ev_read
, speaker_fd
, speaker_readable
, 0);
170 void speaker_reload(void) {
171 struct speaker_message sm
;
173 memset(&sm
, 0, sizeof sm
);
175 speaker_send(speaker_fd
, &sm
);
178 /* timeout for play retry */
179 static int play_again(ev_source
*ev
,
180 const struct timeval
attribute((unused
)) *now
,
181 void attribute((unused
)) *u
) {
187 /* try calling play() again after @offset@ seconds */
188 static void retry_play(ev_source
*ev
, int offset
) {
191 D(("retry_play(%d)", offset
));
194 ev_timeout(ev
, 0, &w
, play_again
, 0);
197 /* Called when the currently playing track finishes playing. This
198 * might be because the player finished or because the speaker process
200 static void finished(ev_source
*ev
) {
201 D(("finished playing=%p", (void *)playing
));
204 if(playing
->state
!= playing_scratched
)
205 notify_not_scratched(playing
->track
, playing
->submitter
);
206 switch(playing
->state
) {
208 eventlog("completed", playing
->track
, (char *)0);
210 case playing_scratched
:
211 eventlog("scratched", playing
->track
, playing
->scratched
, (char *)0);
214 eventlog("failed", playing
->track
, wstat(playing
->wstat
), (char *)0);
219 queue_played(playing
);
221 forget_player_pid(playing
->id
);
223 if(ev
) retry_play(ev
, config
->gap
);
226 /* Called when a player terminates. */
227 static int player_finished(ev_source
*ev
,
230 const struct rusage
attribute((unused
)) *rusage
,
232 struct queue_entry
*q
= u
;
234 D(("player_finished pid=%lu status=%#x",
235 (unsigned long)pid
, (unsigned)status
));
236 /* Record that this PID is dead. If we killed the track we might know this
237 * already, but also it might have exited or crashed. Either way we don't
238 * want to end up signalling it. */
239 if(pid
== find_player_pid(q
->id
))
240 forget_player_pid(q
->id
);
242 case playing_unplayed
:
244 /* If this was a pre-prepared track then either it failed or we
245 * deliberately stopped it because it was removed from the queue or moved
246 * down it. So leave it state alone for future use. */
249 /* We actually started playing this track. */
251 if(q
->state
!= playing_scratched
)
252 q
->state
= playing_failed
;
254 q
->state
= playing_ok
;
257 /* Regardless we always report and record the status and do cleanup for
260 error(0, "player for %s %s", q
->track
, wstat(status
));
261 if(q
->type
& DISORDER_PLAYER_PREFORK
)
262 play_cleanup(q
->pl
, q
->data
);
264 /* If this actually was the current track, and does not use the speaker
265 * process, then it must have finished. For raw-output players we will get a
266 * separate notification from the speaker process. */
268 && (q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
273 /* Find the player for Q */
274 static int find_player(const struct queue_entry
*q
) {
277 for(n
= 0; n
< config
->player
.n
; ++n
)
278 if(fnmatch(config
->player
.s
[n
].s
[0], q
->track
, 0) == 0)
280 if(n
>= config
->player
.n
)
286 /* Return values from start() */
287 #define START_OK 0 /* Succeeded. */
288 #define START_HARDFAIL 1 /* Track is broken. */
289 #define START_SOFTFAIL 2 /* Track OK, system (temporarily?) broken */
291 /** @brief Play or prepare @p q
292 * @param ev Event loop
293 * @param q Track to play/prepare
294 * @param prepare_only If true, only prepares track
295 * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFTAIL
297 static int start(ev_source
*ev
,
298 struct queue_entry
*q
,
303 struct speaker_message sm
;
306 ao_sample_format format
;
310 const char *waitdevice
= 0;
311 const char *const *optv
;
313 struct sockaddr_un addr
;
316 memset(&sm
, 0, sizeof sm
);
317 D(("start %s %d", q
->id
, prepare_only
));
318 if(find_player_pid(q
->id
) > 0) {
319 if(prepare_only
) return START_OK
;
320 /* We have already prepared this track so we just need to tell the speaker
321 * process to start actually playing the queued up audio data */
322 strcpy(sm
.id
, q
->id
);
324 speaker_send(speaker_fd
, &sm
);
325 D(("sent SM_PLAY for %s", sm
.id
));
328 /* Find the player plugin. */
329 if((n
= find_player(q
)) < 0) return START_HARDFAIL
;
330 if(!(q
->pl
= open_plugin(config
->player
.s
[n
].s
[1], 0)))
331 return START_HARDFAIL
;
332 q
->type
= play_get_type(q
->pl
);
333 /* Can't prepare non-raw tracks. */
335 && (q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
337 /* Call the prefork function. */
338 p
= trackdb_rawpath(q
->track
);
339 if(q
->type
& DISORDER_PLAYER_PREFORK
)
340 if(!(q
->data
= play_prefork(q
->pl
, p
))) {
341 error(0, "prefork function for %s failed", q
->track
);
342 return START_HARDFAIL
;
344 /* Use the second arg as the tag if available (it's probably a command name),
345 * otherwise the module name. */
346 lfd
= logfd(ev
, (config
->player
.s
[n
].s
[2]
347 ? config
->player
.s
[n
].s
[2] : config
->player
.s
[n
].s
[1]));
348 optc
= config
->player
.s
[n
].n
- 2;
349 optv
= (void *)&config
->player
.s
[n
].s
[2];
350 while(optc
> 0 && optv
[0][0] == '-') {
351 if(!strcmp(optv
[0], "--")) {
356 if(!strcmp(optv
[0], "--wait-for-device")
357 || !strncmp(optv
[0], "--wait-for-device=", 18)) {
358 if((waitdevice
= strchr(optv
[0], '='))) {
361 waitdevice
= ""; /* use default */
365 error(0, "unknown option %s", optv
[0]);
366 return START_HARDFAIL
;
369 switch(pid
= fork()) {
372 ev_signal_atfork(ev
);
373 signal(SIGPIPE
, SIG_DFL
);
376 xclose(lfd
); /* tidy up */
378 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) == DISORDER_PLAYER_RAW
) {
379 /* "Raw" format players always have their output send down a pipe
380 * to the disorder-normalize process. This will connect to the
381 * speaker process to actually play the audio data.
383 /* np will be the pipe to disorder-normalize */
384 if(socketpair(PF_UNIX
, SOCK_STREAM
, 0, np
) < 0)
385 fatal(errno
, "error calling socketpair");
386 xshutdown(np
[0], SHUT_WR
); /* normalize reads from np[0] */
387 xshutdown(np
[1], SHUT_RD
); /* decoder writes to np[1] */
390 /* Start disorder-normalize */
391 if(!(npid
= xfork())) {
393 /* Connect to the speaker process */
394 memset(&addr
, 0, sizeof addr
);
395 addr
.sun_family
= AF_UNIX
;
396 snprintf(addr
.sun_path
, sizeof addr
.sun_path
,
397 "%s/speaker", config
->home
);
398 sfd
= xsocket(PF_UNIX
, SOCK_STREAM
, 0);
399 if(connect(sfd
, (const struct sockaddr
*)&addr
, sizeof addr
) < 0)
400 fatal(errno
, "connecting to %s", addr
.sun_path
);
402 if(write(sfd
, &l
, sizeof l
) < 0
403 || write(sfd
, q
->id
, l
) < 0)
404 fatal(errno
, "writing to %s", addr
.sun_path
);
413 /* Ask the speaker to actually start playing the track; we do it here
414 * so it's definitely after ack. */
416 strcpy(sm
.id
, q
->id
);
418 speaker_send(speaker_fd
, &sm
);
419 D(("sent SM_PLAY for %s", sm
.id
));
421 execlp("disorder-normalize", "disorder-normalize", (char *)0);
422 fatal(errno
, "executing disorder-normalize");
423 /* end of the innermost fork */
426 /* end of the middle fork */
428 /* Wait for the middle fork to finish */
429 while(waitpid(npid
, &n
, 0) < 0 && errno
== EINTR
)
431 /* Pass the file descriptor to the driver in an environment
433 snprintf(buffer
, sizeof buffer
, "DISORDER_RAW_FD=%d", np
[1]);
434 if(putenv(buffer
) < 0)
435 fatal(errno
, "error calling putenv");
436 /* Close all the FDs we don't need */
442 n
= ao_driver_id(waitdevice
);
444 fatal(0, "invalid libao driver: %s", optv
[0]);
446 n
= ao_default_driver_id();
447 /* Make up a format. */
448 memset(&format
, 0, sizeof format
);
452 format
.byte_format
= AO_FMT_NATIVE
;
455 ts
.tv_nsec
= 100000000; /* 0.1s */
456 while((device
= ao_open_live(n
, &format
, 0)) == 0 && retries
-- > 0)
467 error(errno
, "error calling fork");
468 if(q
->type
& DISORDER_PLAYER_PREFORK
)
469 play_cleanup(q
->pl
, q
->data
); /* else would leak */
471 return START_SOFTFAIL
;
473 store_player_pid(q
->id
, pid
);
476 ev_child(ev
, pid
, 0, player_finished
, q
);
477 D(("player subprocess ID %lu", (unsigned long)pid
));
481 int prepare(ev_source
*ev
,
482 struct queue_entry
*q
) {
485 /* Find the player plugin */
486 if(find_player_pid(q
->id
) > 0) return 0; /* Already going. */
487 if((n
= find_player(q
)) < 0) return -1; /* No player */
488 q
->pl
= open_plugin(config
->player
.s
[n
].s
[1], 0); /* No player */
489 q
->type
= play_get_type(q
->pl
);
490 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
491 return 0; /* Not a raw player */
492 return start(ev
, q
, 1/*prepare_only*/); /* Prepare it */
495 void abandon(ev_source
attribute((unused
)) *ev
,
496 struct queue_entry
*q
) {
497 struct speaker_message sm
;
498 pid_t pid
= find_player_pid(q
->id
);
500 if(pid
< 0) return; /* Not prepared. */
501 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
502 return; /* Not a raw player. */
503 /* Terminate the player. */
504 kill(-pid
, config
->signal
);
505 forget_player_pid(q
->id
);
506 /* Cancel the track. */
507 memset(&sm
, 0, sizeof sm
);
509 strcpy(sm
.id
, q
->id
);
510 speaker_send(speaker_fd
, &sm
);
513 int add_random_track(void) {
514 struct queue_entry
*q
;
519 /* If random play is not enabled then do nothing. */
520 if(shutting_down
|| !random_is_enabled())
522 /* Count how big the queue is */
523 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
525 /* Add random tracks until the queue is at the right size */
526 while(qlen
< config
->queue_pad
) {
527 /* Try to pick a random track */
528 if(!(p
= trackdb_random(16))) {
532 /* Add it to the end of the queue. */
533 q
= queue_add(p
, 0, WHERE_END
);
534 q
->state
= playing_random
;
535 D(("picked %p (%s) at random", (void *)q
, q
->track
));
538 /* Commit the queue */
543 /* try to play a track */
544 void play(ev_source
*ev
) {
545 struct queue_entry
*q
;
546 int random_enabled
= random_is_enabled();
548 D(("play playing=%p", (void *)playing
));
549 if(shutting_down
|| playing
|| !playing_is_enabled()) return;
550 /* If the queue is empty then add a random track. */
551 if(qhead
.next
== &qhead
) {
554 if(add_random_track()) {
555 /* On error, try again in 10s. */
559 /* Now there must be at least one track in the queue. */
562 /* If random play is disabled but the track is a random one then don't play
563 * it. play() will be called again when random play is re-enabled. */
564 if(!random_enabled
&& q
->state
== playing_random
)
566 D(("taken %p (%s) from queue", (void *)q
, q
->track
));
567 /* Try to start playing. */
568 switch(start(ev
, q
, 0/*!prepare_only*/)) {
570 if(q
== qhead
.next
) {
571 queue_remove(q
, 0); /* Abandon this track. */
575 if(qhead
.next
== &qhead
)
576 /* Queue is empty, wait a bit before trying something else (so we don't
577 * sit there looping madly in the presence of persistent problem). Note
578 * that we might not reliably get a random track lookahead in this case,
579 * but if we get here then really there are bigger problems. */
582 /* More in queue, try again now. */
586 /* Try same track again in a bit. */
590 if(q
== qhead
.next
) {
595 time(&playing
->played
);
596 playing
->state
= playing_started
;
597 notify_play(playing
->track
, playing
->submitter
);
598 eventlog("playing", playing
->track
,
599 playing
->submitter ? playing
->submitter
: (const char *)0,
601 /* Maybe add a random track. */
603 /* If there is another track in the queue prepare it now. This could
604 * potentially be a just-added random track. */
605 if(qhead
.next
!= &qhead
)
606 prepare(ev
, qhead
.next
);
611 int playing_is_enabled(void) {
612 const char *s
= trackdb_get_global("playing");
614 return !s
|| !strcmp(s
, "yes");
617 void enable_playing(const char *who
, ev_source
*ev
) {
618 trackdb_set_global("playing", "yes", who
);
619 /* Add a random track if necessary. */
624 void disable_playing(const char *who
) {
625 trackdb_set_global("playing", "no", who
);
628 int random_is_enabled(void) {
629 const char *s
= trackdb_get_global("random-play");
631 return !s
|| !strcmp(s
, "yes");
634 void enable_random(const char *who
, ev_source
*ev
) {
635 trackdb_set_global("random-play", "yes", who
);
640 void disable_random(const char *who
) {
641 trackdb_set_global("random-play", "no", who
);
644 void scratch(const char *who
, const char *id
) {
645 struct queue_entry
*q
;
646 struct speaker_message sm
;
649 D(("scratch playing=%p state=%d id=%s playing->id=%s",
651 playing ? playing
->state
: 0,
653 playing ? playing
->id
: "(none)"));
655 && (playing
->state
== playing_started
656 || playing
->state
== playing_paused
)
658 || !strcmp(id
, playing
->id
))) {
659 playing
->state
= playing_scratched
;
660 playing
->scratched
= who ?
xstrdup(who
) : 0;
661 if((pid
= find_player_pid(playing
->id
)) > 0) {
662 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
663 kill(-pid
, config
->signal
);
664 forget_player_pid(playing
->id
);
666 error(0, "could not find PID for %s", playing
->id
);
667 if((playing
->type
& DISORDER_PLAYER_TYPEMASK
) == DISORDER_PLAYER_RAW
) {
668 memset(&sm
, 0, sizeof sm
);
670 strcpy(sm
.id
, playing
->id
);
671 speaker_send(speaker_fd
, &sm
);
672 D(("sending SM_CANCEL for %s", playing
->id
));
674 /* put a scratch track onto the front of the queue (but don't
675 * bother if playing is disabled) */
676 if(playing_is_enabled() && config
->scratch
.n
) {
677 int r
= rand() * (double)config
->scratch
.n
/ (RAND_MAX
+ 1.0);
678 q
= queue_add(config
->scratch
.s
[r
], who
, WHERE_START
);
679 q
->state
= playing_isscratch
;
681 notify_scratch(playing
->track
, playing
->submitter
, who
,
682 time(0) - playing
->played
);
686 void quitting(ev_source
*ev
) {
687 struct queue_entry
*q
;
690 /* Don't start anything new */
692 /* Shut down the current player */
694 if((pid
= find_player_pid(playing
->id
)) > 0) {
695 kill(-pid
, config
->signal
);
696 forget_player_pid(playing
->id
);
698 error(0, "could not find PID for %s", playing
->id
);
699 playing
->state
= playing_quitting
;
702 /* Zap any other players */
703 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
704 if((pid
= find_player_pid(q
->id
)) > 0) {
705 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
706 kill(-pid
, config
->signal
);
707 forget_player_pid(q
->id
);
709 error(0, "could not find PID for %s", q
->id
);
710 /* Don't need the speaker any more */
711 ev_fd_cancel(ev
, ev_read
, speaker_fd
);
715 int pause_playing(const char *who
) {
716 struct speaker_message sm
;
719 /* Can't pause if already paused or if nothing playing. */
720 if(!playing
|| paused
) return 0;
721 switch(playing
->type
& DISORDER_PLAYER_TYPEMASK
) {
722 case DISORDER_PLAYER_STANDALONE
:
723 if(!(playing
->type
& DISORDER_PLAYER_PAUSES
)) {
725 error(0, "cannot pause because player is not powerful enough");
728 if(play_pause(playing
->pl
, &played
, playing
->data
)) {
729 error(0, "player indicates it cannot pause");
732 time(&playing
->lastpaused
);
733 playing
->uptopause
= played
;
734 playing
->lastresumed
= 0;
736 case DISORDER_PLAYER_RAW
:
737 memset(&sm
, 0, sizeof sm
);
739 speaker_send(speaker_fd
, &sm
);
742 if(who
) info("paused by %s", who
);
743 notify_pause(playing
->track
, who
);
745 if(playing
->state
== playing_started
)
746 playing
->state
= playing_paused
;
747 eventlog("state", "pause", (char *)0);
751 void resume_playing(const char *who
) {
752 struct speaker_message sm
;
757 switch(playing
->type
& DISORDER_PLAYER_TYPEMASK
) {
758 case DISORDER_PLAYER_STANDALONE
:
759 if(!playing
->type
& DISORDER_PLAYER_PAUSES
) {
761 /* Shouldn't happen */
764 play_resume(playing
->pl
, playing
->data
);
765 time(&playing
->lastresumed
);
767 case DISORDER_PLAYER_RAW
:
768 memset(&sm
, 0, sizeof sm
);
770 speaker_send(speaker_fd
, &sm
);
773 if(who
) info("resumed by %s", who
);
774 notify_resume(playing
->track
, who
);
775 if(playing
->state
== playing_paused
)
776 playing
->state
= playing_started
;
777 eventlog("state", "resume", (char *)0);