2 * This file is part of DisOrder
3 * Copyright (C) 2007-2009 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 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/decode.c
19 * @brief General-purpose decoder for use by speaker process
22 #include "disorder-server.h"
26 #include <vorbis/vorbisfile.h>
28 #include <FLAC/stream_decoder.h>
31 #include "speaker-protocol.h"
34 /** @brief Encoding lookup table type */
36 /** @brief Glob pattern matching file */
38 /** @brief Decoder function */
42 static struct hreader input
[1];
44 /** @brief Output file */
45 static FILE *outputfp
;
47 /** @brief Filename */
48 static const char *path
;
50 /** @brief Input buffer */
51 static char input_buffer
[1048576];
53 /** @brief Number of bytes read into buffer */
54 static int input_count
;
56 /** @brief Write an 8-bit word */
57 static inline void output_8(int n
) {
58 if(putc(n
, outputfp
) < 0)
59 disorder_fatal(errno
, "decoding %s: output error", path
);
62 /** @brief Write a 16-bit word in bigendian format */
63 static inline void output_16(uint16_t n
) {
64 if(putc(n
>> 8, outputfp
) < 0
65 || putc(n
, outputfp
) < 0)
66 disorder_fatal(errno
, "decoding %s: output error", path
);
69 /** @brief Write a 24-bit word in bigendian format */
70 static inline void output_24(uint32_t n
) {
71 if(putc(n
>> 16, outputfp
) < 0
72 || putc(n
>> 8, outputfp
) < 0
73 || putc(n
, outputfp
) < 0)
74 disorder_fatal(errno
, "decoding %s: output error", path
);
77 /** @brief Write a 32-bit word in bigendian format */
78 static inline void output_32(uint32_t n
) {
79 if(putc(n
>> 24, outputfp
) < 0
80 || putc(n
>> 16, outputfp
) < 0
81 || putc(n
>> 8, outputfp
) < 0
82 || putc(n
, outputfp
) < 0)
83 disorder_fatal(errno
, "decoding %s: output error", path
);
86 /** @brief Write a block header
87 * @param rate Sample rate in Hz
88 * @param channels Channel count (currently only 1 or 2 supported)
89 * @param bits Bits per sample (must be a multiple of 8, no more than 64)
90 * @param nbytes Total number of data bytes
91 * @param endian @ref ENDIAN_BIG or @ref ENDIAN_LITTLE
93 * Checks that the sample format is a supported one (so other calls do not have
94 * to) and calls disorder_fatal() on error.
96 static void output_header(int rate
,
101 struct stream_header header
;
103 if(bits
<= 0 || bits
% 8 || bits
> 64)
104 disorder_fatal(0, "decoding %s: unsupported sample size %d bits",
106 if(channels
<= 0 || channels
> 2)
107 disorder_fatal(0, "decoding %s: unsupported channel count %d",
110 disorder_fatal(0, "decoding %s: nonsensical sample rate %dHz", path
, rate
);
113 header
.channels
= channels
;
114 header
.endian
= endian
;
115 header
.nbytes
= nbytes
;
116 if(fwrite(&header
, sizeof header
, 1, outputfp
) < 1)
117 disorder_fatal(errno
, "decoding %s: writing format header", path
);
120 /** @brief Dithering state
121 * Filched from mpg321, which credits it to Robert Leslie */
122 struct audio_dither
{
123 mad_fixed_t error
[3];
127 /** @brief 32-bit PRNG
128 * Filched from mpg321, which credits it to Robert Leslie */
129 static inline unsigned long prng(unsigned long state
)
131 return (state
* 0x0019660dL
+ 0x3c6ef35fL
) & 0xffffffffL
;
134 /** @brief Generic linear sample quantize and dither routine
135 * Filched from mpg321, which credits it to Robert Leslie */
136 static long audio_linear_dither(mad_fixed_t sample
,
137 struct audio_dither
*dither
) {
138 unsigned int scalebits
;
139 mad_fixed_t output
, mask
, rnd
;
148 sample
+= dither
->error
[0] - dither
->error
[1] + dither
->error
[2];
150 dither
->error
[2] = dither
->error
[1];
151 dither
->error
[1] = dither
->error
[0] / 2;
154 output
= sample
+ (1L << (MAD_F_FRACBITS
+ 1 - bits
- 1));
156 scalebits
= MAD_F_FRACBITS
+ 1 - bits
;
157 mask
= (1L << scalebits
) - 1;
160 rnd
= prng(dither
->random
);
161 output
+= (rnd
& mask
) - (dither
->random
& mask
);
163 dither
->random
= rnd
;
172 else if (output
< MIN
) {
183 dither
->error
[0] = sample
- output
;
186 return output
>> scalebits
;
189 /** @brief MP3 output callback */
190 static enum mad_flow
mp3_output(void attribute((unused
)) *data
,
191 struct mad_header
const *header
,
192 struct mad_pcm
*pcm
) {
193 size_t n
= pcm
->length
;
194 const mad_fixed_t
*l
= pcm
->samples
[0], *r
= pcm
->samples
[1];
195 static struct audio_dither ld
[1], rd
[1];
197 output_header(header
->samplerate
,
200 2 * pcm
->channels
* pcm
->length
,
202 switch(pcm
->channels
) {
205 output_16(audio_linear_dither(*l
++, ld
));
209 output_16(audio_linear_dither(*l
++, ld
));
210 output_16(audio_linear_dither(*r
++, rd
));
214 return MAD_FLOW_CONTINUE
;
217 /** @brief MP3 input callback */
218 static enum mad_flow
mp3_input(void attribute((unused
)) *data
,
219 struct mad_stream
*stream
) {
222 /* libmad requires its caller to do ALL the buffering work, including coping
223 * with partial frames. Given that it appears to be completely undocumented
224 * you could perhaps be forgiven for not discovering this... */
226 /* Compute total number of bytes consumed */
227 used
= (char *)stream
->next_frame
- input_buffer
;
228 /* Compute number of bytes left to consume */
229 remain
= input_count
- used
;
230 memmove(input_buffer
, input_buffer
+ used
, remain
);
235 n
= hreader_read(input
,
236 input_buffer
+ remain
,
237 (sizeof input_buffer
) - remain
);
239 disorder_fatal(errno
, "reading from %s", path
);
240 /* Compute total number of bytes available */
241 input_count
= remain
+ n
;
243 mad_stream_buffer(stream
, (unsigned char *)input_buffer
, input_count
);
245 return MAD_FLOW_CONTINUE
;
247 return MAD_FLOW_STOP
;
250 /** @brief MP3 error callback */
251 static enum mad_flow
mp3_error(void attribute((unused
)) *data
,
252 struct mad_stream
*stream
,
253 struct mad_frame
attribute((unused
)) *frame
) {
255 /* Just generates pointless verbosity l-( */
256 disorder_error(0, "decoding %s: %s (%#04x)",
257 path
, mad_stream_errorstr(stream
), stream
->error
);
258 return MAD_FLOW_CONTINUE
;
261 /** @brief MP3 decoder */
262 static void decode_mp3(void) {
263 struct mad_decoder mad
[1];
265 if(hreader_init(path
, input
))
266 disorder_fatal(errno
, "opening %s", path
);
267 mad_decoder_init(mad
, 0/*data*/, mp3_input
, 0/*header*/, 0/*filter*/,
268 mp3_output
, mp3_error
, 0/*message*/);
269 if(mad_decoder_run(mad
, MAD_DECODER_MODE_SYNC
))
271 mad_decoder_finish(mad
);
274 static size_t ogg_read_func(void *ptr
, size_t size
, size_t nmemb
, void *datasource
) {
275 struct hreader
*h
= datasource
;
277 int n
= hreader_read(h
, ptr
, size
* nmemb
);
282 static int ogg_seek_func(void *datasource
, ogg_int64_t offset
, int whence
) {
283 struct hreader
*h
= datasource
;
285 return hreader_seek(h
, offset
, whence
) < 0 ?
-1 : 0;
288 static int ogg_close_func(void attribute((unused
)) *datasource
) {
292 static long ogg_tell_func(void *datasource
) {
293 struct hreader
*h
= datasource
;
295 return hreader_seek(h
, 0, SEEK_CUR
);
298 static const ov_callbacks ogg_callbacks
= {
305 /** @brief OGG decoder */
306 static void decode_ogg(void) {
307 struct hreader ogginput
[1];
308 OggVorbis_File vf
[1];
314 hreader_init(path
, ogginput
);
315 /* There doesn't seem to be any standard function for mapping the error codes
317 if((err
= ov_open_callbacks(ogginput
, vf
, 0/*initial*/, 0/*ibytes*/,
319 disorder_fatal(0, "ov_open_callbacks %s: %d", path
, err
);
320 if(!(vi
= ov_info(vf
, 0/*link*/)))
321 disorder_fatal(0, "ov_info %s: failed", path
);
322 while((n
= ov_read(vf
, input_buffer
, sizeof input_buffer
, 1/*bigendianp*/,
323 2/*bytes/word*/, 1/*signed*/, &bitstream
))) {
325 disorder_fatal(0, "ov_read %s: %ld", path
, n
);
327 disorder_fatal(0, "only single-bitstream ogg files are supported");
328 output_header(vi
->rate
, vi
->channels
, 16/*bits*/, n
, ENDIAN_BIG
);
329 if(fwrite(input_buffer
, 1, n
, outputfp
) < (size_t)n
)
330 disorder_fatal(errno
, "decoding %s: writing sample data", path
);
334 /** @brief Sample data callback used by decode_wav() */
335 static int wav_write(struct wavfile
attribute((unused
)) *f
,
338 void attribute((unused
)) *u
) {
339 if(fwrite(data
, 1, nbytes
, outputfp
) < nbytes
)
340 disorder_fatal(errno
, "decoding %s: writing sample data", path
);
344 /** @brief WAV file decoder */
345 static void decode_wav(void) {
349 if((err
= wav_init(f
, path
)))
350 disorder_fatal(err
, "opening %s", path
);
351 output_header(f
->rate
, f
->channels
, f
->bits
, f
->datasize
, ENDIAN_LITTLE
);
352 if((err
= wav_data(f
, wav_write
, 0)))
353 disorder_fatal(err
, "error decoding %s", path
);
356 /** @brief Metadata callback for FLAC decoder
358 * This is a no-op here.
360 static void flac_metadata(const FLAC__StreamDecoder
attribute((unused
)) *decoder
,
361 const FLAC__StreamMetadata
attribute((unused
)) *metadata
,
362 void attribute((unused
)) *client_data
) {
365 /** @brief Error callback for FLAC decoder */
366 static void flac_error(const FLAC__StreamDecoder
attribute((unused
)) *decoder
,
367 FLAC__StreamDecoderErrorStatus status
,
368 void attribute((unused
)) *client_data
) {
369 disorder_fatal(0, "error decoding %s: %s", path
,
370 FLAC__StreamDecoderErrorStatusString
[status
]);
373 /** @brief Write callback for FLAC decoder */
374 static FLAC__StreamDecoderWriteStatus flac_write
375 (const FLAC__StreamDecoder
attribute((unused
)) *decoder
,
376 const FLAC__Frame
*frame
,
377 const FLAC__int32
*const buffer
[],
378 void attribute((unused
)) *client_data
) {
381 output_header(frame
->header
.sample_rate
,
382 frame
->header
.channels
,
383 frame
->header
.bits_per_sample
,
384 (frame
->header
.channels
* frame
->header
.blocksize
385 * frame
->header
.bits_per_sample
) / 8,
387 for(n
= 0; n
< frame
->header
.blocksize
; ++n
) {
388 for(c
= 0; c
< frame
->header
.channels
; ++c
) {
389 switch(frame
->header
.bits_per_sample
) {
390 case 8: output_8(buffer
[c
][n
]); break;
391 case 16: output_16(buffer
[c
][n
]); break;
392 case 24: output_24(buffer
[c
][n
]); break;
393 case 32: output_32(buffer
[c
][n
]); break;
397 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE
;
400 static FLAC__StreamDecoderReadStatus
flac_read(const FLAC__StreamDecoder
attribute((unused
)) *decoder
,
404 struct hreader
*flacinput
= client_data
;
405 int n
= hreader_read(flacinput
, buffer
, *bytes
);
408 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM
;
412 return FLAC__STREAM_DECODER_READ_STATUS_ABORT
;
415 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE
;
418 static FLAC__StreamDecoderSeekStatus
flac_seek(const FLAC__StreamDecoder
attribute((unused
)) *decoder
,
419 FLAC__uint64 absolute_byte_offset
,
421 struct hreader
*flacinput
= client_data
;
422 if(hreader_seek(flacinput
, absolute_byte_offset
, SEEK_SET
) < 0)
423 return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR
;
425 return FLAC__STREAM_DECODER_SEEK_STATUS_OK
;
428 static FLAC__StreamDecoderTellStatus
flac_tell(const FLAC__StreamDecoder
attribute((unused
)) *decoder
,
429 FLAC__uint64
*absolute_byte_offset
,
431 struct hreader
*flacinput
= client_data
;
432 off_t offset
= hreader_seek(flacinput
, 0, SEEK_CUR
);
434 return FLAC__STREAM_DECODER_TELL_STATUS_ERROR
;
435 *absolute_byte_offset
= offset
;
436 return FLAC__STREAM_DECODER_TELL_STATUS_OK
;
439 static FLAC__StreamDecoderLengthStatus
flac_length(const FLAC__StreamDecoder
attribute((unused
)) *decoder
,
440 FLAC__uint64
*stream_length
,
442 struct hreader
*flacinput
= client_data
;
443 *stream_length
= hreader_size(flacinput
);
444 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK
;
447 static FLAC__bool
flac_eof(const FLAC__StreamDecoder
attribute((unused
)) *decoder
,
449 struct hreader
*flacinput
= client_data
;
450 return hreader_eof(flacinput
);
453 /** @brief FLAC file decoder */
454 static void decode_flac(void) {
455 FLAC__StreamDecoder
*sd
= FLAC__stream_decoder_new();
456 FLAC__StreamDecoderInitStatus is
;
457 struct hreader flacinput
[1];
460 disorder_fatal(0, "FLAC__stream_decoder_new failed");
461 if(hreader_init(path
, flacinput
))
462 disorder_fatal(errno
, "error opening %s", path
);
464 if((is
= FLAC__stream_decoder_init_stream(sd
,
470 flac_write
, flac_metadata
,
473 disorder_fatal(0, "FLAC__stream_decoder_init_stream %s: %s",
474 path
, FLAC__StreamDecoderInitStatusString
[is
]);
476 FLAC__stream_decoder_process_until_end_of_stream(sd
);
477 FLAC__stream_decoder_finish(sd
);
478 FLAC__stream_decoder_delete(sd
);
481 /** @brief Lookup table of decoders */
482 static const struct decoder decoders
[] = {
483 { "*.mp3", decode_mp3
},
484 { "*.MP3", decode_mp3
},
485 { "*.ogg", decode_ogg
},
486 { "*.OGG", decode_ogg
},
487 { "*.flac", decode_flac
},
488 { "*.FLAC", decode_flac
},
489 { "*.wav", decode_wav
},
490 { "*.WAV", decode_wav
},
494 static const struct option options
[] = {
495 { "help", no_argument
, 0, 'h' },
496 { "version", no_argument
, 0, 'V' },
500 /* Display usage message and terminate. */
501 static void help(void) {
503 " disorder-decode [OPTIONS] PATH\n"
505 " --help, -h Display usage message\n"
506 " --version, -V Display version number\n"
508 "Audio decoder for DisOrder. Only intended to be used by speaker\n"
509 "process, not for normal users.\n");
514 int main(int argc
, char **argv
) {
519 if(!setlocale(LC_CTYPE
, "")) disorder_fatal(errno
, "calling setlocale");
520 while((n
= getopt_long(argc
, argv
, "hV", options
, 0)) >= 0) {
523 case 'V': version("disorder-decode");
524 default: disorder_fatal(0, "invalid option");
528 disorder_fatal(0, "missing filename");
529 if(optind
+ 1 < argc
)
530 disorder_fatal(0, "excess arguments");
531 if((e
= getenv("DISORDER_RAW_FD"))) {
532 if(!(outputfp
= fdopen(atoi(e
), "wb")))
533 disorder_fatal(errno
, "fdopen");
539 && fnmatch(decoders
[n
].pattern
, path
, 0) != 0;
542 if(!decoders
[n
].pattern
)
543 disorder_fatal(0, "cannot determine file type for %s", path
);
544 decoders
[n
].decode();