2 * This file is part of DisOrder
3 * Copyright (C) 2013 Mark Wooding
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.
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.
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/>.
18 /** @file server/gstdecode.c
19 * @brief Decode compressed audio files, and apply ReplayGain.
22 #include "disorder-server.h"
24 #include "speaker-protocol.h"
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.
35 #include <gst/app/gstappsink.h>
36 #include <gst/audio/audio.h>
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.
43 # define UNUSED __attribute__((unused))
46 #define END ((void *)0)
47 #define N(v) (sizeof(v)/sizeof(*(v)))
50 static const char *file
;
51 static GstAppSink
*appsink
;
52 static GstElement
*pipeline
;
53 static GMainLoop
*loop
;
55 #define MODES(_) _("off", OFF) _("track", TRACK) _("album", ALBUM)
57 #define DEFENUM(name, tag) tag,
62 static const char *const modes
[] = {
63 #define DEFNAME(name, tag) name,
68 static int mode
= ALBUM
;
70 static struct stream_header hdr
;
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.
75 static void report_element_pads(const char *what
, GstElement
*elt
,
82 switch(gst_iterator_next(it
, &pad
)) {
83 case GST_ITERATOR_DONE
:
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
);
91 case GST_ITERATOR_RESYNC
:
92 gst_iterator_resync(it
);
94 case GST_ITERATOR_ERROR
:
95 disorder_error(0, "<failed to enumerate `%s' %s pads>",
96 GST_OBJECT_NAME(elt
), what
);
102 gst_iterator_free(it
);
105 /* Link together two elements; fail with an approximately useful error
106 * message if it didn't work.
108 static void link_elements(GstElement
*left
, GstElement
*right
)
110 /* Try to link things together. */
111 if(gst_element_link(left
, right
)) return;
113 /* If this didn't work, it's probably for some really hairy reason, so
114 * provide a bunch of debugging information.
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
);
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
127 static void decoder_pad_arrived(GstElement
*decode
, GstPad
*pad
, gpointer u
)
129 GstElement
*tail
= u
;
130 GstCaps
*caps
= gst_pad_get_caps(pad
);
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.
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
;
146 /* Yes, it's audio. Link the two elements together. */
147 link_elements(decode
, tail
);
149 /* If requested using the environemnt variable `GST_DEBUG_DUMP_DOT_DIR',
150 * write a dump of the now-completed pipeline.
152 GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(pipeline
),
153 GST_DEBUG_GRAPH_SHOW_ALL
,
154 "disorder-gstdecode");
157 /* Prepare the GStreamer pipeline, ready to decode the given FILE. This sets
158 * up the variables `appsink' and `pipeline'.
160 static void prepare_pipeline(void)
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
;
168 GstCaps
*caps
= gst_caps_new_empty();
170 static const int widths
[] = { 8, 16 };
173 /* Set up the global variables. */
174 pipeline
= gst_pipeline_new("pipe");
175 appsink
= GST_APP_SINK(sink
);
177 /* Configure the various simple elements. */
178 g_object_set(source
, "location", file
, END
);
179 g_object_set(sink
, "sync", FALSE
, END
);
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,
190 gst_caps_append(caps
, c
);
192 gst_app_sink_set_caps(appsink
, caps
);
194 /* Add the various elements into the pipeline. We'll stitch them together
195 * in pieces, because the pipeline is somewhat dynamic.
197 gst_bin_add_many(GST_BIN(pipeline
), source
, decode
, convert
, sink
, END
);
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.
202 link_elements(convert
, tail
); tail
= convert
;
204 /* If we're meant to do ReplayGain then insert it into the pipeline before
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
;
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.
218 link_elements(source
, decode
);
219 g_signal_connect(decode
, "pad-added",
220 G_CALLBACK(decoder_pad_arrived
), tail
);
223 /* Respond to a message from the BUS. The only thing we need worry about
224 * here is errors from the pipeline.
226 static void bus_message(GstBus UNUSED
*bus
, GstMessage
*msg
,
230 case GST_MESSAGE_ERROR
:
231 disorder_fatal(0, "%s",
232 gst_structure_get_string(msg
->structure
, "debug"));
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
); }
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.
248 static GstFlowReturn
cb_preroll(GstAppSink
*sink
, gpointer UNUSED u
)
250 GstBuffer
*buf
= gst_app_sink_pull_preroll(sink
);
251 GstCaps
*caps
= GST_BUFFER_CAPS(buf
);
253 #ifdef HAVE_GST_AUDIO_INFO_FROM_CAPS
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.
263 if(!gst_audio_info_from_caps(&ai
, caps
))
264 disorder_fatal(0, "can't decode `%s': failed to parse audio info", file
);
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
;
275 gint rate
, channels
, bits
, endian
;
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
);
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
,
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
;
299 gst_buffer_unref(buf
);
303 /* A new buffer of sample data has arrived, so we should pass it on with
304 * appropriate framing.
306 static GstFlowReturn
cb_buffer(GstAppSink
*sink
, gpointer UNUSED u
)
308 GstBuffer
*buf
= gst_app_sink_pull_buffer(sink
);
310 /* Make sure we actually have a grip on the sample format here. */
311 if(!hdr
.rate
) disorder_fatal(0, "format unset");
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");
319 /* And we're done. */
320 gst_buffer_unref(buf
);
324 static GstAppSinkCallbacks callbacks
= {
326 .new_preroll
= cb_preroll
,
327 .new_buffer
= cb_buffer
330 /* Decode the audio file. We're already set up for everything. */
331 static void decode(void)
333 GstBus
*bus
= gst_pipeline_get_bus(GST_PIPELINE(pipeline
));
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);
340 /* Tell the sink to call us when interesting things happen. */
341 gst_app_sink_set_callbacks(appsink
, &callbacks
, 0, 0);
343 /* Set the ball rolling. */
344 gst_element_set_state(GST_ELEMENT(pipeline
), GST_STATE_PLAYING
);
346 /* And wait for the miracle to come. */
347 g_main_loop_run(loop
);
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.
352 gst_element_set_state(GST_ELEMENT(pipeline
), GST_STATE_NULL
);
355 static int getenum(const char *what
, const char *s
, const char *const *tags
)
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
);
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' },
371 static void help(void)
374 " disorder-gstdecode [OPTIONS] PATH\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"
380 "Alternative audio decoder for DisOrder. Only intended to be\n"
381 "used by speaker process, not for normal users.\n");
387 int main(int argc
, char *argv
[])
394 if(!setlocale(LC_CTYPE
, "")) disorder_fatal(errno
, "calling setlocale");
396 /* Parse command line. */
397 while((n
= getopt_long(argc
, argv
, "hVr:", options
, 0)) >= 0) {
400 case 'V': version("disorder-gstdecode");
401 case 'r': mode
= getenum("ReplayGain mode", optarg
, modes
); break;
402 default: disorder_fatal(0, "invalid option");
405 if(optind
>= argc
) disorder_fatal(0, "missing filename");
406 file
= argv
[optind
++];
407 if(optind
< argc
) disorder_fatal(0, "excess arguments");
409 /* Set up the GStreamer machinery. */
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");
422 /* And now we're done. */