chiark / gitweb /
Fix mis-merged trackdb_open().
[disorder] / server / play.c
index 13854f7a81dd7bfd523dc91d14e52921978b93bd..f9719912f7f0b62d4c7db982cb37c7710dce962d 100644 (file)
@@ -1,89 +1,59 @@
 /*
  * This file is part of DisOrder.
- * Copyright (C) 2004, 2005, 2006, 2007 Richard Kettlewell
+ * Copyright (C) 2004-2009 Richard Kettlewell
  *
- * This program is free software; you can redistribute it and/or modify
+ * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
+ * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * 
  * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- * USA
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+/** @file server/play.c
+ * @brief Playing tracks
+ *
+ * This file is rather badly organized.  Sorry.  It's better than it was...
  */
 
-#include <config.h>
-#include "types.h"
-
-#include <sys/types.h>
-#include <sys/time.h>
-#include <unistd.h>
-#include <errno.h>
-#include <fnmatch.h>
-#include <time.h>
-#include <signal.h>
-#include <stdlib.h>
-#include <assert.h>
-#include <sys/socket.h>
-#include <string.h>
-#include <stdio.h>
-#include <pcre.h>
+#include "disorder-server.h"
 #include <ao/ao.h>
-#include <sys/wait.h>
-#include <sys/un.h>
-
-#include "event.h"
-#include "log.h"
-#include "mem.h"
-#include "configuration.h"
-#include "queue.h"
-#include "server-queue.h"
-#include "trackdb.h"
-#include "play.h"
-#include "plugin.h"
-#include "wstat.h"
-#include "eventlog.h"
-#include "logfd.h"
-#include "syscalls.h"
-#include "speaker-protocol.h"
-#include "disorder.h"
-#include "signame.h"
-#include "hash.h"
 
 #define SPEAKER "disorder-speaker"
 
+/** @brief The current playing track or NULL */
 struct queue_entry *playing;
+
+/** @brief Set when paused */
 int paused;
 
 static void finished(ev_source *ev);
-
+static int start_child(struct queue_entry *q, 
+                       const struct pbgc_params *params,
+                       void attribute((unused)) *bgdata);
+static int prepare_child(struct queue_entry *q, 
+                         const struct pbgc_params *params,
+                         void attribute((unused)) *bgdata);
+
+/** @brief File descriptor of our end of the socket to the speaker */
 static int speaker_fd = -1;
-static hash *player_pids;
-static int shutting_down;
-
-static void store_player_pid(const char *id, pid_t pid) {
-  if(!player_pids) player_pids = hash_new(sizeof (pid_t));
-  hash_add(player_pids, id, &pid, HASH_INSERT_OR_REPLACE);
-}
 
-static pid_t find_player_pid(const char *id) {
-  pid_t *pidp;
-
-  if(player_pids && (pidp = hash_find(player_pids, id))) return *pidp;
-  return -1;
-}
+/** @brief Set when shutting down */
+static int shutting_down;
 
-static void forget_player_pid(const char *id) {
-  if(player_pids) hash_remove(player_pids, id);
-}
+/* Speaker ------------------------------------------------------------------ */
 
-/* called when speaker process terminates */
+/** @brief Called when speaker process terminates
+ *
+ * Currently kills of DisOrder completely.  A future version could terminate
+ * the speaker when nothing was going on, or recover from failures, though any
+ * tracks with decoders already started would need to have them restarted.
+ */
 static int speaker_terminated(ev_source attribute((unused)) *ev,
                              pid_t attribute((unused)) pid,
                              int attribute((unused)) status,
@@ -93,7 +63,7 @@ static int speaker_terminated(ev_source attribute((unused)) *ev,
        wstat(status));
 }
 
