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