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