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