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>
39 /* libFLAC has had an API change and stupidly taken away the old API */
40 #if HAVE_FLAC_FILE_DECODER_H
41 # include <FLAC/file_decoder.h>
43 # include <FLAC/stream_decoder.h>
44 #define FLAC__FileDecoder FLAC__StreamDecoder
45 #define FLAC__FileDecoderState FLAC__StreamDecoderState
52 #include "speaker-protocol.h"
54 /** @brief Encoding lookup table type */
56 /** @brief Glob pattern matching file */
58 /** @brief Decoder function */
62 /** @brief Input file */
65 /** @brief Output file */
66 static FILE *outputfp
;
68 /** @brief Filename */
69 static const char *path
;
71 /** @brief Input buffer */
72 static char input_buffer
[1048576];
74 /** @brief Number of bytes read into buffer */
75 static int input_count
;
77 /** @brief Write an 8-bit word */
78 static inline void output_8(int n
) {
79 if(putc(n
, outputfp
) < 0)
80 fatal(errno
, "decoding %s: output error", path
);
83 /** @brief Write a 16-bit word in bigendian format */
84 static inline void output_16(uint16_t n
) {
85 if(putc(n
>> 8, outputfp
) < 0
86 || putc(n
, outputfp
) < 0)
87 fatal(errno
, "decoding %s: output error", path
);
90 /** @brief Write a 24-bit word in bigendian format */
91 static inline void output_24(uint32_t n
) {
92 if(putc(n
>> 16, outputfp
) < 0
93 || putc(n
>> 8, outputfp
) < 0
94 || putc(n
, outputfp
) < 0)
95 fatal(errno
, "decoding %s: output error", path
);
98 /** @brief Write a 32-bit word in bigendian format */
99 static inline void output_32(uint32_t n
) {
100 if(putc(n
>> 24, outputfp
) < 0
101 || putc(n
>> 16, outputfp
) < 0
102 || putc(n
>> 8, outputfp
) < 0
103 || putc(n
, outputfp
) < 0)
104 fatal(errno
, "decoding %s: output error", path
);
107 /** @brief Write a block header
108 * @param rate Sample rate in Hz
109 * @param channels Channel count (currently only 1 or 2 supported)
110 * @param bits Bits per sample (must be a multiple of 8, no more than 64)
111 * @param nbytes Total number of data bytes
112 * @param endian @ref ENDIAN_BIG or @ref ENDIAN_LITTLE
114 * Checks that the sample format is a supported one (so other calls do not have
115 * to) and calls fatal() on error.
117 static void output_header(int rate
,
122 struct stream_header header
;
124 if(bits
<= 0 || bits
% 8 || bits
> 64)
125 fatal(0, "decoding %s: unsupported sample size %d bits", path
, bits
);
126 if(channels
<= 0 || channels
> 2)
127 fatal(0, "decoding %s: unsupported channel count %d", path
, channels
);
129 fatal(0, "decoding %s: nonsensical sample rate %dHz", path
, rate
);
132 header
.channels
= channels
;
133 header
.endian
= endian
;
134 header
.nbytes
= nbytes
;
135 if(fwrite(&header
, sizeof header
, 1, outputfp
) < 1)
136 fatal(errno
, "decoding %s: writing format header", path
);
139 /** @brief Dithering state
140 * Filched from mpg321, which credits it to Robert Leslie */
141 struct audio_dither
{
142 mad_fixed_t error
[3];
146 /** @brief 32-bit PRNG
147 * Filched from mpg321, which credits it to Robert Leslie */
148 static inline unsigned long prng(unsigned long state
)
150 return (state
* 0x0019660dL
+ 0x3c6ef35fL
) & 0xffffffffL
;
153 /** @brief Generic linear sample quantize and dither routine
154 * Filched from mpg321, which credits it to Robert Leslie */
155 static long audio_linear_dither(mad_fixed_t sample
,
156 struct audio_dither
*dither
) {
157 unsigned int scalebits
;
158 mad_fixed_t output
, mask
, rnd
;
167 sample
+= dither
->error
[0] - dither
->error
[1] + dither
->error
[2];
169 dither
->error
[2] = dither
->error
[1];
170 dither
->error
[1] = dither
->error
[0] / 2;
173 output
= sample
+ (1L << (MAD_F_FRACBITS
+ 1 - bits
- 1));
175 scalebits
= MAD_F_FRACBITS
+ 1 - bits
;
176 mask
= (1L << scalebits
) - 1;
179 rnd
= prng(dither
->random
);
180 output
+= (rnd
& mask
) - (dither
->random
& mask
);
182 dither
->random
= rnd
;
191 else if (output
< MIN
) {
202 dither
->error
[0] = sample
- output
;
205 return output
>> scalebits
;
208 /** @brief MP3 output callback */
209 static enum mad_flow
mp3_output(void attribute((unused
)) *data
,
210 struct mad_header
const *header
,
211 struct mad_pcm
*pcm
) {
212 size_t n
= pcm
->length
;
213 const mad_fixed_t
*l
= pcm
->samples
[0], *r
= pcm
->samples
[1];
214 static struct audio_dither ld
[1], rd
[1];
216 output_header(header
->samplerate
,
219 2 * pcm
->channels
* pcm
->length
,
221 switch(pcm
->channels
) {
224 output_16(audio_linear_dither(*l
++, ld
));
228 output_16(audio_linear_dither(*l
++, ld
));
229 output_16(audio_linear_dither(*r
++, rd
));
233 return MAD_FLOW_CONTINUE
;
236 /** @brief MP3 input callback */
237 static enum mad_flow
mp3_input(void attribute((unused
)) *data
,
238 struct mad_stream
*stream
) {
241 /* libmad requires its caller to do ALL the buffering work, including coping
242 * with partial frames. Given that it appears to be completely undocumented
243 * you could perhaps be forgiven for not discovering this... */
245 /* Compute total number of bytes consumed */
246 used
= (char *)stream
->next_frame
- input_buffer
;
247 /* Compute number of bytes left to consume */
248 remain
= input_count
- used
;
249 memmove(input_buffer
, input_buffer
+ used
, remain
);
254 n
= read(inputfd
, input_buffer
+ remain
, (sizeof input_buffer
) - remain
);
256 fatal(errno
, "reading from %s", path
);
257 /* Compute total number of bytes available */
258 input_count
= remain
+ n
;
260 mad_stream_buffer(stream
, (unsigned char *)input_buffer
, input_count
);
262 return MAD_FLOW_CONTINUE
;
264 return MAD_FLOW_STOP
;
267 /** @brief MP3 error callback */
268 static enum mad_flow
mp3_error(void attribute((unused
)) *data
,
269 struct mad_stream
*stream
,
270 struct mad_frame
attribute((unused
)) *frame
) {
272 /* Just generates pointless verbosity l-( */
273 error(0, "decoding %s: %s (%#04x)",
274 path
, mad_stream_errorstr(stream
), stream
->error
);
275 return MAD_FLOW_CONTINUE
;
278 /** @brief MP3 decoder */
279 static void decode_mp3(void) {
280 struct mad_decoder mad
[1];
282 if((inputfd
= open(path
, O_RDONLY
)) < 0)
283 fatal(errno
, "opening %s", path
);
284 mad_decoder_init(mad
, 0/*data*/, mp3_input
, 0/*header*/, 0/*filter*/,
285 mp3_output
, mp3_error
, 0/*message*/);
286 if(mad_decoder_run(mad
, MAD_DECODER_MODE_SYNC
))
288 mad_decoder_finish(mad
);
291 /** @brief OGG decoder */
292 static void decode_ogg(void) {
294 OggVorbis_File vf
[1];
300 if(!(fp
= fopen(path
, "rb")))
301 fatal(errno
, "cannot open %s", path
);
302 /* There doesn't seem to be any standard function for mapping the error codes
304 if((err
= ov_open(fp
, vf
, 0/*initial*/, 0/*ibytes*/)))
305 fatal(0, "ov_fopen %s: %d", path
, err
);
306 if(!(vi
= ov_info(vf
, 0/*link*/)))
307 fatal(0, "ov_info %s: failed", path
);
308 while((n
= ov_read(vf
, input_buffer
, sizeof input_buffer
, 1/*bigendianp*/,
309 2/*bytes/word*/, 1/*signed*/, &bitstream
))) {
311 fatal(0, "ov_read %s: %ld", path
, n
);
313 fatal(0, "only single-bitstream ogg files are supported");
314 output_header(vi
->rate
, vi
->channels
, 16/*bits*/, n
, ENDIAN_BIG
);
315 if(fwrite(input_buffer
, 1, n
, outputfp
) < (size_t)n
)
316 fatal(errno
, "decoding %s: writing sample data", path
);
320 /** @brief Sample data callback used by decode_wav() */
321 static int wav_write(struct wavfile
attribute((unused
)) *f
,
324 void attribute((unused
)) *u
) {
325 if(fwrite(data
, 1, nbytes
, outputfp
) < nbytes
)
326 fatal(errno
, "decoding %s: writing sample data", path
);
330 /** @brief WAV file decoder */
331 static void decode_wav(void) {
335 if((err
= wav_init(f
, path
)))
336 fatal(err
, "opening %s", path
);
337 output_header(f
->rate
, f
->channels
, f
->bits
, f
->datasize
, ENDIAN_LITTLE
);
338 if((err
= wav_data(f
, wav_write
, 0)))
339 fatal(err
, "error decoding %s", path
);
342 /** @brief Metadata callback for FLAC decoder
344 * This is a no-op here.
346 static void flac_metadata(const FLAC__FileDecoder
attribute((unused
)) *decoder
,
347 const FLAC__StreamMetadata
attribute((unused
)) *metadata
,
348 void attribute((unused
)) *client_data
) {
351 /** @brief Error callback for FLAC decoder */
352 static void flac_error(const FLAC__FileDecoder
attribute((unused
)) *decoder
,
353 FLAC__StreamDecoderErrorStatus status
,
354 void attribute((unused
)) *client_data
) {
355 fatal(0, "error decoding %s: %s", path
,
356 FLAC__StreamDecoderErrorStatusString
[status
]);
359 /** @brief Write callback for FLAC decoder */
360 static FLAC__StreamDecoderWriteStatus flac_write
361 (const FLAC__FileDecoder
attribute((unused
)) *decoder
,
362 const FLAC__Frame
*frame
,
363 const FLAC__int32
*const buffer
[],
364 void attribute((unused
)) *client_data
) {
367 output_header(frame
->header
.sample_rate
,
368 frame
->header
.channels
,
369 frame
->header
.bits_per_sample
,
370 (frame
->header
.channels
* frame
->header
.blocksize
371 * frame
->header
.bits_per_sample
) / 8,
373 for(n
= 0; n
< frame
->header
.blocksize
; ++n
) {
374 for(c
= 0; c
< frame
->header
.channels
; ++c
) {
375 switch(frame
->header
.bits_per_sample
) {
376 case 8: output_8(buffer
[c
][n
]); break;
377 case 16: output_16(buffer
[c
][n
]); break;
378 case 24: output_24(buffer
[c
][n
]); break;
379 case 32: output_32(buffer
[c
][n
]); break;
383 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE
;
387 /** @brief FLAC file decoder */
388 static void decode_flac(void) {
389 #if HAVE_FLAC_FILE_DECODER_H
390 FLAC__FileDecoder
*fd
= 0;
391 FLAC__FileDecoderState fs
;
393 if(!(fd
= FLAC__file_decoder_new()))
394 fatal(0, "FLAC__file_decoder_new failed");
395 if(!(FLAC__file_decoder_set_filename(fd
, path
)))
396 fatal(0, "FLAC__file_set_filename failed");
397 FLAC__file_decoder_set_metadata_callback(fd
, flac_metadata
);
398 FLAC__file_decoder_set_error_callback(fd
, flac_error
);
399 FLAC__file_decoder_set_write_callback(fd
, flac_write
);
400 if((fs
= FLAC__file_decoder_init(fd
)))
401 fatal(0, "FLAC__file_decoder_init: %s", FLAC__FileDecoderStateString
[fs
]);
402 FLAC__file_decoder_process_until_end_of_file(fd
);
404 FLAC__StreamDecoder
*sd
= 0;
405 FLAC__StreamDecoderInitStatus is
;
407 if((is
= FLAC__stream_decoder_init_file(sd
, path
, flac_write
, flac_metadata
,
409 fatal(0, "FLAC__stream_decoder_init_file %s: %s",
410 path
, FLAC__StreamDecoderInitStatusString
[is
]);
414 /** @brief Lookup table of decoders */
415 static const struct decoder decoders
[] = {
416 { "*.mp3", decode_mp3
},
417 { "*.MP3", decode_mp3
},
418 { "*.ogg", decode_ogg
},
419 { "*.OGG", decode_ogg
},
420 { "*.flac", decode_flac
},
421 { "*.FLAC", decode_flac
},
422 { "*.wav", decode_wav
},
423 { "*.WAV", decode_wav
},
427 static const struct option options
[] = {
428 { "help", no_argument
, 0, 'h' },
429 { "version", no_argument
, 0, 'V' },
433 /* Display usage message and terminate. */
434 static void help(void) {
436 " disorder-decode [OPTIONS] PATH\n"
438 " --help, -h Display usage message\n"
439 " --version, -V Display version number\n"
441 "Audio decoder for DisOrder. Only intended to be used by speaker\n"
442 "process, not for normal users.\n");
447 /* Display version number and terminate. */
448 static void version(void) {
449 xprintf("%s", disorder_version_string
);
454 int main(int argc
, char **argv
) {
459 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "calling setlocale");
460 while((n
= getopt_long(argc
, argv
, "hV", options
, 0)) >= 0) {
464 default: fatal(0, "invalid option");
468 fatal(0, "missing filename");
469 if(optind
+ 1 < argc
)
470 fatal(0, "excess arguments");
471 if((e
= getenv("DISORDER_RAW_FD"))) {
472 if(!(outputfp
= fdopen(atoi(e
), "wb")))
473 fatal(errno
, "fdopen");
479 && fnmatch(decoders
[n
].pattern
, path
, 0) != 0;
482 if(!decoders
[n
].pattern
)
483 fatal(0, "cannot determine file type for %s", path
);
484 decoders
[n
].decode();