chiark / gitweb /
Missing gcry_md_close.
[disorder] / server / decode.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2007-2009 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 3 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,
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  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file server/decode.c
19  * @brief General-purpose decoder for use by speaker process
20  */
21
22 #include "disorder-server.h"
23
24 #include <mad.h>
25 #include <vorbis/vorbisfile.h>
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
35
36 #include "wav.h"
37 #include "speaker-protocol.h"
38
39
40 /** @brief Encoding lookup table type */
41 struct 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 */
49 static int inputfd;
50
51 /** @brief Output file */
52 static FILE *outputfp;
53
54 /** @brief Filename */
55 static const char *path;
56
57 /** @brief Input buffer */
58 static char input_buffer[1048576];
59
60 /** @brief Number of bytes read into buffer */
61 static int input_count;
62
63 /** @brief Write an 8-bit word */
64 static inline void output_8(int n) {
65   if(putc(n, outputfp) < 0)
66     disorder_fatal(errno, "decoding %s: output error", path);
67 }
68
69 /** @brief Write a 16-bit word in bigendian format */
70 static inline void output_16(uint16_t n) {
71   if(putc(n >> 8, outputfp) < 0
72      || putc(n, outputfp) < 0)
73     disorder_fatal(errno, "decoding %s: output error", path);
74 }
75
76 /** @brief Write a 24-bit word in bigendian format */
77 static 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)
81     disorder_fatal(errno, "decoding %s: output error", path);
82 }
83
84 /** @brief Write a 32-bit word in bigendian format */
85 static 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     disorder_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 disorder_fatal() on error.
102  */
103 static void output_header(int rate,
104                           int channels,
105                           int bits,
106                           int nbytes,
107                           int endian) {
108   struct stream_header header;
109
110   if(bits <= 0 || bits % 8 || bits > 64)
111     disorder_fatal(0, "decoding %s: unsupported sample size %d bits",
112                    path, bits);
113   if(channels <= 0 || channels > 2)
114     disorder_fatal(0, "decoding %s: unsupported channel count %d",
115                    path, channels);
116   if(rate <= 0)
117     disorder_fatal(0, "decoding %s: nonsensical sample rate %dHz", path, rate);
118   header.rate = rate;
119   header.bits = bits;
120   header.channels = channels;
121   header.endian = endian;
122   header.nbytes = nbytes;
123   if(fwrite(&header, sizeof header, 1, outputfp) < 1)
124     disorder_fatal(errno, "decoding %s: writing format header", path);
125 }
126
127 /** @brief Dithering state
128  * Filched from mpg321, which credits it to Robert Leslie */
129 struct 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 */
136 static 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 */
143 static long audio_linear_dither(mad_fixed_t sample,
144                                 struct audio_dither *dither) {
145   unsigned int scalebits;
146   mad_fixed_t output, mask, rnd;
147   const int bits = 16;
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 }
195
196 /** @brief MP3 output callback */
197 static 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,
206                 16,
207                 2 * pcm->channels * pcm->length,
208                 ENDIAN_BIG);
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;
220   }
221   return MAD_FLOW_CONTINUE;
222 }
223
224 /** @brief MP3 input callback */
225 static enum mad_flow mp3_input(void attribute((unused)) *data,
226                                struct mad_stream *stream) {
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 */
242   n = read(inputfd, input_buffer + remain, (sizeof input_buffer) - remain);
243   if(n < 0)
244     disorder_fatal(errno, "reading from %s", path);
245   /* Compute total number of bytes available */
246   input_count = remain + n;
247   if(input_count)
248     mad_stream_buffer(stream, (unsigned char *)input_buffer, input_count);
249   if(n)
250     return MAD_FLOW_CONTINUE;
251   else
252     return MAD_FLOW_STOP;
253 }
254
255 /** @brief MP3 error callback */
256 static enum mad_flow mp3_error(void attribute((unused)) *data,
257                                struct mad_stream *stream,
258                                struct mad_frame attribute((unused)) *frame) {
259   if(0)
260     /* Just generates pointless verbosity l-( */
261     disorder_error(0, "decoding %s: %s (%#04x)",
262                    path, mad_stream_errorstr(stream), stream->error);
263   return MAD_FLOW_CONTINUE;
264 }
265
266 /** @brief MP3 decoder */
267 static void decode_mp3(void) {
268   struct mad_decoder mad[1];
269
270   if((inputfd = open(path, O_RDONLY)) < 0)
271     disorder_fatal(errno, "opening %s", path);
272   mad_decoder_init(mad, 0/*data*/, mp3_input, 0/*header*/, 0/*filter*/,
273                    mp3_output, mp3_error, 0/*message*/);
274   if(mad_decoder_run(mad, MAD_DECODER_MODE_SYNC))
275     exit(1);
276   mad_decoder_finish(mad);
277 }
278
279 /** @brief OGG decoder */
280 static void decode_ogg(void) {
281   FILE *fp;
282   OggVorbis_File vf[1];
283   int err;
284   long n;
285   int bitstream;
286   vorbis_info *vi;
287
288   if(!(fp = fopen(path, "rb")))
289     disorder_fatal(errno, "cannot open %s", path);
290   /* There doesn't seem to be any standard function for mapping the error codes
291    * to strings l-( */
292   if((err = ov_open(fp, vf, 0/*initial*/, 0/*ibytes*/)))
293     disorder_fatal(0, "ov_fopen %s: %d", path, err);
294   if(!(vi = ov_info(vf, 0/*link*/)))
295     disorder_fatal(0, "ov_info %s: failed", path);
296   while((n = ov_read(vf, input_buffer, sizeof input_buffer, 1/*bigendianp*/,
297                      2/*bytes/word*/, 1/*signed*/, &bitstream))) {
298     if(n < 0)
299       disorder_fatal(0, "ov_read %s: %ld", path, n);
300     if(bitstream > 0)
301       disorder_fatal(0, "only single-bitstream ogg files are supported");
302     output_header(vi->rate, vi->channels, 16/*bits*/, n, ENDIAN_BIG);
303     if(fwrite(input_buffer, 1, n, outputfp) < (size_t)n)
304       disorder_fatal(errno, "decoding %s: writing sample data", path);
305   }
306 }
307
308 /** @brief Sample data callback used by decode_wav() */
309 static int wav_write(struct wavfile attribute((unused)) *f,
310                      const char *data,
311                      size_t nbytes,
312                      void attribute((unused)) *u) {
313   if(fwrite(data, 1, nbytes, outputfp) < nbytes)
314     disorder_fatal(errno, "decoding %s: writing sample data", path);
315   return 0;
316 }
317
318 /** @brief WAV file decoder */
319 static void decode_wav(void) {
320   struct wavfile f[1];
321   int err;
322
323   if((err = wav_init(f, path)))
324     disorder_fatal(err, "opening %s", path);
325   output_header(f->rate, f->channels, f->bits, f->datasize, ENDIAN_LITTLE);
326   if((err = wav_data(f, wav_write, 0)))
327     disorder_fatal(err, "error decoding %s", path);
328 }
329
330 /** @brief Metadata callback for FLAC decoder
331  *
332  * This is a no-op here.
333  */
334 static void flac_metadata(const FLAC__FileDecoder attribute((unused)) *decoder,
335                           const FLAC__StreamMetadata attribute((unused)) *metadata,
336                           void attribute((unused)) *client_data) {
337 }
338
339 /** @brief Error callback for FLAC decoder */
340 static void flac_error(const FLAC__FileDecoder attribute((unused)) *decoder,
341                        FLAC__StreamDecoderErrorStatus status,
342                        void attribute((unused)) *client_data) {
343   disorder_fatal(0, "error decoding %s: %s", path,
344                  FLAC__StreamDecoderErrorStatusString[status]);
345 }
346
347 /** @brief Write callback for FLAC decoder */
348 static FLAC__StreamDecoderWriteStatus flac_write
349     (const FLAC__FileDecoder attribute((unused)) *decoder,
350      const FLAC__Frame *frame,
351      const FLAC__int32 *const buffer[],
352      void attribute((unused)) *client_data) {
353   size_t n, c;
354
355   output_header(frame->header.sample_rate,
356                 frame->header.channels,
357                 frame->header.bits_per_sample,
358                 (frame->header.channels * frame->header.blocksize
359                  * frame->header.bits_per_sample) / 8,
360                 ENDIAN_BIG);
361   for(n = 0; n < frame->header.blocksize; ++n) {
362     for(c = 0; c < frame->header.channels; ++c) {
363       switch(frame->header.bits_per_sample) {
364       case 8: output_8(buffer[c][n]); break;
365       case 16: output_16(buffer[c][n]); break;
366       case 24: output_24(buffer[c][n]); break;
367       case 32: output_32(buffer[c][n]); break;
368       }
369     }
370   }
371   return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
372 }
373
374
375 /** @brief FLAC file decoder */
376 static void decode_flac(void) {
377 #if HAVE_FLAC_FILE_DECODER_H
378   FLAC__FileDecoder *fd = 0;
379   FLAC__FileDecoderState fs;
380
381   if(!(fd = FLAC__file_decoder_new()))
382     disorder_fatal(0, "FLAC__file_decoder_new failed");
383   if(!(FLAC__file_decoder_set_filename(fd, path)))
384     disorder_fatal(0, "FLAC__file_set_filename failed");
385   FLAC__file_decoder_set_metadata_callback(fd, flac_metadata);
386   FLAC__file_decoder_set_error_callback(fd, flac_error);
387   FLAC__file_decoder_set_write_callback(fd, flac_write);
388   if((fs = FLAC__file_decoder_init(fd)))
389     disorder_fatal(0, "FLAC__file_decoder_init: %s", FLAC__FileDecoderStateString[fs]);
390   FLAC__file_decoder_process_until_end_of_file(fd);
391 #else
392   FLAC__StreamDecoder *sd = FLAC__stream_decoder_new();
393   FLAC__StreamDecoderInitStatus is;
394
395   if (!sd)
396     disorder_fatal(0, "FLAC__stream_decoder_new failed");
397
398   if((is = FLAC__stream_decoder_init_file(sd, path, flac_write, flac_metadata,
399                                           flac_error, 0)))
400     disorder_fatal(0, "FLAC__stream_decoder_init_file %s: %s",
401                    path, FLAC__StreamDecoderInitStatusString[is]);
402
403   FLAC__stream_decoder_process_until_end_of_stream(sd);
404   FLAC__stream_decoder_finish(sd);
405   FLAC__stream_decoder_delete(sd);
406 #endif
407 }
408
409 /** @brief Lookup table of decoders */
410 static const struct decoder decoders[] = {
411   { "*.mp3", decode_mp3 },
412   { "*.MP3", decode_mp3 },
413   { "*.ogg", decode_ogg },
414   { "*.OGG", decode_ogg },
415   { "*.flac", decode_flac },
416   { "*.FLAC", decode_flac },
417   { "*.wav", decode_wav },
418   { "*.WAV", decode_wav },
419   { 0, 0 }
420 };
421
422 static const struct option options[] = {
423   { "help", no_argument, 0, 'h' },
424   { "version", no_argument, 0, 'V' },
425   { 0, 0, 0, 0 }
426 };
427
428 /* Display usage message and terminate. */
429 static void help(void) {
430   xprintf("Usage:\n"
431           "  disorder-decode [OPTIONS] PATH\n"
432           "Options:\n"
433           "  --help, -h              Display usage message\n"
434           "  --version, -V           Display version number\n"
435           "\n"
436           "Audio decoder for DisOrder.  Only intended to be used by speaker\n"
437           "process, not for normal users.\n");
438   xfclose(stdout);
439   exit(0);
440 }
441
442 int main(int argc, char **argv) {
443   int n;
444   const char *e;
445
446   set_progname(argv);
447   if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "calling setlocale");
448   while((n = getopt_long(argc, argv, "hV", options, 0)) >= 0) {
449     switch(n) {
450     case 'h': help();
451     case 'V': version("disorder-decode");
452     default: disorder_fatal(0, "invalid option");
453     }
454   }
455   if(optind >= argc)
456     disorder_fatal(0, "missing filename");
457   if(optind + 1 < argc)
458     disorder_fatal(0, "excess arguments");
459   if((e = getenv("DISORDER_RAW_FD"))) {
460     if(!(outputfp = fdopen(atoi(e), "wb")))
461       disorder_fatal(errno, "fdopen");
462   } else
463     outputfp = stdout;
464   path = argv[optind];
465   for(n = 0;
466       decoders[n].pattern
467         && fnmatch(decoders[n].pattern, path, 0) != 0;
468       ++n)
469     ;
470   if(!decoders[n].pattern)
471     disorder_fatal(0, "cannot determine file type for %s", path);
472   decoders[n].decode();
473   xfclose(outputfp);
474   return 0;
475 }
476
477 /*
478 Local Variables:
479 c-basic-offset:2
480 comment-column:40
481 fill-column:79
482 indent-tabs-mode:nil
483 End:
484 */