chiark / gitweb /
typo
[disorder] / server / normalize.c
CommitLineData
6d2d327c
RK
1/*
2 * This file is part of DisOrder
bfdadcc9 3 * Copyright (C) 2007-2009 Richard Kettlewell
6d2d327c 4 *
e7eb3a27 5 * This program is free software: you can redistribute it and/or modify
6d2d327c 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
6d2d327c
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 *
6d2d327c 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/>.
6d2d327c 17 */
717ba987 18/** @file server/normalize.c
6d2d327c
RK
19 * @brief Convert "raw" format output to the configured format
20 *
bfdadcc9
RK
21 * If libsamplerate is available then resample_convert() is used to do all
22 * conversions. If not then we invoke sox (even for trivial conversions such
23 * as byte-swapping). The sox support might be removed in a future version.
6d2d327c
RK
24 */
25
05b75f8d 26#include "disorder-server.h"
bfdadcc9
RK
27#include "resample.h"
28
29static char buffer[1024 * 1024];
0ca6d097
RK
30
31static const struct option options[] = {
32 { "help", no_argument, 0, 'h' },
33 { "version", no_argument, 0, 'V' },
34 { "config", required_argument, 0, 'c' },
35 { "debug", no_argument, 0, 'd' },
36 { "no-debug", no_argument, 0, 'D' },
37 { "syslog", no_argument, 0, 's' },
38 { "no-syslog", no_argument, 0, 'S' },
39 { 0, 0, 0, 0 }
40};
41
42/* display usage message and terminate */
43static void help(void) {
44 xprintf("Usage:\n"
45 " disorder-normalize [OPTIONS]\n"
46 "Options:\n"
47 " --help, -h Display usage message\n"
48 " --version, -V Display version number\n"
49 " --config PATH, -c PATH Set configuration file\n"
50 " --debug, -d Turn on debugging\n"
51 " --[no-]syslog Force logging\n"
52 "\n"
53 "Audio format normalizer for DisOrder. Not intended to be run\n"
54 "directly.\n");
55 xfclose(stdout);
56 exit(0);
57}
58
6d2d327c
RK
59/** @brief Copy bytes from one file descriptor to another
60 * @param infd File descriptor read from
61 * @param outfd File descriptor to write to
62 * @param n Number of bytes to copy
63 */
64static void copy(int infd, int outfd, size_t n) {
62234e45 65 ssize_t written;
6d2d327c
RK
66
67 while(n > 0) {
62234e45 68 const ssize_t readden = read(infd, buffer,
69 n > sizeof buffer ? sizeof buffer : n);
70 if(readden < 0) {
6d2d327c
RK
71 if(errno == EINTR)
72 continue;
73 else
2e9ba080 74 disorder_fatal(errno, "read error");
6d2d327c 75 }
62234e45 76 if(readden == 0)
2e9ba080 77 disorder_fatal(0, "unexpected EOF");
62234e45 78 n -= readden;
79 written = 0;
80 while(written < readden) {
81 const ssize_t w = write(outfd, buffer + written, readden - written);
6d2d327c 82 if(w < 0)
2e9ba080 83 disorder_fatal(errno, "write error");
62234e45 84 written += w;
6d2d327c
RK
85 }
86 }
87}
88
bfdadcc9 89#if !HAVE_SAMPLERATE_H
6d2d327c
RK
90static void soxargs(const char ***pp, char **qq,
91 const struct stream_header *header) {
92 *(*pp)++ = "-t.raw";
93 *(*pp)++ = "-s";
94 *qq += sprintf((char *)(*(*pp)++ = *qq), "-r%d", header->rate) + 1;
95 *qq += sprintf((char *)(*(*pp)++ = *qq), "-c%d", header->channels) + 1;
96 /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
97 * deployed! */
98 switch(config->sox_generation) {
99 case 0:
100 if(header->bits != 8
101 && header->endian != ENDIAN_NATIVE)
102 *(*pp)++ = "-x";
103 switch(header->bits) {
104 case 8: *(*pp)++ = "-b"; break;
105 case 16: *(*pp)++ = "-w"; break;
106 case 32: *(*pp)++ = "-l"; break;
107 case 64: *(*pp)++ = "-d"; break;
2e9ba080 108 default: disorder_fatal(0, "cannot handle sample size %d", header->bits);
6d2d327c
RK
109 }
110 break;
111 case 1:
112 if(header->bits != 8
113 && header->endian != ENDIAN_NATIVE)
114 switch(header->endian) {
115 case ENDIAN_BIG: *(*pp)++ = "-B"; break;
116 case ENDIAN_LITTLE: *(*pp)++ = "-L"; break;
117 }
118 if(header->bits % 8)
2e9ba080 119 disorder_fatal(0, "cannot handle sample size %d", header->bits);
6d2d327c
RK
120 *qq += sprintf((char *)(*(*pp)++ = *qq), "-%d", header->bits / 8) + 1;
121 break;
122 default:
2e9ba080 123 disorder_fatal(0, "unknown sox_generation %ld", config->sox_generation);
6d2d327c
RK
124 }
125}
bfdadcc9
RK
126#else
127static void converted(uint8_t *bytes,
128 size_t nbytes,
129 void attribute((unused)) *cd) {
130 /*syslog(LOG_INFO, "out: %02x %02x %02x %02x",
131 bytes[0],
132 bytes[1],
133 bytes[2],
134 bytes[3]);*/
135 while(nbytes > 0) {
136 ssize_t n = write(1, bytes, nbytes);
137 if(n < 0)
138 disorder_fatal(errno, "writing to stdout");
139 bytes += n;
140 nbytes -= n;
141 }
142}
143#endif
6d2d327c
RK
144
145int main(int argc, char attribute((unused)) **argv) {
146 struct stream_header header, latest_format;
bfdadcc9 147 int n, outfd = -1, logsyslog = !isatty(2), rs_in_use = 0;
6d2d327c 148 pid_t pid = -1;
bfdadcc9 149 struct resampler rs[1];
6d2d327c
RK
150
151 set_progname(argv);
152 if(!setlocale(LC_CTYPE, ""))
2e9ba080 153 disorder_fatal(errno, "error calling setlocale");
0ca6d097
RK
154 while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
155 switch(n) {
156 case 'h': help();
3fbdc96d 157 case 'V': version("disorder-normalize");
0ca6d097
RK
158 case 'c': configfile = optarg; break;
159 case 'd': debugging = 1; break;
160 case 'D': debugging = 0; break;
161 case 'S': logsyslog = 0; break;
162 case 's': logsyslog = 1; break;
2e9ba080 163 default: disorder_fatal(0, "invalid option");
0ca6d097
RK
164 }
165 }
02ba7921 166 if(config_read(1, NULL))
2e9ba080 167 disorder_fatal(0, "cannot read configuration");
0ca6d097 168 if(logsyslog) {
6d2d327c
RK
169 openlog(progname, LOG_PID, LOG_DAEMON);
170 log_default = &log_syslog;
171 }
172 memset(&latest_format, 0, sizeof latest_format);
173 for(;;) {
bfdadcc9 174 /* Read one header */
e7fd1612
RK
175 n = 0;
176 while((size_t)n < sizeof header) {
177 int r = read(0, (char *)&header + n, sizeof header - n);
178
179 if(r < 0) {
180 if(errno != EINTR)
2e9ba080 181 disorder_fatal(errno, "error reading header");
e99d42b1 182 } else if(r == 0) {
183 if(n)
2e9ba080 184 disorder_fatal(0, "EOF reading header");
e99d42b1 185 break;
186 } else
e7fd1612
RK
187 n += r;
188 }
24fc5e58 189 if(!n)
190 break;
6d2d327c
RK
191 /* Sanity check the header */
192 if(header.rate < 100 || header.rate > 1000000)
2e9ba080
RK
193 disorder_fatal(0, "implausible rate %"PRId32"Hz (%#"PRIx32")",
194 header.rate, header.rate);
6d2d327c 195 if(header.channels < 1 || header.channels > 2)
2e9ba080 196 disorder_fatal(0, "unsupported channel count %d", header.channels);
6d2d327c 197 if(header.bits % 8 || !header.bits || header.bits > 64)
2e9ba080 198 disorder_fatal(0, "unsupported sample size %d bits", header.bits);
6d2d327c 199 if(header.endian != ENDIAN_BIG && header.endian != ENDIAN_LITTLE)
2d0a6606 200 disorder_fatal(0, "unsupported byte order %d", header.endian);
6d2d327c
RK
201 /* Skip empty chunks regardless of their alleged format */
202 if(header.nbytes == 0)
203 continue;
204 /* If the format has changed we stop/start the converter */
bfdadcc9
RK
205#if HAVE_SAMPLERATE_H
206 /* We have libsamplerate */
207 if(formats_equal(&header, &config->sample_format))
208 /* If the format is already correct then we just write out the data */
209 copy(0, 1, header.nbytes);
210 else {
211 /* If we have a resampler active already check it is suitable and destroy
212 * it if not */
213 if(!formats_equal(&header, &latest_format) && rs_in_use) {
214 resample_close(rs);
215 rs_in_use = 0;
216 }
217 /*syslog(LOG_INFO, "%d/%d/%d/%d/%d -> %d/%d/%d/%d/%d",
218 header.bits,
219 header.channels,
220 header.rate,
221 1,
222 header.endian,
223 config->sample_format.bits,
224 config->sample_format.channels,
225 config->sample_format.rate,
226 1,
227 config->sample_format.endian);*/
228 if(!rs_in_use) {
229 /* Create a suitable resampler. */
230 resample_init(rs,
231 header.bits,
232 header.channels,
233 header.rate,
234 1, /* signed */
235 header.endian,
236 config->sample_format.bits,
237 config->sample_format.channels,
238 config->sample_format.rate,
239 1, /* signed */
240 config->sample_format.endian);
241 latest_format = header;
242 rs_in_use = 1;
243 /* TODO speaker protocol does not record signedness of samples. It's
244 * assumed that they are always signed. This should be fixed in the
245 * future (and the sample format syntax extended in a compatible
246 * way). */
247 }
248 /* Feed data through the resampler */
249 size_t used = 0, left = header.nbytes;
250 while(used || left) {
251 if(left) {
252 size_t limit = (sizeof buffer) - used;
253 if(limit > left)
254 limit = left;
255 ssize_t r = read(0, buffer + used, limit);
256 if(r < 0)
257 disorder_fatal(errno, "reading from stdin");
258 if(r == 0)
259 disorder_fatal(0, "unexpected EOF");
260 left -= r;
261 used += r;
262 //syslog(LOG_INFO, "read %zd bytes", r);
263 }
264 /*syslog(LOG_INFO, " in: %02x %02x %02x %02x",
265 (uint8_t)buffer[0],
266 (uint8_t)buffer[1],
267 (uint8_t)buffer[2],
268 (uint8_t)buffer[3]);*/
269 const size_t consumed = resample_convert(rs,
270 (uint8_t *)buffer, used,
271 !left,
272 converted, 0);
273 //syslog(LOG_INFO, "used=%zu consumed=%zu", used, consumed);
274 memmove(buffer, buffer + consumed, used - consumed);
275 used -= consumed;
276 }
277 }
278#else
279 /* We do not have libsamplerate. We will use sox instead. */
6d2d327c
RK
280 if(!formats_equal(&header, &latest_format)) {
281 if(pid != -1) {
282 /* There's a running converter, stop it */
283 xclose(outfd);
284 if(waitpid(pid, &n, 0) < 0)
2e9ba080 285 disorder_fatal(errno, "error calling waitpid");
6d2d327c 286 if(n)
2e9ba080 287 disorder_fatal(0, "sox failed: %#x", n);
6d2d327c
RK
288 pid = -1;
289 outfd = -1;
290 }
291 if(!formats_equal(&header, &config->sample_format)) {
292 const char *av[32], **pp = av;
293 char argbuf[1024], *q = argbuf;
294
295 /* Input format doesn't match target, need to start a converter */
296 *pp++ = "sox";
297 soxargs(&pp, &q, &header);
298 *pp++ = "-"; /* stdin */
299 soxargs(&pp, &q, &config->sample_format);
300 *pp++ = "-"; /* stdout */
301 *pp = 0;
302 /* This pipe will be sox's stdin */
bfdadcc9 303 int p[2];
6d2d327c
RK
304 xpipe(p);
305 if(!(pid = xfork())) {
306 exitfn = _exit;
307 xdup2(p[0], 0);
308 xclose(p[0]);
309 xclose(p[1]);
310 execvp(av[0], (char **)av);
2e9ba080 311 disorder_fatal(errno, "sox");
6d2d327c
RK
312 }
313 xclose(p[0]);
314 outfd = p[1];
315 } else
316 /* Input format matches output, can just copy bytes */
317 outfd = 1;
318 /* Remember current format for next iteration */
319 latest_format = header;
320 }
321 /* Convert or copy this chunk */
322 copy(0, outfd, header.nbytes);
bfdadcc9 323#endif
6d2d327c
RK
324 }
325 if(outfd != -1)
326 xclose(outfd);
60432d3d
RK
327 if(pid != -1) {
328 /* There's still a converter running */
329 if(waitpid(pid, &n, 0) < 0)
2e9ba080 330 disorder_fatal(errno, "error calling waitpid");
60432d3d 331 if(n)
2e9ba080 332 disorder_fatal(0, "sox failed: %#x", n);
60432d3d 333 }
bfdadcc9
RK
334 if(rs_in_use)
335 resample_close(rs);
6d2d327c
RK
336 return 0;
337}
338
339/*
340Local Variables:
341c-basic-offset:2
342comment-column:40
343fill-column:79
344indent-tabs-mode:nil
345End:
346*/