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