finish off FLAC support
[disorder] / server / decode.c
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>
36 #include <vorbis/vorbisfile.h>
37 #include <FLAC/file_decoder.h>
38
39 #include "log.h"
40 #include "syscalls.h"
41 #include "defs.h"
42 #include "wav.h"
43 #include "speaker-protocol.h"
44
45 /** @brief Encoding lookup table type */
46 struct decoder {
47 /** @brief Glob pattern matching file */
48 const char *pattern;
49 /** @brief Decoder function */
50 void (*decode)(void);
51 };
52
53 /** @brief Input file */
54 static int inputfd;
55
56 /** @brief Output file */
57 static FILE *outputfp;
58
59 /** @brief Filename */
60 static const char *path;
61
62 /** @brief Input buffer */
63 static char input_buffer[1048576];
64
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);
69 }
70
71 /** @brief Fill the buffer
72 * @return Number of bytes read
73 */
74 static size_t fill(void) {
75 int n = read(inputfd, input_buffer, sizeof input_buffer);
76
77 if(n < 0)
78 fatal(errno, "reading from %s", path);
79 return n;
80 }
81
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);
86 }
87
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);
93 }
94
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);
101 }
102
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);
110 }
111
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
118 *
119 * Checks that the sample format is a supported one (so other calls do not have
120 * to) and calls fatal() on error.
121 */
122 static void output_header(int rate,
123 int channels,
124 int bits,
125 int nbytes,
126 int endian) {
127 struct stream_header header;
128
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);
133 if(rate <= 0)
134 fatal(0, "decoding %s: nonsensical sample rate %dHz", path, rate);
135 header.rate = rate;
136 header.bits = bits;
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);
142 }
143
144 /** @brief Dithering state
145 * Filched from mpg321, which credits it to Robert Leslie */
146 struct audio_dither {
147 mad_fixed_t error[3];
148 mad_fixed_t random;
149 };
150
151 /** @brief 32-bit PRNG
152 * Filched from mpg321, which credits it to Robert Leslie */
153 static inline unsigned long prng(unsigned long state)
154 {
155 return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
156 }
157
158 /** @brief Generic linear sample quantize and dither routine
159 * Filched from mpg321, which credits it to Robert Leslie */
160 #define bits 16
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;
165
166 enum {
167 MIN = -MAD_F_ONE,
168 MAX = MAD_F_ONE - 1
169 };
170
171 /* noise shape */
172 sample += dither->error[0] - dither->error[1] + dither->error[2];
173
174 dither->error[2] = dither->error[1];
175 dither->error[1] = dither->error[0] / 2;
176
177 /* bias */
178 output = sample + (1L << (MAD_F_FRACBITS + 1 - bits - 1));
179
180 scalebits = MAD_F_FRACBITS + 1 - bits;
181 mask = (1L << scalebits) - 1;
182
183 /* dither */
184 rnd = prng(dither->random);
185 output += (rnd & mask) - (dither->random & mask);
186
187 dither->random = rnd;
188
189 /* clip */
190 if (output > MAX) {
191 output = MAX;
192
193 if (sample > MAX)
194 sample = MAX;
195 }
196 else if (output < MIN) {
197 output = MIN;
198
199 if (sample < MIN)
200 sample = MIN;
201 }
202
203 /* quantize */
204 output &= ~mask;
205
206 /* error feedback */
207 dither->error[0] = sample - output;
208
209 /* scale */
210 return output >> scalebits;
211 }
212 #undef bits
213
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];
221
222 output_header(header->samplerate,
223 pcm->channels,
224 16,
225 2 * pcm->channels * pcm->length,
226 ENDIAN_BIG);
227 switch(pcm->channels) {
228 case 1:
229 while(n--)
230 output_16(audio_linear_dither(*l++, ld));
231 break;
232 case 2:
233 while(n--) {
234 output_16(audio_linear_dither(*l++, ld));
235 output_16(audio_linear_dither(*r++, rd));
236 }
237 break;
238 }
239 return MAD_FLOW_CONTINUE;
240 }
241
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();
246
247 if(!n)
248 return MAD_FLOW_STOP;
249 mad_stream_buffer(stream, (unsigned char *)input_buffer, n);
250 return MAD_FLOW_CONTINUE;
251 }
252
253
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) {
258 if(0)
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;
263 }
264
265 /** @brief MP3 decoder */
266 static void decode_mp3(void) {
267 struct mad_decoder mad[1];
268
269 open_input();
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))
273 exit(1);
274 mad_decoder_finish(mad);
275 }
276
277 /** @brief OGG decoder */
278 static void decode_ogg(void) {
279 FILE *fp;
280 OggVorbis_File vf[1];
281 int err;
282 long n;
283 int bitstream;
284 vorbis_info *vi;
285
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
289 * to strings l-( */
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))) {
296 if(n < 0)
297 fatal(0, "ov_read %s: %ld", path, n);
298 if(bitstream > 0)
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);
303 }
304 }
305
306 /** @brief Sample data callback used by decode_wav() */
307 static int wav_write(struct wavfile attribute((unused)) *f,
308 const char *data,
309 size_t nbytes,
310 void attribute((unused)) *u) {
311 if(fwrite(data, 1, nbytes, outputfp) < nbytes)
312 fatal(errno, "decoding %s: writing sample data", path);
313 return 0;
314 }
315
316 /** @brief WAV file decoder */
317 static void decode_wav(void) {
318 struct wavfile f[1];
319 int err;
320
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);
326 }
327
328 /** @brief Metadata callback for FLAC decoder
329 *
330 * This is a no-op here.
331 */
332 static void flac_metadata(const FLAC__FileDecoder attribute((unused)) *decoder,
333 const FLAC__StreamMetadata attribute((unused)) *metadata,
334 void attribute((unused)) *client_data) {
335 }
336
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]);
343 }
344
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) {
351 size_t n, c;
352
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,
358 ENDIAN_BIG);
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;
366 }
367 }
368 }
369 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
370 }
371
372
373 /** @brief FLAC file decoder */
374 static void decode_flac(void) {
375 FLAC__FileDecoder *fd = 0;
376 FLAC__FileDecoderState fs;
377
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);
388 }
389
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 },
400 { 0, 0 }
401 };
402
403 static const struct option options[] = {
404 { "help", no_argument, 0, 'h' },
405 { "version", no_argument, 0, 'V' },
406 { 0, 0, 0, 0 }
407 };
408
409 /* Display usage message and terminate. */
410 static void help(void) {
411 xprintf("Usage:\n"
412 " disorder-decode [OPTIONS] PATH\n"
413 "Options:\n"
414 " --help, -h Display usage message\n"
415 " --version, -V Display version number\n"
416 "\n"
417 "Audio decoder for DisOrder. Only intended to be used by speaker\n"
418 "process, not for normal users.\n");
419 xfclose(stdout);
420 exit(0);
421 }
422
423 /* Display version number and terminate. */
424 static void version(void) {
425 xprintf("disorder-decode version %s\n", disorder_version_string);
426 xfclose(stdout);
427 exit(0);
428 }
429
430 int main(int argc, char **argv) {
431 int n;
432 const char *e;
433
434 set_progname(argv);
435 if(!setlocale(LC_CTYPE, "")) fatal(errno, "calling setlocale");
436 while((n = getopt_long(argc, argv, "hV", options, 0)) >= 0) {
437 switch(n) {
438 case 'h': help();
439 case 'V': version();
440 default: fatal(0, "invalid option");
441 }
442 }
443 if(optind >= argc)
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");
450 } else
451 outputfp = stdout;
452 path = argv[optind];
453 for(n = 0;
454 decoders[n].pattern
455 && fnmatch(decoders[n].pattern, path, 0) != 0;
456 ++n)
457 ;
458 if(!decoders[n].pattern)
459 fatal(0, "cannot determine file type for %s", path);
460 decoders[n].decode();
461 xfclose(outputfp);
462 return 0;
463 }
464
465 /*
466 Local Variables:
467 c-basic-offset:2
468 comment-column:40
469 fill-column:79
470 indent-tabs-mode:nil
471 End:
472 */