chiark / gitweb /
Fix type of shift in disorder-choose.
[disorder] / server / normalize.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2007, 2008 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/normalize.c
21  * @brief Convert "raw" format output to the configured format
22  *
23  * Currently we invoke sox even for trivial conversions such as byte-swapping.
24  * Ideally we would do all conversion including resampling in this one process
25  * and eliminate the dependency on sox.
26  */
27
28 #include <config.h>
29 #include "types.h"
30
31 #include <getopt.h>
32 #include <locale.h>
33 #include <errno.h>
34 #include <unistd.h>
35 #include <syslog.h>
36 #include <string.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39
40 #include "syscalls.h"
41 #include "log.h"
42 #include "configuration.h"
43 #include "speaker-protocol.h"
44 #include "defs.h"
45 #include "version.h"
46
47 static const struct option options[] = {
48   { "help", no_argument, 0, 'h' },
49   { "version", no_argument, 0, 'V' },
50   { "config", required_argument, 0, 'c' },
51   { "debug", no_argument, 0, 'd' },
52   { "no-debug", no_argument, 0, 'D' },
53   { "syslog", no_argument, 0, 's' },
54   { "no-syslog", no_argument, 0, 'S' },
55   { 0, 0, 0, 0 }
56 };
57
58 /* display usage message and terminate */
59 static void help(void) {
60   xprintf("Usage:\n"
61           "  disorder-normalize [OPTIONS]\n"
62           "Options:\n"
63           "  --help, -h              Display usage message\n"
64           "  --version, -V           Display version number\n"
65           "  --config PATH, -c PATH  Set configuration file\n"
66           "  --debug, -d             Turn on debugging\n"
67           "  --[no-]syslog           Force logging\n"
68           "\n"
69           "Audio format normalizer for DisOrder.  Not intended to be run\n"
70           "directly.\n");
71   xfclose(stdout);
72   exit(0);
73 }
74
75 /** @brief Copy bytes from one file descriptor to another
76  * @param infd File descriptor read from
77  * @param outfd File descriptor to write to
78  * @param n Number of bytes to copy
79  */
80 static void copy(int infd, int outfd, size_t n) {
81   char buffer[4096];
82   ssize_t written;
83
84   while(n > 0) {
85     const ssize_t readden = read(infd, buffer,
86                                  n > sizeof buffer ? sizeof buffer : n);
87     if(readden < 0) {
88       if(errno == EINTR)
89         continue;
90       else
91         fatal(errno, "read error");
92     }
93     if(readden == 0)
94       fatal(0, "unexpected EOF");
95     n -= readden;
96     written = 0;
97     while(written < readden) {
98       const ssize_t w = write(outfd, buffer + written, readden - written);
99       if(w < 0)
100         fatal(errno, "write error");
101       written += w;
102     }
103   }
104 }
105
106 static void soxargs(const char ***pp, char **qq,
107                     const struct stream_header *header) {
108   *(*pp)++ = "-t.raw";
109   *(*pp)++ = "-s";
110   *qq += sprintf((char *)(*(*pp)++ = *qq), "-r%d", header->rate) + 1;
111   *qq += sprintf((char *)(*(*pp)++ = *qq), "-c%d", header->channels) + 1;
112   /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
113    * deployed! */
114   switch(config->sox_generation) {
115   case 0:
116     if(header->bits != 8
117        && header->endian != ENDIAN_NATIVE)
118       *(*pp)++ = "-x";
119     switch(header->bits) {
120     case 8: *(*pp)++ = "-b"; break;
121     case 16: *(*pp)++ = "-w"; break;
122     case 32: *(*pp)++ = "-l"; break;
123     case 64: *(*pp)++ = "-d"; break;
124     default: fatal(0, "cannot handle sample size %d", header->bits);
125     }
126     break;
127   case 1:
128     if(header->bits != 8
129        && header->endian != ENDIAN_NATIVE)
130       switch(header->endian) {
131       case ENDIAN_BIG: *(*pp)++ = "-B"; break;
132       case ENDIAN_LITTLE: *(*pp)++ = "-L"; break;
133       }
134     if(header->bits % 8)
135       fatal(0, "cannot handle sample size %d", header->bits);
136     *qq += sprintf((char *)(*(*pp)++ = *qq), "-%d", header->bits / 8) + 1;
137     break;
138   default:
139     fatal(0, "unknown sox_generation %ld", config->sox_generation);
140   }
141 }
142
143 int main(int argc, char attribute((unused)) **argv) {
144   struct stream_header header, latest_format;
145   int n, p[2], outfd = -1, logsyslog = !isatty(2);
146   pid_t pid = -1;
147
148   set_progname(argv);
149   if(!setlocale(LC_CTYPE, ""))
150     fatal(errno, "error calling setlocale");
151   while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
152     switch(n) {
153     case 'h': help();
154     case 'V': version("disorder-normalize");
155     case 'c': configfile = optarg; break;
156     case 'd': debugging = 1; break;
157     case 'D': debugging = 0; break;
158     case 'S': logsyslog = 0; break;
159     case 's': logsyslog = 1; break;
160     default: fatal(0, "invalid option");
161     }
162   }
163   if(config_read(1))
164     fatal(0, "cannot read configuration");
165   if(logsyslog) {
166     openlog(progname, LOG_PID, LOG_DAEMON);
167     log_default = &log_syslog;
168   }
169   memset(&latest_format, 0, sizeof latest_format);
170   for(;;) {
171     n = 0;
172     while((size_t)n < sizeof header) {
173       int r = read(0, (char *)&header + n, sizeof header - n);
174
175       if(r < 0) {
176         if(errno != EINTR)
177           fatal(errno, "error reading header");
178       } else if(r == 0) {
179         if(n)
180           fatal(0, "EOF reading header");
181         break;
182       } else
183         n += r;
184     }
185     if(!n)
186       break;
187     /* Sanity check the header */
188     if(header.rate < 100 || header.rate > 1000000)
189       fatal(0, "implausible rate %"PRId32"Hz (%#"PRIx32")",
190             header.rate, header.rate);
191     if(header.channels < 1 || header.channels > 2)
192       fatal(0, "unsupported channel count %d", header.channels);
193     if(header.bits % 8 || !header.bits || header.bits > 64)
194       fatal(0, "unsupported sample size %d bits", header.bits);
195     if(header.endian != ENDIAN_BIG && header.endian != ENDIAN_LITTLE)
196       fatal(0, "unsupported byte order %x", header.bits);
197     /* Skip empty chunks regardless of their alleged format */
198     if(header.nbytes == 0)
199       continue;
200     /* If the format has changed we stop/start the converter */
201     if(!formats_equal(&header, &latest_format)) {
202       if(pid != -1) {
203         /* There's a running converter, stop it */
204         xclose(outfd);
205         if(waitpid(pid, &n, 0) < 0)
206           fatal(errno, "error calling waitpid");
207         if(n)
208           fatal(0, "sox failed: %#x", n);
209         pid = -1;
210         outfd = -1;
211       }
212       if(!formats_equal(&header, &config->sample_format)) {
213         const char *av[32], **pp = av;
214         char argbuf[1024], *q = argbuf;
215         
216         /* Input format doesn't match target, need to start a converter */
217         *pp++ = "sox";
218         soxargs(&pp, &q, &header);
219         *pp++ = "-";                  /* stdin */
220         soxargs(&pp, &q, &config->sample_format);
221         *pp++ = "-";                  /* stdout */
222         *pp = 0;
223         /* This pipe will be sox's stdin */
224         xpipe(p);
225         if(!(pid = xfork())) {
226           exitfn = _exit;
227           xdup2(p[0], 0);
228           xclose(p[0]);
229           xclose(p[1]);
230           execvp(av[0], (char **)av);
231           fatal(errno, "sox");
232         }
233         xclose(p[0]);
234         outfd = p[1];
235       } else
236         /* Input format matches output, can just copy bytes */
237         outfd = 1;
238       /* Remember current format for next iteration */
239       latest_format = header;
240     }
241     /* Convert or copy this chunk */
242     copy(0, outfd, header.nbytes);
243   }
244   if(outfd != -1)
245     xclose(outfd);
246   if(pid != -1) {
247     /* There's still a converter running */
248     if(waitpid(pid, &n, 0) < 0)
249       fatal(errno, "error calling waitpid");
250     if(n)
251       fatal(0, "sox failed: %#x", n);
252   }
253   return 0;
254 }
255
256 /*
257 Local Variables:
258 c-basic-offset:2
259 comment-column:40
260 fill-column:79
261 indent-tabs-mode:nil
262 End:
263 */