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