-/* called when speaker process has something to say */
+/** @brief Called when we get a message from the speaker process */
 static int speaker_readable(ev_source *ev, int fd,
                            void attribute((unused)) *u) {
   struct speaker_message sm;
@@ -110,10 +80,11 @@ static int speaker_readable(ev_source *ev, int fd,
     D(("SM_PAUSED %s %ld", sm.id, sm.data));
     playing->sofar = sm.data;
     break;
-  case SM_FINISHED:
-    /* the playing track finished */
-    D(("SM_FINISHED %s", sm.id));
-    finished(ev);
+  case SM_FINISHED:                    /* scratched the playing track */
+  case SM_STILLBORN:                   /* scratched too early */
+  case SM_UNKNOWN:                     /* scratched WAY too early */
+    if(playing && !strcmp(sm.id, playing->id))
+      finished(ev);
     break;
   case SM_PLAYING:
     /* track ID is playing, DATA seconds played */
@@ -121,22 +92,19 @@ static int speaker_readable(ev_source *ev, int fd,
     playing->sofar = sm.data;
     break;
   default:
-    error(0, "unknown message type %d", sm.type);
+    error(0, "unknown speaker message type %d", sm.type);
   }
   return 0;
 }
 
+/** @brief Initialize the speaker process */
 void speaker_setup(ev_source *ev) {
-  int sp[2], lfd;
+  int sp[2];
   pid_t pid;
   struct speaker_message sm;
 
   if(socketpair(PF_UNIX, SOCK_DGRAM, 0, sp) < 0)
     fatal(errno, "error calling socketpair");
-  if(!isatty(2))
-    lfd = logfd(ev, SPEAKER);
-  else
-    lfd = -1;
   if(!(pid = xfork())) {
     exitfn = _exit;
     ev_signal_atfork(ev);
@@ -144,10 +112,6 @@ void speaker_setup(ev_source *ev) {
     xdup2(sp[0], 1);
     xclose(sp[0]);
     xclose(sp[1]);
-    if(lfd != -1) {
-      xdup2(lfd, 2);
-      xclose(lfd);
-    }
     signal(SIGPIPE, SIG_DFL);
 #if 0
     execlp("valgrind", "valgrind", SPEAKER, "--config", configfile,
@@ -169,9 +133,11 @@ void speaker_setup(ev_source *ev) {
   /* Wait for the speaker to be ready */
   speaker_recv(speaker_fd, &sm);
   nonblock(speaker_fd);
-  ev_fd(ev, ev_read, speaker_fd, speaker_readable, 0, "speaker read");
+  if(ev_fd(ev, ev_read, speaker_fd, speaker_readable, 0, "speaker read") < 0)
+    fatal(0, "error registering speaker socket fd");
 }
 
+/** @brief Tell the speaker to reload its configuration */
 void speaker_reload(void) {
   struct speaker_message sm;
 
@@ -180,28 +146,23 @@ void speaker_reload(void) {
   speaker_send(speaker_fd, &sm);
 }
 
-/* timeout for play retry */
-static int play_again(ev_source *ev,
-                     const struct timeval attribute((unused)) *now,
-                     void attribute((unused)) *u) {
-  D(("play_again"));
-  play(ev);
-  return 0;
-}
-
-/* try calling play() again after @offset@ seconds */
-static void retry_play(ev_source *ev, int offset) {
-  struct timeval w;
-
-  D(("retry_play(%d)", offset));
-  gettimeofday(&w, 0);
-  w.tv_sec += offset;
-  ev_timeout(ev, 0, &w, play_again, 0);
-}
+/* Track termination -------------------------------------------------------- */
 
-/* Called when the currently playing track finishes playing.  This
- * might be because the player finished or because the speaker process
- * told us so. */
+/** @brief Called when the currently playing track finishes playing
+ * @param ev Event loop or NULL
+ *
+ * There are three places this is called from:
+ * 
+ * 1) speaker_readable(), when the speaker tells us the playing track finished.
+ * (Technically the speaker lies a little to arrange for gapless play.)
+ *
+ * 2) player_finished(), when the player for a non-raw track (i.e. one that
+ * does not use the speaker) finishes.
+ *
+ * 3) quitting(), after signalling the decoder or player but possible before it
+ * has actually terminated.  In this case @p ev is NULL, inhibiting any further
+ * attempt to play anything.
+ */
 static void finished(ev_source *ev) {
   D(("finished playing=%p", (void *)playing));
   if(!playing)
@@ -223,12 +184,20 @@ static void finished(ev_source *ev) {
   }
   queue_played(playing);
   recent_write();
-  forget_player_pid(playing->id);
   playing = 0;
-  if(ev) retry_play(ev, config->gap);
+  /* Try to play something else */
+  if(ev)
+    play(ev);
 }
 
-/* Called when a player terminates. */
+/** @brief Called when a player or decoder process terminates
+ *
+ * This is called when a decoder process terminates (which might actually be
+ * some time before the speaker reports it as finished) or when a non-raw
+ * (i.e. non-speaker) player terminates.  In the latter case it's imaginable
+ * that the OS has buffered the last few samples.
+ * 
+ */
 static int player_finished(ev_source *ev,
                           pid_t pid,
                           int status,
@@ -241,18 +210,20 @@ static int player_finished(ev_source *ev,
   /* Record that this PID is dead.  If we killed the track we might know this
    * already, but also it might have exited or crashed.  Either way we don't
    * want to end up signalling it. */
-  if(pid == find_player_pid(q->id))
-    forget_player_pid(q->id);
+  q->pid = -1;
   switch(q->state) {
   case playing_unplayed:
   case playing_random:
     /* If this was a pre-prepared track then either it failed or we
-     * deliberately stopped it because it was removed from the queue or moved
-     * down it.  So leave it state alone for future use. */
+     * deliberately stopped it: it might have been removed from the queue, or
+     * moved down the queue, or the speaker might be on a break.  So we leave
+     * it state alone for future use.
+     */
     break;
   default:
     /* We actually started playing this track. */
     if(status) {
+      /* Don't override 'scratched' with 'failed'. */
       if(q->state != playing_scratched)
        q->state = playing_failed;
     } else 
@@ -275,246 +246,240 @@ static int player_finished(ev_source *ev,
   return 0;
 }
 
-/* Find the player for Q */
-static int find_player(const struct queue_entry *q) {
+/* Track initiation --------------------------------------------------------- */
+
+/** @brief Find the player for @p q */
+static const struct stringlist *find_player(const struct queue_entry *q) {
   int n;
   
   for(n = 0; n < config->player.n; ++n)
     if(fnmatch(config->player.s[n].s[0], q->track, 0) == 0)
       break;
   if(n >= config->player.n)
-    return -1;
+    return NULL;
   else
-    return n;
+    return &config->player.s[n];
 }
 
-/* Return values from start() */
-#define START_OK 0                     /**< @brief Succeeded. */
-#define START_HARDFAIL 1               /**< @brief Track is broken. */
-#define START_SOFTFAIL 2          /**< @brief Track OK, system (temporarily?) broken */
-
-/** @brief Play or prepare @p q
+/** @brief Start to play @p q
  * @param ev Event loop
  * @param q Track to play/prepare
- * @param prepare_only If true, only prepares track
  * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
+ *
+ * This makes @p actually start playing.  It calls prepare() if necessary and
+ * either sends an @ref SM_START command or invokes the player itself in a
+ * subprocess.
+ *
+ * It's up to the caller to set @ref playing and @c playing->state (this might
+ * be changed in the future).
  */
 static int start(ev_source *ev,
-                struct queue_entry *q,
-                int prepare_only) {
-  int n, lfd;
-  const char *p;
-  int np[2], sfd;
-  struct speaker_message sm;
-  char buffer[64];
-  int optc;
-  ao_sample_format format;
-  ao_device *device;
-  int retries;
-  struct timespec ts;
-  const char *waitdevice = 0;
-  const char *const *optv;
-  pid_t pid, npid;
-  struct sockaddr_un addr;
-  uint32_t l;
+                struct queue_entry *q) {
+  const struct stringlist *player;
+  int rc;
 
-  memset(&sm, 0, sizeof sm);
-  D(("start %s %d", q->id, prepare_only));
-  if(find_player_pid(q->id) > 0) {
-    if(prepare_only) return START_OK;
-    /* We have already prepared this track so we just need to tell the speaker
-     * process to start actually playing the queued up audio data */
-    strcpy(sm.id, q->id);
-    sm.type = SM_PLAY;
-    speaker_send(speaker_fd, &sm);
-    D(("sent SM_PLAY for %s", sm.id));
-    return START_OK;
-  }
+  D(("start %s", q->id));
   /* Find the player plugin. */
-  if((n = find_player(q)) < 0) return START_HARDFAIL;
-  if(!(q->pl = open_plugin(config->player.s[n].s[1], 0)))
+  if(!(player = find_player(q)) < 0)
+    return START_HARDFAIL;              /* No player */
+  if(!(q->pl = open_plugin(player->s[1], 0)))
     return START_HARDFAIL;
   q->type = play_get_type(q->pl);
-  /* Can't prepare non-raw tracks. */
-  if(prepare_only
-     && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
+  /* Special handling for raw-format players */
+  if((q->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
+    /* Make sure that the track is prepared */
+    if((rc = prepare(ev, q)))
+      return rc;
+    /* Now we're sure it's prepared, start it playing */
+    /* TODO actually it might not be fully prepared yet - it's all happening in
+     * a subprocess.  See speaker.c for further discussion.  */
+    struct speaker_message sm[1];
+    memset(sm, 0, sizeof sm);
+    strcpy(sm->id, q->id);
+    sm->type = SM_PLAY;
+    speaker_send(speaker_fd, sm);
+    D(("sent SM_PLAY for %s", sm->id));
+    /* Our caller will set playing and playing->state = playing_started */
     return START_OK;
-  /* Call the prefork function. */
-  p = trackdb_rawpath(q->track);
-  if(q->type & DISORDER_PLAYER_PREFORK)
-    if(!(q->data = play_prefork(q->pl, p))) {
-      error(0, "prefork function for %s failed", q->track);
-      return START_HARDFAIL;
-    }
-  /* Use the second arg as the tag if available (it's probably a command name),
-   * otherwise the module name. */
-  if(!isatty(2))
-    lfd = logfd(ev, (config->player.s[n].s[2]
-                    ? config->player.s[n].s[2] : config->player.s[n].s[1]));
-  else
-    lfd = -1;
-  optc = config->player.s[n].n - 2;
-  optv = (void *)&config->player.s[n].s[2];
-  while(optc > 0 && optv[0][0] == '-') {
-    if(!strcmp(optv[0], "--")) {
-      ++optv;
-      --optc;
-      break;
-    }
-    if(!strcmp(optv[0], "--wait-for-device")
-       || !strncmp(optv[0], "--wait-for-device=", 18)) {
-      if((waitdevice = strchr(optv[0], '='))) {
-       ++waitdevice;
-      } else
-       waitdevice = "";                /* use default */
-      ++optv;
-      --optc;
-    } else {
-      error(0, "unknown option %s", optv[0]);
-      return START_HARDFAIL;
-    }
+  } else {
+    rc = play_background(ev, player, q, start_child, NULL);
+    if(rc == START_OK)
+      ev_child(ev, q->pid, 0, player_finished, q);
+      /* Our caller will set playing and playing->state = playing_started */
+    return rc;
   }
-  switch(pid = fork()) {
-  case 0:                      /* child */
-    exitfn = _exit;
-    ev_signal_atfork(ev);
-    signal(SIGPIPE, SIG_DFL);
-    if(lfd != -1) {
-      xdup2(lfd, 1);
-      xdup2(lfd, 2);
-      xclose(lfd);                     /* tidy up */
-    }
-    setpgid(0, 0);
-    if((q->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
-      /* "Raw" format players always have their output send down a pipe
-       * to the disorder-normalize process.  This will connect to the
-       * speaker process to actually play the audio data.
-       */
-      /* np will be the pipe to disorder-normalize */
-      if(socketpair(PF_UNIX, SOCK_STREAM, 0, np) < 0)
-       fatal(errno, "error calling socketpair");
-      xshutdown(np[0], SHUT_WR);       /* normalize reads from np[0] */
-      xshutdown(np[1], SHUT_RD);       /* decoder writes to np[1] */
-      blocking(np[0]);
-      blocking(np[1]);
-      /* Start disorder-normalize */
-      if(!(npid = xfork())) {
-       if(!xfork()) {
-         /* Connect to the speaker process */
-         memset(&addr, 0, sizeof addr);
-         addr.sun_family = AF_UNIX;
-         snprintf(addr.sun_path, sizeof addr.sun_path,
-                  "%s/speaker", config->home);
-         sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
-         if(connect(sfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
-           fatal(errno, "connecting to %s", addr.sun_path);
-         l = strlen(q->id);
-         if(write(sfd, &l, sizeof l) < 0
-            || write(sfd, q->id, l) < 0)
-           fatal(errno, "writing to %s", addr.sun_path);
-         /* Await the ack */
-         read(sfd, &l, 1);
-         /* Plumbing */
-         xdup2(np[0], 0);
-         xdup2(sfd, 1);
-         xclose(np[0]);
-         xclose(np[1]);
-         xclose(sfd);
-         /* Ask the speaker to actually start playing the track; we do it here
-          * so it's definitely after ack. */
-         if(!prepare_only) {
-           strcpy(sm.id, q->id);
-           sm.type = SM_PLAY;
-           speaker_send(speaker_fd, &sm);
-           D(("sent SM_PLAY for %s", sm.id));
-         }
-         execlp("disorder-normalize", "disorder-normalize", (char *)0);
-         fatal(errno, "executing disorder-normalize");
-         /* end of the innermost fork */
-       }
-       _exit(0);
-       /* end of the middle fork */
-      }
-      /* Wait for the middle fork to finish */
-      while(waitpid(npid, &n, 0) < 0 && errno == EINTR)
-       ;
-      /* Pass the file descriptor to the driver in an environment
-       * variable. */
-      snprintf(buffer, sizeof buffer, "DISORDER_RAW_FD=%d", np[1]);
-      if(putenv(buffer) < 0)
-       fatal(errno, "error calling putenv");
-      /* Close all the FDs we don't need */
-      xclose(np[0]);
-    }
-    if(waitdevice) {
-      ao_initialize();
-      if(*waitdevice) {
-       n = ao_driver_id(waitdevice);
-       if(n == -1)
-         fatal(0, "invalid libao driver: %s", optv[0]);
-       } else
-         n = ao_default_driver_id();
-      /* Make up a format. */
-      memset(&format, 0, sizeof format);
-      format.bits = 8;
-      format.rate = 44100;
-      format.channels = 1;
-      format.byte_format = AO_FMT_NATIVE;
-      retries = 20;
-      ts.tv_sec = 0;
-      ts.tv_nsec = 100000000;  /* 0.1s */
-      while((device = ao_open_live(n, &format, 0)) == 0 && retries-- > 0)
-         nanosleep(&ts, 0);
-      if(device)
-       ao_close(device);
-    }
-    play_track(q->pl,
-              optv, optc,
-              p,
-              q->track);
-    _exit(0);
-  case -1:                     /* error */
-    error(errno, "error calling fork");
-    if(q->type & DISORDER_PLAYER_PREFORK)
-      play_cleanup(q->pl, q->data);    /* else would leak */
-    if(lfd != -1)
-      xclose(lfd);
-    return START_SOFTFAIL;
+}
+
+/** @brief Child-process half of start() */
+static int start_child(struct queue_entry *q, 
+                       const struct pbgc_params *params,
+                       void attribute((unused)) *bgdata) {
+  int n;
+
+  /* Wait for a device to clear.  This ugliness is now deprecated and will
+   * eventually be removed. */
+  if(params->waitdevice) {
+    ao_initialize();
+    if(*params->waitdevice) {
+      n = ao_driver_id(params->waitdevice);
+      if(n == -1)
+        fatal(0, "invalid libao driver: %s", params->waitdevice);
+    } else
+      n = ao_default_driver_id();
+    /* Make up a format. */
+    ao_sample_format format;
+    memset(&format, 0, sizeof format);
+    format.bits = 8;
+    format.rate = 44100;
+    format.channels = 1;
+    format.byte_format = AO_FMT_NATIVE;
+    int retries = 20;
+    struct timespec ts;
+    ts.tv_sec = 0;
+    ts.tv_nsec = 100000000;             /* 0.1s */
+    ao_device *device;
+    while((device = ao_open_live(n, &format, 0)) == 0 && retries-- > 0)
+      nanosleep(&ts, 0);
+    if(device)
+      ao_close(device);
   }
-  store_player_pid(q->id, pid);
-  if(lfd != -1)
-    xclose(lfd);
-  setpgid(pid, pid);
-  ev_child(ev, pid, 0, player_finished, q);
-  D(("player subprocess ID %lu", (unsigned long)pid));
-  return START_OK;
+  /* Play the track */
+  play_track(q->pl,
+             params->argv, params->argc,
+             params->rawpath,
+             q->track);
+  return 0;
 }
 
+/** @brief Prepare a track for later play
+ * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
+ *
+ * Only applies to raw-format (i.e. speaker-using) players; everything else
+ * gets @c START_OK.
+ */
 int prepare(ev_source *ev,
            struct queue_entry *q) {
-  int n;
+  const struct stringlist *player;
 
+  /* If there's a decoder (or player!) going we do nothing */
+  if(q->pid >= 0)
+    return START_OK;
+  /* If the track is already prepared, do nothing */
+  if(q->prepared)
+    return START_OK;
   /* Find the player plugin */
-  if(find_player_pid(q->id) > 0) return 0; /* Already going. */
-  if((n = find_player(q)) < 0) return -1; /* No player */
-  q->pl = open_plugin(config->player.s[n].s[1], 0); /* No player */
+  if(!(player = find_player(q)) < 0) 
+    return START_HARDFAIL;              /* No player */
+  q->pl = open_plugin(player->s[1], 0);
   q->type = play_get_type(q->pl);
   if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
-    return 0;                          /* Not a raw player */
-  return start(ev, q, 1/*prepare_only*/); /* Prepare it */
+    return START_OK;                    /* Not a raw player */
+  const int rc = play_background(ev, player, q, prepare_child, NULL);
+  if(rc == START_OK) {
+    ev_child(ev, q->pid, 0, player_finished, q);
+    q->prepared = 1;
+  }
+  return rc;
+}
+
+/** @brief Child-process half of prepare() */
+static int prepare_child(struct queue_entry *q, 
+                         const struct pbgc_params *params,
+                         void attribute((unused)) *bgdata) {
+  /* np will be the pipe to disorder-normalize */
+  int np[2];
+  if(socketpair(PF_UNIX, SOCK_STREAM, 0, np) < 0)
+    fatal(errno, "error calling socketpair");
+  /* Beware of the Leopard!  On OS X 10.5.x, the order of the shutdown
+   * calls here DOES MATTER.  If you do the SHUT_WR first then the SHUT_RD
+   * fails with "Socket is not connected".  I think this is a bug but
+   * provided implementors either don't care about the order or all agree
+   * about the order, choosing the reliable order is an adequate
+   * workaround.  */
+  xshutdown(np[1], SHUT_RD);   /* decoder writes to np[1] */
+  xshutdown(np[0], SHUT_WR);   /* normalize reads from np[0] */
+  blocking(np[0]);
+  blocking(np[1]);
+  /* Start disorder-normalize.  We double-fork so that nothing has to wait
+   * for disorder-normalize. */
+  pid_t npid;
+  if(!(npid = xfork())) {
+    /* Grandchild of disorderd */
+    if(!xfork()) {
+      /* Great-grandchild of disorderd */
+      /* Connect to the speaker process */
+      struct sockaddr_un addr;
+      memset(&addr, 0, sizeof addr);
+      addr.sun_family = AF_UNIX;
+      snprintf(addr.sun_path, sizeof addr.sun_path,
+               "%s/speaker/socket", config->home);
+      int sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
+      if(connect(sfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
+        fatal(errno, "connecting to %s", addr.sun_path);
+      /* Send the ID, with a NATIVE-ENDIAN 32 bit length */
+      uint32_t l = strlen(q->id);
+      if(write(sfd, &l, sizeof l) < 0
+         || write(sfd, q->id, l) < 0)
+        fatal(errno, "writing to %s", addr.sun_path);
+      /* Await the ack */
+      if (read(sfd, &l, 1) < 0) 
+        fatal(errno, "reading ack from %s", addr.sun_path);
+      /* Plumbing */
+      xdup2(np[0], 0);
+      xdup2(sfd, 1);
+      xclose(np[0]);
+      xclose(np[1]);
+      xclose(sfd);
+      /* TODO stderr shouldn't be redirected for disorder-normalize
+       * (but it should be for play_track() */
+      execlp("disorder-normalize", "disorder-normalize",
+             log_default == &log_syslog ? "--syslog" : "--no-syslog",
+             "--config", configfile,
+             (char *)0);
+      fatal(errno, "executing disorder-normalize");
+      /* End of the great-grandchild of disorderd */
+    }
+    /* Back in the grandchild of disorderd */
+    _exit(0);
+    /* End of the grandchild of disorderd */
+  }
+  /* Back in the child of disorderd */
+  /* Wait for the grandchild of disordered to finish */
+  int n;
+  while(waitpid(npid, &n, 0) < 0 && errno == EINTR)
+    ;
+  /* Pass the file descriptor to the driver in an environment
+   * variable. */
+  char buffer[64];
+  snprintf(buffer, sizeof buffer, "DISORDER_RAW_FD=%d", np[1]);
+  if(putenv(buffer) < 0)
+    fatal(errno, "error calling putenv");
+  /* Close all the FDs we don't need */
+  xclose(np[0]);
+  /* Start the decoder itself */
+  play_track(q->pl,
+             params->argv, params->argc,
+             params->rawpath,
+             q->track);
+  return 0;
 }
 
+/** @brief Abandon a queue entry
+ *
+ * Called from c_remove() (but NOT when scratching a track).  Only does
+ * anything to raw-format tracks.  Terminates the background decoder and tells
+ * the speaker process to cancel the track.
+ */
 void abandon(ev_source attribute((unused)) *ev,
             struct queue_entry *q) {
   struct speaker_message sm;
-  pid_t pid = find_player_pid(q->id);
 
-  if(pid < 0) return;                  /* Not prepared. */
+  if(q->pid < 0)
+    return;                             /* Not prepared. */
   if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
     return;                            /* Not a raw player. */
   /* Terminate the player. */
-  kill(-pid, config->signal);
-  forget_player_pid(q->id);
+  kill(-q->pid, config->signal);
   /* Cancel the track. */
   memset(&sm, 0, sizeof sm);
   sm.type = SM_CANCEL;
@@ -522,87 +487,101 @@ void abandon(ev_source attribute((unused)) *ev,
   speaker_send(speaker_fd, &sm);
 }
 
-int add_random_track(void) {
+/* Random tracks ------------------------------------------------------------ */
+
+/** @brief Called with a new random track
+ * @param ev Event loop
+ * @param track Track name
+ */
+static void chosen_random_track(ev_source *ev,
+                               const char *track) {
+  struct queue_entry *q;
+
+  if(!track)
+    return;
+  /* Add the track to the queue */
+  q = queue_add(track, 0, WHERE_END, origin_random);
+  D(("picked %p (%s) at random", (void *)q, q->track));
+  queue_write();
+  /* Maybe a track can now be played */
+  play(ev);
+}
+
+/** @brief Maybe add a randomly chosen track
+ * @param ev Event loop
+ *
+ * Picking can take some time so the track will only be added after this
+ * function has returned.
+ */
+void add_random_track(ev_source *ev) {
   struct queue_entry *q;
-  const char *p;
   long qlen = 0;
-  int rc = 0;
 
   /* If random play is not enabled then do nothing. */
   if(shutting_down || !random_is_enabled())
-    return 0;
+    return;
   /* Count how big the queue is */
   for(q = qhead.next; q != &qhead; q = q->next)
     ++qlen;
-  /* Add random tracks until the queue is at the right size */
-  while(qlen < config->queue_pad) {
-    /* Try to pick a random track */
-    if(!(p = trackdb_random(16))) {
-      rc = -1;
-      break;
-    }
-    /* Add it to the end of the queue. */
-    q = queue_add(p, 0, WHERE_END);
-    q->state = playing_random;
-    D(("picked %p (%s) at random", (void *)q, q->track));
-    ++qlen;
-  }
-  /* Commit the queue */
-  queue_write();
-  return rc;
+  /* If it's smaller than the desired size then add a track */
+  if(qlen < config->queue_pad)
+    trackdb_request_random(ev, chosen_random_track);
 }
 
-/* try to play a track */
+/* Track initiation (part 2) ------------------------------------------------ */
+
+/** @brief Attempt to play something
+ *
+ * This is called from numerous locations - whenever it might conceivably have
+ * become possible to play something.
+ */
 void play(ev_source *ev) {
   struct queue_entry *q;
   int random_enabled = random_is_enabled();
 
   D(("play playing=%p", (void *)playing));
+  /* If we're shutting down, or there's something playing, or playing is not
+   * enabled, give up now */
   if(shutting_down || playing || !playing_is_enabled()) return;
-  /* If the queue is empty then add a random track. */
+  /* See if there's anything to play */
   if(qhead.next == &qhead) {
-    if(!random_enabled)
-      return;
-    if(add_random_track()) {
-      /* On error, try again in 10s. */
-      retry_play(ev, 10);
-      return;
-    }
-    /* Now there must be at least one track in the queue. */
+    /* Queue is empty.  We could just wait around since there are periodic
+     * attempts to add a random track anyway.  However they are rarer than
+     * attempts to force a track so we initiate one now. */
+    add_random_track(ev);
+    /* chosen_random_track() will call play() when a new random track has been
+     * added to the queue. */
+    return;
   }
+  /* There must be at least one track in the queue. */
   q = qhead.next;
-  /* If random play is disabled but the track is a random one then don't play
-   * it.  play() will be called again when random play is re-enabled. */
-  if(!random_enabled && q->state == playing_random)
+  /* If random play is disabled but the track is a non-adopted random one
+   * then don't play it.  play() will be called again when random play is
+   * re-enabled. */
+  if(!random_enabled && q->origin == origin_random)
     return;
   D(("taken %p (%s) from queue", (void *)q, q->track));
   /* Try to start playing. */
-  switch(start(ev, q, 0/*!prepare_only*/)) {
+  switch(start(ev, q)) {
   case START_HARDFAIL:
     if(q == qhead.next) {
       queue_remove(q, 0);              /* Abandon this track. */
       queue_played(q);
       recent_write();
     }
-    if(qhead.next == &qhead)
-      /* Queue is empty, wait a bit before trying something else (so we don't
-       * sit there looping madly in the presence of persistent problem).  Note
-       * that we might not reliably get a random track lookahead in this case,
-       * but if we get here then really there are bigger problems. */
-      retry_play(ev, 1);
-    else
-      /* More in queue, try again now. */
-      play(ev);
+    /* Oh well, try the next one */
+    play(ev);
     break;
   case START_SOFTFAIL:
-    /* Try same track again in a bit. */
-    retry_play(ev, 10);
+    /* We'll try the same track again shortly. */
     break;
   case START_OK:
+    /* Remove from the queue */
     if(q == qhead.next) {
       queue_remove(q, 0);
       queue_write();
     }
+    /* It's become the playing track */
     playing = q;
     time(&playing->played);
     playing->state = playing_started;
@@ -611,7 +590,7 @@ void play(ev_source *ev) {
             playing->submitter ? playing->submitter : (const char *)0,
             (const char *)0);
     /* Maybe add a random track. */
-    add_random_track();
+    add_random_track(ev);
     /* If there is another track in the queue prepare it now.  This could
      * potentially be a just-added random track. */
     if(qhead.next != &qhead)
@@ -620,62 +599,78 @@ void play(ev_source *ev) {
   }
 }
 
+/* Miscelleneous ------------------------------------------------------------ */
+
+/** @brief Return true if play is enabled */
 int playing_is_enabled(void) {
   const char *s = trackdb_get_global("playing");
 
   return !s || !strcmp(s, "yes");
 }
 
+/** @brief Enable play */
 void enable_playing(const char *who, ev_source *ev) {
   trackdb_set_global("playing", "yes", who);
   /* Add a random track if necessary. */
-  add_random_track();
+  add_random_track(ev);
   play(ev);
 }
 
+/** @brief Disable play */
 void disable_playing(const char *who) {
   trackdb_set_global("playing", "no", who);
 }
 
+/** @brief Return true if random play is enabled */
 int random_is_enabled(void) {
   const char *s = trackdb_get_global("random-play");
 
   return !s || !strcmp(s, "yes");
 }
 
+/** @brief Enable random play */
 void enable_random(const char *who, ev_source *ev) {
   trackdb_set_global("random-play", "yes", who);
-  add_random_track();
+  add_random_track(ev);
   play(ev);
 }
 
+/** @brief Disable random play */
 void disable_random(const char *who) {
   trackdb_set_global("random-play", "no", who);
 }
 
+/* Scratching --------------------------------------------------------------- */
+
+/** @brief Scratch a track
+ * @param User responsible (or NULL)
+ * @param Track ID (or NULL for current)
+ */
 void scratch(const char *who, const char *id) {
   struct queue_entry *q;
   struct speaker_message sm;
-  pid_t pid;
 
   D(("scratch playing=%p state=%d id=%s playing->id=%s",
      (void *)playing,
      playing ? playing->state : 0,
      id ? id : "(none)",
      playing ? playing->id : "(none)"));
+  /* There must be a playing track; it must be in a scratchable state; if a
+   * specific ID was mentioned it must be that track. */
   if(playing
      && (playing->state == playing_started
         || playing->state == playing_paused)
      && (!id
         || !strcmp(id, playing->id))) {
+    /* Update state (for the benefit of the 'recent' list) */
     playing->state = playing_scratched;
     playing->scratched = who ? xstrdup(who) : 0;
-    if((pid = find_player_pid(playing->id)) > 0) {
-      D(("kill -%d %lu", config->signal, (unsigned long)pid));
-      kill(-pid, config->signal);
-      forget_player_pid(playing->id);
-    } else
-      error(0, "could not find PID for %s", playing->id);
+    /* Find the player and kill the whole process group */
+    if(playing->pid >= 0) {
+      D(("kill -%d -%lu", config->signal, (unsigned long)playing->pid));
+      kill(-playing->pid, config->signal);
+    }
+    /* Tell the speaker, if we think it'll care */
     if((playing->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
       memset(&sm, 0, sizeof sm);
       sm.type = SM_CANCEL;
@@ -687,43 +682,42 @@ void scratch(const char *who, const char *id) {
      * bother if playing is disabled) */
     if(playing_is_enabled() && config->scratch.n) {
       int r = rand() * (double)config->scratch.n / (RAND_MAX + 1.0);
-      q = queue_add(config->scratch.s[r], who, WHERE_START);
-      q->state = playing_isscratch;
+      q = queue_add(config->scratch.s[r], who, WHERE_START, origin_scratch);
     }
     notify_scratch(playing->track, playing->submitter, who,
                   time(0) - playing->played);
   }
 }
 
+/* Server termination ------------------------------------------------------- */
+
+/** @brief Called from quit() to tear down everything belonging to this file */
 void quitting(ev_source *ev) {
   struct queue_entry *q;
-  pid_t pid;
 
   /* Don't start anything new */
   shutting_down = 1;
   /* Shut down the current player */
   if(playing) {
-    if((pid = find_player_pid(playing->id)) > 0) {
-      kill(-pid, config->signal);
-      forget_player_pid(playing->id);
-    } else
-      error(0, "could not find PID for %s", playing->id);
+    if(playing->pid >= 0)
+      kill(-playing->pid, config->signal);
     playing->state = playing_quitting;
     finished(0);
   }
-  /* Zap any other players */
+  /* Zap any background decoders that are going */
   for(q = qhead.next; q != &qhead; q = q->next)
-    if((pid = find_player_pid(q->id)) > 0) {
-      D(("kill -%d %lu", config->signal, (unsigned long)pid));
-      kill(-pid, config->signal);
-      forget_player_pid(q->id);
-    } else
-      error(0, "could not find PID for %s", q->id);
+    if(q->pid >= 0) {
+      D(("kill -%d %lu", config->signal, (unsigned long)q->pid));
+      kill(-q->pid, config->signal);
+    }
   /* Don't need the speaker any more */
   ev_fd_cancel(ev, ev_read, speaker_fd);
   xclose(speaker_fd);
 }
 
+/* Pause and resume --------------------------------------------------------- */
+
+/** @brief Pause the playing track */
 int pause_playing(const char *who) {
   struct speaker_message sm;
   long played;
@@ -760,6 +754,7 @@ int pause_playing(const char *who) {
   return 0;
 }
 
+/** @brief Resume playing after a pause */
 void resume_playing(const char *who) {
   struct speaker_message sm;
 
@@ -768,7 +763,7 @@ void resume_playing(const char *who) {
   if(!playing) return;
   switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
   case DISORDER_PLAYER_STANDALONE:
-    if(!playing->type & DISORDER_PLAYER_PAUSES) {
+    if(!(playing->type & DISORDER_PLAYER_PAUSES)) {
     default:
       /* Shouldn't happen */
       return;
@@ -794,5 +789,6 @@ Local Variables:
 c-basic-offset:2
 comment-column:40
 fill-column:79
+indent-tabs-mode:nil
 End:
 */