chiark / gitweb /
server/gstdecode.c: Allow user to tweak the various parameters.
[disorder] / server / gstdecode.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2013 Mark Wooding
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/gstdecode.c
19  * @brief Decode compressed audio files, and apply ReplayGain.
20  */
21
22 #include "disorder-server.h"
23
24 #include "speaker-protocol.h"
25
26 /* Ugh.  It turns out that libxml tries to define a function called
27  * `attribute', and it's included by GStreamer for some unimaginable reason.
28  * So undefine it here.  We'll want GCC attributes for special effects, but
29  * can take care of ourselves.
30  */
31 #undef attribute
32
33 #include <glib.h>
34 #include <gst/gst.h>
35 #include <gst/app/gstappsink.h>
36 #include <gst/audio/audio.h>
37
38 /* The only application we have for `attribute' is declaring function
39  * arguments as being unused, because we have a lot of callback functions
40  * which are meant to comply with an externally defined interface.
41  */
42 #ifdef __GNUC__
43 #  define UNUSED __attribute__((unused))
44 #endif
45
46 #define END ((void *)0)
47 #define N(v) (sizeof(v)/sizeof(*(v)))
48
49 static FILE *fp;
50 static const char *file;
51 static GstAppSink *appsink;
52 static GstElement *pipeline;
53 static GMainLoop *loop;
54
55 #define MODES(_) _("off", OFF) _("track", TRACK) _("album", ALBUM)
56 enum {
57 #define DEFENUM(name, tag) tag,
58   MODES(DEFENUM)
59 #undef DEFENUM
60   NMODES
61 };
62 static const char *const modes[] = {
63 #define DEFNAME(name, tag) name,
64   MODES(DEFNAME)
65 #undef DEFNAME
66   0
67 };
68
69 static const char *const dithers[] = {
70   "none", "rpdf", "tpdf", "tpdf-hf", 0
71 };
72
73 static const char *const shapes[] = {
74   "none", "error-feedback", "simple", "medium", "high", 0
75 };
76
77 static int dither = -1;
78 static int mode = ALBUM;
79 static int shape = -1;
80 static gdouble fallback = 0.0;
81
82 static struct stream_header hdr;
83
84 /* Report the pads of an element ELT, as iterated by IT; WHAT is an adjective
85  * phrase describing the pads for use in the output.
86  */
87 static void report_element_pads(const char *what, GstElement *elt,
88                                 GstIterator *it)
89 {
90   gchar *cs;
91   gpointer pad;
92
93   for(;;) {
94     switch(gst_iterator_next(it, &pad)) {
95     case GST_ITERATOR_DONE:
96       goto done;
97     case GST_ITERATOR_OK:
98       cs = gst_caps_to_string(gst_pad_get_caps(pad));
99       disorder_error(0, "  `%s' %s pad: %s", GST_OBJECT_NAME(elt), what, cs);
100       g_free(cs);
101       g_object_unref(pad);
102       break;
103     case GST_ITERATOR_RESYNC:
104       gst_iterator_resync(it);
105       break;
106     case GST_ITERATOR_ERROR:
107       disorder_error(0, "<failed to enumerate `%s' %s pads>",
108                      GST_OBJECT_NAME(elt), what);
109       goto done;
110     }
111   }
112
113 done:
114   gst_iterator_free(it);
115 }
116
117 /* Link together two elements; fail with an approximately useful error
118  * message if it didn't work.
119  */
120 static void link_elements(GstElement *left, GstElement *right)
121 {
122   /* Try to link things together. */
123   if(gst_element_link(left, right)) return;
124
125   /* If this didn't work, it's probably for some really hairy reason, so
126    * provide a bunch of debugging information.
127    */
128   disorder_error(0, "failed to link GStreamer elements `%s' and `%s'",
129                  GST_OBJECT_NAME(left), GST_OBJECT_NAME(right));
130   report_element_pads("source", left, gst_element_iterate_src_pads(left));
131   report_element_pads("source", right, gst_element_iterate_sink_pads(right));
132   disorder_fatal(0, "can't decode `%s'", file);
133 }
134
135 /* The `decoderbin' element (DECODE) has deigned to announce a new PAD.
136  * Maybe we should attach the tag end of our pipeline (starting with the
137  * element U) to it.
138  */
139 static void decoder_pad_arrived(GstElement *decode, GstPad *pad, gpointer u)
140 {
141   GstElement *tail = u;
142   GstCaps *caps = gst_pad_get_caps(pad);
143   GstStructure *s;
144   guint i, n;
145   const gchar *name;
146
147   /* The input file could be more or less anything, so this could be any kind
148    * of pad.  We're only interested if it's audio, so let's go check.
149    */
150   for(i = 0, n = gst_caps_get_size(caps); i < n; i++) {
151     s = gst_caps_get_structure(caps, i);
152     name = gst_structure_get_name(s);
153     if(strncmp(name, "audio/x-raw-", 12) == 0) goto match;
154   }
155   return;
156
157 match:
158   /* Yes, it's audio.  Link the two elements together. */
159   link_elements(decode, tail);
160
161   /* If requested using the environemnt variable `GST_DEBUG_DUMP_DOT_DIR',
162    * write a dump of the now-completed pipeline.
163    */
164   GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(pipeline),
165                             GST_DEBUG_GRAPH_SHOW_ALL,
166                             "disorder-gstdecode");
167 }
168
169 /* Prepare the GStreamer pipeline, ready to decode the given FILE.  This sets
170  * up the variables `appsink' and `pipeline'.
171  */
172 static void prepare_pipeline(void)
173 {
174   GstElement *source = gst_element_factory_make("filesrc", "file");
175   GstElement *decode = gst_element_factory_make("decodebin", "decode");
176   GstElement *convert = gst_element_factory_make("audioconvert", "convert");
177   GstElement *sink = gst_element_factory_make("appsink", "sink");
178   GstElement *tail = sink;
179   GstElement *gain;
180   GstCaps *caps = gst_caps_new_empty();
181   GstCaps *c;
182   static const int widths[] = { 8, 16 };
183   size_t i;
184
185   /* Set up the global variables. */
186   pipeline = gst_pipeline_new("pipe");
187   appsink = GST_APP_SINK(sink);
188
189   /* Configure the various simple elements. */
190   g_object_set(source, "location", file, END);
191   g_object_set(sink, "sync", FALSE, END);
192
193   /* Configure the converter.  Leave things as their defaults if the user
194    * hasn't made an explicit request.
195    */
196   if(dither >= 0) g_object_set(convert, "dithering", dither, END);
197   if(shape >= 0) g_object_set(convert, "noise-shaping", shape, END);
198
199   /* Set up the sink's capabilities. */
200   for(i = 0; i < N(widths); i++) {
201     c = gst_caps_new_simple("audio/x-raw-int",
202                             "width", G_TYPE_INT, widths[i],
203                             "depth", G_TYPE_INT, widths[i],
204                             "channels", GST_TYPE_INT_RANGE, 1, 2,
205                             "signed", G_TYPE_BOOLEAN, TRUE,
206                             "rate", GST_TYPE_INT_RANGE, 100, 1000000,
207                             END);
208     gst_caps_append(caps, c);
209   }
210   gst_app_sink_set_caps(appsink, caps);
211
212   /* Add the various elements into the pipeline.  We'll stitch them together
213    * in pieces, because the pipeline is somewhat dynamic.
214    */
215   gst_bin_add_many(GST_BIN(pipeline), source, decode, convert, sink, END);
216
217   /* Link an audio conversion stage onto the front.  The rest of DisOrder
218    * doesn't handle much of the full panoply of exciting audio formats.
219    */
220   link_elements(convert, tail); tail = convert;
221
222   /* If we're meant to do ReplayGain then insert it into the pipeline before
223    * the converter.
224    */
225   if(mode != OFF) {
226     gain = gst_element_factory_make("rgvolume", "gain");
227     g_object_set(gain,
228                  "album-mode", mode == ALBUM,
229                  "fallback-gain", fallback,
230                  END);
231     gst_bin_add(GST_BIN(pipeline), gain);
232     link_elements(gain, tail); tail = gain;
233   }
234
235   /* Link the source and the decoder together.  The `decodebin' is annoying
236    * and doesn't have any source pads yet, so the best we can do is make two
237    * halves of the chain, and add a hook to stitch them together later.
238    */
239   link_elements(source, decode);
240   g_signal_connect(decode, "pad-added",
241                    G_CALLBACK(decoder_pad_arrived), tail);
242 }
243
244 /* Respond to a message from the BUS.  The only thing we need worry about
245  * here is errors from the pipeline.
246  */
247 static void bus_message(GstBus UNUSED *bus, GstMessage *msg,
248                         gpointer UNUSED u)
249 {
250   switch(msg->type) {
251   case GST_MESSAGE_ERROR:
252     disorder_fatal(0, "%s",
253                    gst_structure_get_string(msg->structure, "debug"));
254   default:
255     break;
256   }
257 }
258
259 /* End of stream.  Stop polling the main loop. */
260 static void cb_eos(GstAppSink UNUSED *sink, gpointer UNUSED u)
261   { g_main_loop_quit(loop); }
262
263 /* Preroll buffers are prepared when the pipeline moves to the `paused'
264  * state, so that they're ready for immediate playback.  Conveniently, they
265  * also carry format information, which is what we want here.  Stash the
266  * sample format information in the `stream_header' structure ready for
267  * actual buffers of interesting data.
268  */
269 static GstFlowReturn cb_preroll(GstAppSink *sink, gpointer UNUSED u)
270 {
271   GstBuffer *buf = gst_app_sink_pull_preroll(sink);
272   GstCaps *caps = GST_BUFFER_CAPS(buf);
273
274 #ifdef HAVE_GST_AUDIO_INFO_FROM_CAPS
275
276   /* Parse the audio format information out of the caps.  There's a handy
277    * function to do this in later versions of gst-plugins-base, so use that
278    * if it's available.  Once we no longer care about supporting such old
279    * versions we can delete the version which does the job the hard way.
280    */
281
282   GstAudioInfo ai;
283
284   if(!gst_audio_info_from_caps(&ai, caps))
285     disorder_fatal(0, "can't decode `%s': failed to parse audio info", file);
286   hdr.rate = ai.rate;
287   hdr.channels = ai.channels;
288   hdr.bits = ai.finfo->width;
289   hdr.endian = ai.finfo->endianness == G_BIG_ENDIAN ?
290     ENDIAN_BIG : ENDIAN_LITTLE;
291
292 #else
293
294   GstStructure *s;
295   const char *ty;
296   gint rate, channels, bits, endian;
297   gboolean signedp;
298
299   /* Make sure that the caps is basically the right shape. */
300   if(!GST_CAPS_IS_SIMPLE(caps)) disorder_fatal(0, "expected simple caps");
301   s = gst_caps_get_structure(caps, 0);
302   ty = gst_structure_get_name(s);
303   if(strcmp(ty, "audio/x-raw-int") != 0)
304     disorder_fatal(0, "unexpected content type `%s'", ty);
305
306   /* Extract fields from the structure. */
307   if(!gst_structure_get(s,
308                         "rate", G_TYPE_INT, &rate,
309                         "channels", G_TYPE_INT, &channels,
310                         "width", G_TYPE_INT, &bits,
311                         "endianness", G_TYPE_INT, &endian,
312                         "signed", G_TYPE_BOOLEAN, &signedp,
313                         END))
314     disorder_fatal(0, "can't decode `%s': failed to parse audio caps", file);
315   hdr.rate = rate; hdr.channels = channels; hdr.bits = bits;
316   hdr.endian = endian == G_BIG_ENDIAN ? ENDIAN_BIG : ENDIAN_LITTLE;
317
318 #endif
319
320   gst_buffer_unref(buf);
321   return GST_FLOW_OK;
322 }
323
324 /* A new buffer of sample data has arrived, so we should pass it on with
325  * appropriate framing.
326  */
327 static GstFlowReturn cb_buffer(GstAppSink *sink, gpointer UNUSED u)
328 {
329   GstBuffer *buf = gst_app_sink_pull_buffer(sink);
330
331   /* Make sure we actually have a grip on the sample format here. */
332   if(!hdr.rate) disorder_fatal(0, "format unset");
333
334   /* Write out a frame of audio data. */
335   hdr.nbytes = GST_BUFFER_SIZE(buf);
336   if(fwrite(&hdr, sizeof(hdr), 1, fp) != 1 ||
337      fwrite(GST_BUFFER_DATA(buf), 1, hdr.nbytes, fp) != hdr.nbytes)
338     disorder_fatal(errno, "output");
339
340   /* And we're done. */
341   gst_buffer_unref(buf);
342   return GST_FLOW_OK;
343 }
344
345 static GstAppSinkCallbacks callbacks = {
346   .eos = cb_eos,
347   .new_preroll = cb_preroll,
348   .new_buffer = cb_buffer
349 };
350
351 /* Decode the audio file.  We're already set up for everything. */
352 static void decode(void)
353 {
354   GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
355
356   /* Set up the message bus and main loop. */
357   gst_bus_add_signal_watch(bus);
358   loop = g_main_loop_new(0, FALSE);
359   g_signal_connect(bus, "message", G_CALLBACK(bus_message), 0);
360
361   /* Tell the sink to call us when interesting things happen. */
362   gst_app_sink_set_callbacks(appsink, &callbacks, 0, 0);
363
364   /* Set the ball rolling. */
365   gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_PLAYING);
366
367   /* And wait for the miracle to come. */
368   g_main_loop_run(loop);
369
370   /* Shut down the pipeline.  This isn't strictly necessary, since we're
371    * about to exit very soon, but it's kind of polite.
372    */
373   gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL);
374 }
375
376 static int getenum(const char *what, const char *s, const char *const *tags)
377 {
378   int i;
379
380   for(i = 0; tags[i]; i++)
381     if(strcmp(s, tags[i]) == 0) return i;
382   disorder_fatal(0, "unknown %s `%s'", what, s);
383 }
384
385 static double getfloat(const char *what, const char *s)
386 {
387   double d;
388   char *q;
389
390   errno = 0;
391   d = strtod(s, &q);
392   if(*q || errno) disorder_fatal(0, "invalid %s `%s'", what, s);
393   return d;
394 }
395
396 static const struct option options[] = {
397   { "help", no_argument, 0, 'h' },
398   { "version", no_argument, 0, 'V' },
399   { "dither", required_argument, 0, 'd' },
400   { "fallback-gain", required_argument, 0, 'f' },
401   { "noise-shape", required_argument, 0, 'n' },
402   { "replay-gain", required_argument, 0, 'r' },
403   { 0, 0, 0, 0 }
404 };
405
406 static void help(void)
407 {
408   xprintf("Usage:\n"
409           "  disorder-gstdecode [OPTIONS] PATH\n"
410           "Options:\n"
411           "  --help, -h                 Display usage message\n"
412           "  --version, -V              Display version number\n"
413           "  --dither TYPE, -d TYPE     TYPE is `none', `rpdf', `tpdf', or "
414                                                 "`tpdf-hf'\n"
415           "  --fallback-gain DB, -f DB  For tracks without ReplayGain data\n"
416           "  --noise-shape TYPE, -n TYPE  TYPE is `none', `error-feedback',\n"
417           "                                     `simple', `medium' or `high'\n"
418           "  --replay-gain MODE, -r MODE  MODE is `off', `track' or `album'\n"
419           "\n"
420           "Alternative audio decoder for DisOrder.  Only intended to be\n"
421           "used by speaker process, not for normal users.\n");
422   xfclose(stdout);
423   exit(0);
424 }
425
426 /* Main program. */
427 int main(int argc, char *argv[])
428 {
429   int n;
430   const char *e;
431
432   /* Initial setup. */
433   set_progname(argv);
434   if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "calling setlocale");
435
436   /* Parse command line. */
437   while((n = getopt_long(argc, argv, "hVd:f:n:r:", options, 0)) >= 0) {
438     switch(n) {
439     case 'h': help();
440     case 'V': version("disorder-gstdecode");
441     case 'd': dither = getenum("dither type", optarg, dithers); break;
442     case 'f': fallback = getfloat("fallback gain", optarg); break;
443     case 'n': shape = getenum("noise-shaping type", optarg, shapes); break;
444     case 'r': mode = getenum("ReplayGain mode", optarg, modes); break;
445     default: disorder_fatal(0, "invalid option");
446     }
447   }
448   if(optind >= argc) disorder_fatal(0, "missing filename");
449   file = argv[optind++];
450   if(optind < argc) disorder_fatal(0, "excess arguments");
451
452   /* Set up the GStreamer machinery. */
453   gst_init(0, 0);
454   prepare_pipeline();
455
456   /* Set up the output file. */
457   if((e = getenv("DISORDER_RAW_FD")) != 0) {
458     if((fp = fdopen(atoi(e), "wb")) == 0) disorder_fatal(errno, "fdopen");
459   } else
460     fp = stdout;
461
462   /* Let's go. */
463   decode();
464
465   /* And now we're done. */
466   xfclose(fp);
467   return (0);
468 }
469
470 /*
471 Local Variables:
472 c-basic-offset:2
473 comment-column:40
474 fill-column:77
475 indent-tabs-mode:nil
476 End:
477 */