chiark / gitweb /
libtests: Include the Unicode test files directly.
[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 static unsigned flags = 0;
55 #define f_stream 1u
56
57 #define MODES(_) _("off", OFF) _("track", TRACK) _("album", ALBUM)
58 enum {
59 #define DEFENUM(name, tag) tag,
60   MODES(DEFENUM)
61 #undef DEFENUM
62   NMODES
63 };
64 static const char *const modes[] = {
65 #define DEFNAME(name, tag) name,
66   MODES(DEFNAME)
67 #undef DEFNAME
68   0
69 };
70
71 static const char *const dithers[] = {
72   "none", "rpdf", "tpdf", "tpdf-hf", 0
73 };
74
75 static const char *const shapes[] = {
76   "none", "error-feedback", "simple", "medium", "high", 0
77 };
78
79 static int dither = -1;
80 static int mode = ALBUM;
81 static int quality = -1;
82 static int shape = -1;
83 static gdouble fallback = 0.0;
84
85 static struct stream_header hdr;
86
87 /* Report the pads of an element ELT, as iterated by IT; WHAT is an adjective
88  * phrase describing the pads for use in the output.
89  */
90 static void report_element_pads(const char *what, GstElement *elt,
91                                 GstIterator *it)
92 {
93   gchar *cs;
94 #ifdef HAVE_GSTREAMER_0_10
95   gpointer pad;
96 #else
97   GValue gv;
98   GstPad *pad;
99   GstCaps *caps;
100 #endif
101
102   for(;;) {
103 #ifdef HAVE_GSTREAMER_0_10
104     switch(gst_iterator_next(it, &pad)) {
105 #else
106     switch(gst_iterator_next(it, &gv)) {
107 #endif
108     case GST_ITERATOR_DONE:
109       goto done;
110     case GST_ITERATOR_OK:
111 #ifdef HAVE_GSTREAMER_0_10
112       cs = gst_caps_to_string(gst_pad_get_caps(pad));
113 #else
114       assert(G_VALUE_HOLDS(&gv, GST_TYPE_PAD));
115       pad = g_value_get_object(&gv);
116       caps = gst_pad_query_caps(pad, 0);
117       cs = gst_caps_to_string(caps);
118       g_object_unref(caps);
119 #endif
120       disorder_error(0, "  `%s' %s pad: %s", GST_OBJECT_NAME(elt), what, cs);
121       g_free(cs);
122 #ifdef HAVE_GSTREAMER_0_10
123       g_object_unref(pad);
124 #endif
125       break;
126     case GST_ITERATOR_RESYNC:
127       gst_iterator_resync(it);
128       break;
129     case GST_ITERATOR_ERROR:
130       disorder_error(0, "<failed to enumerate `%s' %s pads>",
131                      GST_OBJECT_NAME(elt), what);
132       goto done;
133     }
134   }
135
136 done:
137   gst_iterator_free(it);
138 }
139
140 /* Link together two elements; fail with an approximately useful error
141  * message if it didn't work.
142  */
143 static void link_elements(GstElement *left, GstElement *right)
144 {
145   /* Try to link things together. */
146   if(gst_element_link(left, right)) return;
147
148   /* If this didn't work, it's probably for some really hairy reason, so
149    * provide a bunch of debugging information.
150    */
151   disorder_error(0, "failed to link GStreamer elements `%s' and `%s'",
152                  GST_OBJECT_NAME(left), GST_OBJECT_NAME(right));
153   report_element_pads("source", left, gst_element_iterate_src_pads(left));
154   report_element_pads("source", right, gst_element_iterate_sink_pads(right));
155   disorder_fatal(0, "can't decode `%s'", file);
156 }
157
158 /* The `decoderbin' element (DECODE) has deigned to announce a new PAD.
159  * Maybe we should attach the tag end of our pipeline (starting with the
160  * element U) to it.
161  */
162 static void decoder_pad_arrived(GstElement *decode, GstPad *pad, gpointer u)
163 {
164   GstElement *tail = u;
165 #ifdef HAVE_GSTREAMER_0_10
166   GstCaps *caps = gst_pad_get_caps(pad);
167 #else
168   GstCaps *caps = gst_pad_get_current_caps(pad);
169 #endif
170   GstStructure *s;
171   guint i, n;
172   const gchar *name;
173
174   /* The input file could be more or less anything, so this could be any kind
175    * of pad.  We're only interested if it's audio, so let's go check.
176    */
177   for(i = 0, n = gst_caps_get_size(caps); i < n; i++) {
178     s = gst_caps_get_structure(caps, i);
179     name = gst_structure_get_name(s);
180 #ifdef HAVE_GSTREAMER_0_10
181     if(strncmp(name, "audio/x-raw-", 12) == 0)
182 #else
183     if(strcmp(name, "audio/x-raw") == 0)
184 #endif
185       goto match;
186   }
187 #ifndef HAVE_GSTREAMER_0_10
188   g_object_unref(caps);
189 #endif
190   return;
191
192 match:
193   /* Yes, it's audio.  Link the two elements together. */
194   link_elements(decode, tail);
195
196   /* If requested using the environemnt variable `GST_DEBUG_DUMP_DOT_DIR',
197    * write a dump of the now-completed pipeline.
198    */
199   GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(pipeline),
200                             GST_DEBUG_GRAPH_SHOW_ALL,
201                             "disorder-gstdecode");
202 }
203
204 /* Prepare the GStreamer pipeline, ready to decode the given FILE.  This sets
205  * up the variables `appsink' and `pipeline'.
206  */
207 static void prepare_pipeline(void)
208 {
209   GstElement *source = gst_element_factory_make("filesrc", "file");
210   GstElement *decode = gst_element_factory_make("decodebin", "decode");
211   GstElement *resample = gst_element_factory_make("audioresample",
212                                                   "resample");
213   GstElement *convert = gst_element_factory_make("audioconvert", "convert");
214   GstElement *sink = gst_element_factory_make("appsink", "sink");
215   GstElement *tail = sink;
216   GstElement *gain;
217   GstCaps *caps;
218   const struct stream_header *fmt = &config->sample_format;
219
220 #ifndef HAVE_GSTREAMER_0_10
221   static const struct fmttab {
222     const char *fmt;
223     unsigned bits;
224     unsigned endian;
225   } fmttab[] = {
226     { "S8", 8, ENDIAN_BIG },
227     { "S8", 8, ENDIAN_LITTLE },
228     { "S16BE", 16, ENDIAN_BIG },
229     { "S16LE", 16, ENDIAN_LITTLE },
230     { 0 }
231   };
232   const struct fmttab *ft;
233 #endif
234
235   /* Set up the global variables. */
236   pipeline = gst_pipeline_new("pipe");
237   appsink = GST_APP_SINK(sink);
238
239   /* Configure the various simple elements. */
240   g_object_set(source, "location", file, END);
241   g_object_set(sink, "sync", FALSE, END);
242
243   /* Configure the resampler and converter.  Leave things as their defaults
244    * if the user hasn't made an explicit request.
245    */
246   if(quality >= 0) g_object_set(resample, "quality", quality, END);
247   if(dither >= 0) g_object_set(convert, "dithering", dither, END);
248   if(shape >= 0) g_object_set(convert, "noise-shaping", shape, END);
249
250   /* Set up the sink's capabilities from the configuration. */
251 #ifdef HAVE_GSTREAMER_0_10
252   caps = gst_caps_new_simple("audio/x-raw-int",
253                              "width", G_TYPE_INT, fmt->bits,
254                              "depth", G_TYPE_INT, fmt->bits,
255                              "channels", G_TYPE_INT, fmt->channels,
256                              "signed", G_TYPE_BOOLEAN, TRUE,
257                              "rate", G_TYPE_INT, fmt->rate,
258                              "endianness", G_TYPE_INT,
259                                fmt->endian == ENDIAN_BIG ?
260                                  G_BIG_ENDIAN : G_LITTLE_ENDIAN,
261                              END);
262 #else
263   for (ft = fmttab; ft->fmt; ft++)
264     if (ft->bits == fmt->bits && ft->endian == fmt->endian) break;
265   if(!ft->fmt) {
266     disorder_fatal(0, "unsupported sample format: bits=%"PRIu32", endian=%u",
267                    fmt->bits, fmt->endian);
268   }
269   caps = gst_caps_new_simple("audio/x-raw",
270                              "format", G_TYPE_STRING, ft->fmt,
271                              "channels", G_TYPE_INT, fmt->channels,
272                              "rate", G_TYPE_INT, fmt->rate,
273                              END);
274 #endif
275   gst_app_sink_set_caps(appsink, caps);
276
277   /* Add the various elements into the pipeline.  We'll stitch them together
278    * in pieces, because the pipeline is somewhat dynamic.
279    */
280   gst_bin_add_many(GST_BIN(pipeline),
281                    source, decode,
282                    resample, convert, sink, END);
283
284   /* Link audio conversion stages onto the front.  The rest of DisOrder
285    * doesn't handle much of the full panoply of exciting audio formats.
286    */
287   link_elements(convert, tail); tail = convert;
288   link_elements(resample, tail); tail = resample;
289
290   /* If we're meant to do ReplayGain then insert it into the pipeline before
291    * the converter.
292    */
293   if(mode != OFF) {
294     gain = gst_element_factory_make("rgvolume", "gain");
295     g_object_set(gain,
296                  "album-mode", mode == ALBUM,
297                  "fallback-gain", fallback,
298                  END);
299     gst_bin_add(GST_BIN(pipeline), gain);
300     link_elements(gain, tail); tail = gain;
301   }
302
303   /* Link the source and the decoder together.  The `decodebin' is annoying
304    * and doesn't have any source pads yet, so the best we can do is make two
305    * halves of the chain, and add a hook to stitch them together later.
306    */
307   link_elements(source, decode);
308   g_signal_connect(decode, "pad-added",
309                    G_CALLBACK(decoder_pad_arrived), tail);
310 }
311
312 /* Respond to a message from the BUS.  The only thing we need worry about
313  * here is errors from the pipeline.
314  */
315 static void bus_message(GstBus UNUSED *bus, GstMessage *msg,
316                         gpointer UNUSED u)
317 {
318   switch(msg->type) {
319   case GST_MESSAGE_ERROR:
320 #ifdef HAVE_GSTREAMER_0_10
321     disorder_fatal(0, "%s",
322                    gst_structure_get_string(msg->structure, "debug"));
323 #else
324     disorder_fatal(0, "%s",
325                    gst_structure_get_string(gst_message_get_structure(msg),
326                                             "debug"));
327 #endif
328   default:
329     break;
330   }
331 }
332
333 /* End of stream.  Stop polling the main loop. */
334 static void cb_eos(GstAppSink UNUSED *sink, gpointer UNUSED u)
335   { g_main_loop_quit(loop); }
336
337 /* Preroll buffers are prepared when the pipeline moves to the `paused'
338  * state, so that they're ready for immediate playback.  Conveniently, they
339  * also carry format information, which is what we want here.  Stash the
340  * sample format information in the `stream_header' structure ready for
341  * actual buffers of interesting data.
342  */
343 static GstFlowReturn cb_preroll(GstAppSink *sink, gpointer UNUSED u)
344 {
345 #ifdef HAVE_GSTREAMER_0_10
346   GstBuffer *buf = gst_app_sink_pull_preroll(sink);
347   GstCaps *caps = GST_BUFFER_CAPS(buf);
348 #else
349   GstSample *samp = gst_app_sink_pull_preroll(sink);
350   GstCaps *caps = gst_sample_get_caps(samp);
351 #endif
352
353 #ifdef HAVE_GST_AUDIO_INFO_FROM_CAPS
354
355   /* Parse the audio format information out of the caps.  There's a handy
356    * function to do this in later versions of gst-plugins-base, so use that
357    * if it's available.  Once we no longer care about supporting such old
358    * versions we can delete the version which does the job the hard way.
359    */
360
361   GstAudioInfo ai;
362
363   if(!gst_audio_info_from_caps(&ai, caps))
364     disorder_fatal(0, "can't decode `%s': failed to parse audio info", file);
365   hdr.rate = ai.rate;
366   hdr.channels = ai.channels;
367   hdr.bits = ai.finfo->width;
368   hdr.endian = ai.finfo->endianness == G_BIG_ENDIAN ?
369     ENDIAN_BIG : ENDIAN_LITTLE;
370
371 #else
372
373   GstStructure *s;
374   const char *ty;
375   gint rate, channels, bits, endian;
376   gboolean signedp;
377
378   /* Make sure that the caps is basically the right shape. */
379   if(!GST_CAPS_IS_SIMPLE(caps)) disorder_fatal(0, "expected simple caps");
380   s = gst_caps_get_structure(caps, 0);
381   ty = gst_structure_get_name(s);
382   if(strcmp(ty, "audio/x-raw-int") != 0)
383     disorder_fatal(0, "unexpected content type `%s'", ty);
384
385   /* Extract fields from the structure. */
386   if(!gst_structure_get(s,
387                         "rate", G_TYPE_INT, &rate,
388                         "channels", G_TYPE_INT, &channels,
389                         "width", G_TYPE_INT, &bits,
390                         "endianness", G_TYPE_INT, &endian,
391                         "signed", G_TYPE_BOOLEAN, &signedp,
392                         END))
393     disorder_fatal(0, "can't decode `%s': failed to parse audio caps", file);
394   hdr.rate = rate; hdr.channels = channels; hdr.bits = bits;
395   hdr.endian = endian == G_BIG_ENDIAN ? ENDIAN_BIG : ENDIAN_LITTLE;
396
397 #endif
398
399 #ifdef HAVE_GSTREAMER_0_10
400   gst_buffer_unref(buf);
401 #else
402   gst_sample_unref(samp);
403 #endif
404   return GST_FLOW_OK;
405 }
406
407 /* A new buffer of sample data has arrived, so we should pass it on with
408  * appropriate framing.
409  */
410 static GstFlowReturn cb_buffer(GstAppSink *sink, gpointer UNUSED u)
411 {
412 #ifdef HAVE_GSTREAMER_0_10
413   GstBuffer *buf = gst_app_sink_pull_buffer(sink);
414 #else
415   GstSample *samp = gst_app_sink_pull_sample(sink);
416   GstBuffer *buf = gst_sample_get_buffer(samp);
417   GstMemory *mem;
418   GstMapInfo map;
419   gint i, n;
420 #endif
421
422   /* Make sure we actually have a grip on the sample format here. */
423   if(!hdr.rate) disorder_fatal(0, "format unset");
424
425   /* Write out a frame of audio data. */
426 #ifdef HAVE_GSTREAMER_0_10
427   hdr.nbytes = GST_BUFFER_SIZE(buf);
428   if((!(flags&f_stream) && fwrite(&hdr, sizeof(hdr), 1, fp) != 1) ||
429      fwrite(GST_BUFFER_DATA(buf), 1, hdr.nbytes, fp) != hdr.nbytes)
430     disorder_fatal(errno, "output");
431 #else
432   for(i = 0, n = gst_buffer_n_memory(buf); i < n; i++) {
433     mem = gst_buffer_peek_memory(buf, i);
434     if(!gst_memory_map(mem, &map, GST_MAP_READ))
435       disorder_fatal(0, "failed to map sample buffer");
436     hdr.nbytes = map.size;
437     if((!(flags&f_stream) && fwrite(&hdr, sizeof(hdr), 1, fp) != 1) ||
438        fwrite(map.data, 1, map.size, fp) != map.size)
439       disorder_fatal(errno, "output");
440     gst_memory_unmap(mem, &map);
441   }
442 #endif
443
444   /* And we're done. */
445 #ifdef HAVE_GSTREAMER_0_10
446   gst_buffer_unref(buf);
447 #else
448   gst_sample_unref(samp);
449 #endif
450   return GST_FLOW_OK;
451 }
452
453 static GstAppSinkCallbacks callbacks = {
454   .eos = cb_eos,
455   .new_preroll = cb_preroll,
456 #ifdef HAVE_GSTREAMER_0_10
457   .new_buffer = cb_buffer
458 #else
459   .new_sample = cb_buffer
460 #endif
461 };
462
463 /* Decode the audio file.  We're already set up for everything. */
464 static void decode(void)
465 {
466   GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
467
468   /* Set up the message bus and main loop. */
469   gst_bus_add_signal_watch(bus);
470   loop = g_main_loop_new(0, FALSE);
471   g_signal_connect(bus, "message", G_CALLBACK(bus_message), 0);
472
473   /* Tell the sink to call us when interesting things happen. */
474   gst_app_sink_set_max_buffers(appsink, 16);
475   gst_app_sink_set_drop(appsink, FALSE);
476   gst_app_sink_set_callbacks(appsink, &callbacks, 0, 0);
477
478   /* Set the ball rolling. */
479   gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_PLAYING);
480
481   /* And wait for the miracle to come. */
482   g_main_loop_run(loop);
483
484   /* Shut down the pipeline.  This isn't strictly necessary, since we're
485    * about to exit very soon, but it's kind of polite.
486    */
487   gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL);
488 }
489
490 static int getenum(const char *what, const char *s, const char *const *tags)
491 {
492   int i;
493
494   for(i = 0; tags[i]; i++)
495     if(strcmp(s, tags[i]) == 0) return i;
496   disorder_fatal(0, "unknown %s `%s'", what, s);
497 }
498
499 static double getfloat(const char *what, const char *s)
500 {
501   double d;
502   char *q;
503
504   errno = 0;
505   d = strtod(s, &q);
506   if(*q || errno) disorder_fatal(0, "invalid %s `%s'", what, s);
507   return d;
508 }
509
510 static int getint(const char *what, const char *s, int min, int max)
511 {
512   long i;
513   char *q;
514
515   errno = 0;
516   i = strtol(s, &q, 10);
517   if(*q || errno || min > i || i > max)
518     disorder_fatal(0, "invalid %s `%s'", what, s);
519   return (int)i;
520 }
521
522 static const struct option options[] = {
523   { "help", no_argument, 0, 'h' },
524   { "version", no_argument, 0, 'V' },
525   { "config", required_argument, 0, 'c' },
526   { "dither", required_argument, 0, 'd' },
527   { "fallback-gain", required_argument, 0, 'f' },
528   { "noise-shape", required_argument, 0, 'n' },
529   { "quality", required_argument, 0, 'q' },
530   { "replay-gain", required_argument, 0, 'r' },
531   { "stream", no_argument, 0, 's' },
532   { 0, 0, 0, 0 }
533 };
534
535 static void help(void)
536 {
537   xprintf("Usage:\n"
538           "  disorder-gstdecode [OPTIONS] PATH\n"
539           "Options:\n"
540           "  --help, -h                 Display usage message\n"
541           "  --version, -V              Display version number\n"
542           "  --config PATH, -c PATH     Set configuration file\n"
543           "  --dither TYPE, -d TYPE     TYPE is `none', `rpdf', `tpdf', or "
544                                                 "`tpdf-hf'\n"
545           "  --fallback-gain DB, -f DB  For tracks without ReplayGain data\n"
546           "  --noise-shape TYPE, -n TYPE  TYPE is `none', `error-feedback',\n"
547           "                                     `simple', `medium' or `high'\n"
548           "  --quality QUAL, -q QUAL    Resampling quality: 0 poor, 10 good\n"
549           "  --replay-gain MODE, -r MODE  MODE is `off', `track' or `album'\n"
550           "  --stream, -s               Output raw samples, without framing\n"
551           "\n"
552           "Alternative audio decoder for DisOrder.  Only intended to be\n"
553           "used by speaker process, not for normal users.\n");
554   xfclose(stdout);
555   exit(0);
556 }
557
558 /* Main program. */
559 int main(int argc, char *argv[])
560 {
561   int n;
562   const char *e;
563
564   /* Initial setup. */
565   set_progname(argv);
566   if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "calling setlocale");
567
568   /* Parse command line. */
569   while((n = getopt_long(argc, argv, "hVc:d:f:n:q:r:s", options, 0)) >= 0) {
570     switch(n) {
571     case 'h': help();
572     case 'V': version("disorder-gstdecode");
573     case 'c': configfile = optarg; break;
574     case 'd': dither = getenum("dither type", optarg, dithers); break;
575     case 'f': fallback = getfloat("fallback gain", optarg); break;
576     case 'n': shape = getenum("noise-shaping type", optarg, shapes); break;
577     case 'q': quality = getint("resample quality", optarg, 0, 10); break;
578     case 'r': mode = getenum("ReplayGain mode", optarg, modes); break;
579     case 's': flags |= f_stream; break;
580     default: disorder_fatal(0, "invalid option");
581     }
582   }
583   if(optind >= argc) disorder_fatal(0, "missing filename");
584   file = argv[optind++];
585   if(optind < argc) disorder_fatal(0, "excess arguments");
586   if(config_read(1, 0)) disorder_fatal(0, "cannot read configuration");
587
588   /* Set up the GStreamer machinery. */
589   gst_init(0, 0);
590   prepare_pipeline();
591
592   /* Set up the output file. */
593   if((e = getenv("DISORDER_RAW_FD")) != 0) {
594     if((fp = fdopen(atoi(e), "wb")) == 0) disorder_fatal(errno, "fdopen");
595   } else
596     fp = stdout;
597
598   /* Let's go. */
599   decode();
600
601   /* And now we're done. */
602   xfclose(fp);
603   return (0);
604 }
605
606 /*
607 Local Variables:
608 c-basic-offset:2
609 comment-column:40
610 fill-column:77
611 indent-tabs-mode:nil
612 End:
613 */