chiark / gitweb /
Merge branch 'mdw/gstdecode'
authorMark Wooding <mdw@distorted.org.uk>
Tue, 15 Dec 2015 19:15:23 +0000 (19:15 +0000)
committerMark Wooding <mdw@distorted.org.uk>
Sat, 16 Jan 2016 01:25:26 +0000 (01:25 +0000)
* mdw/gstdecode:
  Add documentation and administrivia about `disorder-gstdecode'.
  server/gstdecode.c: Produce the configured sample format directly.
  server/gstdecode.c: Allow user to tweak the various parameters.
  server/gstdecode.c: New program, like `disorder-decode'.

Conflicts:
.gitignore
CHANGES.html
README
debian/control

.gitignore
CHANGES.html
configure.ac
debian/control
debian/rules
doc/Makefile.am
doc/disorder-gstdecode.8.in [new file with mode: 0644]
server/Makefile.am
server/gstdecode.c [new file with mode: 0644]

index 694d0e7075df0eeb30e828c7a63f9562ae413714..83cdf9bc7fa4e98a02ba1a9748c0541a2284bb4e 100644 (file)
@@ -207,6 +207,8 @@ libtests/test-suite.log
 /GRTAGS
 /GSYMS
 /GTAGS
+debian/disorder-gstdecode
+server/disorder-gstdecode
 /Debug
 /lib/Debug
 /clients/Debug
index 403f2780cd04d6fc4602d3e3aafa35dfd5e8615f..24f2ac0f1fa3c4076eb9a52df501944de55ef549 100644 (file)
@@ -49,6 +49,42 @@ href="README.upgrades.html">README.upgrades</a> before upgrading.</p>
 
   </div>
 
+  <h3>GStreamer support</h3>
+
+  <div class=section>
+
+    <p>If it's detected at <tt>configure</tt> time, a new decoder
+    program <tt>disorder-gstdecode</tt> is built.  It uses the GStreamer
+    library for audio decoding and sample-rate conversion, among other
+    features.
+
+    <p>The decoder has a number of options for controlling the sample-rate and
+    audio format conversion, allowing various tradeoffs between quality and
+    processor time.  (High-quality conversion can consume more processor time
+    than decoding, so this is potentially useful on very a small device such as
+    a Raspberry Pi.</p>
+
+    <p>The GStreamer decoder can also use ReplayGain information stored in
+    audio files' metadata to adjust playback volume, so that tracks with very
+    wide dynamic range don't sound really quiet in comparison.  This
+    information can be added using tools such as <tt>mp3gain</tt>,
+    <tt>vorbisgain</tt>, or <tt>metaflac</tt>.  This is turned on by default if
+    you use the decoder; you can choose between per-album or per-track
+    settings, or turn it off entirely, using command-line options.</p> 
+
+    <p>The GStreamer decoder is not used by default, but it can be enabled
+    easily enough by dropping something like the following into the server
+    configuration file:
+      <pre>
+        player
+        player *.flac execraw /usr/sbin/disorder-gstdecode -ralbum -f-8.0
+        player *.mp2 execraw /usr/sbin/disorder-gstdecode -ralbum -f-8.0
+        player *.mp3 execraw /usr/sbin/disorder-gstdecode -ralbum -f-8.0
+        player *.ogg execraw /usr/sbin/disorder-gstdecode -ralbum -f-8.0
+        player *.wav execraw /usr/sbin/disorder-gstdecode -ralbum -f-8.0
+      </pre>
+    </p>
+
   <h3>Bug fixes</h3>
 
   <div class=section>
index e93d7a4d4aaf8f44f42077d510cfaeb9a96c56ab..2ade4ca2c74c15d7efd8b057d9d7daa0306255b8 100644 (file)
@@ -33,6 +33,7 @@ want_gtk=yes
 want_python=yes
 want_tests=yes
 want_server=yes
+want_gstdecode=whatever
 want_cgi=yes
 
 # APIs we want
@@ -250,9 +251,14 @@ AC_ARG_WITH([python],
            [AS_HELP_STRING([--without-python],
                            [do not build Python support])],
            [want_python=$withval])
+AC_ARG_WITH([gstdecode],
+            [AS_HELP_STRING([--with-gstdecode],
+                           [require GStreamer-based decoder])],
+            [want_gstdecode=$withval])
 
 if test $want_server = no; then
   want_cgi=no
+  want_gstdecode=no
 fi
 
 #
@@ -432,6 +438,38 @@ fi
 AC_SUBST([finkdir])
 AC_SUBST([finkbindir])
 
+# Checks for packages.
+case $want_gstdecode in
+  yes | whatever)
+    PKG_CHECK_MODULES([GSTREAMER], [gstreamer-0.10],
+        [have_gstreamer=yes], [have_gstreamer=no])
+    PKG_CHECK_MODULES([GSTREAMER_PLUGINS_BASE],
+        [gstreamer-plugins-base-0.10],
+        [have_gst_plugins_base=yes], [have_gst_plugins_base=no])
+    ;;
+esac
+case $want_gstdecode,$have_gstreamer,$have_gst_plugins_base in
+  whatever,yes,yes | yes,yes,yes) want_gstdecode=yes ;;
+  whatever,*) want_gstdecode=no ;;
+  yes,*)
+    case $have_gstreamer in
+      no) missing_libraries="$missing_libraries gstreamer-0.10" ;;
+    esac
+    case $have_gst_plugins_base in
+      no) missing_libraries="$missing_libraries gstreamer-plugins-base-0.10" ;;
+    esac
+esac
+
+mdw_SAVE_CFLAGS=$CFLAGS
+mdw_SAVE_LIBS=$LIBS
+CFLAGS="$CFLAGS $GSTREAMER_CFLAGS $GSTREAMER_PLUGINS_BASE_CFLAGS"
+LIBS="$LIBS \
+        $GSTREAMER_LIBS $GSTREAMER_PLUGINS_BASE_LIBS
+        -lgstaudio-0.10 -lgstapp-0.10"
+AC_CHECK_FUNCS([gst_audio_info_from_caps])
+CFLAGS=$mdw_SAVE_CFLAGS
+LIBS=$mdw_SAVE_LIBS
+
 # Checks for libraries.
 # We save up a list of missing libraries that we can't do without
 # and report them all at once.
