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