chiark / gitweb /
Merge playlist support.
[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"
f8f8039f 23
f8f8039f 24#include <mad.h>
572c2899 25#include <vorbis/vorbisfile.h>
762806f1
RK
26
27/* libFLAC has had an API change and stupidly taken away the old API */
28#if HAVE_FLAC_FILE_DECODER_H
29# include <FLAC/file_decoder.h>
30#else
31# include <FLAC/stream_decoder.h>
32#define FLAC__FileDecoder FLAC__StreamDecoder
33#define FLAC__FileDecoderState FLAC__StreamDecoderState
34#endif
f8f8039f 35
ce6c36be 36#include "wav.h"
39492555 37#include "speaker-protocol.h"
f8f8039f 38
e7eb3a27 39
f8f8039f
RK
40/** @brief Encoding lookup table type */
41struct decoder {
42 /** @brief Glob pattern matching file */
43 const char *pattern;
44 /** @brief Decoder function */
45 void (*decode)(void);
46};
47
48/** @brief Input file */
49static int inputfd;
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)
66 fatal(errno, "decoding %s: output error", path);
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)
73 fatal(errno, "decoding %s: output error", path);
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)
f8f8039f
RK
81 fatal(errno, "decoding %s: output error", path);
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)
90 fatal(errno, "decoding %s: output error", path);
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
101 * to) and calls 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)
111 fatal(0, "decoding %s: unsupported sample size %d bits", path, bits);
112 if(channels <= 0 || channels > 2)
113 fatal(0, "decoding %s: unsupported channel count %d", path, channels);
114 if(rate <= 0)
115 fatal(0, "decoding %s: nonsensical sample rate %dHz", path, rate);
39492555 116 header.rate = rate;
117 header.bits = bits;
118 header.channels = channels;
ce6c36be 119 header.endian = endian;
39492555 120 header.nbytes = nbytes;
121 if(fwrite(&header, sizeof header, 1, outputfp) < 1)
122 fatal(errno, "decoding %s: writing format header", path);
f8f8039f
RK
123}
124
125/** @brief Dithering state
126 * Filched from mpg321, which credits it to Robert Leslie */
127struct audio_dither {
128 mad_fixed_t error[3];
129 mad_fixed_t random;
130};
131
132/** @brief 32-bit PRNG
133 * Filched from mpg321, which credits it to Robert Leslie */
134static inline unsigned long prng(unsigned long state)
135{
136 return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
137}
138
139/** @brief Generic linear sample quantize and dither routine
140 * Filched from mpg321, which credits it to Robert Leslie */
f8f8039f
RK
141static long audio_linear_dither(mad_fixed_t sample,
142 struct audio_dither *dither) {
143 unsigned int scalebits;
144 mad_fixed_t output, mask, rnd;
87b5259b 145 const int bits = 16;
f8f8039f
RK
146
147 enum {
148 MIN = -MAD_F_ONE,
149 MAX = MAD_F_ONE - 1
150 };
151
152 /* noise shape */
153 sample += dither->error[0] - dither->error[1] + dither->error[2];
154
155 dither->error[2] = dither->error[1];
156 dither->error[1] = dither->error[0] / 2;
157
158 /* bias */
159 output = sample + (1L << (MAD_F_FRACBITS + 1 - bits - 1));
160
161 scalebits = MAD_F_FRACBITS + 1 - bits;
162 mask = (1L << scalebits) - 1;
163
164 /* dither */
165 rnd = prng(dither->random);
166 output += (rnd & mask) - (dither->random & mask);
167
168 dither->random = rnd;
169
170 /* clip */
171 if (output > MAX) {
172 output = MAX;
173
174 if (sample > MAX)
175 sample = MAX;
176 }
177 else if (output < MIN) {
178 output = MIN;
179
180 if (sample < MIN)
181 sample = MIN;
182 }
183
184 /* quantize */
185 output &= ~mask;
186
187 /* error feedback */
188 dither->error[0] = sample - output;
189
190 /* scale */
191 return output >> scalebits;
192}
f8f8039f
RK
193
194/** @brief MP3 output callback */
195static enum mad_flow mp3_output(void attribute((unused)) *data,
196 struct mad_header const *header,
197 struct mad_pcm *pcm) {
198 size_t n = pcm->length;
199 const mad_fixed_t *l = pcm->samples[0], *r = pcm->samples[1];
200 static struct audio_dither ld[1], rd[1];
201
202 output_header(header->samplerate,
203 pcm->channels,
39492555 204 16,
ce6c36be 205 2 * pcm->channels * pcm->length,
206 ENDIAN_BIG);
f8f8039f
RK
207 switch(pcm->channels) {
208 case 1:
209 while(n--)
210 output_16(audio_linear_dither(*l++, ld));
211 break;
212 case 2:
213 while(n--) {
214 output_16(audio_linear_dither(*l++, ld));
215 output_16(audio_linear_dither(*r++, rd));
216 }
217 break;
f8f8039f
RK
218 }
219 return MAD_FLOW_CONTINUE;
220}
221
222/** @brief MP3 input callback */
223static enum mad_flow mp3_input(void attribute((unused)) *data,
224 struct mad_stream *stream) {
87b5259b 225 int used, remain, n;
226
227 /* libmad requires its caller to do ALL the buffering work, including coping
228 * with partial frames. Given that it appears to be completely undocumented
229 * you could perhaps be forgiven for not discovering this... */
230 if(input_count) {
231 /* Compute total number of bytes consumed */
232 used = (char *)stream->next_frame - input_buffer;
233 /* Compute number of bytes left to consume */
234 remain = input_count - used;
235 memmove(input_buffer, input_buffer + used, remain);
236 } else {
237 remain = 0;
238 }
239 /* Read new data */
240 n = read(inputfd, input_buffer + remain, (sizeof input_buffer) - remain);
241 if(n < 0)
242 fatal(errno, "reading from %s", path);
243 /* Compute total number of bytes available */
244 input_count = remain + n;
245 if(input_count)
246 mad_stream_buffer(stream, (unsigned char *)input_buffer, input_count);
247 if(n)
248 return MAD_FLOW_CONTINUE;
249 else
f8f8039f 250 return MAD_FLOW_STOP;
f8f8039f
RK
251}
252
f8f8039f
RK
253/** @brief MP3 error callback */
254static enum mad_flow mp3_error(void attribute((unused)) *data,
255 struct mad_stream *stream,
256 struct mad_frame attribute((unused)) *frame) {
39492555 257 if(0)
258 /* Just generates pointless verbosity l-( */
259 error(0, "decoding %s: %s (%#04x)",
260 path, mad_stream_errorstr(stream), stream->error);
f8f8039f
RK
261 return MAD_FLOW_CONTINUE;
262}
263
264/** @brief MP3 decoder */
265static void decode_mp3(void) {
266 struct mad_decoder mad[1];
267
87b5259b 268 if((inputfd = open(path, O_RDONLY)) < 0)
269 fatal(errno, "opening %s", path);
39492555 270 mad_decoder_init(mad, 0/*data*/, mp3_input, 0/*header*/, 0/*filter*/,
f8f8039f
RK
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
572c2899 277/** @brief OGG decoder */
278static 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);
75db8354 294 while((n = ov_read(vf, input_buffer, sizeof input_buffer, 1/*bigendianp*/,
572c2899 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");
ce6c36be 300 output_header(vi->rate, vi->channels, 16/*bits*/, n, ENDIAN_BIG);
75db8354 301 if(fwrite(input_buffer, 1, n, outputfp) < (size_t)n)
572c2899 302 fatal(errno, "decoding %s: writing sample data", path);
303 }
304}
305
ce6c36be 306/** @brief Sample data callback used by decode_wav() */
307static 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 */
317static 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);
ce6c36be 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
75db8354 328/** @brief Metadata callback for FLAC decoder
329 *
330 * This is a no-op here.
331 */
332static 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 */
338static 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 */
346static 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 */
374static void decode_flac(void) {
762806f1 375#if HAVE_FLAC_FILE_DECODER_H
75db8354 376 FLAC__FileDecoder *fd = 0;
377 FLAC__FileDecoderState fs;
378
379 if(!(fd = FLAC__file_decoder_new()))
380 fatal(0, "FLAC__file_decoder_new failed");
381 if(!(FLAC__file_decoder_set_filename(fd, path)))
382 fatal(0, "FLAC__file_set_filename failed");
383 FLAC__file_decoder_set_metadata_callback(fd, flac_metadata);
384 FLAC__file_decoder_set_error_callback(fd, flac_error);
385 FLAC__file_decoder_set_write_callback(fd, flac_write);
386 if((fs = FLAC__file_decoder_init(fd)))
387 fatal(0, "FLAC__file_decoder_init: %s", FLAC__FileDecoderStateString[fs]);
388 FLAC__file_decoder_process_until_end_of_file(fd);
762806f1 389#else
05af10e9 390 FLAC__StreamDecoder *sd = FLAC__stream_decoder_new();
762806f1
RK
391 FLAC__StreamDecoderInitStatus is;
392
05af10e9
RK
393 if (!sd)
394 fatal(0, "FLAC__stream_decoder_new failed");
395
762806f1
RK
396 if((is = FLAC__stream_decoder_init_file(sd, path, flac_write, flac_metadata,
397 flac_error, 0)))
398 fatal(0, "FLAC__stream_decoder_init_file %s: %s",
399 path, FLAC__StreamDecoderInitStatusString[is]);
05af10e9
RK
400
401 FLAC__stream_decoder_process_until_end_of_stream(sd);
402 FLAC__stream_decoder_finish(sd);
403 FLAC__stream_decoder_delete(sd);
762806f1 404#endif
75db8354 405}
406
f8f8039f
RK
407/** @brief Lookup table of decoders */
408static const struct decoder decoders[] = {
409 { "*.mp3", decode_mp3 },
410 { "*.MP3", decode_mp3 },
572c2899 411 { "*.ogg", decode_ogg },
412 { "*.OGG", decode_ogg },
75db8354 413 { "*.flac", decode_flac },
414 { "*.FLAC", decode_flac },
ce6c36be 415 { "*.wav", decode_wav },
416 { "*.WAV", decode_wav },
f8f8039f
RK
417 { 0, 0 }
418};
419
420static const struct option options[] = {
421 { "help", no_argument, 0, 'h' },
422 { "version", no_argument, 0, 'V' },
423 { 0, 0, 0, 0 }
424};
425
426/* Display usage message and terminate. */
427static void help(void) {
428 xprintf("Usage:\n"
429 " disorder-decode [OPTIONS] PATH\n"
430 "Options:\n"
431 " --help, -h Display usage message\n"
432 " --version, -V Display version number\n"
433 "\n"
434 "Audio decoder for DisOrder. Only intended to be used by speaker\n"
435 "process, not for normal users.\n");
436 xfclose(stdout);
437 exit(0);
438}
439
f8f8039f
RK
440int main(int argc, char **argv) {
441 int n;
442 const char *e;
443
444 set_progname(argv);
445 if(!setlocale(LC_CTYPE, "")) fatal(errno, "calling setlocale");
446 while((n = getopt_long(argc, argv, "hV", options, 0)) >= 0) {
447 switch(n) {
448 case 'h': help();
3fbdc96d 449 case 'V': version("disorder-decode");
f8f8039f
RK
450 default: fatal(0, "invalid option");
451 }
452 }
453 if(optind >= argc)
454 fatal(0, "missing filename");
455 if(optind + 1 < argc)
456 fatal(0, "excess arguments");
457 if((e = getenv("DISORDER_RAW_FD"))) {
458 if(!(outputfp = fdopen(atoi(e), "wb")))
459 fatal(errno, "fdopen");
460 } else
461 outputfp = stdout;
462 path = argv[optind];
463 for(n = 0;
464 decoders[n].pattern
465 && fnmatch(decoders[n].pattern, path, 0) != 0;
466 ++n)
467 ;
468 if(!decoders[n].pattern)
469 fatal(0, "cannot determine file type for %s", path);
470 decoders[n].decode();
471 xfclose(outputfp);
472 return 0;
473}
474
475/*
476Local Variables:
477c-basic-offset:2
478comment-column:40
479fill-column:79
480indent-tabs-mode:nil
481End:
482*/