chiark / gitweb /
More comments.
[disorder] / server / play.c
CommitLineData
460b9539 1/*
2 * This file is part of DisOrder.
16fb2830 3 * Copyright (C) 2004-2009 Richard Kettlewell
460b9539 4 *
e7eb3a27 5 * This program is free software: you can redistribute it and/or modify
460b9539 6 * it under the terms of the GNU General Public License as published by
e7eb3a27 7 * the Free Software Foundation, either version 3 of the License, or
460b9539 8 * (at your option) any later version.
9 *
e7eb3a27
RK
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.
14 *
460b9539 15 * You should have received a copy of the GNU General Public License
e7eb3a27 16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
460b9539 17 */
132a5a4a
RK
18/** @file server/play.c
19 * @brief Playing tracks
20 */
460b9539 21
05b75f8d 22#include "disorder-server.h"
460b9539 23#include <ao/ao.h>
460b9539 24
25#define SPEAKER "disorder-speaker"
26
16fb2830 27/** @brief The current playing track or NULL */
460b9539 28struct queue_entry *playing;
16fb2830
RK
29
30/** @brief Set when paused */
460b9539 31int paused;
32
33static void finished(ev_source *ev);
34
16fb2830 35/** @brief File descriptor of our end of the socket to the speaker */
460b9539 36static int speaker_fd = -1;
16fb2830
RK
37
38/** @brief Mapping of track IDs to associated decoder process IDs */
460b9539 39static hash *player_pids;
16fb2830
RK
40
41/** @brief Set when shutting down */
460b9539 42static int shutting_down;
43
16fb2830 44/** @brief Remember a player's PID */
460b9539 45static void store_player_pid(const char *id, pid_t pid) {
46 if(!player_pids) player_pids = hash_new(sizeof (pid_t));
47 hash_add(player_pids, id, &pid, HASH_INSERT_OR_REPLACE);
48}
49
16fb2830 50/** @brief Find a player's PID */
460b9539 51static pid_t find_player_pid(const char *id) {
52 pid_t *pidp;
53
54 if(player_pids && (pidp = hash_find(player_pids, id))) return *pidp;
55 return -1;
56}
57
16fb2830
RK
58/** @brief Discard a player's ID->PID mappin
59 *
60 * Used when the player terminates.
61 */
460b9539 62static void forget_player_pid(const char *id) {
63 if(player_pids) hash_remove(player_pids, id);
64}
65
16fb2830
RK
66/** @brief Called when speaker process terminates
67 *
68 * Currently kills of DisOrder completely. A future version could terminate
69 * the speaker when nothing was going on, or recover from failures, though any
70 * tracks with decoders already started would need to have them restarted.
71 */
460b9539 72static int speaker_terminated(ev_source attribute((unused)) *ev,
73 pid_t attribute((unused)) pid,
74 int attribute((unused)) status,
75 const struct rusage attribute((unused)) *rusage,
76 void attribute((unused)) *u) {
0213d16c 77 fatal(0, "speaker subprocess %s",
2a6c7b79 78 wstat(status));
460b9539 79}
80
16fb2830 81/** @brief Called when we get a message from the speaker process */
460b9539 82static int speaker_readable(ev_source *ev, int fd,
83 void attribute((unused)) *u) {
84 struct speaker_message sm;
84aa9f93 85 int ret = speaker_recv(fd, &sm);
460b9539 86
87 if(ret < 0) return 0; /* EAGAIN */
88 if(!ret) { /* EOF */
89 ev_fd_cancel(ev, ev_read, fd);
90 return 0;
91 }
92 switch(sm.type) {
93 case SM_PAUSED:
94 /* track ID is paused, DATA seconds played */
95 D(("SM_PAUSED %s %ld", sm.id, sm.data));
96 playing->sofar = sm.data;
97 break;
819f5988
RK
98 case SM_FINISHED: /* scratched the playing track */
99 case SM_STILLBORN: /* scratched too early */
100 case SM_UNKNOWN: /* scratched WAY too early */
2b2a5fed
RK
101 if(playing && !strcmp(sm.id, playing->id))
102 finished(ev);
103 break;
460b9539 104 case SM_PLAYING:
105 /* track ID is playing, DATA seconds played */
106 D(("SM_PLAYING %s %ld", sm.id, sm.data));
107 playing->sofar = sm.data;
108 break;
109 default:
16fb2830 110 error(0, "unknown speaker message type %d", sm.type);
460b9539 111 }
112 return 0;
113}
114
16fb2830 115/** @brief Initialize the speaker process */
460b9539 116void speaker_setup(ev_source *ev) {
4387f694 117 int sp[2];
460b9539 118 pid_t pid;
937be4c0 119 struct speaker_message sm;
460b9539 120
121 if(socketpair(PF_UNIX, SOCK_DGRAM, 0, sp) < 0)
122 fatal(errno, "error calling socketpair");
460b9539 123 if(!(pid = xfork())) {
124 exitfn = _exit;
125 ev_signal_atfork(ev);
126 xdup2(sp[0], 0);
127 xdup2(sp[0], 1);
128 xclose(sp[0]);
129 xclose(sp[1]);
460b9539 130 signal(SIGPIPE, SIG_DFL);
131#if 0
132 execlp("valgrind", "valgrind", SPEAKER, "--config", configfile,
0ca6d097
RK
133 debugging ? "--debug" : "--no-debug",
134 log_default == &log_syslog ? "--syslog" : "--no-syslog",
135 (char *)0);
460b9539 136#else
137 execlp(SPEAKER, SPEAKER, "--config", configfile,
0ca6d097
RK
138 debugging ? "--debug" : "--no-debug",
139 log_default == &log_syslog ? "--syslog" : "--no-syslog",
140 (char *)0);
460b9539 141#endif
142 fatal(errno, "error invoking %s", SPEAKER);
143 }
144 ev_child(ev, pid, 0, speaker_terminated, 0);
145 speaker_fd = sp[1];
146 xclose(sp[0]);
147 cloexec(speaker_fd);
937be4c0
RK
148 /* Wait for the speaker to be ready */
149 speaker_recv(speaker_fd, &sm);
150 nonblock(speaker_fd);
31e2a93e
RK
151 if(ev_fd(ev, ev_read, speaker_fd, speaker_readable, 0, "speaker read") < 0)
152 fatal(0, "error registering speaker socket fd");
460b9539 153}
154
16fb2830 155/** @brief Tell the speaker to reload its configuration */
460b9539 156void speaker_reload(void) {
157 struct speaker_message sm;
158
159 memset(&sm, 0, sizeof sm);
160 sm.type = SM_RELOAD;
84aa9f93 161 speaker_send(speaker_fd, &sm);
460b9539 162}
163
16fb2830
RK
164/** @brief Called when the currently playing track finishes playing
165 * @param ev Event loop or NULL
166 *
167 * There are three places this is called from:
168 *
169 * 1) speaker_readable(), when the speaker tells us the playing track finished.
170 * (Technically the speaker lies a little to arrange for gapless play.)
171 *
172 * 2) player_finished(), when the player for a non-raw track (i.e. one that
173 * does not use the speaker) finishes.
174 *
175 * 3) quitting(), after signalling the decoder or player but possible before it
176 * has actually terminated. In this case @p ev is NULL, inhibiting any further
177 * attempt to play anything.
178 */
460b9539 179static void finished(ev_source *ev) {
180 D(("finished playing=%p", (void *)playing));
181 if(!playing)
182 return;
183 if(playing->state != playing_scratched)
184 notify_not_scratched(playing->track, playing->submitter);
185 switch(playing->state) {
186 case playing_ok:
187 eventlog("completed", playing->track, (char *)0);
188 break;
189 case playing_scratched:
190 eventlog("scratched", playing->track, playing->scratched, (char *)0);
191 break;
192 case playing_failed:
193 eventlog("failed", playing->track, wstat(playing->wstat), (char *)0);
194 break;
195 default:
196 break;
197 }
198 queue_played(playing);
199 recent_write();
200 forget_player_pid(playing->id);
201 playing = 0;
49a773eb
RK
202 /* Try to play something else */
203 /* TODO re-support config->gap? */
204 if(ev)
205 play(ev);
460b9539 206}
207
16fb2830
RK
208/** @brief Called when a player or decoder process terminates
209 *
210 * This is called when a decoder process terminates (which might actually be
211 * some time before the speaker reports it as finished) or when a non-raw
212 * (i.e. non-speaker) player terminates. In the latter case it's imaginable
213 * that the OS has buffered the last few samples.
214 *
215 */
460b9539 216static int player_finished(ev_source *ev,
217 pid_t pid,
218 int status,
219 const struct rusage attribute((unused)) *rusage,
220 void *u) {
221 struct queue_entry *q = u;
222
223 D(("player_finished pid=%lu status=%#x",
224 (unsigned long)pid, (unsigned)status));
225 /* Record that this PID is dead. If we killed the track we might know this
226 * already, but also it might have exited or crashed. Either way we don't
227 * want to end up signalling it. */
228 if(pid == find_player_pid(q->id))
229 forget_player_pid(q->id);
230 switch(q->state) {
231 case playing_unplayed:
232 case playing_random:
84aa9f93 233 /* If this was a pre-prepared track then either it failed or we
16fb2830
RK
234 * deliberately stopped it: it might have been removed from the queue, or
235 * moved down the queue, or the speaker might be on a break. So we leave
236 * it state alone for future use.
237 */
460b9539 238 break;
239 default:
240 /* We actually started playing this track. */
241 if(status) {
16fb2830 242 /* Don't override 'scratched' with 'failed'. */
460b9539 243 if(q->state != playing_scratched)
244 q->state = playing_failed;
245 } else
246 q->state = playing_ok;
247 break;
248 }
249 /* Regardless we always report and record the status and do cleanup for
250 * prefork calls. */
251 if(status)
252 error(0, "player for %s %s", q->track, wstat(status));
253 if(q->type & DISORDER_PLAYER_PREFORK)
254 play_cleanup(q->pl, q->data);
255 q->wstat = status;
256 /* If this actually was the current track, and does not use the speaker
257 * process, then it must have finished. For raw-output players we will get a
258 * separate notification from the speaker process. */
259 if(q == playing
260 && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
261 finished(ev);
262 return 0;
263}
264
16fb2830 265/** @brief Find the player for @p q */
460b9539 266static int find_player(const struct queue_entry *q) {
267 int n;
268
269 for(n = 0; n < config->player.n; ++n)
270 if(fnmatch(config->player.s[n].s[0], q->track, 0) == 0)
271 break;
272 if(n >= config->player.n)
273 return -1;
274 else
275 return n;
276}
277
278/* Return values from start() */
16fb2830
RK
279#define START_OK 0 /**< @brief Succeeded. */
280#define START_HARDFAIL 1 /**< @brief Track is broken. */
281#define START_SOFTFAIL 2 /**< @brief Track OK, system (temporarily?) broken */
460b9539 282
84aa9f93
RK
283/** @brief Play or prepare @p q
284 * @param ev Event loop
285 * @param q Track to play/prepare
286 * @param prepare_only If true, only prepares track
3149c1e2 287 * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
16fb2830
RK
288 *
289 * TODO: probably ought to be split up into separate prepare() and start()
290 * operations, the latter calling the former if necessary and perhaps the two
291 * sharing some subprocess creation logic.
292 *
293 * "Preparing" a track means starting a background decoder and connecting it to
294 * the speaker process. Obviously this only applies to raw-format
295 * (i.e. speaker-using) players.
84aa9f93 296 */
460b9539 297static int start(ev_source *ev,
298 struct queue_entry *q,
84aa9f93 299 int prepare_only) {
460b9539 300 int n, lfd;
301 const char *p;
84aa9f93 302 int np[2], sfd;
460b9539 303 struct speaker_message sm;
304 char buffer[64];
305 int optc;
306 ao_sample_format format;
307 ao_device *device;
308 int retries;
309 struct timespec ts;
310 const char *waitdevice = 0;
311 const char *const *optv;
6d2d327c 312 pid_t pid, npid;
84aa9f93
RK
313 struct sockaddr_un addr;
314 uint32_t l;
460b9539 315
316 memset(&sm, 0, sizeof sm);
84aa9f93 317 D(("start %s %d", q->id, prepare_only));
66bb2e02 318 if(q->prepared) {
16fb2830 319 /* The track is already prepared */
66bb2e02
RK
320 if(!prepare_only) {
321 /* We want to run it, since it's prepared the answer is to tell the
322 * speaker to set it off */
323 strcpy(sm.id, q->id);
324 sm.type = SM_PLAY;
325 speaker_send(speaker_fd, &sm);
326 D(("sent SM_PLAY for %s", sm.id));
327 }
460b9539 328 return START_OK;
329 }
330 /* Find the player plugin. */
331 if((n = find_player(q)) < 0) return START_HARDFAIL;
332 if(!(q->pl = open_plugin(config->player.s[n].s[1], 0)))
333 return START_HARDFAIL;
334 q->type = play_get_type(q->pl);
335 /* Can't prepare non-raw tracks. */
84aa9f93 336 if(prepare_only
460b9539 337 && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
338 return START_OK;
16fb2830
RK
339 /* Call the prefork function in the player module. None of the built-in
340 * modules use this so it's not well tested, unfortunately. */
460b9539 341 p = trackdb_rawpath(q->track);
342 if(q->type & DISORDER_PLAYER_PREFORK)
343 if(!(q->data = play_prefork(q->pl, p))) {
344 error(0, "prefork function for %s failed", q->track);
345 return START_HARDFAIL;
346 }
16fb2830
RK
347 /* Capture the player/decoder's stderr and feed it into our logs.
348 *
349 * Use the second arg as the tag if available (it's probably a command name),
460b9539 350 * otherwise the module name. */
e99d42b1 351 if(!isatty(2))
352 lfd = logfd(ev, (config->player.s[n].s[2]
353 ? config->player.s[n].s[2] : config->player.s[n].s[1]));
354 else
355 lfd = -1;
16fb2830 356 /* Parse player arguments */
460b9539 357 optc = config->player.s[n].n - 2;
358 optv = (void *)&config->player.s[n].s[2];
359 while(optc > 0 && optv[0][0] == '-') {
360 if(!strcmp(optv[0], "--")) {
361 ++optv;
362 --optc;
363 break;
364 }
365 if(!strcmp(optv[0], "--wait-for-device")
366 || !strncmp(optv[0], "--wait-for-device=", 18)) {
367 if((waitdevice = strchr(optv[0], '='))) {
368 ++waitdevice;
369 } else
370 waitdevice = ""; /* use default */
371 ++optv;
372 --optc;
373 } else {
374 error(0, "unknown option %s", optv[0]);
375 return START_HARDFAIL;
376 }
377 }
16fb2830 378 /* Create the subprocess */
460b9539 379 switch(pid = fork()) {
16fb2830
RK
380 case 0:
381 /* Child of disorderd */
460b9539 382 exitfn = _exit;
ba3d1d36 383 progname = "disorderd-fork";
460b9539 384 ev_signal_atfork(ev);
385 signal(SIGPIPE, SIG_DFL);
16fb2830 386 /* Send our log output to DisOrder's logs */
e99d42b1 387 if(lfd != -1) {
388 xdup2(lfd, 1);
389 xdup2(lfd, 2);
390 xclose(lfd); /* tidy up */
391 }
16fb2830 392 /* Create a new process group, ID = child PID */
460b9539 393 setpgid(0, 0);
394 if((q->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
84aa9f93
RK
395 /* "Raw" format players always have their output send down a pipe
396 * to the disorder-normalize process. This will connect to the
397 * speaker process to actually play the audio data.
6d2d327c
RK
398 */
399 /* np will be the pipe to disorder-normalize */
400 if(socketpair(PF_UNIX, SOCK_STREAM, 0, np) < 0)
401 fatal(errno, "error calling socketpair");
ba3d1d36
RK
402 /* Beware of the Leopard! On OS X 10.5.x, the order of the shutdown
403 * calls here DOES MATTER. If you do the SHUT_WR first then the SHUT_RD
af7a85b7 404 * fails with "Socket is not connected". I think this is a bug but
ba3d1d36
RK
405 * provided implementors either don't care about the order or all agree
406 * about the order, choosing the reliable order is an adequate
407 * workaround. */
6d2d327c 408 xshutdown(np[1], SHUT_RD); /* decoder writes to np[1] */
ba3d1d36 409 xshutdown(np[0], SHUT_WR); /* normalize reads from np[0] */
937be4c0
RK
410 blocking(np[0]);
411 blocking(np[1]);
16fb2830
RK
412 /* Start disorder-normalize. We double-fork so that nothing has to wait
413 * for disorder-normalize. */
6d2d327c 414 if(!(npid = xfork())) {
16fb2830 415 /* Grandchild of disorderd */
6d2d327c 416 if(!xfork()) {
16fb2830 417 /* Great-grandchild of disorderd */
84aa9f93
RK
418 /* Connect to the speaker process */
419 memset(&addr, 0, sizeof addr);
420 addr.sun_family = AF_UNIX;
421 snprintf(addr.sun_path, sizeof addr.sun_path,
85cb23d7 422 "%s/speaker/socket", config->home);
84aa9f93 423 sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
dc450d30 424 if(connect(sfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
84aa9f93 425 fatal(errno, "connecting to %s", addr.sun_path);
16fb2830 426 /* Send the ID, with a NATIVE-ENDIAN 32 bit length */
84aa9f93
RK
427 l = strlen(q->id);
428 if(write(sfd, &l, sizeof l) < 0
429 || write(sfd, q->id, l) < 0)
430 fatal(errno, "writing to %s", addr.sun_path);
431 /* Await the ack */
918393ff
RK
432 if (read(sfd, &l, 1) < 0)
433 fatal(errno, "reading ack from %s", addr.sun_path);
84aa9f93 434 /* Plumbing */
6d2d327c 435 xdup2(np[0], 0);
84aa9f93 436 xdup2(sfd, 1);
6d2d327c
RK
437 xclose(np[0]);
438 xclose(np[1]);
84aa9f93
RK
439 xclose(sfd);
440 /* Ask the speaker to actually start playing the track; we do it here
16fb2830
RK
441 * so it's definitely after ack.
442 *
443 * This is actually insufficient. If the track is prepared and then
444 * very shortly afterwards played, then the race we're trying to
445 * avoid here will still exist. So either the speaker must cope with
446 * SM_PLAY before connection has arrived (in which case we might as
447 * well move the SM_PLAY somewhere saner) or we must do more work
448 * here to avoid the race.
449 *
450 * In fact the current speaker can indeed cope with SM_PLAY before
451 * the connection arrives. So this code can probably be moved
452 * somewhere saner in due course. TODO!
453 */
84aa9f93
RK
454 if(!prepare_only) {
455 strcpy(sm.id, q->id);
456 sm.type = SM_PLAY;
457 speaker_send(speaker_fd, &sm);
458 D(("sent SM_PLAY for %s", sm.id));
459 }
4387f694
RK
460 /* TODO stderr shouldn't be redirected for disorder-normalize
461 * (but it should be for play_track() */
b44ca625
RK
462 execlp("disorder-normalize", "disorder-normalize",
463 log_default == &log_syslog ? "--syslog" : "--no-syslog",
816e6088 464 "--config", configfile,
b44ca625 465 (char *)0);
6d2d327c 466 fatal(errno, "executing disorder-normalize");
16fb2830 467 /* End of the great-grandchild of disorderd */
6d2d327c 468 }
16fb2830 469 /* Back in the grandchild of disorderd */
6d2d327c 470 _exit(0);
16fb2830 471 /* End of the grandchild of disorderd */
6d2d327c 472 }
16fb2830
RK
473 /* Back in the child of disorderd */
474 /* Wait for the grandchild of disordered to finish */
84aa9f93
RK
475 while(waitpid(npid, &n, 0) < 0 && errno == EINTR)
476 ;
460b9539 477 /* Pass the file descriptor to the driver in an environment
478 * variable. */
6d2d327c 479 snprintf(buffer, sizeof buffer, "DISORDER_RAW_FD=%d", np[1]);
460b9539 480 if(putenv(buffer) < 0)
481 fatal(errno, "error calling putenv");
6d2d327c 482 /* Close all the FDs we don't need */
6d2d327c 483 xclose(np[0]);
460b9539 484 }
16fb2830
RK
485 /* Wait for a device to clear. This ugliness is now deprecated and will
486 * eventually be removed. */
460b9539 487 if(waitdevice) {
488 ao_initialize();
489 if(*waitdevice) {
490 n = ao_driver_id(waitdevice);
491 if(n == -1)
492 fatal(0, "invalid libao driver: %s", optv[0]);
493 } else
494 n = ao_default_driver_id();
495 /* Make up a format. */
496 memset(&format, 0, sizeof format);
497 format.bits = 8;
498 format.rate = 44100;
499 format.channels = 1;
500 format.byte_format = AO_FMT_NATIVE;
501 retries = 20;
502 ts.tv_sec = 0;
503 ts.tv_nsec = 100000000; /* 0.1s */
504 while((device = ao_open_live(n, &format, 0)) == 0 && retries-- > 0)
505 nanosleep(&ts, 0);
506 if(device)
507 ao_close(device);
508 }
509 play_track(q->pl,
510 optv, optc,
511 p,
512 q->track);
16fb2830 513 /* End of child of disorderd */
460b9539 514 _exit(0);
16fb2830
RK
515 case -1:
516 /* Back in disorderd (child could not be created) */
460b9539 517 error(errno, "error calling fork");
518 if(q->type & DISORDER_PLAYER_PREFORK)
519 play_cleanup(q->pl, q->data); /* else would leak */
e99d42b1 520 if(lfd != -1)
521 xclose(lfd);
460b9539 522 return START_SOFTFAIL;
523 }
16fb2830
RK
524 /* Back in disorderd (child was created) */
525 /* Remmber the PID */
460b9539 526 store_player_pid(q->id, pid);
16fb2830
RK
527 /* This track is prepared. (Non-raw tracks are by implication prepared as
528 * soon as they are playing, but really the question doesn't make much sense
529 * for them.) */
66bb2e02 530 q->prepared = 1;
e99d42b1 531 if(lfd != -1)
532 xclose(lfd);
16fb2830
RK
533 /* Set the child's process group ID.
534 *
535 * But wait, didn't we already set it in the child? Yes, but it's possible
536 * that we'll need to address it by process group ID before it gets that far,
537 * so we set it here too. One or the other may fail but as long as one
538 * succeeds that's fine.
539 */
460b9539 540 setpgid(pid, pid);
16fb2830 541 /* Ask the event loop to tell us when the child terminates */
460b9539 542 ev_child(ev, pid, 0, player_finished, q);
543 D(("player subprocess ID %lu", (unsigned long)pid));
544 return START_OK;
545}
546
16fb2830
RK
547/** @brief Prepare a track for later play
548 *
549 * Only applies to raw-format (speaker-using) players.
550 */
460b9539 551int prepare(ev_source *ev,
552 struct queue_entry *q) {
553 int n;
554
555 /* Find the player plugin */
556 if(find_player_pid(q->id) > 0) return 0; /* Already going. */
557 if((n = find_player(q)) < 0) return -1; /* No player */
558 q->pl = open_plugin(config->player.s[n].s[1], 0); /* No player */
559 q->type = play_get_type(q->pl);
560 if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
561 return 0; /* Not a raw player */
84aa9f93 562 return start(ev, q, 1/*prepare_only*/); /* Prepare it */
460b9539 563}
564
16fb2830
RK
565/** @brief Abandon a queue entry
566 *
567 * Called from c_remove() (but NOT when scratching a track). Only does
568 * anything to raw-format tracks. Terminates the background decoder and tells
569 * the speaker process to cancel the track.
570 */
460b9539 571void abandon(ev_source attribute((unused)) *ev,
572 struct queue_entry *q) {
573 struct speaker_message sm;
574 pid_t pid = find_player_pid(q->id);
575
576 if(pid < 0) return; /* Not prepared. */
577 if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
578 return; /* Not a raw player. */
579 /* Terminate the player. */
580 kill(-pid, config->signal);
581 forget_player_pid(q->id);
582 /* Cancel the track. */
583 memset(&sm, 0, sizeof sm);
584 sm.type = SM_CANCEL;
585 strcpy(sm.id, q->id);
84aa9f93 586 speaker_send(speaker_fd, &sm);
460b9539 587}
588
49a773eb 589/** @brief Called with a new random track
59cf25c4 590 * @param ev Event loop
49a773eb
RK
591 * @param track Track name
592 */
593static void chosen_random_track(ev_source *ev,
594 const char *track) {
595 struct queue_entry *q;
596
597 if(!track)
598 return;
599 /* Add the track to the queue */
2dc2f478 600 q = queue_add(track, 0, WHERE_END, origin_random);
49a773eb
RK
601 D(("picked %p (%s) at random", (void *)q, q->track));
602 queue_write();
603 /* Maybe a track can now be played */
604 play(ev);
605}
606
607/** @brief Maybe add a randomly chosen track
608 * @param ev Event loop
16fb2830
RK
609 *
610 * Picking can take some time so the track will only be added after this
611 * function has returned.
49a773eb
RK
612 */
613void add_random_track(ev_source *ev) {
460b9539 614 struct queue_entry *q;
459d4402 615 long qlen = 0;
460b9539 616
617 /* If random play is not enabled then do nothing. */
618 if(shutting_down || !random_is_enabled())
49a773eb 619 return;
459d4402 620 /* Count how big the queue is */
460b9539 621 for(q = qhead.next; q != &qhead; q = q->next)
459d4402 622 ++qlen;
49a773eb
RK
623 /* If it's smaller than the desired size then add a track */
624 if(qlen < config->queue_pad)
625 trackdb_request_random(ev, chosen_random_track);
460b9539 626}
627
16fb2830
RK
628/** @brief Attempt to play something
629 *
630 * This is called from numerous locations - whenever it might conceivably have
631 * become possible to play something.
632 */
460b9539 633void play(ev_source *ev) {
634 struct queue_entry *q;
635 int random_enabled = random_is_enabled();
636
637 D(("play playing=%p", (void *)playing));
16fb2830
RK
638 /* If we're shutting down, or there's something playing, or playing is not
639 * enabled, give up now */
460b9539 640 if(shutting_down || playing || !playing_is_enabled()) return;
49a773eb 641 /* See if there's anything to play */
460b9539 642 if(qhead.next == &qhead) {
49a773eb
RK
643 /* Queue is empty. We could just wait around since there are periodic
644 * attempts to add a random track anyway. However they are rarer than
645 * attempts to force a track so we initiate one now. */
646 add_random_track(ev);
16fb2830
RK
647 /* chosen_random_track() will call play() when a new random track has been
648 * added to the queue. */
49a773eb 649 return;
460b9539 650 }
49a773eb 651 /* There must be at least one track in the queue. */
460b9539 652 q = qhead.next;
2dc2f478
RK
653 /* If random play is disabled but the track is a non-adopted random one
654 * then don't play it. play() will be called again when random play is
655 * re-enabled. */
656 if(!random_enabled && q->origin == origin_random)
460b9539 657 return;
658 D(("taken %p (%s) from queue", (void *)q, q->track));
659 /* Try to start playing. */
84aa9f93 660 switch(start(ev, q, 0/*!prepare_only*/)) {
460b9539 661 case START_HARDFAIL:
662 if(q == qhead.next) {
663 queue_remove(q, 0); /* Abandon this track. */
664 queue_played(q);
665 recent_write();
666 }
49a773eb
RK
667 /* Oh well, try the next one */
668 play(ev);
460b9539 669 break;
670 case START_SOFTFAIL:
49a773eb 671 /* We'll try the same track again shortly. */
460b9539 672 break;
673 case START_OK:
16fb2830 674 /* Remove from the queue */
460b9539 675 if(q == qhead.next) {
676 queue_remove(q, 0);
677 queue_write();
678 }
16fb2830 679 /* It's become the playing track */
460b9539 680 playing = q;
681 time(&playing->played);
682 playing->state = playing_started;
683 notify_play(playing->track, playing->submitter);
684 eventlog("playing", playing->track,
685 playing->submitter ? playing->submitter : (const char *)0,
686 (const char *)0);
687 /* Maybe add a random track. */
49a773eb 688 add_random_track(ev);
460b9539 689 /* If there is another track in the queue prepare it now. This could
690 * potentially be a just-added random track. */
691 if(qhead.next != &qhead)
692 prepare(ev, qhead.next);
693 break;
694 }
695}
696
16fb2830 697/** @brief Return true if play is enabled */
460b9539 698int playing_is_enabled(void) {
699 const char *s = trackdb_get_global("playing");
700
701 return !s || !strcmp(s, "yes");
702}
703
16fb2830 704/** @brief Enable play */
460b9539 705void enable_playing(const char *who, ev_source *ev) {
706 trackdb_set_global("playing", "yes", who);
707 /* Add a random track if necessary. */
49a773eb 708 add_random_track(ev);
460b9539 709 play(ev);
710}
711
16fb2830 712/** @brief Disable play */
460b9539 713void disable_playing(const char *who) {
714 trackdb_set_global("playing", "no", who);
715}
716
16fb2830 717/** @brief Return true if random play is enabled */
460b9539 718int random_is_enabled(void) {
719 const char *s = trackdb_get_global("random-play");
720
721 return !s || !strcmp(s, "yes");
722}
723
16fb2830 724/** @brief Enable random play */
460b9539 725void enable_random(const char *who, ev_source *ev) {
726 trackdb_set_global("random-play", "yes", who);
49a773eb 727 add_random_track(ev);
460b9539 728 play(ev);
729}
730
16fb2830 731/** @brief Disable random play */
460b9539 732void disable_random(const char *who) {
733 trackdb_set_global("random-play", "no", who);
734}
735
16fb2830
RK
736/** @brief Scratch a track
737 * @param User responsible (or NULL)
738 * @param Track ID (or NULL for current)
739 */
460b9539 740void scratch(const char *who, const char *id) {
741 struct queue_entry *q;
742 struct speaker_message sm;
743 pid_t pid;
744
745 D(("scratch playing=%p state=%d id=%s playing->id=%s",
746 (void *)playing,
747 playing ? playing->state : 0,
748 id ? id : "(none)",
749 playing ? playing->id : "(none)"));
16fb2830
RK
750 /* There must be a playing track; it must be in a scratchable state; if a
751 * specific ID was mentioned it must be that track. */
460b9539 752 if(playing
753 && (playing->state == playing_started
754 || playing->state == playing_paused)
755 && (!id
756 || !strcmp(id, playing->id))) {
16fb2830 757 /* Update state (for the benefit of the 'recent' list) */
460b9539 758 playing->state = playing_scratched;
759 playing->scratched = who ? xstrdup(who) : 0;
16fb2830 760 /* Find the player and kill the whole process group */
460b9539 761 if((pid = find_player_pid(playing->id)) > 0) {
16fb2830 762 D(("kill -%d -%lu", config->signal, (unsigned long)pid));
460b9539 763 kill(-pid, config->signal);
764 forget_player_pid(playing->id);
16fb2830
RK
765 } else {
766 /* TODO if the background decoder finished and the speaker is working
767 * through buffered data this will produce a bogus log message. */
460b9539 768 error(0, "could not find PID for %s", playing->id);
16fb2830
RK
769 }
770 /* Tell the speaker, if we think it'll care */
460b9539 771 if((playing->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
772 memset(&sm, 0, sizeof sm);
773 sm.type = SM_CANCEL;
774 strcpy(sm.id, playing->id);
84aa9f93 775 speaker_send(speaker_fd, &sm);
460b9539 776 D(("sending SM_CANCEL for %s", playing->id));
777 }
778 /* put a scratch track onto the front of the queue (but don't
779 * bother if playing is disabled) */
780 if(playing_is_enabled() && config->scratch.n) {
781 int r = rand() * (double)config->scratch.n / (RAND_MAX + 1.0);
2dc2f478 782 q = queue_add(config->scratch.s[r], who, WHERE_START, origin_scratch);
460b9539 783 }
784 notify_scratch(playing->track, playing->submitter, who,
785 time(0) - playing->played);
786 }
787}
788
16fb2830 789/** @brief Called from quit() to tear down eveyrthing belonging to this file */
460b9539 790void quitting(ev_source *ev) {
791 struct queue_entry *q;
792 pid_t pid;
793
794 /* Don't start anything new */
795 shutting_down = 1;
796 /* Shut down the current player */
797 if(playing) {
798 if((pid = find_player_pid(playing->id)) > 0) {
799 kill(-pid, config->signal);
800 forget_player_pid(playing->id);
16fb2830
RK
801 } else{
802 /* TODO if the background decoder finished and the speaker is working
803 * through buffered data this will produce a bogus log message. */
460b9539 804 error(0, "could not find PID for %s", playing->id);
16fb2830 805 }
460b9539 806 playing->state = playing_quitting;
807 finished(0);
808 }
809 /* Zap any other players */
810 for(q = qhead.next; q != &qhead; q = q->next)
811 if((pid = find_player_pid(q->id)) > 0) {
812 D(("kill -%d %lu", config->signal, (unsigned long)pid));
813 kill(-pid, config->signal);
814 forget_player_pid(q->id);
16fb2830
RK
815 } else {
816 /* TODO if we never started a background decoder then this will produce a
817 * very bogus log message (see issue 32) */
460b9539 818 error(0, "could not find PID for %s", q->id);
16fb2830 819 }
460b9539 820 /* Don't need the speaker any more */
821 ev_fd_cancel(ev, ev_read, speaker_fd);
822 xclose(speaker_fd);
823}
824
16fb2830 825/** @brief Pause the playing track */
460b9539 826int pause_playing(const char *who) {
827 struct speaker_message sm;
828 long played;
829
830 /* Can't pause if already paused or if nothing playing. */
831 if(!playing || paused) return 0;
832 switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
833 case DISORDER_PLAYER_STANDALONE:
834 if(!(playing->type & DISORDER_PLAYER_PAUSES)) {
835 default:
836 error(0, "cannot pause because player is not powerful enough");
837 return -1;
838 }
839 if(play_pause(playing->pl, &played, playing->data)) {
840 error(0, "player indicates it cannot pause");
841 return -1;
842 }
843 time(&playing->lastpaused);
844 playing->uptopause = played;
845 playing->lastresumed = 0;
846 break;
847 case DISORDER_PLAYER_RAW:
848 memset(&sm, 0, sizeof sm);
849 sm.type = SM_PAUSE;
84aa9f93 850 speaker_send(speaker_fd, &sm);
460b9539 851 break;
852 }
853 if(who) info("paused by %s", who);
854 notify_pause(playing->track, who);
855 paused = 1;
856 if(playing->state == playing_started)
857 playing->state = playing_paused;
858 eventlog("state", "pause", (char *)0);
859 return 0;
860}
861
16fb2830 862/** @brief Resume playing after a pause */
460b9539 863void resume_playing(const char *who) {
864 struct speaker_message sm;
865
866 if(!paused) return;
867 paused = 0;
868 if(!playing) return;
869 switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
870 case DISORDER_PLAYER_STANDALONE:
871 if(!playing->type & DISORDER_PLAYER_PAUSES) {
872 default:
873 /* Shouldn't happen */
874 return;
875 }
876 play_resume(playing->pl, playing->data);
877 time(&playing->lastresumed);
878 break;
879 case DISORDER_PLAYER_RAW:
880 memset(&sm, 0, sizeof sm);
881 sm.type = SM_RESUME;
84aa9f93 882 speaker_send(speaker_fd, &sm);
460b9539 883 break;
884 }
885 if(who) info("resumed by %s", who);
886 notify_resume(playing->track, who);
887 if(playing->state == playing_paused)
888 playing->state = playing_started;
889 eventlog("state", "resume", (char *)0);
890}
891
892/*
893Local Variables:
894c-basic-offset:2
895comment-column:40
896fill-column:79
16fb2830 897indent-tabs-mode:nil
460b9539 898End:
899*/