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>
37 #include <FLAC/file_decoder.h>
43 #include "speaker-protocol.h"
45 /** @brief Encoding lookup table type */
47 /** @brief Glob pattern matching file */
49 /** @brief Decoder function */
53 /** @brief Input file */
56 /** @brief Output file */
57 static FILE *outputfp
;
59 /** @brief Filename */
60 static const char *path
;
62 /** @brief Input buffer */
63 static char input_buffer
[1048576];
65 /** @brief Open the input file */
66 static void open_input(void) {
67 if((inputfd
= open(path
, O_RDONLY
)) < 0)
68 fatal(errno
, "opening %s", path
);
71 /** @brief Fill the buffer
72 * @return Number of bytes read
74 static size_t fill(void) {
75 int n
= read(inputfd
, input_buffer
, sizeof input_buffer
);
78 fatal(errno
, "reading from %s", path
);
82 /** @brief Write an 8-bit word */
83 static inline void output_8(int n
) {
84 if(putc(n
, outputfp
) < 0)
85 fatal(errno
, "decoding %s: output error", path
);
88 /** @brief Write a 16-bit word in bigendian format */
89 static inline void output_16(uint16_t n
) {
90 if(putc(n
>> 8, outputfp
) < 0
91 || putc(n
, outputfp
) < 0)
92 fatal(errno
, "decoding %s: output error", path
);
95 /** @brief Write a 24-bit word in bigendian format */
96 static inline void output_24(uint32_t n
) {
97 if(putc(n
>> 16, outputfp
) < 0
98 || putc(n
>> 8, outputfp
) < 0
99 || putc(n
, outputfp
) < 0)
100 fatal(errno
, "decoding %s: output error", path
);
103 /** @brief Write a 32-bit word in bigendian format */
104 static inline void output_32(uint32_t n
) {
105 if(putc(n
>> 24, outputfp
) < 0
106 || putc(n
>> 16, outputfp
) < 0
107 || putc(n
>> 8, outputfp
) < 0
108 || putc(n
, outputfp
) < 0)
109 fatal(errno
, "decoding %s: output error", path
);
112 /** @brief Write a block header
113 * @param rate Sample rate in Hz
114 * @param channels Channel count (currently only 1 or 2 supported)
115 * @param bits Bits per sample (must be a multiple of 8, no more than 64)
116 * @param nbytes Total number of data bytes
117 * @param endian @ref ENDIAN_BIG or @ref ENDIAN_LITTLE
119 * Checks that the sample format is a supported one (so other calls do not have
120 * to) and calls fatal() on error.
122 static void output_header(int rate
,
127 struct stream_header header
;
129 if(bits
<= 0 || bits
% 8 || bits
> 64)
130 fatal(0, "decoding %s: unsupported sample size %d bits", path
, bits
);
131 if(channels
<= 0 || channels
> 2)
132 fatal(0, "decoding %s: unsupported channel count %d", path
, channels
);
134 fatal(0, "decoding %s: nonsensical sample rate %dHz", path
, rate
);
137 header
.channels
= channels
;
138 header
.endian
= endian
;
139 header
.nbytes
= nbytes
;
140 if(fwrite(&header
, sizeof header
, 1, outputfp
) < 1)
141 fatal(errno
, "decoding %s: writing format header", path
);
144 /** @brief Dithering state
145 * Filched from mpg321, which credits it to Robert Leslie */
146 struct audio_dither
{
147 mad_fixed_t error
[3];
151 /** @brief 32-bit PRNG
152 * Filched from mpg321, which credits it to Robert Leslie */
153 static inline unsigned long prng(unsigned long state
)
155 return (state
* 0x0019660dL
+ 0x3c6ef35fL
) & 0xffffffffL
;
158 /** @brief Generic linear sample quantize and dither routine
159 * Filched from mpg321, which credits it to Robert Leslie */
161 static long audio_linear_dither(mad_fixed_t sample
,
162 struct audio_dither
*dither
) {
163 unsigned int scalebits
;
164 mad_fixed_t output
, mask
, rnd
;
172 sample
+= dither
->error
[0] - dither
->error
[1] + dither
->error
[2];
174 dither
->error
[2] = dither
->error
[1];
175 dither
->error
[1] = dither
->error
[0] / 2;
178 output
= sample
+ (1L << (MAD_F_FRACBITS
+ 1 - bits
- 1));
180 scalebits
= MAD_F_FRACBITS
+ 1 - bits
;
181 mask
= (1L << scalebits
) - 1;
184 rnd
= prng(dither
->random
);
185 output
+= (rnd
& mask
) - (dither
->random
& mask
);
187 dither
->random
= rnd
;
196 else if (output
< MIN
) {
207 dither
->error
[0] = sample
- output
;
210 return output
>> scalebits
;
214 /** @brief MP3 output callback */
215 static enum mad_flow
mp3_output(void attribute((unused
)) *data
,
216 struct mad_header
const *header
,
217 struct mad_pcm
*pcm
) {
218 size_t n
= pcm
->length
;
219 const mad_fixed_t
*l
= pcm
->samples
[0], *r
= pcm
->samples
[1];
220 static struct audio_dither ld
[1], rd
[1];
222 output_header(header
->samplerate
,
225 2 * pcm
->channels
* pcm
->length
,
227 switch(pcm
->channels
) {
230 output_16(audio_linear_dither(*l
++, ld
));
234 output_16(audio_linear_dither(*l
++, ld
));
235 output_16(audio_linear_dither(*r
++, rd
));
239 return MAD_FLOW_CONTINUE
;
242 /** @brief MP3 input callback */
243 static enum mad_flow
mp3_input(void attribute((unused
)) *data
,
244 struct mad_stream
*stream
) {
245 const size_t n
= fill();
248 return MAD_FLOW_STOP
;
249 mad_stream_buffer(stream
, (unsigned char *)input_buffer
, n
);
250 return MAD_FLOW_CONTINUE
;
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];
270 mad_decoder_init(mad
, 0/*data*/, mp3_input
, 0/*header*/, 0/*filter*/,
271 mp3_output
, mp3_error
, 0/*message*/);
272 if(mad_decoder_run(mad
, MAD_DECODER_MODE_SYNC
))
274 mad_decoder_finish(mad
);
277 /** @brief OGG decoder */
278 static void decode_ogg(void) {
280 OggVorbis_File vf
[1];
286 if(!(fp
= fopen(path
, "rb")))
287 fatal(errno
, "cannot open %s", path
);
288 /* There doesn't seem to be any standard function for mapping the error codes
290 if((err
= ov_open(fp
, vf
, 0/*initial*/, 0/*ibytes*/)))
291 fatal(0, "ov_fopen %s: %d", path
, err
);
292 if(!(vi
= ov_info(vf
, 0/*link*/)))
293 fatal(0, "ov_info %s: failed", path
);
294 while((n
= ov_read(vf
, input_buffer
, sizeof input_buffer
, 1/*bigendianp*/,
295 2/*bytes/word*/, 1/*signed*/, &bitstream
))) {
297 fatal(0, "ov_read %s: %ld", path
, n
);
299 fatal(0, "only single-bitstream ogg files are supported");
300 output_header(vi
->rate
, vi
->channels
, 16/*bits*/, n
, ENDIAN_BIG
);
301 if(fwrite(input_buffer
, 1, n
, outputfp
) < (size_t)n
)
302 fatal(errno
, "decoding %s: writing sample data", path
);
306 /** @brief Sample data callback used by decode_wav() */
307 static int wav_write(struct wavfile
attribute((unused
)) *f
,
310 void attribute((unused
)) *u
) {
311 if(fwrite(data
, 1, nbytes
, outputfp
) < nbytes
)
312 fatal(errno
, "decoding %s: writing sample data", path
);
316 /** @brief WAV file decoder */
317 static void decode_wav(void) {
321 if((err
= wav_init(f
, path
)))
322 fatal(err
, "opening %s", path
);
323 output_header(f
->rate
, f
->channels
, f
->bits
, f
->datasize
, ENDIAN_LITTLE
);
324 if((err
= wav_data(f
, wav_write
, 0)))
325 fatal(err
, "error decoding %s", path
);
328 /** @brief Metadata callback for FLAC decoder
330 * This is a no-op here.
332 static void flac_metadata(const FLAC__FileDecoder
attribute((unused
)) *decoder
,
333 const FLAC__StreamMetadata
attribute((unused
)) *metadata
,
334 void attribute((unused
)) *client_data
) {
337 /** @brief Error callback for FLAC decoder */
338 static void flac_error(const FLAC__FileDecoder
attribute((unused
)) *decoder
,
339 FLAC__StreamDecoderErrorStatus status
,
340 void attribute((unused
)) *client_data
) {
341 fatal(0, "error decoding %s: %s", path
,
342 FLAC__StreamDecoderErrorStatusString
[status
]);
345 /** @brief Write callback for FLAC decoder */
346 static FLAC__StreamDecoderWriteStatus flac_write
347 (const FLAC__FileDecoder
attribute((unused
)) *decoder
,
348 const FLAC__Frame
*frame
,
349 const FLAC__int32
*const buffer
[],
350 void attribute((unused
)) *client_data
) {
353 output_header(frame
->header
.sample_rate
,
354 frame
->header
.channels
,
355 frame
->header
.bits_per_sample
,
356 (frame
->header
.channels
* frame
->header
.blocksize
357 * frame
->header
.bits_per_sample
) / 8,
359 for(n
= 0; n
< frame
->header
.blocksize
; ++n
) {
360 for(c
= 0; c
< frame
->header
.channels
; ++c
) {
361 switch(frame
->header
.bits_per_sample
) {
362 case 8: output_8(buffer
[c
][n
]); break;
363 case 16: output_16(buffer
[c
][n
]); break;
364 case 24: output_24(buffer
[c
][n
]); break;
365 case 32: output_32(buffer
[c
][n
]); break;
369 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE
;
373 /** @brief FLAC file decoder */
374 static void decode_flac(void) {
375 FLAC__FileDecoder
*fd
= 0;
376 FLAC__FileDecoderState fs
;
378 if(!(fd
= FLAC__file_decoder_new()))
379 fatal(0, "FLAC__file_decoder_new failed");
380 if(!(FLAC__file_decoder_set_filename(fd
, path
)))
381 fatal(0, "FLAC__file_set_filename failed");
382 FLAC__file_decoder_set_metadata_callback(fd
, flac_metadata
);
383 FLAC__file_decoder_set_error_callback(fd
, flac_error
);
384 FLAC__file_decoder_set_write_callback(fd
, flac_write
);
385 if((fs
= FLAC__file_decoder_init(fd
)))
386 fatal(0, "FLAC__file_decoder_init: %s", FLAC__FileDecoderStateString
[fs
]);
387 FLAC__file_decoder_process_until_end_of_file(fd
);
390 /** @brief Lookup table of decoders */
391 static const struct decoder decoders
[] = {
392 { "*.mp3", decode_mp3
},
393 { "*.MP3", decode_mp3
},
394 { "*.ogg", decode_ogg
},
395 { "*.OGG", decode_ogg
},
396 { "*.flac", decode_flac
},
397 { "*.FLAC", decode_flac
},
398 { "*.wav", decode_wav
},
399 { "*.WAV", decode_wav
},
403 static const struct option options
[] = {
404 { "help", no_argument
, 0, 'h' },
405 { "version", no_argument
, 0, 'V' },
409 /* Display usage message and terminate. */
410 static void help(void) {
412 " disorder-decode [OPTIONS] PATH\n"
414 " --help, -h Display usage message\n"
415 " --version, -V Display version number\n"
417 "Audio decoder for DisOrder. Only intended to be used by speaker\n"
418 "process, not for normal users.\n");
423 /* Display version number and terminate. */
424 static void version(void) {
425 xprintf("disorder-decode version %s\n", disorder_version_string
);
430 int main(int argc
, char **argv
) {
435 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "calling setlocale");
436 while((n
= getopt_long(argc
, argv
, "hV", options
, 0)) >= 0) {
440 default: fatal(0, "invalid option");
444 fatal(0, "missing filename");
445 if(optind
+ 1 < argc
)
446 fatal(0, "excess arguments");
447 if((e
= getenv("DISORDER_RAW_FD"))) {
448 if(!(outputfp
= fdopen(atoi(e
), "wb")))
449 fatal(errno
, "fdopen");
455 && fnmatch(decoders
[n
].pattern
, path
, 0) != 0;
458 if(!decoders
[n
].pattern
)
459 fatal(0, "cannot determine file type for %s", path
);
460 decoders
[n
].decode();