chiark / gitweb /
disobedience now embeds image files
[disorder] / server / normalize.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/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 <locale.h>
32 #include <errno.h>
33 #include <unistd.h>
34 #include <syslog.h>
35 #include <string.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38
39 #include "syscalls.h"
40 #include "log.h"
41 #include "configuration.h"
42 #include "speaker-protocol.h"
43
44 /** @brief Copy bytes from one file descriptor to another
45  * @param infd File descriptor read from
46  * @param outfd File descriptor to write to
47  * @param n Number of bytes to copy
48  */
49 static void copy(int infd, int outfd, size_t n) {
50   char buffer[4096];
51   ssize_t written;
52
53   while(n > 0) {
54     const ssize_t readden = read(infd, buffer,
55                                  n > sizeof buffer ? sizeof buffer : n);
56     if(readden < 0) {
57       if(errno == EINTR)
58         continue;
59       else
60         fatal(errno, "read error");
61     }
62     if(readden == 0)
63       fatal(0, "unexpected EOF");
64     n -= readden;
65     written = 0;
66     while(written < readden) {
67       const ssize_t w = write(outfd, buffer + written, readden - written);
68       if(w < 0)
69         fatal(errno, "write error");
70       written += w;
71     }
72   }
73 }
74
75 static void soxargs(const char ***pp, char **qq,
76                     const struct stream_header *header) {
77   *(*pp)++ = "-t.raw";
78   *(*pp)++ = "-s";
79   *qq += sprintf((char *)(*(*pp)++ = *qq), "-r%d", header->rate) + 1;
80   *qq += sprintf((char *)(*(*pp)++ = *qq), "-c%d", header->channels) + 1;
81   /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are
82    * deployed! */
83   switch(config->sox_generation) {
84   case 0:
85     if(header->bits != 8
86        && header->endian != ENDIAN_NATIVE)
87       *(*pp)++ = "-x";
88     switch(header->bits) {
89     case 8: *(*pp)++ = "-b"; break;
90     case 16: *(*pp)++ = "-w"; break;
91     case 32: *(*pp)++ = "-l"; break;
92     case 64: *(*pp)++ = "-d"; break;
93     default: fatal(0, "cannot handle sample size %d", header->bits);
94     }
95     break;
96   case 1:
97     if(header->bits != 8
98        && header->endian != ENDIAN_NATIVE)
99       switch(header->endian) {
100       case ENDIAN_BIG: *(*pp)++ = "-B"; break;
101       case ENDIAN_LITTLE: *(*pp)++ = "-L"; break;
102       }
103     if(header->bits % 8)
104       fatal(0, "cannot handle sample size %d", header->bits);
105     *qq += sprintf((char *)(*(*pp)++ = *qq), "-%d", header->bits / 8) + 1;
106     break;
107   default:
108     fatal(0, "unknown sox_generation %ld", config->sox_generation);
109   }
110 }
111
112 int main(int argc, char attribute((unused)) **argv) {
113   struct stream_header header, latest_format;
114   int n, p[2], outfd = -1;
115   pid_t pid = -1;
116
117   set_progname(argv);
118   if(!setlocale(LC_CTYPE, ""))
119     fatal(errno, "error calling setlocale");
120   if(argc > 1)
121     fatal(0, "not intended to be invoked by users");
122   if(config_read(1))
123     fatal(0, "cannot read configuration");
124   if(!isatty(2)) {
125     openlog(progname, LOG_PID, LOG_DAEMON);
126     log_default = &log_syslog;
127   }
128   memset(&latest_format, 0, sizeof latest_format);
129   for(;;) {
130     n = 0;
131     while((size_t)n < sizeof header) {
132       int r = read(0, (char *)&header + n, sizeof header - n);
133
134       if(r < 0) {
135         if(errno != EINTR)
136           fatal(errno, "error reading header");
137       } else if(r == 0) {
138         if(n)
139           fatal(0, "EOF reading header");
140         break;
141       } else
142         n += r;
143     }
144     if(!n)
145       break;
146     /* Sanity check the header */
147     if(header.rate < 100 || header.rate > 1000000)
148       fatal(0, "implausible rate %"PRId32"Hz (%#"PRIx32")",
149             header.rate, header.rate);
150     if(header.channels < 1 || header.channels > 2)
151       fatal(0, "unsupported channel count %d", header.channels);
152     if(header.bits % 8 || !header.bits || header.bits > 64)
153       fatal(0, "unsupported sample size %d bits", header.bits);
154     if(header.endian != ENDIAN_BIG && header.endian != ENDIAN_LITTLE)
155       fatal(0, "unsupported byte order %x", header.bits);
156     /* Skip empty chunks regardless of their alleged format */
157     if(header.nbytes == 0)
158       continue;
159     /* If the format has changed we stop/start the converter */
160     if(!formats_equal(&header, &latest_format)) {
161       if(pid != -1) {
162         /* There's a running converter, stop it */
163         xclose(outfd);
164         if(waitpid(pid, &n, 0) < 0)
165           fatal(errno, "error calling waitpid");
166         if(n)
167           fatal(0, "sox failed: %#x", n);
168         pid = -1;
169         outfd = -1;
170       }
171       if(!formats_equal(&header, &config->sample_format)) {
172         const char *av[32], **pp = av;
173         char argbuf[1024], *q = argbuf;
174         
175         /* Input format doesn't match target, need to start a converter */
176         *pp++ = "sox";
177         soxargs(&pp, &q, &header);
178         *pp++ = "-";                  /* stdin */
179         soxargs(&pp, &q, &config->sample_format);
180         *pp++ = "-";                  /* stdout */
181         *pp = 0;
182         /* This pipe will be sox's stdin */
183         xpipe(p);
184         if(!(pid = xfork())) {
185           exitfn = _exit;
186           xdup2(p[0], 0);
187           xclose(p[0]);
188           xclose(p[1]);
189           execvp(av[0], (char **)av);
190           fatal(errno, "sox");
191         }
192         xclose(p[0]);
193         outfd = p[1];
194       } else
195         /* Input format matches output, can just copy bytes */
196         outfd = 1;
197       /* Remember current format for next iteration */
198       latest_format = header;
199     }
200     /* Convert or copy this chunk */
201     copy(0, outfd, header.nbytes);
202   }
203   if(outfd != -1)
204     xclose(outfd);
205   return 0;
206 }
207
208 /*
209 Local Variables:
210 c-basic-offset:2
211 comment-column:40
212 fill-column:79
213 indent-tabs-mode:nil
214 End:
215 */