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