2 * This file is part of DisOrder
3 * Copyright (C) 2007, 2008 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
24 #include "disorder-server.h"
27 #include <vorbis/vorbisfile.h>
29 /* libFLAC has had an API change and stupidly taken away the old API */
30 #if HAVE_FLAC_FILE_DECODER_H
31 # include <FLAC/file_decoder.h>
33 # include <FLAC/stream_decoder.h>
34 #define FLAC__FileDecoder FLAC__StreamDecoder
35 #define FLAC__FileDecoderState FLAC__StreamDecoderState
39 #include "speaker-protocol.h"
41 /** @brief Encoding lookup table type */
43 /** @brief Glob pattern matching file */
45 /** @brief Decoder function */
49 /** @brief Input file */
52 /** @brief Output file */
53 static FILE *outputfp
;
55 /** @brief Filename */
56 static const char *path
;
58 /** @brief Input buffer */
59 static char input_buffer
[1048576];
61 /** @brief Number of bytes read into buffer */
62 static int input_count
;
64 /** @brief Write an 8-bit word */
65 static inline void output_8(int n
) {
66 if(putc(n
, outputfp
) < 0)
67 fatal(errno
, "decoding %s: output error", path
);
70 /** @brief Write a 16-bit word in bigendian format */
71 static inline void output_16(uint16_t n
) {
72 if(putc(n
>> 8, outputfp
) < 0
73 || putc(n
, outputfp
) < 0)
74 fatal(errno
, "decoding %s: output error", path
);
77 /** @brief Write a 24-bit word in bigendian format */
78 static inline void output_24(uint32_t n
) {
79 if(putc(n
>> 16, outputfp
) < 0
80 || putc(n
>> 8, outputfp
) < 0
81 || putc(n
, outputfp
) < 0)
82 fatal(errno
, "decoding %s: output error", path
);
85 /** @brief Write a 32-bit word in bigendian format */
86 static inline void output_32(uint32_t n
) {
87 if(putc(n
>> 24, outputfp
) < 0
88 || putc(n
>> 16, outputfp
) < 0
89 || putc(n
>> 8, outputfp
) < 0
90 || putc(n
, outputfp
) < 0)
91 fatal(errno
, "decoding %s: output error", path
);
94 /** @brief Write a block header
95 * @param rate Sample rate in Hz
96 * @param channels Channel count (currently only 1 or 2 supported)
97 * @param bits Bits per sample (must be a multiple of 8, no more than 64)
98 * @param nbytes Total number of data bytes
99 * @param endian @ref ENDIAN_BIG or @ref ENDIAN_LITTLE
101 * Checks that the sample format is a supported one (so other calls do not have
102 * to) and calls fatal() on error.
104 static void output_header(int rate
,
109 struct stream_header header
;
111 if(bits
<= 0 || bits
% 8 || bits
> 64)
112 fatal(0, "decoding %s: unsupported sample size %d bits", path
, bits
);
113 if(channels
<= 0 || channels
> 2)
114 fatal(0, "decoding %s: unsupported channel count %d", path
, channels
);
116 fatal(0, "decoding %s: nonsensical sample rate %dHz", path
, rate
);
119 header
.channels
= channels
;
120 header
.endian
= endian
;
121 header
.nbytes
= nbytes
;
122 if(fwrite(&header
, sizeof header
, 1, outputfp
) < 1)
123 fatal(errno
, "decoding %s: writing format header", path
);
126 /** @brief Dithering state
127 * Filched from mpg321, which credits it to Robert Leslie */
128 struct audio_dither
{
129 mad_fixed_t error
[3];
133 /** @brief 32-bit PRNG
134 * Filched from mpg321, which credits it to Robert Leslie */
135 static inline unsigned long prng(unsigned long state
)
137 return (state
* 0x0019660dL
+ 0x3c6ef35fL
) & 0xffffffffL
;
140 /** @brief Generic linear sample quantize and dither routine
141 * Filched from mpg321, which credits it to Robert Leslie */
142 static long audio_linear_dither(mad_fixed_t sample
,
143 struct audio_dither
*dither
) {
144 unsigned int scalebits
;
145 mad_fixed_t output
, mask
, rnd
;
154 sample
+= dither
->error
[0] - dither
->error
[1] + dither
->error
[2];
156 dither
->error
[2] = dither
->error
[1];
157 dither
->error
[1] = dither
->error
[0] / 2;
160 output
= sample
+ (1L << (MAD_F_FRACBITS
+ 1 - bits
- 1));
162 scalebits
= MAD_F_FRACBITS
+ 1 - bits
;
163 mask
= (1L << scalebits
) - 1;
166 rnd
= prng(dither
->random
);
167 output
+= (rnd
& mask
) - (dither
->random
& mask
);
169 dither
->random
= rnd
;
178 else if (output
< MIN
) {
189 dither
->error
[0] = sample
- output
;
192 return output
>> scalebits
;
195 /** @brief MP3 output callback */
196 static enum mad_flow
mp3_output(void attribute((unused
)) *data
,
197 struct mad_header
const *header
,
198 struct mad_pcm
*pcm
) {
199 size_t n
= pcm
->length
;
200 const mad_fixed_t
*l
= pcm
->samples
[0], *r
= pcm
->samples
[1];
201 static struct audio_dither ld
[1], rd
[1];
203 output_header(header
->samplerate
,
206 2 * pcm
->channels
* pcm
->length
,
208 switch(pcm
->channels
) {
211 output_16(audio_linear_dither(*l
++, ld
));
215 output_16(audio_linear_dither(*l
++, ld
));
216 output_16(audio_linear_dither(*r
++, rd
));
220 return MAD_FLOW_CONTINUE
;
223 /** @brief MP3 input callback */
224 static enum mad_flow
mp3_input(void attribute((unused
)) *data
,
225 struct mad_stream
*stream
) {
228 /* libmad requires its caller to do ALL the buffering work, including coping
229 * with partial frames. Given that it appears to be completely undocumented
230 * you could perhaps be forgiven for not discovering this... */
232 /* Compute total number of bytes consumed */
233 used
= (char *)stream
->next_frame
- input_buffer
;
234 /* Compute number of bytes left to consume */
235 remain
= input_count
- used
;
236 memmove(input_buffer
, input_buffer
+ used
, remain
);
241 n
= read(inputfd
, input_buffer
+ remain
, (sizeof input_buffer
) - remain
);
243 fatal(errno
, "reading from %s", path
);
244 /* Compute total number of bytes available */
245 input_count
= remain
+ n
;
247 mad_stream_buffer(stream
, (unsigned char *)input_buffer
, input_count
);
249 return MAD_FLOW_CONTINUE
;
251 return MAD_FLOW_STOP
;
254 /** @brief MP3 error callback */
255 static enum mad_flow
mp3_error(void attribute((unused
)) *data
,
256 struct mad_stream
*stream
,
257 struct mad_frame
attribute((unused
)) *frame
) {
259 /* Just generates pointless verbosity l-( */
260 error(0, "decoding %s: %s (%#04x)",
261 path
, mad_stream_errorstr(stream
), stream
->error
);
262 return MAD_FLOW_CONTINUE
;
265 /** @brief MP3 decoder */
266 static void decode_mp3(void) {
267 struct mad_decoder mad
[1];
269 if((inputfd
= open(path
, O_RDONLY
)) < 0)
270 fatal(errno
, "opening %s", path
);
271 mad_decoder_init(mad
, 0/*data*/, mp3_input
, 0/*header*/, 0/*filter*/,
272 mp3_output
, mp3_error
, 0/*message*/);
273 if(mad_decoder_run(mad
, MAD_DECODER_MODE_SYNC
))
275 mad_decoder_finish(mad
);
278 /** @brief OGG decoder */
279 static void decode_ogg(void) {
281 OggVorbis_File vf
[1];
287 if(!(fp
= fopen(path
, "rb")))
288 fatal(errno
, "cannot open %s", path
);
289 /* There doesn't seem to be any standard function for mapping the error codes
291 if((err
= ov_open(fp
, vf
, 0/*initial*/, 0/*ibytes*/)))
292 fatal(0, "ov_fopen %s: %d", path
, err
);
293 if(!(vi
= ov_info(vf
, 0/*link*/)))
294 fatal(0, "ov_info %s: failed", path
);
295 while((n
= ov_read(vf
, input_buffer
, sizeof input_buffer
, 1/*bigendianp*/,
296 2/*bytes/word*/, 1/*signed*/, &bitstream
))) {
298 fatal(0, "ov_read %s: %ld", path
, n
);
300 fatal(0, "only single-bitstream ogg files are supported");
301 output_header(vi
->rate
, vi
->channels
, 16/*bits*/, n
, ENDIAN_BIG
);
302 if(fwrite(input_buffer
, 1, n
, outputfp
) < (size_t)n
)
303 fatal(errno
, "decoding %s: writing sample data", path
);
307 /** @brief Sample data callback used by decode_wav() */
308 static int wav_write(struct wavfile
attribute((unused
)) *f
,
311 void attribute((unused
)) *u
) {
312 if(fwrite(data
, 1, nbytes
, outputfp
) < nbytes
)
313 fatal(errno
, "decoding %s: writing sample data", path
);
317 /** @brief WAV file decoder */
318 static void decode_wav(void) {
322 if((err
= wav_init(f
, path
)))
323 fatal(err
, "opening %s", path
);
324 output_header(f
->rate
, f
->channels
, f
->bits
, f
->datasize
, ENDIAN_LITTLE
);
325 if((err
= wav_data(f
, wav_write
, 0)))
326 fatal(err
, "error decoding %s", path
);
329 /** @brief Metadata callback for FLAC decoder
331 * This is a no-op here.
333 static void flac_metadata(const FLAC__FileDecoder
attribute((unused
)) *decoder
,
334 const FLAC__StreamMetadata
attribute((unused
)) *metadata
,
335 void attribute((unused
)) *client_data
) {
338 /** @brief Error callback for FLAC decoder */
339 static void flac_error(const FLAC__FileDecoder
attribute((unused
)) *decoder
,
340 FLAC__StreamDecoderErrorStatus status
,
341 void attribute((unused
)) *client_data
) {
342 fatal(0, "error decoding %s: %s", path
,
343 FLAC__StreamDecoderErrorStatusString
[status
]);
346 /** @brief Write callback for FLAC decoder */
347 static FLAC__StreamDecoderWriteStatus flac_write
348 (const FLAC__FileDecoder
attribute((unused
)) *decoder
,
349 const FLAC__Frame
*frame
,
350 const FLAC__int32
*const buffer
[],
351 void attribute((unused
)) *client_data
) {
354 output_header(frame
->header
.sample_rate
,
355 frame
->header
.channels
,
356 frame
->header
.bits_per_sample
,
357 (frame
->header
.channels
* frame
->header
.blocksize
358 * frame
->header
.bits_per_sample
) / 8,
360 for(n
= 0; n
< frame
->header
.blocksize
; ++n
) {
361 for(c
= 0; c
< frame
->header
.channels
; ++c
) {
362 switch(frame
->header
.bits_per_sample
) {
363 case 8: output_8(buffer
[c
][n
]); break;
364 case 16: output_16(buffer
[c
][n
]); break;
365 case 24: output_24(buffer
[c
][n
]); break;
366 case 32: output_32(buffer
[c
][n
]); break;
370 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE
;
374 /** @brief FLAC file decoder */
375 static void decode_flac(void) {
376 #if HAVE_FLAC_FILE_DECODER_H
377 FLAC__FileDecoder
*fd
= 0;
378 FLAC__FileDecoderState fs
;
380 if(!(fd
= FLAC__file_decoder_new()))
381 fatal(0, "FLAC__file_decoder_new failed");
382 if(!(FLAC__file_decoder_set_filename(fd
, path
)))
383 fatal(0, "FLAC__file_set_filename failed");
384 FLAC__file_decoder_set_metadata_callback(fd
, flac_metadata
);
385 FLAC__file_decoder_set_error_callback(fd
, flac_error
);
386 FLAC__file_decoder_set_write_callback(fd
, flac_write
);
387 if((fs
= FLAC__file_decoder_init(fd
)))
388 fatal(0, "FLAC__file_decoder_init: %s", FLAC__FileDecoderStateString
[fs
]);
389 FLAC__file_decoder_process_until_end_of_file(fd
);
391 FLAC__StreamDecoder
*sd
= 0;
392 FLAC__StreamDecoderInitStatus is
;
394 if((is
= FLAC__stream_decoder_init_file(sd
, path
, flac_write
, flac_metadata
,
396 fatal(0, "FLAC__stream_decoder_init_file %s: %s",
397 path
, FLAC__StreamDecoderInitStatusString
[is
]);
401 /** @brief Lookup table of decoders */
402 static const struct decoder decoders
[] = {
403 { "*.mp3", decode_mp3
},
404 { "*.MP3", decode_mp3
},
405 { "*.ogg", decode_ogg
},
406 { "*.OGG", decode_ogg
},
407 { "*.flac", decode_flac
},
408 { "*.FLAC", decode_flac
},
409 { "*.wav", decode_wav
},
410 { "*.WAV", decode_wav
},
414 static const struct option options
[] = {
415 { "help", no_argument
, 0, 'h' },
416 { "version", no_argument
, 0, 'V' },
420 /* Display usage message and terminate. */
421 static void help(void) {
423 " disorder-decode [OPTIONS] PATH\n"
425 " --help, -h Display usage message\n"
426 " --version, -V Display version number\n"
428 "Audio decoder for DisOrder. Only intended to be used by speaker\n"
429 "process, not for normal users.\n");
434 int main(int argc
, char **argv
) {
439 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "calling setlocale");
440 while((n
= getopt_long(argc
, argv
, "hV", options
, 0)) >= 0) {
443 case 'V': version("disorder-decode");
444 default: fatal(0, "invalid option");
448 fatal(0, "missing filename");
449 if(optind
+ 1 < argc
)
450 fatal(0, "excess arguments");
451 if((e
= getenv("DISORDER_RAW_FD"))) {
452 if(!(outputfp
= fdopen(atoi(e
), "wb")))
453 fatal(errno
, "fdopen");
459 && fnmatch(decoders
[n
].pattern
, path
, 0) != 0;
462 if(!decoders
[n
].pattern
)
463 fatal(0, "cannot determine file type for %s", path
);
464 decoders
[n
].decode();