chiark / gitweb /
c63ca2020738290b86cdda7070fdb8aa2a1c46e9
[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
37 #include "log.h"
38 #include "syscalls.h"
39 #include "defs.h"
40 #include "speaker-protocol.h"
41
42 /** @brief Encoding lookup table type */
43 struct decoder {
44   /** @brief Glob pattern matching file */
45   const char *pattern;
46   /** @brief Decoder function */
47   void (*decode)(void);
48 };
49
50 /** @brief Input file */
51 static int inputfd;
52
53 /** @brief Output file */
54 static FILE *outputfp;
55
56 /** @brief Filename */
57 static const char *path;
58
59 /** @brief Input buffer */
60 static unsigned char buffer[1048576];
61
62 /** @brief Open the input file */
63 static void open_input(void) {
64   if((inputfd = open(path, O_RDONLY)) < 0)
65     fatal(errno, "opening %s", path);
66 }
67
68 /** @brief Fill the buffer
69  * @return Number of bytes read
70  */
71 static size_t fill(void) {
72   int n = read(inputfd, buffer, sizeof buffer);
73
74   if(n < 0)
75     fatal(errno, "reading from %s", path);
76   return n;
77 }
78
79 /** @brief Write a 16-bit word in bigendian format */
80 static inline void output_16(uint16_t n) {
81   if(putc(n >> 8, outputfp) < 0
82      || putc(n & 0xFF, outputfp) < 0)
83     fatal(errno, "decoding %s: output error", path);
84 }
85
86 /** @brief Write the header
87  * If called more than once, either does nothing (if you kept the same
88  * output encoding) or fails (if you changed it).
89  */
90 static void output_header(int rate,
91                           int channels,
92                           int bits,
93                           int nbytes) {
94   struct stream_header header;
95
96   header.rate = rate;
97   header.bits = bits;
98   header.channels = channels;
99   header.endian = ENDIAN_BIG;
100   header.nbytes = nbytes;
101   if(fwrite(&header, sizeof header, 1, outputfp) < 1)
102     fatal(errno, "decoding %s: writing format header", path);
103 }
104
105 /** @brief Dithering state
106  * Filched from mpg321, which credits it to Robert Leslie */
107 struct audio_dither {
108   mad_fixed_t error[3];
109   mad_fixed_t random;
110 };
111
112 /** @brief 32-bit PRNG
113  * Filched from mpg321, which credits it to Robert Leslie */
114 static inline unsigned long prng(unsigned long state)
115 {
116   return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
117 }
118
119 /** @brief Generic linear sample quantize and dither routine
120  * Filched from mpg321, which credits it to Robert Leslie */
121 #define bits 16
122 static long audio_linear_dither(mad_fixed_t sample,
123                                 struct audio_dither *dither) {
124   unsigned int scalebits;
125   mad_fixed_t output, mask, rnd;
126
127   enum {
128     MIN = -MAD_F_ONE,
129     MAX =  MAD_F_ONE - 1
130   };
131
132   /* noise shape */
133   sample += dither->error[0] - dither->error[1] + dither->error[2];
134
135   dither->error[2] = dither->error[1];
136   dither->error[1] = dither->error[0] / 2;
137
138   /* bias */
139   output = sample + (1L << (MAD_F_FRACBITS + 1 - bits - 1));
140
141   scalebits = MAD_F_FRACBITS + 1 - bits;
142   mask = (1L << scalebits) - 1;
143
144   /* dither */
145   rnd  = prng(dither->random);
146   output += (rnd & mask) - (dither->random & mask);
147
148   dither->random = rnd;
149
150   /* clip */
151   if (output > MAX) {
152     output = MAX;
153
154     if (sample > MAX)
155       sample = MAX;
156   }
157   else if (output < MIN) {
158     output = MIN;
159
160     if (sample < MIN)
161       sample = MIN;
162   }
163
164   /* quantize */
165   output &= ~mask;
166
167   /* error feedback */
168   dither->error[0] = sample - output;
169
170   /* scale */
171   return output >> scalebits;
172 }
173 #undef bits
174
175 /** @brief MP3 output callback */
176 static enum mad_flow mp3_output(void attribute((unused)) *data,
177                                 struct mad_header const *header,
178                                 struct mad_pcm *pcm) {
179   size_t n = pcm->length;
180   const mad_fixed_t *l = pcm->samples[0], *r = pcm->samples[1];
181   static struct audio_dither ld[1], rd[1];
182
183   output_header(header->samplerate,
184                 pcm->channels,
185                 16,
186                 2 * pcm->channels * pcm->length);
187   switch(pcm->channels) {
188   case 1:
189     while(n--)
190       output_16(audio_linear_dither(*l++, ld));
191     break;
192   case 2:
193     while(n--) {
194       output_16(audio_linear_dither(*l++, ld));
195       output_16(audio_linear_dither(*r++, rd));
196     }
197     break;
198   default:
199     fatal(0, "decoding %s: unsupported channel count %d", path, pcm->channels);
200   }
201   return MAD_FLOW_CONTINUE;
202 }
203
204 /** @brief MP3 input callback */
205 static enum mad_flow mp3_input(void attribute((unused)) *data,
206                                struct mad_stream *stream) {
207   const size_t n = fill();
208   fprintf(stderr, "n=%zu\n", n);
209   if(!n)
210     return MAD_FLOW_STOP;
211   mad_stream_buffer(stream, buffer, n);
212   return MAD_FLOW_CONTINUE;
213 }
214
215
216 /** @brief MP3 error callback */
217 static enum mad_flow mp3_error(void attribute((unused)) *data,
218                                struct mad_stream *stream,
219                                struct mad_frame attribute((unused)) *frame) {
220   if(0)
221     /* Just generates pointless verbosity l-( */
222     error(0, "decoding %s: %s (%#04x)",
223           path, mad_stream_errorstr(stream), stream->error);
224   return MAD_FLOW_CONTINUE;
225 }
226
227 /** @brief MP3 decoder */
228 static void decode_mp3(void) {
229   struct mad_decoder mad[1];
230
231   open_input();
232   mad_decoder_init(mad, 0/*data*/, mp3_input, 0/*header*/, 0/*filter*/,
233                    mp3_output, mp3_error, 0/*message*/);
234   if(mad_decoder_run(mad, MAD_DECODER_MODE_SYNC))
235     exit(1);
236   mad_decoder_finish(mad);
237 }
238
239 /** @brief Lookup table of decoders */
240 static const struct decoder decoders[] = {
241   { "*.mp3", decode_mp3 },
242   { "*.MP3", decode_mp3 },
243   { 0, 0 }
244 };
245
246 static const struct option options[] = {
247   { "help", no_argument, 0, 'h' },
248   { "version", no_argument, 0, 'V' },
249   { 0, 0, 0, 0 }
250 };
251
252 /* Display usage message and terminate. */
253 static void help(void) {
254   xprintf("Usage:\n"
255           "  disorder-decode [OPTIONS] PATH\n"
256           "Options:\n"
257           "  --help, -h              Display usage message\n"
258           "  --version, -V           Display version number\n"
259           "\n"
260           "Audio decoder for DisOrder.  Only intended to be used by speaker\n"
261           "process, not for normal users.\n");
262   xfclose(stdout);
263   exit(0);
264 }
265
266 /* Display version number and terminate. */
267 static void version(void) {
268   xprintf("disorder-decode version %s\n", disorder_version_string);
269   xfclose(stdout);
270   exit(0);
271 }
272
273 int main(int argc, char **argv) {
274   int n;
275   const char *e;
276
277   set_progname(argv);
278   if(!setlocale(LC_CTYPE, "")) fatal(errno, "calling setlocale");
279   while((n = getopt_long(argc, argv, "hV", options, 0)) >= 0) {
280     switch(n) {
281     case 'h': help();
282     case 'V': version();
283     default: fatal(0, "invalid option");
284     }
285   }
286   if(optind >= argc)
287     fatal(0, "missing filename");
288   if(optind + 1 < argc)
289     fatal(0, "excess arguments");
290   if((e = getenv("DISORDER_RAW_FD"))) {
291     if(!(outputfp = fdopen(atoi(e), "wb")))
292       fatal(errno, "fdopen");
293   } else
294     outputfp = stdout;
295   path = argv[optind];
296   for(n = 0;
297       decoders[n].pattern
298         && fnmatch(decoders[n].pattern, path, 0) != 0;
299       ++n)
300     ;
301   if(!decoders[n].pattern)
302     fatal(0, "cannot determine file type for %s", path);
303   decoders[n].decode();
304   xfclose(outputfp);
305   return 0;
306 }
307
308 /*
309 Local Variables:
310 c-basic-offset:2
311 comment-column:40
312 fill-column:79
313 indent-tabs-mode:nil
314 End:
315 */