chiark / gitweb /
build fix for linux
[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>
762806f1
RK
37
38/* libFLAC has had an API change and stupidly taken away the old API */
39#if HAVE_FLAC_FILE_DECODER_H
40# include <FLAC/file_decoder.h>
41#else
42# include <FLAC/stream_decoder.h>
43#define FLAC__FileDecoder FLAC__StreamDecoder
44#define FLAC__FileDecoderState FLAC__StreamDecoderState
45#endif
f8f8039f
RK
46
47#include "log.h"
48#include "syscalls.h"
49#include "defs.h"
ce6c36be 50#include "wav.h"
39492555 51#include "speaker-protocol.h"
f8f8039f
RK
52
53/** @brief Encoding lookup table type */
54struct decoder {
55 /** @brief Glob pattern matching file */
56 const char *pattern;
57 /** @brief Decoder function */
58 void (*decode)(void);
59};
60
61/** @brief Input file */
62static int inputfd;
63
64/** @brief Output file */
65static FILE *outputfp;
66
67/** @brief Filename */
68static const char *path;
69
70/** @brief Input buffer */
75db8354 71static char input_buffer[1048576];
f8f8039f
RK
72
73/** @brief Open the input file */
74static void open_input(void) {
75 if((inputfd = open(path, O_RDONLY)) < 0)
76 fatal(errno, "opening %s", path);
77}
78
79/** @brief Fill the buffer
80 * @return Number of bytes read
81 */
82static size_t fill(void) {
75db8354 83 int n = read(inputfd, input_buffer, sizeof input_buffer);
f8f8039f
RK
84
85 if(n < 0)
86 fatal(errno, "reading from %s", path);
87 return n;
88}
89
75db8354 90/** @brief Write an 8-bit word */
91static inline void output_8(int n) {
92 if(putc(n, outputfp) < 0)
93 fatal(errno, "decoding %s: output error", path);
94}
95
f8f8039f
RK
96/** @brief Write a 16-bit word in bigendian format */
97static inline void output_16(uint16_t n) {
98 if(putc(n >> 8, outputfp) < 0
75db8354 99 || putc(n, outputfp) < 0)
100 fatal(errno, "decoding %s: output error", path);
101}
102
103/** @brief Write a 24-bit word in bigendian format */
104static inline void output_24(uint32_t n) {
105 if(putc(n >> 16, outputfp) < 0
106 || putc(n >> 8, outputfp) < 0
107 || putc(n, outputfp) < 0)
f8f8039f
RK
108 fatal(errno, "decoding %s: output error", path);
109}
110
75db8354 111/** @brief Write a 32-bit word in bigendian format */
112static inline void output_32(uint32_t n) {
113 if(putc(n >> 24, outputfp) < 0
114 || putc(n >> 16, outputfp) < 0
115 || putc(n >> 8, outputfp) < 0
116 || putc(n, outputfp) < 0)
117 fatal(errno, "decoding %s: output error", path);
118}
119
120/** @brief Write a block header
121 * @param rate Sample rate in Hz
122 * @param channels Channel count (currently only 1 or 2 supported)
123 * @param bits Bits per sample (must be a multiple of 8, no more than 64)
124 * @param nbytes Total number of data bytes
125 * @param endian @ref ENDIAN_BIG or @ref ENDIAN_LITTLE
126 *
127 * Checks that the sample format is a supported one (so other calls do not have
128 * to) and calls fatal() on error.
f8f8039f
RK
129 */
130static void output_header(int rate,
131 int channels,
39492555 132 int bits,
ce6c36be 133 int nbytes,
134 int endian) {
39492555 135 struct stream_header header;
136
75db8354 137 if(bits <= 0 || bits % 8 || bits > 64)
138 fatal(0, "decoding %s: unsupported sample size %d bits", path, bits);
139 if(channels <= 0 || channels > 2)
140 fatal(0, "decoding %s: unsupported channel count %d", path, channels);
141 if(rate <= 0)
142 fatal(0, "decoding %s: nonsensical sample rate %dHz", path, rate);
39492555 143 header.rate = rate;
144 header.bits = bits;
145 header.channels = channels;
ce6c36be 146 header.endian = endian;
39492555 147 header.nbytes = nbytes;
148 if(fwrite(&header, sizeof header, 1, outputfp) < 1)
149 fatal(errno, "decoding %s: writing format header", path);
f8f8039f
RK
150}
151
152/** @brief Dithering state
153 * Filched from mpg321, which credits it to Robert Leslie */
154struct audio_dither {
155 mad_fixed_t error[3];
156 mad_fixed_t random;
157};
158
159/** @brief 32-bit PRNG
160 * Filched from mpg321, which credits it to Robert Leslie */
161static inline unsigned long prng(unsigned long state)
162{
163 return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
164}
165
166/** @brief Generic linear sample quantize and dither routine
167 * Filched from mpg321, which credits it to Robert Leslie */
168#define bits 16
169static long audio_linear_dither(mad_fixed_t sample,
170 struct audio_dither *dither) {
171 unsigned int scalebits;
172 mad_fixed_t output, mask, rnd;
173
174 enum {
175 MIN = -MAD_F_ONE,
176 MAX = MAD_F_ONE - 1
177 };
178
179 /* noise shape */
180 sample += dither->error[0] - dither->error[1] + dither->error[2];
181
182 dither->error[2] = dither->error[1];
183 dither->error[1] = dither->error[0] / 2;
184
185 /* bias */
186 output = sample + (1L << (MAD_F_FRACBITS + 1 - bits - 1));
187
188 scalebits = MAD_F_FRACBITS + 1 - bits;
189 mask = (1L << scalebits) - 1;
190
191 /* dither */
192 rnd = prng(dither->random);
193 output += (rnd & mask) - (dither->random & mask);
194
195 dither->random = rnd;
196
197 /* clip */
198 if (output > MAX) {
199 output = MAX;
200
201 if (sample > MAX)
202 sample = MAX;
203 }
204 else if (output < MIN) {
205 output = MIN;
206
207 if (sample < MIN)
208 sample = MIN;
209 }
210
211 /* quantize */
212 output &= ~mask;
213
214 /* error feedback */
215 dither->error[0] = sample - output;
216
217 /* scale */
218 return output >> scalebits;
219}
220#undef bits
221
222/** @brief MP3 output callback */
223static enum mad_flow mp3_output(void attribute((unused)) *data,
224 struct mad_header const *header,
225 struct mad_pcm *pcm) {
226 size_t n = pcm->length;
227 const mad_fixed_t *l = pcm->samples[0], *r = pcm->samples[1];
228 static struct audio_dither ld[1], rd[1];
229
230 output_header(header->samplerate,
231 pcm->channels,
39492555 232 16,
ce6c36be 233 2 * pcm->channels * pcm->length,
234 ENDIAN_BIG);
f8f8039f
RK
235 switch(pcm->channels) {
236 case 1:
237 while(n--)
238 output_16(audio_linear_dither(*l++, ld));
239 break;
240 case 2:
241 while(n--) {
242 output_16(audio_linear_dither(*l++, ld));
243 output_16(audio_linear_dither(*r++, rd));
244 }
245 break;
f8f8039f
RK
246 }
247 return MAD_FLOW_CONTINUE;
248}
249
250/** @brief MP3 input callback */
251static enum mad_flow mp3_input(void attribute((unused)) *data,
252 struct mad_stream *stream) {
253 const size_t n = fill();
572c2899 254
f8f8039f
RK
255 if(!n)
256 return MAD_FLOW_STOP;
75db8354 257 mad_stream_buffer(stream, (unsigned char *)input_buffer, n);
f8f8039f
RK
258 return MAD_FLOW_CONTINUE;
259}
260
261
262/** @brief MP3 error callback */
263static enum mad_flow mp3_error(void attribute((unused)) *data,
264 struct mad_stream *stream,
265 struct mad_frame attribute((unused)) *frame) {
39492555 266 if(0)
267 /* Just generates pointless verbosity l-( */
268 error(0, "decoding %s: %s (%#04x)",
269 path, mad_stream_errorstr(stream), stream->error);
f8f8039f
RK
270 return MAD_FLOW_CONTINUE;
271}
272
273/** @brief MP3 decoder */
274static void decode_mp3(void) {
275 struct mad_decoder mad[1];
276
277 open_input();
39492555 278 mad_decoder_init(mad, 0/*data*/, mp3_input, 0/*header*/, 0/*filter*/,
f8f8039f
RK
279 mp3_output, mp3_error, 0/*message*/);
280 if(mad_decoder_run(mad, MAD_DECODER_MODE_SYNC))
281 exit(1);
282 mad_decoder_finish(mad);
283}
284
572c2899 285/** @brief OGG decoder */
286static void decode_ogg(void) {
287 FILE *fp;
288 OggVorbis_File vf[1];
289 int err;
290 long n;
291 int bitstream;
292 vorbis_info *vi;
293
294 if(!(fp = fopen(path, "rb")))
295 fatal(errno, "cannot open %s", path);
296 /* There doesn't seem to be any standard function for mapping the error codes
297 * to strings l-( */
298 if((err = ov_open(fp, vf, 0/*initial*/, 0/*ibytes*/)))
299 fatal(0, "ov_fopen %s: %d", path, err);
300 if(!(vi = ov_info(vf, 0/*link*/)))
301 fatal(0, "ov_info %s: failed", path);
75db8354 302 while((n = ov_read(vf, input_buffer, sizeof input_buffer, 1/*bigendianp*/,
572c2899 303 2/*bytes/word*/, 1/*signed*/, &bitstream))) {
304 if(n < 0)
305 fatal(0, "ov_read %s: %ld", path, n);
306 if(bitstream > 0)
307 fatal(0, "only single-bitstream ogg files are supported");
ce6c36be 308 output_header(vi->rate, vi->channels, 16/*bits*/, n, ENDIAN_BIG);
75db8354 309 if(fwrite(input_buffer, 1, n, outputfp) < (size_t)n)
572c2899 310 fatal(errno, "decoding %s: writing sample data", path);
311 }
312}
313
ce6c36be 314/** @brief Sample data callback used by decode_wav() */
315static int wav_write(struct wavfile attribute((unused)) *f,
316 const char *data,
317 size_t nbytes,
318 void attribute((unused)) *u) {
319 if(fwrite(data, 1, nbytes, outputfp) < nbytes)
320 fatal(errno, "decoding %s: writing sample data", path);
321 return 0;
322}
323
324/** @brief WAV file decoder */
325static void decode_wav(void) {
326 struct wavfile f[1];
327 int err;
328
329 if((err = wav_init(f, path)))
330 fatal(err, "opening %s", path);
ce6c36be 331 output_header(f->rate, f->channels, f->bits, f->datasize, ENDIAN_LITTLE);
332 if((err = wav_data(f, wav_write, 0)))
333 fatal(err, "error decoding %s", path);
334}
335
75db8354 336/** @brief Metadata callback for FLAC decoder
337 *
338 * This is a no-op here.
339 */
340static void flac_metadata(const FLAC__FileDecoder attribute((unused)) *decoder,
341 const FLAC__StreamMetadata attribute((unused)) *metadata,
342 void attribute((unused)) *client_data) {
343}
344
345/** @brief Error callback for FLAC decoder */
346static void flac_error(const FLAC__FileDecoder attribute((unused)) *decoder,
347 FLAC__StreamDecoderErrorStatus status,
348 void attribute((unused)) *client_data) {
349 fatal(0, "error decoding %s: %s", path,
350 FLAC__StreamDecoderErrorStatusString[status]);
351}
352
353/** @brief Write callback for FLAC decoder */
354static FLAC__StreamDecoderWriteStatus flac_write
355 (const FLAC__FileDecoder attribute((unused)) *decoder,
356 const FLAC__Frame *frame,
357 const FLAC__int32 *const buffer[],
358 void attribute((unused)) *client_data) {
359 size_t n, c;
360
361 output_header(frame->header.sample_rate,
362 frame->header.channels,
363 frame->header.bits_per_sample,
364 (frame->header.channels * frame->header.blocksize
365 * frame->header.bits_per_sample) / 8,
366 ENDIAN_BIG);
367 for(n = 0; n < frame->header.blocksize; ++n) {
368 for(c = 0; c < frame->header.channels; ++c) {
369 switch(frame->header.bits_per_sample) {
370 case 8: output_8(buffer[c][n]); break;
371 case 16: output_16(buffer[c][n]); break;
372 case 24: output_24(buffer[c][n]); break;
373 case 32: output_32(buffer[c][n]); break;
374 }
375 }
376 }
377 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
378}
379
380
381/** @brief FLAC file decoder */
382static void decode_flac(void) {
762806f1 383#if HAVE_FLAC_FILE_DECODER_H
75db8354 384 FLAC__FileDecoder *fd = 0;
385 FLAC__FileDecoderState fs;
386
387 if(!(fd = FLAC__file_decoder_new()))
388 fatal(0, "FLAC__file_decoder_new failed");
389 if(!(FLAC__file_decoder_set_filename(fd, path)))
390 fatal(0, "FLAC__file_set_filename failed");
391 FLAC__file_decoder_set_metadata_callback(fd, flac_metadata);
392 FLAC__file_decoder_set_error_callback(fd, flac_error);
393 FLAC__file_decoder_set_write_callback(fd, flac_write);
394 if((fs = FLAC__file_decoder_init(fd)))
395 fatal(0, "FLAC__file_decoder_init: %s", FLAC__FileDecoderStateString[fs]);
396 FLAC__file_decoder_process_until_end_of_file(fd);
762806f1
RK
397#else
398 FLAC__StreamDecoder *sd = 0;
399 FLAC__StreamDecoderInitStatus is;
400
401 if((is = FLAC__stream_decoder_init_file(sd, path, flac_write, flac_metadata,
402 flac_error, 0)))
403 fatal(0, "FLAC__stream_decoder_init_file %s: %s",
404 path, FLAC__StreamDecoderInitStatusString[is]);
405#endif
75db8354 406}
407
f8f8039f
RK
408/** @brief Lookup table of decoders */
409static const struct decoder decoders[] = {
410 { "*.mp3", decode_mp3 },
411 { "*.MP3", decode_mp3 },
572c2899 412 { "*.ogg", decode_ogg },
413 { "*.OGG", decode_ogg },
75db8354 414 { "*.flac", decode_flac },
415 { "*.FLAC", decode_flac },
ce6c36be 416 { "*.wav", decode_wav },
417 { "*.WAV", decode_wav },
f8f8039f
RK
418 { 0, 0 }
419};
420
421static const struct option options[] = {
422 { "help", no_argument, 0, 'h' },
423 { "version", no_argument, 0, 'V' },
424 { 0, 0, 0, 0 }
425};
426
427/* Display usage message and terminate. */
428static void help(void) {
429 xprintf("Usage:\n"
430 " disorder-decode [OPTIONS] PATH\n"
431 "Options:\n"
432 " --help, -h Display usage message\n"
433 " --version, -V Display version number\n"
434 "\n"
435 "Audio decoder for DisOrder. Only intended to be used by speaker\n"
436 "process, not for normal users.\n");
437 xfclose(stdout);
438 exit(0);
439}
440
441/* Display version number and terminate. */
442static void version(void) {
443 xprintf("disorder-decode version %s\n", disorder_version_string);
444 xfclose(stdout);
445 exit(0);
446}
447
448int main(int argc, char **argv) {
449 int n;
450 const char *e;
451
452 set_progname(argv);
453 if(!setlocale(LC_CTYPE, "")) fatal(errno, "calling setlocale");
454 while((n = getopt_long(argc, argv, "hV", options, 0)) >= 0) {
455 switch(n) {
456 case 'h': help();
457 case 'V': version();
458 default: fatal(0, "invalid option");
459 }
460 }
461 if(optind >= argc)
462 fatal(0, "missing filename");
463 if(optind + 1 < argc)
464 fatal(0, "excess arguments");
465 if((e = getenv("DISORDER_RAW_FD"))) {
466 if(!(outputfp = fdopen(atoi(e), "wb")))
467 fatal(errno, "fdopen");
468 } else
469 outputfp = stdout;
470 path = argv[optind];
471 for(n = 0;
472 decoders[n].pattern
473 && fnmatch(decoders[n].pattern, path, 0) != 0;
474 ++n)
475 ;
476 if(!decoders[n].pattern)
477 fatal(0, "cannot determine file type for %s", path);
478 decoders[n].decode();
479 xfclose(outputfp);
480 return 0;
481}
482
483/*
484Local Variables:
485c-basic-offset:2
486comment-column:40
487fill-column:79
488indent-tabs-mode:nil
489End:
490*/