@@ -696,6 +734,7 @@ if test $want_gtk = yes; then
   AC_DEFINE([WITH_GTK], [1], [define if using GTK+])
 fi
 AM_CONDITIONAL([GTK], [test x$want_gtk = xyes])
+AM_CONDITIONAL([GSTDECODE], [test x$want_gstdecode = xyes])
 
 # Some GCC invocations warn for converting function pointers to void *.
 # This is fair enough, as it's technically forbidden, but we use dlsym()
index 78d9508c5f9332becd9fd989fbace8928c45890f..0aece1dd6e37cb6e6fb19786c04edb44ccf240e3 100644 (file)
@@ -3,7 +3,7 @@ Maintainer: Richard Kettlewell <rjk@greenend.org.uk>
 Section: sound
 Priority: optional
 Standards-Version: 3.8.1.0
-Build-Depends: libgc6-dev | libgc-dev, libgcrypt-dev, libdb4.3-dev | libdb4.5-dev | libdb4.7-dev | libdb4.8-dev | libdb5.1-dev, libpcre3-dev, libvorbis-dev, libmad0-dev, libasound2-dev, libpulse-dev, python, libflac-dev, libgtk2.0-dev (>= 2.12.12)
+Build-Depends: libgc6-dev | libgc-dev, libgcrypt-dev, libdb4.3-dev | libdb4.5-dev | libdb4.7-dev | libdb4.8-dev | libdb5.1-dev, libpcre3-dev, libvorbis-dev, libmad0-dev, libasound2-dev, libpulse-dev, python, libflac-dev, libgtk2.0-dev (>= 2.12.12), pkg-config, libgstreamer0.10-dev, libgstreamer-plugins-base0.10-dev
 Vcs-Git: https://code.google.com/p/disorder/
 Homepage: http://www.greenend.org.uk/rjk/disorder/
 
@@ -53,6 +53,22 @@ Description: Network play client for DisOrder
  This package contains the RTP player.  It can play audio streams generated
  by the server, received over a LAN.
 
+Package: disorder-gstdecode
+Architecture: any
+Section: sound
+Priority: extra
+Depends: ${shlibs:Depends}
+Enhances: disorder-server
+Description: GStreamer-based audio decoder for DisOrder
+ DisOrder is a software jukebox.  It can play OGG, MP3, WAV and FLAC files,
+ and other formats with suitable configuration.  It is capable of playing
+ either via a locally attached sound device or over the network using
+ an RTP stream.
+ .
+ This package contains a GStreamer-based audio decoder.  This can (with
+ appropriate GStreamer plugins) decode different kinds of audio files, and
+ also apply ReplayGain to the decoded audio.
+
 Package: disobedience
 Architecture: any
 Section: sound
index 135b0a170e0b15a44fb8e2e2376a2ed84aaac93e..def2d53e68c72b20561174d5374ad5d5299f8164 100755 (executable)
@@ -169,6 +169,7 @@ pkg-disorder-server: build
        rm -f debian/disorder-server/usr/share/man/man5/disorder_config.5
        rm -f debian/disorder-server/usr/share/man/man5/disorder_preferences.5
        rm -f debian/disorder-server/usr/share/man/man5/disorder_protocol.5
