chiark / gitweb /
Only report failure to find OSS devices once, not every time we think
[disorder] / server / decode.c
CommitLineData
f8f8039f
RK
1/*
2 * This file is part of DisOrder
3 * Copyright (C) 2007 Richard Kettlewell
4 *
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.
9 *
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.
14 *
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
18 * USA
19 */
20/** @file server/decode.c
21 * @brief General-purpose decoder for use by speaker process
22 */
23
24#include <config.h>
25#include "types.h"
26
27#include <getopt.h>
28#include <unistd.h>
29#include <fcntl.h>
30#include <errno.h>
31#include <stdlib.h>
32#include <locale.h>
33#include <assert.h>
34#include <fnmatch.h>
35#include <mad.h>
572c2899 36#include <vorbis/vorbisfile.h>
87b5259b 37#include <string.h>
762806f1
RK
38
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>
42#else
43# include <FLAC/stream_decoder.h>
44#define FLAC__FileDecoder FLAC__StreamDecoder
45#define FLAC__FileDecoderState FLAC__StreamDecoderState
46#endif
f8f8039f
RK
47
48#include "log.h"
49#include "syscalls.h"
50#include "defs.h"
ce6c36be 51#include "wav.h"
39492555 52#include "speaker-protocol.h"
f8f8039f
RK
53
54/** @brief Encoding lookup table type */
55struct decoder {
56 /** @brief Glob pattern matching file */
57 const char *pattern;
58 /** @brief Decoder function */
59 void (*decode)(void);
60};
61
62/** @brief Input file */
63static int inputfd;
64
65/** @brief Output file */
66static FILE *outputfp;
67
68/** @brief Filename */
69static const char *path;
70
71/** @brief Input buffer */
75db8354 72static char input_buffer[1048576];
f8f8039f 73
87b5259b 74/** @brief Number of bytes read into buffer */
75static int input_count;
f8f8039f 76
75db8354 77/** @brief Write an 8-bit word */
78static inline void output_8(int n) {
79 if(putc(n, outputfp) < 0)
80 fatal(errno, "decoding %s: output error", path);
81}
82
f8f8039f
RK
83/** @brief Write a 16-bit word in bigendian format */
84static inline void output_16(uint16_t n) {
85 if(putc(n >> 8, outputfp) < 0
75db8354 86 || putc(n, outputfp) < 0)
87 fatal(errno, "decoding %s: output error", path);
88}
89
90/** @brief Write a 24-bit word in bigendian format */
91static 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)
f8f8039f
RK
95 fatal(errno, "decoding %s: output error", path);
96}
97
75db8354 98/** @brief Write a 32-bit word in bigendian format */
99static 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);
105}
106
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
113 *
114 * Checks that the sample format is a supported one (so other calls do not have
115 * to) and calls fatal() on error.
f8f8039f
RK
116 */
117static void output_header(int rate,
118 int channels,
39492555 119 int bits,
ce6c36be 120 int nbytes,
121 int endian) {
39492555 122 struct stream_header header;
123
75db8354 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);
128 if(rate <= 0)
129 fatal(0, "decoding %s: nonsensical sample rate %dHz", path, rate);
39492555 130 header.rate = rate;
131 header.bits = bits;
132 header.channels = channels;
ce6c36be 133 header.endian = endian;
39492555 134 header.nbytes = nbytes;
135 if(fwrite(&header, sizeof header, 1, outputfp) < 1)
136 fatal(errno, "decoding %s: writing format header", path);
f8f8039f
RK
137}
138
139/** @brief Dithering state
140 * Filched from mpg321, which credits it to Robert Leslie */
141struct audio_dither {
142 mad_fixed_t error[3];
143 mad_fixed_t random;
144};
145
146/** @brief 32-bit PRNG
147 * Filched from mpg321, which credits it to Robert Leslie */
148static inline unsigned long prng(unsigned long state)
149{
150 return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
151}
152
153/** @brief Generic linear sample quantize and dither routine
154 * Filched from mpg321, which credits it to Robert Leslie */
f8f8039f
RK
155static long audio_linear_dither(mad_fixed_t sample,
156 struct audio_dither *dither) {
157 unsigned int scalebits;
158 mad_fixed_t output, mask, rnd;
87b5259b 159 const int bits = 16;
f8f8039f
RK
160
161 enum {
162 MIN = -MAD_F_ONE,
163 MAX = MAD_F_ONE - 1
164 };
165
166 /* noise shape */
167 sample += dither->error[0] - dither->error[1] + dither->error[2];
168
169 dither->error[2] = dither->error[1];
170 dither->error[1] = dither->error[0] / 2;
171
172 /* bias */
173 output = sample + (1L << (MAD_F_FRACBITS + 1 - bits - 1));
174
175 scalebits = MAD_F_FRACBITS + 1 - bits;
176 mask = (1L << scalebits) - 1;
177
178 /* dither */
179 rnd = prng(dither->random);
180 output += (rnd & mask) - (dither->random & mask);
181
182 dither->random = rnd;
183
184 /* clip */
185 if (output > MAX) {
186 output = MAX;
187
188 if (sample > MAX)
189 sample = MAX;
190 }
191 else if (output < MIN) {
192 output = MIN;
193
194 if (sample < MIN)
195 sample = MIN;
196 }
197
198 /* quantize */
199 output &= ~mask;
200
201 /* error feedback */
202 dither->error[0] = sample - output;
203
204 /* scale */
205 return output >> scalebits;
206}
f8f8039f
RK
207
208/** @brief MP3 output callback */
209static 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];
215
216 output_header(header->samplerate,
217 pcm->channels,
39492555 218 16,
ce6c36be 219 2 * pcm->channels * pcm->length,
220 ENDIAN_BIG);
f8f8039f
RK
221 switch(pcm->channels) {
222 case 1:
223 while(n--)
224 output_16(audio_linear_dither(*l++, ld));
225 break;
226 case 2:
227 while(n--) {
228 output_16(audio_linear_dither(*l++, ld));
229 output_16(audio_linear_dither(*r++, rd));
230 }
231 break;
f8f8039f
RK
232 }
233 return MAD_FLOW_CONTINUE;
234}
235
236/** @brief MP3 input callback */
237static enum mad_flow mp3_input(void attribute((unused)) *data,
238 struct mad_stream *stream) {
87b5259b 239 int used, remain, n;
240
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... */
244 if(input_count) {
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);
250 } else {
251 remain = 0;
252 }
253 /* Read new data */
254 n = read(inputfd, input_buffer + remain, (sizeof input_buffer) - remain);
255 if(n < 0)
256 fatal(errno, "reading from %s", path);
257 /* Compute total number of bytes available */
258 input_count = remain + n;
259 if(input_count)
260 mad_stream_buffer(stream, (unsigned char *)input_buffer, input_count);
261 if(n)
262 return MAD_FLOW_CONTINUE;
263 else
f8f8039f 264 return MAD_FLOW_STOP;
f8f8039f
RK
265}
266
f8f8039f
RK
267/** @brief MP3 error callback */
268static enum mad_flow mp3_error(void attribute((unused)) *data,
269 struct mad_stream *stream,
270 struct mad_frame attribute((unused)) *frame) {
39492555 271 if(0)
272 /* Just generates pointless verbosity l-( */
273 error(0, "decoding %s: %s (%#04x)",
274 path, mad_stream_errorstr(stream), stream->error);
f8f8039f
RK
275 return MAD_FLOW_CONTINUE;
276}
277
278/** @brief MP3 decoder */
279static void decode_mp3(void) {
280 struct mad_decoder mad[1];
281
87b5259b 282 if((inputfd = open(path, O_RDONLY)) < 0)
283 fatal(errno, "opening %s", path);
39492555 284 mad_decoder_init(mad, 0/*data*/, mp3_input, 0/*header*/, 0/*filter*/,
f8f8039f
RK
285 mp3_output, mp3_error, 0/*message*/);
286 if(mad_decoder_run(mad, MAD_DECODER_MODE_SYNC))
287 exit(1);
288 mad_decoder_finish(mad);
289}
290
572c2899 291/** @brief OGG decoder */
292static void decode_ogg(void) {
293 FILE *fp;
294 OggVorbis_File vf[1];
295 int err;
296 long n;
297 int bitstream;
298 vorbis_info *vi;
299
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
303 * to strings l-( */
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);
75db8354 308 while((n = ov_read(vf, input_buffer, sizeof input_buffer, 1/*bigendianp*/,
572c2899 309 2/*bytes/word*/, 1/*signed*/, &bitstream))) {
310 if(n < 0)
311 fatal(0, "ov_read %s: %ld", path, n);
312 if(bitstream > 0)
313 fatal(0, "only single-bitstream ogg files are supported");
ce6c36be 314 output_header(vi->rate, vi->channels, 16/*bits*/, n, ENDIAN_BIG);
75db8354 315 if(fwrite(input_buffer, 1, n, outputfp) < (size_t)n)
572c2899 316 fatal(errno, "decoding %s: writing sample data", path);
317 }
318}
319
ce6c36be 320/** @brief Sample data callback used by decode_wav() */
321static int wav_write(struct wavfile attribute((unused)) *f,
322 const char *data,
323 size_t nbytes,
324 void attribute((unused)) *u) {
325 if(fwrite(data, 1, nbytes, outputfp) < nbytes)
326 fatal(errno, "decoding %s: writing sample data", path);
327 return 0;
328}
329
330/** @brief WAV file decoder */
331static void decode_wav(void) {
332 struct wavfile f[1];
333 int err;
334
335 if((err = wav_init(f, path)))
336 fatal(err, "opening %s", path);
ce6c36be 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);
340}
341
75db8354 342/** @brief Metadata callback for FLAC decoder
343 *
344 * This is a no-op here.
345 */
346static void flac_metadata(const FLAC__FileDecoder attribute((unused)) *decoder,
347 const FLAC__StreamMetadata attribute((unused)) *metadata,
348 void attribute((unused)) *client_data) {
349}
350
351/** @brief Error callback for FLAC decoder */
352static 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]);
357}
358
359/** @brief Write callback for FLAC decoder */
360static 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) {
365 size_t n, c;
366
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,
372 ENDIAN_BIG);
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;
380 }
381 }
382 }
383 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
384}
385
386
387/** @brief FLAC file decoder */
388static void decode_flac(void) {
762806f1 389#if HAVE_FLAC_FILE_DECODER_H
75db8354 390 FLAC__FileDecoder *fd = 0;
391 FLAC__FileDecoderState fs;
392
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);
762806f1
RK
403#else
404 FLAC__StreamDecoder *sd = 0;
405 FLAC__StreamDecoderInitStatus is;
406
407 if((is = FLAC__stream_decoder_init_file(sd, path, flac_write, flac_metadata,
408 flac_error, 0)))
409 fatal(0, "FLAC__stream_decoder_init_file %s: %s",
410 path, FLAC__StreamDecoderInitStatusString[is]);
411#endif
75db8354 412}
413
f8f8039f
RK
414/** @brief Lookup table of decoders */
415static const struct decoder decoders[] = {
416 { "*.mp3", decode_mp3 },
417 { "*.MP3", decode_mp3 },
572c2899 418 { "*.ogg", decode_ogg },
419 { "*.OGG", decode_ogg },
75db8354 420 { "*.flac", decode_flac },
421 { "*.FLAC", decode_flac },
ce6c36be 422 { "*.wav", decode_wav },
423 { "*.WAV", decode_wav },
f8f8039f
RK
424 { 0, 0 }
425};
426
427static const struct option options[] = {
428 { "help", no_argument, 0, 'h' },
429 { "version", no_argument, 0, 'V' },
430 { 0, 0, 0, 0 }
431};
432
433/* Display usage message and terminate. */
434static void help(void) {
435 xprintf("Usage:\n"
436 " disorder-decode [OPTIONS] PATH\n"
437 "Options:\n"
438 " --help, -h Display usage message\n"
439 " --version, -V Display version number\n"
440 "\n"
441 "Audio decoder for DisOrder. Only intended to be used by speaker\n"
442 "process, not for normal users.\n");
443 xfclose(stdout);
444 exit(0);
445}
446
447/* Display version number and terminate. */
448static void version(void) {
a05e4467 449 xprintf("%s", disorder_version_string);
f8f8039f
RK
450 xfclose(stdout);
451 exit(0);
452}
453
454int main(int argc, char **argv) {
455 int n;
456 const char *e;
457
458 set_progname(argv);
459 if(!setlocale(LC_CTYPE, "")) fatal(errno, "calling setlocale");
460 while((n = getopt_long(argc, argv, "hV", options, 0)) >= 0) {
461 switch(n) {
462 case 'h': help();
463 case 'V': version();
464 default: fatal(0, "invalid option");
465 }
466 }
467 if(optind >= argc)
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");
474 } else
475 outputfp = stdout;
476 path = argv[optind];
477 for(n = 0;
478 decoders[n].pattern
479 && fnmatch(decoders[n].pattern, path, 0) != 0;
480 ++n)
481 ;
482 if(!decoders[n].pattern)
483 fatal(0, "cannot determine file type for %s", path);
484 decoders[n].decode();
485 xfclose(outputfp);
486 return 0;
487}
488
489/*
490Local Variables:
491c-basic-offset:2
492comment-column:40
493fill-column:79
494indent-tabs-mode:nil
495End:
496*/