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 if(ev_fd(ev
, ev_read
, speaker_fd
, speaker_readable
, 0, "speaker read") < 0)
132 fatal(0, "error registering speaker socket fd");
135 void speaker_reload(void) {
136 struct speaker_message sm
;
138 memset(&sm
, 0, sizeof sm
);
140 speaker_send(speaker_fd
, &sm
);
143 /* Called when the currently playing track finishes playing. This
144 * might be because the player finished or because the speaker process
146 static void finished(ev_source
*ev
) {
147 D(("finished playing=%p", (void *)playing
));
150 if(playing
->state
!= playing_scratched
)
151 notify_not_scratched(playing
->track
, playing
->submitter
);
152 switch(playing
->state
) {
154 eventlog("completed", playing
->track
, (char *)0);
156 case playing_scratched
:
157 eventlog("scratched", playing
->track
, playing
->scratched
, (char *)0);
160 eventlog("failed", playing
->track
, wstat(playing
->wstat
), (char *)0);
165 queue_played(playing
);
167 forget_player_pid(playing
->id
);
169 /* Try to play something else */
170 /* TODO re-support config->gap? */
175 /* Called when a player terminates. */
176 static int player_finished(ev_source
*ev
,
179 const struct rusage
attribute((unused
)) *rusage
,
181 struct queue_entry
*q
= u
;
183 D(("player_finished pid=%lu status=%#x",
184 (unsigned long)pid
, (unsigned)status
));
185 /* Record that this PID is dead. If we killed the track we might know this
186 * already, but also it might have exited or crashed. Either way we don't
187 * want to end up signalling it. */
188 if(pid
== find_player_pid(q
->id
))
189 forget_player_pid(q
->id
);
191 case playing_unplayed
:
193 /* If this was a pre-prepared track then either it failed or we
194 * deliberately stopped it because it was removed from the queue or moved
195 * down it. So leave it state alone for future use. */
198 /* We actually started playing this track. */
200 if(q
->state
!= playing_scratched
)
201 q
->state
= playing_failed
;
203 q
->state
= playing_ok
;
206 /* Regardless we always report and record the status and do cleanup for
209 error(0, "player for %s %s", q
->track
, wstat(status
));
210 if(q
->type
& DISORDER_PLAYER_PREFORK
)
211 play_cleanup(q
->pl
, q
->data
);
213 /* If this actually was the current track, and does not use the speaker
214 * process, then it must have finished. For raw-output players we will get a
215 * separate notification from the speaker process. */
217 && (q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
222 /* Find the player for Q */
223 static int find_player(const struct queue_entry
*q
) {
226 for(n
= 0; n
< config
->player
.n
; ++n
)
227 if(fnmatch(config
->player
.s
[n
].s
[0], q
->track
, 0) == 0)
229 if(n
>= config
->player
.n
)
235 /* Return values from start() */
236 #define START_OK 0 /**< @brief Succeeded. */
237 #define START_HARDFAIL 1 /**< @brief Track is broken. */
238 #define START_SOFTFAIL 2 /**< @brief Track OK, system (temporarily?) broken */
240 /** @brief Play or prepare @p q
241 * @param ev Event loop
242 * @param q Track to play/prepare
243 * @param prepare_only If true, only prepares track
244 * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
246 static int start(ev_source
*ev
,
247 struct queue_entry
*q
,
252 struct speaker_message sm
;
255 ao_sample_format format
;
259 const char *waitdevice
= 0;
260 const char *const *optv
;
262 struct sockaddr_un addr
;
265 memset(&sm
, 0, sizeof sm
);
266 D(("start %s %d", q
->id
, prepare_only
));
268 /* The track is alraedy prepared */
270 /* We want to run it, since it's prepared the answer is to tell the
271 * speaker to set it off */
272 strcpy(sm
.id
, q
->id
);
274 speaker_send(speaker_fd
, &sm
);
275 D(("sent SM_PLAY for %s", sm
.id
));
279 /* Find the player plugin. */
280 if((n
= find_player(q
)) < 0) return START_HARDFAIL
;
281 if(!(q
->pl
= open_plugin(config
->player
.s
[n
].s
[1], 0)))
282 return START_HARDFAIL
;
283 q
->type
= play_get_type(q
->pl
);
284 /* Can't prepare non-raw tracks. */
286 && (q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
288 /* Call the prefork function. */
289 p
= trackdb_rawpath(q
->track
);
290 if(q
->type
& DISORDER_PLAYER_PREFORK
)
291 if(!(q
->data
= play_prefork(q
->pl
, p
))) {
292 error(0, "prefork function for %s failed", q
->track
);
293 return START_HARDFAIL
;
295 /* Use the second arg as the tag if available (it's probably a command name),
296 * otherwise the module name. */
298 lfd
= logfd(ev
, (config
->player
.s
[n
].s
[2]
299 ? config
->player
.s
[n
].s
[2] : config
->player
.s
[n
].s
[1]));
302 optc
= config
->player
.s
[n
].n
- 2;
303 optv
= (void *)&config
->player
.s
[n
].s
[2];
304 while(optc
> 0 && optv
[0][0] == '-') {
305 if(!strcmp(optv
[0], "--")) {
310 if(!strcmp(optv
[0], "--wait-for-device")
311 || !strncmp(optv
[0], "--wait-for-device=", 18)) {
312 if((waitdevice
= strchr(optv
[0], '='))) {
315 waitdevice
= ""; /* use default */
319 error(0, "unknown option %s", optv
[0]);
320 return START_HARDFAIL
;
323 switch(pid
= fork()) {
326 progname
= "disorderd-fork";
327 ev_signal_atfork(ev
);
328 signal(SIGPIPE
, SIG_DFL
);
332 xclose(lfd
); /* tidy up */
335 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) == DISORDER_PLAYER_RAW
) {
336 /* "Raw" format players always have their output send down a pipe
337 * to the disorder-normalize process. This will connect to the
338 * speaker process to actually play the audio data.
340 /* np will be the pipe to disorder-normalize */
341 if(socketpair(PF_UNIX
, SOCK_STREAM
, 0, np
) < 0)
342 fatal(errno
, "error calling socketpair");
343 /* Beware of the Leopard! On OS X 10.5.x, the order of the shutdown
344 * calls here DOES MATTER. If you do the SHUT_WR first then the SHUT_RD
345 * fails with "Socket is not connected". I think this is a bug but
346 * provided implementors either don't care about the order or all agree
347 * about the order, choosing the reliable order is an adequate
349 xshutdown(np
[1], SHUT_RD
); /* decoder writes to np[1] */
350 xshutdown(np
[0], SHUT_WR
); /* normalize reads from np[0] */
353 /* Start disorder-normalize */
354 if(!(npid
= xfork())) {
356 /* Connect to the speaker process */
357 memset(&addr
, 0, sizeof addr
);
358 addr
.sun_family
= AF_UNIX
;
359 snprintf(addr
.sun_path
, sizeof addr
.sun_path
,
360 "%s/speaker/socket", config
->home
);
361 sfd
= xsocket(PF_UNIX
, SOCK_STREAM
, 0);
362 if(connect(sfd
, (const struct sockaddr
*)&addr
, sizeof addr
) < 0)
363 fatal(errno
, "connecting to %s", addr
.sun_path
);
365 if(write(sfd
, &l
, sizeof l
) < 0
366 || write(sfd
, q
->id
, l
) < 0)
367 fatal(errno
, "writing to %s", addr
.sun_path
);
369 if (read(sfd
, &l
, 1) < 0)
370 fatal(errno
, "reading ack from %s", addr
.sun_path
);
377 /* Ask the speaker to actually start playing the track; we do it here
378 * so it's definitely after ack. */
380 strcpy(sm
.id
, q
->id
);
382 speaker_send(speaker_fd
, &sm
);
383 D(("sent SM_PLAY for %s", sm
.id
));
385 /* TODO stderr shouldn't be redirected for disorder-normalize
386 * (but it should be for play_track() */
387 execlp("disorder-normalize", "disorder-normalize",
388 log_default
== &log_syslog ?
"--syslog" : "--no-syslog",
389 "--config", configfile
,
391 fatal(errno
, "executing disorder-normalize");
392 /* end of the innermost fork */
395 /* end of the middle fork */
397 /* Wait for the middle fork to finish */
398 while(waitpid(npid
, &n
, 0) < 0 && errno
== EINTR
)
400 /* Pass the file descriptor to the driver in an environment
402 snprintf(buffer
, sizeof buffer
, "DISORDER_RAW_FD=%d", np
[1]);
403 if(putenv(buffer
) < 0)
404 fatal(errno
, "error calling putenv");
405 /* Close all the FDs we don't need */
411 n
= ao_driver_id(waitdevice
);
413 fatal(0, "invalid libao driver: %s", optv
[0]);
415 n
= ao_default_driver_id();
416 /* Make up a format. */
417 memset(&format
, 0, sizeof format
);
421 format
.byte_format
= AO_FMT_NATIVE
;
424 ts
.tv_nsec
= 100000000; /* 0.1s */
425 while((device
= ao_open_live(n
, &format
, 0)) == 0 && retries
-- > 0)
436 error(errno
, "error calling fork");
437 if(q
->type
& DISORDER_PLAYER_PREFORK
)
438 play_cleanup(q
->pl
, q
->data
); /* else would leak */
441 return START_SOFTFAIL
;
443 store_player_pid(q
->id
, pid
);
448 ev_child(ev
, pid
, 0, player_finished
, q
);
449 D(("player subprocess ID %lu", (unsigned long)pid
));
453 int prepare(ev_source
*ev
,
454 struct queue_entry
*q
) {
457 /* Find the player plugin */
458 if(find_player_pid(q
->id
) > 0) return 0; /* Already going. */
459 if((n
= find_player(q
)) < 0) return -1; /* No player */
460 q
->pl
= open_plugin(config
->player
.s
[n
].s
[1], 0); /* No player */
461 q
->type
= play_get_type(q
->pl
);
462 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
463 return 0; /* Not a raw player */
464 return start(ev
, q
, 1/*prepare_only*/); /* Prepare it */
467 void abandon(ev_source
attribute((unused
)) *ev
,
468 struct queue_entry
*q
) {
469 struct speaker_message sm
;
470 pid_t pid
= find_player_pid(q
->id
);
472 if(pid
< 0) return; /* Not prepared. */
473 if((q
->type
& DISORDER_PLAYER_TYPEMASK
) != DISORDER_PLAYER_RAW
)
474 return; /* Not a raw player. */
475 /* Terminate the player. */
476 kill(-pid
, config
->signal
);
477 forget_player_pid(q
->id
);
478 /* Cancel the track. */
479 memset(&sm
, 0, sizeof sm
);
481 strcpy(sm
.id
, q
->id
);
482 speaker_send(speaker_fd
, &sm
);
485 /** @brief Called with a new random track
486 * @param ev Event loop
487 * @param track Track name
489 static void chosen_random_track(ev_source
*ev
,
491 struct queue_entry
*q
;
495 /* Add the track to the queue */
496 q
= queue_add(track
, 0, WHERE_END
, origin_random
);
497 D(("picked %p (%s) at random", (void *)q
, q
->track
));
499 /* Maybe a track can now be played */
503 /** @brief Maybe add a randomly chosen track
504 * @param ev Event loop
506 void add_random_track(ev_source
*ev
) {
507 struct queue_entry
*q
;
510 /* If random play is not enabled then do nothing. */
511 if(shutting_down
|| !random_is_enabled())
513 /* Count how big the queue is */
514 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
516 /* If it's smaller than the desired size then add a track */
517 if(qlen
< config
->queue_pad
)
518 trackdb_request_random(ev
, chosen_random_track
);
521 /* try to play a track */
522 void play(ev_source
*ev
) {
523 struct queue_entry
*q
;
524 int random_enabled
= random_is_enabled();
526 D(("play playing=%p", (void *)playing
));
527 if(shutting_down
|| playing
|| !playing_is_enabled()) return;
528 /* See if there's anything to play */
529 if(qhead
.next
== &qhead
) {
530 /* Queue is empty. We could just wait around since there are periodic
531 * attempts to add a random track anyway. However they are rarer than
532 * attempts to force a track so we initiate one now. */
533 add_random_track(ev
);
536 /* There must be at least one track in the queue. */
538 /* If random play is disabled but the track is a non-adopted random one
539 * then don't play it. play() will be called again when random play is
541 if(!random_enabled
&& q
->origin
== origin_random
)
543 D(("taken %p (%s) from queue", (void *)q
, q
->track
));
544 /* Try to start playing. */
545 switch(start(ev
, q
, 0/*!prepare_only*/)) {
547 if(q
== qhead
.next
) {
548 queue_remove(q
, 0); /* Abandon this track. */
552 /* Oh well, try the next one */
556 /* We'll try the same track again shortly. */
559 if(q
== qhead
.next
) {
564 time(&playing
->played
);
565 playing
->state
= playing_started
;
566 notify_play(playing
->track
, playing
->submitter
);
567 eventlog("playing", playing
->track
,
568 playing
->submitter ? playing
->submitter
: (const char *)0,
570 /* Maybe add a random track. */
571 add_random_track(ev
);
572 /* If there is another track in the queue prepare it now. This could
573 * potentially be a just-added random track. */
574 if(qhead
.next
!= &qhead
)
575 prepare(ev
, qhead
.next
);
580 int playing_is_enabled(void) {
581 const char *s
= trackdb_get_global("playing");
583 return !s
|| !strcmp(s
, "yes");
586 void enable_playing(const char *who
, ev_source
*ev
) {
587 trackdb_set_global("playing", "yes", who
);
588 /* Add a random track if necessary. */
589 add_random_track(ev
);
593 void disable_playing(const char *who
) {
594 trackdb_set_global("playing", "no", who
);
597 int random_is_enabled(void) {
598 const char *s
= trackdb_get_global("random-play");
600 return !s
|| !strcmp(s
, "yes");
603 void enable_random(const char *who
, ev_source
*ev
) {
604 trackdb_set_global("random-play", "yes", who
);
605 add_random_track(ev
);
609 void disable_random(const char *who
) {
610 trackdb_set_global("random-play", "no", who
);
613 void scratch(const char *who
, const char *id
) {
614 struct queue_entry
*q
;
615 struct speaker_message sm
;
618 D(("scratch playing=%p state=%d id=%s playing->id=%s",
620 playing ? playing
->state
: 0,
622 playing ? playing
->id
: "(none)"));
624 && (playing
->state
== playing_started
625 || playing
->state
== playing_paused
)
627 || !strcmp(id
, playing
->id
))) {
628 playing
->state
= playing_scratched
;
629 playing
->scratched
= who ?
xstrdup(who
) : 0;
630 if((pid
= find_player_pid(playing
->id
)) > 0) {
631 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
632 kill(-pid
, config
->signal
);
633 forget_player_pid(playing
->id
);
635 error(0, "could not find PID for %s", playing
->id
);
636 if((playing
->type
& DISORDER_PLAYER_TYPEMASK
) == DISORDER_PLAYER_RAW
) {
637 memset(&sm
, 0, sizeof sm
);
639 strcpy(sm
.id
, playing
->id
);
640 speaker_send(speaker_fd
, &sm
);
641 D(("sending SM_CANCEL for %s", playing
->id
));
643 /* put a scratch track onto the front of the queue (but don't
644 * bother if playing is disabled) */
645 if(playing_is_enabled() && config
->scratch
.n
) {
646 int r
= rand() * (double)config
->scratch
.n
/ (RAND_MAX
+ 1.0);
647 q
= queue_add(config
->scratch
.s
[r
], who
, WHERE_START
, origin_scratch
);
649 notify_scratch(playing
->track
, playing
->submitter
, who
,
650 time(0) - playing
->played
);
654 void quitting(ev_source
*ev
) {
655 struct queue_entry
*q
;
658 /* Don't start anything new */
660 /* Shut down the current player */
662 if((pid
= find_player_pid(playing
->id
)) > 0) {
663 kill(-pid
, config
->signal
);
664 forget_player_pid(playing
->id
);
666 error(0, "could not find PID for %s", playing
->id
);
667 playing
->state
= playing_quitting
;
670 /* Zap any other players */
671 for(q
= qhead
.next
; q
!= &qhead
; q
= q
->next
)
672 if((pid
= find_player_pid(q
->id
)) > 0) {
673 D(("kill -%d %lu", config
->signal
, (unsigned long)pid
));
674 kill(-pid
, config
->signal
);
675 forget_player_pid(q
->id
);
677 error(0, "could not find PID for %s", q
->id
);
678 /* Don't need the speaker any more */
679 ev_fd_cancel(ev
, ev_read
, speaker_fd
);
683 int pause_playing(const char *who
) {
684 struct speaker_message sm
;
687 /* Can't pause if already paused or if nothing playing. */
688 if(!playing
|| paused
) return 0;
689 switch(playing
->type
& DISORDER_PLAYER_TYPEMASK
) {
690 case DISORDER_PLAYER_STANDALONE
:
691 if(!(playing
->type
& DISORDER_PLAYER_PAUSES
)) {
693 error(0, "cannot pause because player is not powerful enough");
696 if(play_pause(playing
->pl
, &played
, playing
->data
)) {
697 error(0, "player indicates it cannot pause");
700 time(&playing
->lastpaused
);
701 playing
->uptopause
= played
;
702 playing
->lastresumed
= 0;
704 case DISORDER_PLAYER_RAW
:
705 memset(&sm
, 0, sizeof sm
);
707 speaker_send(speaker_fd
, &sm
);
710 if(who
) info("paused by %s", who
);
711 notify_pause(playing
->track
, who
);
713 if(playing
->state
== playing_started
)
714 playing
->state
= playing_paused
;
715 eventlog("state", "pause", (char *)0);
719 void resume_playing(const char *who
) {
720 struct speaker_message sm
;
725 switch(playing
->type
& DISORDER_PLAYER_TYPEMASK
) {
726 case DISORDER_PLAYER_STANDALONE
:
727 if(!playing
->type
& DISORDER_PLAYER_PAUSES
) {
729 /* Shouldn't happen */
732 play_resume(playing
->pl
, playing
->data
);
733 time(&playing
->lastresumed
);
735 case DISORDER_PLAYER_RAW
:
736 memset(&sm
, 0, sizeof sm
);
738 speaker_send(speaker_fd
, &sm
);
741 if(who
) info("resumed by %s", who
);
742 notify_resume(playing
->track
, who
);
743 if(playing
->state
== playing_paused
)
744 playing
->state
= playing_started
;
745 eventlog("state", "resume", (char *)0);