+       rm -f debian/disorder-server/usr/sbin/disorder-gstdecode
        find debian/disorder-server -name '*.la' -print0 | xargs -r0 rm -f
        find debian/disorder-server -name '*.so.0' -print0 | xargs -r0 rm -f
        @for f in debian/disorder-server/usr/lib/disorder/*.so.0.0.0; do \
@@ -254,6 +255,42 @@ pkg-disorder-playrtp: build
        chmod -R g-ws debian/disorder-playrtp
        dpkg --build debian/disorder-playrtp ..
 
+pkg-disorder-gstdecode: build
+       rm -rf debian/disorder-gstdecode
+       $(MKDIR) debian/disorder-gstdecode
+       $(MKDIR) debian/disorder-gstdecode/DEBIAN
+       $(MKDIR) debian/disorder-gstdecode/usr/share/doc/disorder-gstdecode
+       $(INSTALL_DATA) debian/copyright \
+               debian/disorder-gstdecode/usr/share/doc/disorder-gstdecode/copyright
+       $(INSTALL_DATA) debian/changelog \
+               debian/disorder-gstdecode/usr/share/doc/disorder-gstdecode/changelog
+       gzip -9 debian/disorder-gstdecode/usr/share/doc/disorder-gstdecode/changelog*
+       @for f in preinst postinst prerm postrm conffiles templates config; do\
+         if test -e debian/$$f.disorder-gstdecode; then\
+           echo $(INSTALL_SCRIPT) debian/$$f.disorder-gstdecode debian/disorder-gstdecode/DEBIAN/$$f; \
+           $(INSTALL_SCRIPT) debian/$$f.disorder-gstdecode debian/disorder-gstdecode/DEBIAN/$$f; \
+         fi;\
+       done
+       $(MKDIR) debian/disorder-gstdecode/usr/sbin
+       $(MKDIR) debian/disorder-gstdecode/usr/share/man/man8
+       $(INSTALL_PROGRAM) server/disorder-gstdecode \
+               debian/disorder-gstdecode/usr/sbin/disorder-gstdecode
+       strip --remove-section=.comment debian/disorder-gstdecode/usr/sbin/disorder-gstdecode
+       $(INSTALL_DATA) doc/disorder-gstdecode.8 \
+               debian/disorder-gstdecode/usr/share/man/man8/disorder-gstdecode.8
+       dpkg-shlibdeps -Tdebian/substvars.disorder-gstdecode \
+               debian/disorder-gstdecode/usr/sbin/*
+       $(INSTALL_DATA) CHANGES.html debian/disorder-gstdecode/usr/share/doc/disorder-gstdecode/CHANGES.html
+       gzip -9f debian/disorder-gstdecode/usr/share/man/man*/*
+       cd debian/disorder-gstdecode && \
+               find -name DEBIAN -prune -o -type f -print \
+                       | sed 's/^\.\///' \
+                       | xargs md5sum > DEBIAN/md5sums
+       dpkg-gencontrol -isp -pdisorder-gstdecode -Pdebian/disorder-gstdecode -Tdebian/substvars.disorder-gstdecode
+       chown -R root:root debian/disorder-gstdecode
+       chmod -R g-ws debian/disorder-gstdecode
+       dpkg --build debian/disorder-gstdecode ..
+
 pkg-disobedience: build
        rm -rf debian/disobedience
        $(MKDIR) debian/disobedience
@@ -319,7 +356,7 @@ source-check: source
 
 binary: binary-arch binary-indep
 binary-arch: pkg-disorder pkg-disorder-server pkg-disorder-playrtp \
-            pkg-disobedience
+            pkg-disorder-gstdecode pkg-disobedience
 binary-indep: 
 
 clean:
index b3d892604f46a1ccdf9c9854e25e615ebaf0f1a7..391913519ef952e29865a98fcd9074742a0ba224 100644 (file)
@@ -24,14 +24,15 @@ man_MANS=disorderd.8 disorder.1 disorder.3 disorder_config.5 disorder-dump.8 \
        disorder-playrtp.1 disorder-normalize.8 disorder-decode.8 \
        disorder-stats.8 disorder-dbupgrade.8 disorder_templates.5 \
        disorder_actions.5 disorder_options.5 disorder.cgi.8 \
-       disorder_preferences.5 disorder-choose.8
+       disorder_preferences.5 disorder-choose.8 disorder-gstdecode.8
 
 SEDFILES=disorder.1 disorderd.8 disorder_config.5 \
        disorder-dump.8 disorder_protocol.5 disorder-deadlock.8 \
        disorder-rescan.8 disobedience.1 disorderfm.1 disorder-playrtp.1 \
        disorder-decode.8 disorder-stats.8 disorder-dbupgrade.8 \
        disorder_options.5 disorder.cgi.8 disorder_templates.5 \
-       disorder_actions.5 disorder_preferences.5 disorder-choose.8
+       disorder_actions.5 disorder_preferences.5 disorder-choose.8 \
+       disorder-gstdecode.8
 
 include ${top_srcdir}/scripts/sedfiles.make
 
@@ -42,7 +43,8 @@ disorderfm.1.html disorder-speaker.8.html disorder-playrtp.1.html     \
 disorder-normalize.8.html disorder-decode.8.html disorder-stats.8.html \
 disorder-dbupgrade.8.html disorder_templates.5.html                    \
 disorder_actions.5.html disorder_options.5.html disorder.cgi.8.html    \
-disorder_preferences.5.html disorder-choose.8.html
+disorder_preferences.5.html disorder-choose.8.html                     \
+disorder-gstdecode.8.html
 
 $(wordlist 2,9999,$(HTMLMAN)): disorderd.8.html
 disorderd.8.html: $(man_MANS)
