2 * This file is part of DisOrder
3 * Copyright (C) 2007 Richard Kettlewell
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 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * 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, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 /** @file server/decode.c
21 * @brief General-purpose decoder for use by speaker process
36 #include <vorbis/vorbisfile.h>
38 /* libFLAC has had an API change and stupidly taken away the old API */
39 #if HAVE_FLAC_FILE_DECODER_H
40 # include <FLAC/file_decoder.h>
42 # include <FLAC/stream_decoder.h>
43 #define FLAC__FileDecoder FLAC__StreamDecoder
44 #define FLAC__FileDecoderState FLAC__StreamDecoderState
51 #include "speaker-protocol.h"
53 /** @brief Encoding lookup table type */
55 /** @brief Glob pattern matching file */
57 /** @brief Decoder function */
61 /** @brief Input file */
64 /** @brief Output file */
65 static FILE *outputfp;
67 /** @brief Filename */
68 static const char *path;
70 /** @brief Input buffer */
71 static char input_buffer[1048576];
73 /** @brief Open the input file */
74 static void open_input(void) {
75 if((inputfd = open(path, O_RDONLY)) < 0)
76 fatal(errno, "opening %s", path);
79 /** @brief Fill the buffer
80 * @return Number of bytes read
82 static size_t fill(void) {
83 int n = read(inputfd, input_buffer, sizeof input_buffer);
86 fatal(errno, "reading from %s", path);
90 /** @brief Write an 8-bit word */
91 static inline void output_8(int n) {
92 if(putc(n, outputfp) < 0)
93 fatal(errno, "decoding %s: output error", path);
96 /** @brief Write a 16-bit word in bigendian format */
97 static inline void output_16(uint16_t n) {
98 if(putc(n >> 8, outputfp) < 0
99 || putc(n, outputfp) < 0)
100 fatal(errno, "decoding %s: output error", path);
103 /** @brief Write a 24-bit word in bigendian format */
104 static inline void output_24(uint32_t n) {
105 if(putc(n >> 16, outputfp) < 0
106 || putc(n >> 8, outputfp) < 0
107 || putc(n, outputfp) < 0)
108 fatal(errno, "decoding %s: output error", path);
111 /** @brief Write a 32-bit word in bigendian format */
112 static inline void output_32(uint32_t n) {
113 if(putc(n >> 24, outputfp) < 0
114 || putc(n >> 16, outputfp) < 0
115 || putc(n >> 8, outputfp) < 0
116 || putc(n, outputfp) < 0)
117 fatal(errno, "decoding %s: output error", path);
120 /** @brief Write a block header
121 * @param rate Sample rate in Hz
122 * @param channels Channel count (currently only 1 or 2 supported)
123 * @param bits Bits per sample (must be a multiple of 8, no more than 64)
124 * @param nbytes Total number of data bytes
125 * @param endian @ref ENDIAN_BIG or @ref ENDIAN_LITTLE
127 * Checks that the sample format is a supported one (so other calls do not have
128 * to) and calls fatal() on error.
130 static void output_header(int rate,
135 struct stream_header header;
137 if(bits <= 0 || bits % 8 || bits > 64)
138 fatal(0, "decoding %s: unsupported sample size %d bits", path, bits);
139 if(channels <= 0 || channels > 2)
140 fatal(0, "decoding %s: unsupported channel count %d", path, channels);
142 fatal(0, "decoding %s: nonsensical sample rate %dHz", path, rate);
145 header.channels = channels;
146 header.endian = endian;
147 header.nbytes = nbytes;
148 if(fwrite(&header, sizeof header, 1, outputfp) < 1)
149 fatal(errno, "decoding %s: writing format header", path);
152 /** @brief Dithering state
153 * Filched from mpg321, which credits it to Robert Leslie */
154 struct audio_dither {
155 mad_fixed_t error[3];
159 /** @brief 32-bit PRNG
160 * Filched from mpg321, which credits it to Robert Leslie */
161 static inline unsigned long prng(unsigned long state)
163 return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
166 /** @brief Generic linear sample quantize and dither routine
167 * Filched from mpg321, which credits it to Robert Leslie */
169 static long audio_linear_dither(mad_fixed_t sample,
170 struct audio_dither *dither) {
171 unsigned int scalebits;
172 mad_fixed_t output, mask, rnd;
180 sample += dither->error[0] - dither->error[1] + dither->error[2];
182 dither->error[2] = dither->error[1];
183 dither->error[1] = dither->error[0] / 2;
186 output = sample + (1L << (MAD_F_FRACBITS + 1 - bits - 1));
188 scalebits = MAD_F_FRACBITS + 1 - bits;
189 mask = (1L << scalebits) - 1;
192 rnd = prng(dither->random);
193 output += (rnd & mask) - (dither->random & mask);
195 dither->random = rnd;
204 else if (output < MIN) {
215 dither->error[0] = sample - output;
218 return output >> scalebits;
222 /** @brief MP3 output callback */
223 static enum mad_flow mp3_output(void attribute((unused)) *data,
224 struct mad_header const *header,
225 struct mad_pcm *pcm) {
226 size_t n = pcm->length;
227 const mad_fixed_t *l = pcm->samples[0], *r = pcm->samples[1];
228 static struct audio_dither ld[1], rd[1];
230 output_header(header->samplerate,
233 2 * pcm->channels * pcm->length,
235 switch(pcm->channels) {
238 output_16(audio_linear_dither(*l++, ld));
242 output_16(audio_linear_dither(*l++, ld));
243 output_16(audio_linear_dither(*r++, rd));
247 return MAD_FLOW_CONTINUE;
250 /** @brief MP3 input callback */
251 static enum mad_flow mp3_input(void attribute((unused)) *data,
252 struct mad_stream *stream) {
253 const size_t n = fill();
256 return MAD_FLOW_STOP;
257 mad_stream_buffer(stream, (unsigned char *)input_buffer, n);
258 return MAD_FLOW_CONTINUE;
262 /** @brief MP3 error callback */
263 static enum mad_flow mp3_error(void attribute((unused)) *data,
264 struct mad_stream *stream,
265 struct mad_frame attribute((unused)) *frame) {
267 /* Just generates pointless verbosity l-( */
268 error(0, "decoding %s: %s (%#04x)",
269 path, mad_stream_errorstr(stream), stream->error);
270 return MAD_FLOW_CONTINUE;
273 /** @brief MP3 decoder */
274 static void decode_mp3(void) {
275 struct mad_decoder mad[1];
278 mad_decoder_init(mad, 0/*data*/, mp3_input, 0/*header*/, 0/*filter*/,
279 mp3_output, mp3_error, 0/*message*/);
280 if(mad_decoder_run(mad, MAD_DECODER_MODE_SYNC))
282 mad_decoder_finish(mad);
285 /** @brief OGG decoder */
286 static void decode_ogg(void) {
288 OggVorbis_File vf[1];
294 if(!(fp = fopen(path, "rb")))
295 fatal(errno, "cannot open %s", path);
296 /* There doesn't seem to be any standard function for mapping the error codes
298 if((err = ov_open(fp, vf, 0/*initial*/, 0/*ibytes*/)))
299 fatal(0, "ov_fopen %s: %d", path, err);
300 if(!(vi = ov_info(vf, 0/*link*/)))
301 fatal(0, "ov_info %s: failed", path);
302 while((n = ov_read(vf, input_buffer, sizeof input_buffer, 1/*bigendianp*/,
303 2/*bytes/word*/, 1/*signed*/, &bitstream))) {
305 fatal(0, "ov_read %s: %ld", path, n);
307 fatal(0, "only single-bitstream ogg files are supported");
308 output_header(vi->rate, vi->channels, 16/*bits*/, n, ENDIAN_BIG);
309 if(fwrite(input_buffer, 1, n, outputfp) < (size_t)n)
310 fatal(errno, "decoding %s: writing sample data", path);
314 /** @brief Sample data callback used by decode_wav() */
315 static int wav_write(struct wavfile attribute((unused)) *f,
318 void attribute((unused)) *u) {
319 if(fwrite(data, 1, nbytes, outputfp) < nbytes)
320 fatal(errno, "decoding %s: writing sample data", path);
324 /** @brief WAV file decoder */
325 static void decode_wav(void) {
329 if((err = wav_init(f, path)))
330 fatal(err, "opening %s", path);
331 output_header(f->rate, f->channels, f->bits, f->datasize, ENDIAN_LITTLE);
332 if((err = wav_data(f, wav_write, 0)))
333 fatal(err, "error decoding %s", path);
336 /** @brief Metadata callback for FLAC decoder
338 * This is a no-op here.
340 static void flac_metadata(const FLAC__FileDecoder attribute((unused)) *decoder,
341 const FLAC__StreamMetadata attribute((unused)) *metadata,
342 void attribute((unused)) *client_data) {
345 /** @brief Error callback for FLAC decoder */
346 static void flac_error(const FLAC__FileDecoder attribute((unused)) *decoder,
347 FLAC__StreamDecoderErrorStatus status,
348 void attribute((unused)) *client_data) {
349 fatal(0, "error decoding %s: %s", path,
350 FLAC__StreamDecoderErrorStatusString[status]);
353 /** @brief Write callback for FLAC decoder */
354 static FLAC__StreamDecoderWriteStatus flac_write
355 (const FLAC__FileDecoder attribute((unused)) *decoder,
356 const FLAC__Frame *frame,
357 const FLAC__int32 *const buffer[],
358 void attribute((unused)) *client_data) {
361 output_header(frame->header.sample_rate,
362 frame->header.channels,
363 frame->header.bits_per_sample,
364 (frame->header.channels * frame->header.blocksize
365 * frame->header.bits_per_sample) / 8,
367 for(n = 0; n < frame->header.blocksize; ++n) {
368 for(c = 0; c < frame->header.channels; ++c) {
369 switch(frame->header.bits_per_sample) {
370 case 8: output_8(buffer[c][n]); break;
371 case 16: output_16(buffer[c][n]); break;
372 case 24: output_24(buffer[c][n]); break;
373 case 32: output_32(buffer[c][n]); break;
377 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
381 /** @brief FLAC file decoder */
382 static void decode_flac(void) {
383 #if HAVE_FLAC_FILE_DECODER_H
384 FLAC__FileDecoder *fd = 0;
385 FLAC__FileDecoderState fs;
387 if(!(fd = FLAC__file_decoder_new()))
388 fatal(0, "FLAC__file_decoder_new failed");
389 if(!(FLAC__file_decoder_set_filename(fd, path)))
390 fatal(0, "FLAC__file_set_filename failed");
391 FLAC__file_decoder_set_metadata_callback(fd, flac_metadata);
392 FLAC__file_decoder_set_error_callback(fd, flac_error);
393 FLAC__file_decoder_set_write_callback(fd, flac_write);
394 if((fs = FLAC__file_decoder_init(fd)))
395 fatal(0, "FLAC__file_decoder_init: %s", FLAC__FileDecoderStateString[fs]);
396 FLAC__file_decoder_process_until_end_of_file(fd);
398 FLAC__StreamDecoder *sd = 0;
399 FLAC__StreamDecoderInitStatus is;
401 if((is = FLAC__stream_decoder_init_file(sd, path, flac_write, flac_metadata,
403 fatal(0, "FLAC__stream_decoder_init_file %s: %s",
404 path, FLAC__StreamDecoderInitStatusString[is]);
408 /** @brief Lookup table of decoders */
409 static const struct decoder decoders[] = {
410 { "*.mp3", decode_mp3 },
411 { "*.MP3", decode_mp3 },
412 { "*.ogg", decode_ogg },
413 { "*.OGG", decode_ogg },
414 { "*.flac", decode_flac },
415 { "*.FLAC", decode_flac },
416 { "*.wav", decode_wav },
417 { "*.WAV", decode_wav },
421 static const struct option options[] = {
422 { "help", no_argument, 0, 'h' },
423 { "version", no_argument, 0, 'V' },
427 /* Display usage message and terminate. */
428 static void help(void) {
430 " disorder-decode [OPTIONS] PATH\n"
432 " --help, -h Display usage message\n"
433 " --version, -V Display version number\n"
435 "Audio decoder for DisOrder. Only intended to be used by speaker\n"
436 "process, not for normal users.\n");
441 /* Display version number and terminate. */
442 static void version(void) {
443 xprintf("disorder-decode version %s\n", disorder_version_string);
448 int main(int argc, char **argv) {
453 if(!setlocale(LC_CTYPE, "")) fatal(errno, "calling setlocale");
454 while((n = getopt_long(argc, argv, "hV", options, 0)) >= 0) {
458 default: fatal(0, "invalid option");
462 fatal(0, "missing filename");
463 if(optind + 1 < argc)
464 fatal(0, "excess arguments");
465 if((e = getenv("DISORDER_RAW_FD"))) {
466 if(!(outputfp = fdopen(atoi(e), "wb")))
467 fatal(errno, "fdopen");
473 && fnmatch(decoders[n].pattern, path, 0) != 0;
476 if(!decoders[n].pattern)
477 fatal(0, "cannot determine file type for %s", path);
478 decoders[n].decode();