@@ -55,7 +57,8 @@ disorderfm.1.tmpl disorder-speaker.8.tmpl disorder-playrtp.1.tmpl     \
 disorder-normalize.8.tmpl disorder-decode.8.tmpl disorder-stats.8.tmpl \
 disorder-dbupgrade.8.tmpl disorder_templates.5.tmpl                    \
 disorder_actions.5.tmpl disorder_options.5.tmpl disorder.cgi.8.tmpl    \
-disorder_preferences.5.tmpl disorder-choose.8.tmpl
+disorder_preferences.5.tmpl disorder-choose.8.tmpl                     \
+disorder-gstdecode.8.tmpl
 
 $(wordlist 2,9999,$(TMPLMAN)): disorderd.8.tmpl
 disorderd.8.tmpl: $(man_MANS)
@@ -101,7 +104,7 @@ EXTRA_DIST=disorderd.8.in disorder.1.in disorder_config.5.in \
           disorder_actions.5.head disorder_templates.5.head \
           disorder_actions.5.tail disorder_templates.5.tail \
           disorder_options.5.in disorder.cgi.8.in disorder_preferences.5.in \
-          disorder-choose.8.in
+          disorder-choose.8.in disorder-gstdecode.8.in
 
 CLEANFILES=$(SEDFILES) $(HTMLMAN) $(TMPLMAN) \
        disorder_actions.5.in disorder_templates.5.in
diff --git a/doc/disorder-gstdecode.8.in b/doc/disorder-gstdecode.8.in
new file mode 100644 (file)
index 0000000..16fb458
--- /dev/null
@@ -0,0 +1,110 @@
+.\" -*-nroff-*-
+.\"
+.\" Copyright (C) 2007, 2008 Richard Kettlewell
+.\" Copyright (C) 2016 Mark Wooding
+.\"
+.\" 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 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.
+.\" 
+.\" You should have received a copy of the GNU General Public License
+.\" along with this program.  If not, see <http://www.gnu.org/licenses/>.
+.\"
+.TH disorder-gstdecode 8
+.SH NAME
+disorder-gstdecode \- DisOrder audio decoder using GStreamer
+.SH SYNOPSIS
+.B disorder\-gstdecode
+.RB [ -c
+.IR CONFIGFILE ]
+.RB [ -d
+.IR DITHER ]
+.RB [ -f
+.IR GAIN ]
+.br
+\h'8n'\c
+.RB [ -n
+.IR SHAPE ]
+.RB [ -q
+.IR QUALITY ]
+.RB [ -r
+.IR MODE ]
+.I PATH
+.SH DESCRIPTION
+.B disorder\-gstdecode
+converts encoded audio files into DisOrder's "raw" format.
+It uses the GStreamer library for conversion,
+and can decode any kind of audio file
+for which the necessary GStreamer plugins are available.
+.PP
+It is suitable for use as an
+.B execraw
+player.
+.PP
+It is not intended to be used from the command line,
+but command-line options can usefully be provided
+in DisOrder's configuration file.
+.SH OPTIONS
+.TP
+.B \-\-help\fR, \fB\-h
+Display a usage message.
+.TP
+.B \-\-version\fR, \fB\-V
+Display version number.
+.TP
+.B \-\-config \fICONFIGFILE\fR, \fB\-c \fICONFIGFILE
+Set the configuration file.
+.TP
+.B \-\-dither \fITYPE\fR, \fB\-d \fIDITHER
+Set the dither type used during audio format conversion.
+This can be \fBnone\fR,
+\fBrpdf\fR for rectangular dithering,
+\fBtpdf\fR for triangular dithering, or
+\fBtpdf-hf\fR for high-frequency triangular dithering.
+Maybe the GStreamer documentation will explain what these mean.
+The default is to leave the decision
+to GStreamer's \fBaudioconvert\fR plugin.
+.TP
+.B \-\-fallback-gain \fIGAIN\fR, \fB\-f \fIGAIN
+Set the gain to be applied to tracks
+which don't have ReplayGain information.
+This is in decibels, and will usually be negative.
+The default is zero, which is probably wrong.
+.TP
+.B \-\-noise-shape \fITYPE\fR, \fB-n \fITYPE
+Set the noise shaping type used during audio format conversion.
+This can be \fBnone\fR,
+\fBerror-feedback\fR,
+\fBsimple\fR for 2-pole noise shaping,
+\fBmedium\fR for 5-pole noise shaping, or
+\fBhigh\fR for 8-pole noise shaping.
+Maybe the GStreamer documentation will explain what these mean.
+The default is to leave the decision
+to GStreamer's \fBaudioconvert\fR plugin.
+.TP
+.B \-\-quality \fIQUALITY\fR, \fB\-q \fIQUALITY
+Set the quality level to be used for resampling.
+This should be an integer between
+0 (poor, but fast) and
+10 (good, but slow).
+See the GStreamer documentation for more information.
+The default is to leave the decision
+to GStreamer's \fBaudioresample\fR plugin.
+.TP
+.B \-\-replay-gain \fIMODE\fR, \fB\-r \fIMODE
+Set the ReplayGain mode.
+This can be \fBoff\fR to not bother with ReplayGain at all,
+\fBtrack\fR to use the per-track gain setting, or
+\fBalbum\fR to use the per-album gain setting
+(so that the volume level sounds consistent
+when playing an entire album).
+The default is \fBalbum\fR.
+.SH "SEE ALSO"
+.BR disorderd (8),
+.BR disorder_config (5)
index 01e769a0b44ee922dc39fd5226cca4da73a04b6b..2f049eea8bdf2c9c6be8fd9a81c0571ebe057f12 100644 (file)
@@ -23,6 +23,7 @@ noinst_PROGRAMS=trackname endian
 
 AUTOMAKE_OPTIONS=subdir-objects
 AM_CPPFLAGS=-I${top_srcdir}/lib -I../lib
+AM_CFLAGS=
 
 disorderd_SOURCES=disorderd.c api.c api-server.c daemonize.c play.c    \
        server.c server-queue.c queue-ops.c state.c plugin.c            \
@@ -53,6 +54,16 @@ disorder_decode_LDADD=$(LIBOBJS) ../lib/libdisorder.a \
        $(LIBMAD) $(LIBVORBISFILE) $(LIBFLAC)
 disorder_decode_DEPENDENCIES=../lib/libdisorder.a
 
+if GSTDECODE
+AM_CFLAGS+=$(GSTREAMER_CFLAGS)
+sbin_PROGRAMS+=disorder-gstdecode
+disorder_gstdecode_SOURCES=gstdecode.c disorder-server.h
+disorder_gstdecode_LDADD=$(LIBOBJS) ../lib/libdisorder.a \
+       $(GSTREAMER_PLUGINS_BASE_LIBS) -lgstaudio-0.10 -lgstapp-0.10 \
+       $(GSTREAMER_LIBS) $(LIBGCRYPT)
+disorder_gstdecode_DEPENDENCIES=../lib/libdisorder.a
+endif
+
 disorder_normalize_SOURCES=normalize.c disorder-server.h
 disorder_normalize_LDADD=$(LIBOBJS) ../lib/libdisorder.a \
        $(LIBPCRE) $(LIBICONV) $(LIBGCRYPT) $(LIBSAMPLERATE)
diff --git a/server/gstdecode.c b/server/gstdecode.c
new file mode 100644 (file)
index 0000000..10884a4
--- /dev/null
@@ -0,0 +1,501 @@
+/*
+ * This file is part of DisOrder
+ * Copyright (C) 2013 Mark Wooding
+ *
+ * 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 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+/** @file server/gstdecode.c
+ * @brief Decode compressed audio files, and apply ReplayGain.
+ */
+
+#include "disorder-server.h"
+
+#include "speaker-protocol.h"
+
+/* Ugh.  It turns out that libxml tries to define a function called
+ * `attribute', and it's included by GStreamer for some unimaginable reason.
+ * So undefine it here.  We'll want GCC attributes for special effects, but
+ * can take care of ourselves.
+ */
+#undef attribute
+
+#include <glib.h>
+#include <gst/gst.h>
+#include <gst/app/gstappsink.h>
+#include <gst/audio/audio.h>
+
+/* The only application we have for `attribute' is declaring function
+ * arguments as being unused, because we have a lot of callback functions
+ * which are meant to comply with an externally defined interface.
+ */
+#ifdef __GNUC__
+#  define UNUSED __attribute__((unused))
+#endif
+
+#define END ((void *)0)
+#define N(v) (sizeof(v)/sizeof(*(v)))
+
+static FILE *fp;
+static const char *file;
+static GstAppSink *appsink;
+static GstElement *pipeline;
+static GMainLoop *loop;
+
+#define MODES(_) _("off", OFF) _("track", TRACK) _("album", ALBUM)
+enum {
+#define DEFENUM(name, tag) tag,
+  MODES(DEFENUM)
+#undef DEFENUM
+  NMODES
+};
+static const char *const modes[] = {
+#define DEFNAME(name, tag) name,
+  MODES(DEFNAME)
+#undef DEFNAME
+  0
+};
+
+static const char *const dithers[] = {
+  "none", "rpdf", "tpdf", "tpdf-hf", 0
+};
+
+static const char *const shapes[] = {
+  "none", "error-feedback", "simple", "medium", "high", 0
+};
+
+static int dither = -1;
+static int mode = ALBUM;
+static int quality = -1;
+static int shape = -1;
+static gdouble fallback = 0.0;
+
+static struct stream_header hdr;
+
+/* Report the pads of an element ELT, as iterated by IT; WHAT is an adjective
+ * phrase describing the pads for use in the output.
+ */
+static void report_element_pads(const char *what, GstElement *elt,
+                                GstIterator *it)
+{
+  gchar *cs;
+  gpointer pad;
+
+  for(;;) {
+    switch(gst_iterator_next(it, &pad)) {
+    case GST_ITERATOR_DONE:
+      goto done;
+    case GST_ITERATOR_OK:
+      cs = gst_caps_to_string(gst_pad_get_caps(pad));
+      disorder_error(0, "  `%s' %s pad: %s", GST_OBJECT_NAME(elt), what, cs);
+      g_free(cs);
+      g_object_unref(pad);
+      break;
+    case GST_ITERATOR_RESYNC:
+      gst_iterator_resync(it);
+      break;
+    case GST_ITERATOR_ERROR:
+      disorder_error(0, "<failed to enumerate `%s' %s pads>",
+                     GST_OBJECT_NAME(elt), what);
+      goto done;
+    }
+  }
+
+done:
+  gst_iterator_free(it);
+}
+
+/* Link together two elements; fail with an approximately useful error
+ * message if it didn't work.
+ */
+static void link_elements(GstElement *left, GstElement *right)
+{
+  /* Try to link things together. */
+  if(gst_element_link(left, right)) return;
+
+  /* If this didn't work, it's probably for some really hairy reason, so
+   * provide a bunch of debugging information.
+   */
+  disorder_error(0, "failed to link GStreamer elements `%s' and `%s'",
+                 GST_OBJECT_NAME(left), GST_OBJECT_NAME(right));
+  report_element_pads("source", left, gst_element_iterate_src_pads(left));
+  report_element_pads("source", right, gst_element_iterate_sink_pads(right));
+  disorder_fatal(0, "can't decode `%s'", file);
+}
+
+/* The `decoderbin' element (DECODE) has deigned to announce a new PAD.
+ * Maybe we should attach the tag end of our pipeline (starting with the
+ * element U) to it.
+ */
+static void decoder_pad_arrived(GstElement *decode, GstPad *pad, gpointer u)
+{
+  GstElement *tail = u;
+  GstCaps *caps = gst_pad_get_caps(pad);
+  GstStructure *s;
+  guint i, n;
+  const gchar *name;
+
+  /* The input file could be more or less anything, so this could be any kind
+   * of pad.  We're only interested if it's audio, so let's go check.
+   */
+  for(i = 0, n = gst_caps_get_size(caps); i < n; i++) {
+    s = gst_caps_get_structure(caps, i);
+    name = gst_structure_get_name(s);
+    if(strncmp(name, "audio/x-raw-", 12) == 0) goto match;
+  }
+  return;
+
+match:
+  /* Yes, it's audio.  Link the two elements together. */
+  link_elements(decode, tail);
+
+  /* If requested using the environemnt variable `GST_DEBUG_DUMP_DOT_DIR',
+   * write a dump of the now-completed pipeline.
+   */
+  GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(pipeline),
+                            GST_DEBUG_GRAPH_SHOW_ALL,
+                            "disorder-gstdecode");
+}
+
+/* Prepare the GStreamer pipeline, ready to decode the given FILE.  This sets
+ * up the variables `appsink' and `pipeline'.
+ */
+static void prepare_pipeline(void)
+{
+  GstElement *source = gst_element_factory_make("filesrc", "file");
+  GstElement *decode = gst_element_factory_make("decodebin", "decode");
+  GstElement *resample = gst_element_factory_make("audioresample",
+                                                  "resample");
+  GstElement *convert = gst_element_factory_make("audioconvert", "convert");
+  GstElement *sink = gst_element_factory_make("appsink", "sink");
+  GstElement *tail = sink;
+  GstElement *gain;
+  GstCaps *caps;
+  const struct stream_header *fmt = &config->sample_format;
+
+  /* Set up the global variables. */
+  pipeline = gst_pipeline_new("pipe");
+  appsink = GST_APP_SINK(sink);
+
+  /* Configure the various simple elements. */
+  g_object_set(source, "location", file, END);
+  g_object_set(sink, "sync", FALSE, END);
+
+  /* Configure the resampler and converter.  Leave things as their defaults
+   * if the user hasn't made an explicit request.
+   */
+  if(quality >= 0) g_object_set(resample, "quality", quality, END);
+  if(dither >= 0) g_object_set(convert, "dithering", dither, END);
+  if(shape >= 0) g_object_set(convert, "noise-shaping", shape, END);
+
+  /* Set up the sink's capabilities from the configuration. */
+  caps = gst_caps_new_simple("audio/x-raw-int",
+                             "width", G_TYPE_INT, fmt->bits,
+                             "depth", G_TYPE_INT, fmt->bits,
+                             "channels", G_TYPE_INT, fmt->channels,
+                             "signed", G_TYPE_BOOLEAN, TRUE,
+                             "rate", G_TYPE_INT, fmt->rate,
+                             "endianness", G_TYPE_INT,
+                               fmt->endian == ENDIAN_BIG ?
+                                 G_BIG_ENDIAN : G_LITTLE_ENDIAN,
+                             END);
+  gst_app_sink_set_caps(appsink, caps);
+
+  /* Add the various elements into the pipeline.  We'll stitch them together
+   * in pieces, because the pipeline is somewhat dynamic.
+   */
+  gst_bin_add_many(GST_BIN(pipeline),
+                   source, decode,
+                   resample, convert, sink, END);
+
+  /* Link audio conversion stages onto the front.  The rest of DisOrder
+   * doesn't handle much of the full panoply of exciting audio formats.
+   */
+  link_elements(convert, tail); tail = convert;
+  link_elements(resample, tail); tail = resample;
+
+  /* If we're meant to do ReplayGain then insert it into the pipeline before
+   * the converter.
+   */
+  if(mode != OFF) {
+    gain = gst_element_factory_make("rgvolume", "gain");
+    g_object_set(gain,
+                 "album-mode", mode == ALBUM,
+                 "fallback-gain", fallback,
+                 END);
+    gst_bin_add(GST_BIN(pipeline), gain);
+    link_elements(gain, tail); tail = gain;
+  }
+
+  /* Link the source and the decoder together.  The `decodebin' is annoying
+   * and doesn't have any source pads yet, so the best we can do is make two
+   * halves of the chain, and add a hook to stitch them together later.
+   */
+  link_elements(source, decode);
+  g_signal_connect(decode, "pad-added",
+                   G_CALLBACK(decoder_pad_arrived), tail);
+}
+
+/* Respond to a message from the BUS.  The only thing we need worry about
+ * here is errors from the pipeline.
+ */
+static void bus_message(GstBus UNUSED *bus, GstMessage *msg,
+                        gpointer UNUSED u)
+{
+  switch(msg->type) {
+  case GST_MESSAGE_ERROR:
+    disorder_fatal(0, "%s",
+                   gst_structure_get_string(msg->structure, "debug"));
+  default:
+    break;
+  }
+}
+
+/* End of stream.  Stop polling the main loop. */
+static void cb_eos(GstAppSink UNUSED *sink, gpointer UNUSED u)
+  { g_main_loop_quit(loop); }
+
+/* Preroll buffers are prepared when the pipeline moves to the `paused'
+ * state, so that they're ready for immediate playback.  Conveniently, they
+ * also carry format information, which is what we want here.  Stash the
+ * sample format information in the `stream_header' structure ready for
+ * actual buffers of interesting data.
+ */
+static GstFlowReturn cb_preroll(GstAppSink *sink, gpointer UNUSED u)
+{
+  GstBuffer *buf = gst_app_sink_pull_preroll(sink);
+  GstCaps *caps = GST_BUFFER_CAPS(buf);
+
+#ifdef HAVE_GST_AUDIO_INFO_FROM_CAPS
+
+  /* Parse the audio format information out of the caps.  There's a handy
+   * function to do this in later versions of gst-plugins-base, so use that
+   * if it's available.  Once we no longer care about supporting such old
+   * versions we can delete the version which does the job the hard way.
+   */
+
+  GstAudioInfo ai;
+
+  if(!gst_audio_info_from_caps(&ai, caps))
+    disorder_fatal(0, "can't decode `%s': failed to parse audio info", file);
+  hdr.rate = ai.rate;
+  hdr.channels = ai.channels;
+  hdr.bits = ai.finfo->width;
+  hdr.endian = ai.finfo->endianness == G_BIG_ENDIAN ?
+    ENDIAN_BIG : ENDIAN_LITTLE;
+
+#else
+
+  GstStructure *s;
+  const char *ty;
+  gint rate, channels, bits, endian;
+  gboolean signedp;
+
+  /* Make sure that the caps is basically the right shape. */
+  if(!GST_CAPS_IS_SIMPLE(caps)) disorder_fatal(0, "expected simple caps");
+  s = gst_caps_get_structure(caps, 0);
+  ty = gst_structure_get_name(s);
+  if(strcmp(ty, "audio/x-raw-int") != 0)
+    disorder_fatal(0, "unexpected content type `%s'", ty);
+
+  /* Extract fields from the structure. */
+  if(!gst_structure_get(s,
+                        "rate", G_TYPE_INT, &rate,
+                        "channels", G_TYPE_INT, &channels,
+                        "width", G_TYPE_INT, &bits,
+                        "endianness", G_TYPE_INT, &endian,
+                        "signed", G_TYPE_BOOLEAN, &signedp,
+                        END))
+    disorder_fatal(0, "can't decode `%s': failed to parse audio caps", file);
+  hdr.rate = rate; hdr.channels = channels; hdr.bits = bits;
+  hdr.endian = endian == G_BIG_ENDIAN ? ENDIAN_BIG : ENDIAN_LITTLE;
+
+#endif
+
+  gst_buffer_unref(buf);
+  return GST_FLOW_OK;
+}
+
+/* A new buffer of sample data has arrived, so we should pass it on with
+ * appropriate framing.
+ */
+static GstFlowReturn cb_buffer(GstAppSink *sink, gpointer UNUSED u)
+{
+  GstBuffer *buf = gst_app_sink_pull_buffer(sink);
+
+  /* Make sure we actually have a grip on the sample format here. */
+  if(!hdr.rate) disorder_fatal(0, "format unset");
+
+  /* Write out a frame of audio data. */
+  hdr.nbytes = GST_BUFFER_SIZE(buf);
+  if(fwrite(&hdr, sizeof(hdr), 1, fp) != 1 ||
+     fwrite(GST_BUFFER_DATA(buf), 1, hdr.nbytes, fp) != hdr.nbytes)
+    disorder_fatal(errno, "output");
+
+  /* And we're done. */
+  gst_buffer_unref(buf);
+  return GST_FLOW_OK;
+}
+
+static GstAppSinkCallbacks callbacks = {
+  .eos = cb_eos,
+  .new_preroll = cb_preroll,
+  .new_buffer = cb_buffer
+};
+
+/* Decode the audio file.  We're already set up for everything. */
+static void decode(void)
+{
+  GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
+
+  /* Set up the message bus and main loop. */
+  gst_bus_add_signal_watch(bus);
+  loop = g_main_loop_new(0, FALSE);
+  g_signal_connect(bus, "message", G_CALLBACK(bus_message), 0);
+
+  /* Tell the sink to call us when interesting things happen. */
+  gst_app_sink_set_callbacks(appsink, &callbacks, 0, 0);
+
+  /* Set the ball rolling. */
+  gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_PLAYING);
+
+  /* And wait for the miracle to come. */
+  g_main_loop_run(loop);
+
+  /* Shut down the pipeline.  This isn't strictly necessary, since we're
+   * about to exit very soon, but it's kind of polite.
+   */
+  gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL);
+}
+
+static int getenum(const char *what, const char *s, const char *const *tags)
+{
+  int i;
+
+  for(i = 0; tags[i]; i++)
+    if(strcmp(s, tags[i]) == 0) return i;
+  disorder_fatal(0, "unknown %s `%s'", what, s);
+}
+
+static double getfloat(const char *what, const char *s)
+{
+  double d;
+  char *q;
+
+  errno = 0;
+  d = strtod(s, &q);
+  if(*q || errno) disorder_fatal(0, "invalid %s `%s'", what, s);
+  return d;
+}
+
+static int getint(const char *what, const char *s, int min, int max)
+{
+  long i;
+  char *q;
+
+  errno = 0;
+  i = strtol(s, &q, 10);
+  if(*q || errno || min > i || i > max)
+    disorder_fatal(0, "invalid %s `%s'", what, s);
+  return (int)i;
+}
+
+static const struct option options[] = {
+  { "help", no_argument, 0, 'h' },
+  { "version", no_argument, 0, 'V' },
+  { "config", required_argument, 0, 'c' },
+  { "dither", required_argument, 0, 'd' },
+  { "fallback-gain", required_argument, 0, 'f' },
+  { "noise-shape", required_argument, 0, 'n' },
+  { "quality", required_argument, 0, 'q' },
+  { "replay-gain", required_argument, 0, 'r' },
+  { 0, 0, 0, 0 }
+};
+
+static void help(void)
+{
+  xprintf("Usage:\n"
+          "  disorder-gstdecode [OPTIONS] PATH\n"
+          "Options:\n"
+          "  --help, -h                 Display usage message\n"
+          "  --version, -V              Display version number\n"
+          "  --config PATH, -c PATH     Set configuration file\n"
+          "  --dither TYPE, -d TYPE     TYPE is `none', `rpdf', `tpdf', or "
+                                                "`tpdf-hf'\n"
+          "  --fallback-gain DB, -f DB  For tracks without ReplayGain data\n"
+          "  --noise-shape TYPE, -n TYPE  TYPE is `none', `error-feedback',\n"
+          "                                     `simple', `medium' or `high'\n"
+          "  --quality QUAL, -q QUAL    Resampling quality: 0 poor, 10 good\n"
+          "  --replay-gain MODE, -r MODE  MODE is `off', `track' or `album'\n"
+          "\n"
+          "Alternative audio decoder for DisOrder.  Only intended to be\n"
+          "used by speaker process, not for normal users.\n");
+  xfclose(stdout);
+  exit(0);
+}
+
+/* Main program. */
+int main(int argc, char *argv[])
+{
+  int n;
+  const char *e;
+
+  /* Initial setup. */
+  set_progname(argv);
+  if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "calling setlocale");
+
+  /* Parse command line. */
+  while((n = getopt_long(argc, argv, "hVc:d:f:n:q:r:", options, 0)) >= 0) {
+    switch(n) {
+    case 'h': help();
+    case 'V': version("disorder-gstdecode");
+    case 'c': configfile = optarg; break;
+    case 'd': dither = getenum("dither type", optarg, dithers); break;
+    case 'f': fallback = getfloat("fallback gain", optarg); break;
+    case 'n': shape = getenum("noise-shaping type", optarg, shapes); break;
+    case 'q': quality = getint("resample quality", optarg, 0, 10); break;
+    case 'r': mode = getenum("ReplayGain mode", optarg, modes); break;
+    default: disorder_fatal(0, "invalid option");
+    }
+  }
+  if(optind >= argc) disorder_fatal(0, "missing filename");
+  file = argv[optind++];
+  if(optind < argc) disorder_fatal(0, "excess arguments");
+  if(config_read(1, 0)) disorder_fatal(0, "cannot read configuration");
+
+  /* Set up the GStreamer machinery. */
+  gst_init(0, 0);
+  prepare_pipeline();
+
+  /* Set up the output file. */
+  if((e = getenv("DISORDER_RAW_FD")) != 0) {
+    if((fp = fdopen(atoi(e), "wb")) == 0) disorder_fatal(errno, "fdopen");
+  } else
+    fp = stdout;
+
+  /* Let's go. */
+  decode();
+
+  /* And now we're done. */
+  xfclose(fp);
+  return (0);
+}
+
+/*
+Local Variables:
+c-basic-offset:2
+comment-column:40
+fill-column:77
+indent-tabs-mode:nil
+End:
+*/