Commit | Line | Data |
---|---|---|
460b9539 | 1 | /* |
2 | * This file is part of DisOrder | |
dea8f8aa | 3 | * Copyright (C) 2005, 2006, 2007 Richard Kettlewell |
460b9539 | 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 | */ | |
1674096e | 20 | /** @file server/speaker.c |
21 | * @brief Speaker processs | |
22 | * | |
23 | * This program is responsible for transmitting a single coherent audio stream | |
24 | * to its destination (over the network, to some sound API, to some | |
25 | * subprocess). It receives connections from decoders via file descriptor | |
26 | * passing from the main server and plays them in the right order. | |
27 | * | |
795192f4 | 28 | * @b Encodings. For the <a href="http://www.alsa-project.org/">ALSA</a> API, |
29 | * 8- and 16- bit stereo and mono are supported, with any sample rate (within | |
30 | * the limits that ALSA can deal with.) | |
1674096e | 31 | * |
32 | * When communicating with a subprocess, <a | |
33 | * href="http://sox.sourceforge.net/">sox</a> is invoked to convert the inbound | |
34 | * data to a single consistent format. The same applies for network (RTP) | |
35 | * play, though in that case currently only 44.1KHz 16-bit stereo is supported. | |
36 | * | |
37 | * The inbound data starts with a structure defining the data format. Note | |
38 | * that this is NOT portable between different platforms or even necessarily | |
39 | * between versions; the speaker is assumed to be built from the same source | |
40 | * and run on the same host as the main server. | |
41 | * | |
795192f4 | 42 | * @b Garbage @b Collection. This program deliberately does not use the |
43 | * garbage collector even though it might be convenient to do so. This is for | |
44 | * two reasons. Firstly some sound APIs use thread threads and we do not want | |
45 | * to have to deal with potential interactions between threading and garbage | |
46 | * collection. Secondly this process needs to be able to respond quickly and | |
47 | * this is not compatible with the collector hanging the program even | |
48 | * relatively briefly. | |
49 | * | |
50 | * @b Units. This program thinks at various times in three different units. | |
51 | * Bytes are obvious. A sample is a single sample on a single channel. A | |
52 | * frame is several samples on different channels at the same point in time. | |
53 | * So (for instance) a 16-bit stereo frame is 4 bytes and consists of a pair of | |
54 | * 2-byte samples. | |
1674096e | 55 | */ |
460b9539 | 56 | |
57 | #include <config.h> | |
58 | #include "types.h" | |
59 | ||
60 | #include <getopt.h> | |
61 | #include <stdio.h> | |
62 | #include <stdlib.h> | |
63 | #include <locale.h> | |
64 | #include <syslog.h> | |
65 | #include <unistd.h> | |
66 | #include <errno.h> | |
67 | #include <ao/ao.h> | |
68 | #include <string.h> | |
69 | #include <assert.h> | |
70 | #include <sys/select.h> | |
9d5da576 | 71 | #include <sys/wait.h> |
460b9539 | 72 | #include <time.h> |
8023f60b | 73 | #include <fcntl.h> |
74 | #include <poll.h> | |
e83d0967 RK |
75 | #include <sys/socket.h> |
76 | #include <netdb.h> | |
77 | #include <gcrypt.h> | |
78 | #include <sys/uio.h> | |
460b9539 | 79 | |
80 | #include "configuration.h" | |
81 | #include "syscalls.h" | |
82 | #include "log.h" | |
83 | #include "defs.h" | |
84 | #include "mem.h" | |
85 | #include "speaker.h" | |
86 | #include "user.h" | |
e83d0967 RK |
87 | #include "addr.h" |
88 | #include "timeval.h" | |
89 | #include "rtp.h" | |
460b9539 | 90 | |
8023f60b | 91 | #if API_ALSA |
dea8f8aa | 92 | #include <alsa/asoundlib.h> |
8023f60b | 93 | #endif |
dea8f8aa | 94 | |
5330d674 | 95 | #ifdef WORDS_BIGENDIAN |
96 | # define MACHINE_AO_FMT AO_FMT_BIG | |
97 | #else | |
98 | # define MACHINE_AO_FMT AO_FMT_LITTLE | |
99 | #endif | |
100 | ||
1674096e | 101 | /** @brief How many seconds of input to buffer |
102 | * | |
103 | * While any given connection has this much audio buffered, no more reads will | |
104 | * be issued for that connection. The decoder will have to wait. | |
105 | */ | |
106 | #define BUFFER_SECONDS 5 | |
460b9539 | 107 | |
108 | #define FRAMES 4096 /* Frame batch size */ | |
109 | ||
1674096e | 110 | /** @brief Bytes to send per network packet |
111 | * | |
112 | * Don't make this too big or arithmetic will start to overflow. | |
113 | */ | |
8d2482ec | 114 | #define NETWORK_BYTES (1024+sizeof(struct rtp_header)) |
e83d0967 | 115 | |
508acf7a RK |
116 | /** @brief Maximum RTP playahead (ms) */ |
117 | #define RTP_AHEAD_MS 1000 | |
e83d0967 | 118 | |
1674096e | 119 | /** @brief Maximum number of FDs to poll for */ |
120 | #define NFDS 256 | |
460b9539 | 121 | |
1674096e | 122 | /** @brief Track structure |
123 | * | |
124 | * Known tracks are kept in a linked list. Usually there will be at most two | |
125 | * of these but rearranging the queue can cause there to be more. | |
126 | */ | |
460b9539 | 127 | static struct track { |
128 | struct track *next; /* next track */ | |
129 | int fd; /* input FD */ | |
130 | char id[24]; /* ID */ | |
131 | size_t start, used; /* start + bytes used */ | |
132 | int eof; /* input is at EOF */ | |
133 | int got_format; /* got format yet? */ | |
134 | ao_sample_format format; /* sample format */ | |
135 | unsigned long long played; /* number of frames played */ | |
136 | char *buffer; /* sample buffer */ | |
137 | size_t size; /* sample buffer size */ | |
138 | int slot; /* poll array slot */ | |
139 | } *tracks, *playing; /* all tracks + playing track */ | |
140 | ||
141 | static time_t last_report; /* when we last reported */ | |
142 | static int paused; /* pause status */ | |
460b9539 | 143 | static size_t bpf; /* bytes per frame */ |
144 | static struct pollfd fds[NFDS]; /* if we need more than that */ | |
145 | static int fdno; /* fd number */ | |
8023f60b | 146 | static size_t bufsize; /* buffer size */ |
147 | #if API_ALSA | |
50ae38dd | 148 | /** @brief The current PCM handle */ |
149 | static snd_pcm_t *pcm; | |
0c207c37 | 150 | static snd_pcm_uframes_t last_pcm_bufsize; /* last seen buffer size */ |
0763e1f4 | 151 | static ao_sample_format pcm_format; /* current format if aodev != 0 */ |
8023f60b | 152 | #endif |
50ae38dd | 153 | |
154 | /** @brief Ready to send audio | |
155 | * | |
156 | * This is set when the destination is ready to receive audio. Generally | |
157 | * this implies that the sound device is open. In the ALSA backend it | |
158 | * does @b not necessarily imply that is has the right sample format. | |
159 | */ | |
160 | static int ready; | |
161 | ||
460b9539 | 162 | static int forceplay; /* frames to force play */ |
e83d0967 RK |
163 | static int cmdfd = -1; /* child process input */ |
164 | static int bfd = -1; /* broadcast FD */ | |
7aa087a7 RK |
165 | |
166 | /** @brief RTP timestamp | |
167 | * | |
168 | * This counts the number of samples played (NB not the number of frames | |
169 | * played). | |
170 | * | |
171 | * The timestamp in the packet header is only 32 bits wide. With 44100Hz | |
172 | * stereo, that only gives about half a day before wrapping, which is not | |
173 | * particularly convenient for certain debugging purposes. Therefore the | |
174 | * timestamp is maintained as a 64-bit integer, giving around six million years | |
175 | * before wrapping, and truncated to 32 bits when transmitting. | |
176 | */ | |
177 | static uint64_t rtp_time; | |
178 | ||
179 | /** @brief RTP base timestamp | |
180 | * | |
181 | * This is the real time correspoding to an @ref rtp_time of 0. It is used | |
182 | * to recalculate the timestamp after idle periods. | |
183 | */ | |
184 | static struct timeval rtp_time_0; | |
185 | ||
e83d0967 RK |
186 | static uint16_t rtp_seq; /* frame sequence number */ |
187 | static uint32_t rtp_id; /* RTP SSRC */ | |
188 | static int idled; /* set when idled */ | |
189 | static int audio_errors; /* audio error counter */ | |
460b9539 | 190 | |
29601377 | 191 | /** @brief Structure of a backend */ |
192 | struct speaker_backend { | |
193 | /** @brief Which backend this is | |
194 | * | |
195 | * @c -1 terminates the list. | |
196 | */ | |
197 | int backend; | |
0763e1f4 | 198 | |
199 | /** @brief Flags | |
200 | * | |
201 | * Possible values | |
202 | * - @ref FIXED_FORMAT | |
203 | */ | |
204 | unsigned flags; | |
205 | /** @brief Lock to configured sample format */ | |
206 | #define FIXED_FORMAT 0x0001 | |
29601377 | 207 | |
208 | /** @brief Initialization | |
209 | * | |
50ae38dd | 210 | * Called once at startup. This is responsible for one-time setup |
211 | * operations, for instance opening a network socket to transmit to. | |
212 | * | |
213 | * When writing to a native sound API this might @b not imply opening the | |
214 | * native sound device - that might be done by @c activate below. | |
29601377 | 215 | */ |
216 | void (*init)(void); | |
217 | ||
218 | /** @brief Activation | |
219 | * @return 0 on success, non-0 on error | |
220 | * | |
221 | * Called to activate the output device. | |
50ae38dd | 222 | * |
223 | * After this function succeeds, @ref ready should be non-0. As well as | |
224 | * opening the audio device, this function is responsible for reconfiguring | |
225 | * if it necessary to cope with different samples formats (for backends that | |
226 | * don't demand a single fixed sample format for the lifetime of the server). | |
29601377 | 227 | */ |
228 | int (*activate)(void); | |
b5a99ad0 | 229 | |
7f9d5847 | 230 | /** @brief Play sound |
231 | * @param frames Number of frames to play | |
232 | * @return Number of frames actually played | |
233 | */ | |
234 | size_t (*play)(size_t frames); | |
235 | ||
b5a99ad0 | 236 | /** @brief Deactivation |
237 | * | |
238 | * Called to deactivate the sound device. This is the inverse of | |
239 | * @c activate above. | |
240 | */ | |
241 | void (*deactivate)(void); | |
6ba5f1ea | 242 | |
243 | /** @brief Called before poll() | |
244 | * | |
245 | * Called before the call to poll(). Should call addfd() to update the FD | |
246 | * array and stash the slot number somewhere safe. | |
247 | */ | |
248 | void (*beforepoll)(void); | |
d62d6873 | 249 | |
250 | /** @brief Called after poll() | |
251 | * @return 0 if we could play, non-0 if not | |
252 | * | |
253 | * Called after the call to poll(). Should arrange to play some audio if the | |
254 | * output device is ready. | |
255 | * | |
256 | * The return value should be 0 if the device was ready to play, or nonzero | |
257 | * if it was not. | |
258 | */ | |
259 | int (*afterpoll)(void); | |
29601377 | 260 | }; |
261 | ||
262 | /** @brief Selected backend */ | |
263 | static const struct speaker_backend *backend; | |
264 | ||
460b9539 | 265 | static const struct option options[] = { |
266 | { "help", no_argument, 0, 'h' }, | |
267 | { "version", no_argument, 0, 'V' }, | |
268 | { "config", required_argument, 0, 'c' }, | |
269 | { "debug", no_argument, 0, 'd' }, | |
270 | { "no-debug", no_argument, 0, 'D' }, | |
271 | { 0, 0, 0, 0 } | |
272 | }; | |
273 | ||
274 | /* Display usage message and terminate. */ | |
275 | static void help(void) { | |
276 | xprintf("Usage:\n" | |
277 | " disorder-speaker [OPTIONS]\n" | |
278 | "Options:\n" | |
279 | " --help, -h Display usage message\n" | |
280 | " --version, -V Display version number\n" | |
281 | " --config PATH, -c PATH Set configuration file\n" | |
282 | " --debug, -d Turn on debugging\n" | |
283 | "\n" | |
284 | "Speaker process for DisOrder. Not intended to be run\n" | |
285 | "directly.\n"); | |
286 | xfclose(stdout); | |
287 | exit(0); | |
288 | } | |
289 | ||
290 | /* Display version number and terminate. */ | |
291 | static void version(void) { | |
292 | xprintf("disorder-speaker version %s\n", disorder_version_string); | |
293 | xfclose(stdout); | |
294 | exit(0); | |
295 | } | |
296 | ||
1674096e | 297 | /** @brief Return the number of bytes per frame in @p format */ |
460b9539 | 298 | static size_t bytes_per_frame(const ao_sample_format *format) { |
299 | return format->channels * format->bits / 8; | |
300 | } | |
301 | ||
1674096e | 302 | /** @brief Find track @p id, maybe creating it if not found */ |
460b9539 | 303 | static struct track *findtrack(const char *id, int create) { |
304 | struct track *t; | |
305 | ||
306 | D(("findtrack %s %d", id, create)); | |
307 | for(t = tracks; t && strcmp(id, t->id); t = t->next) | |
308 | ; | |
309 | if(!t && create) { | |
310 | t = xmalloc(sizeof *t); | |
311 | t->next = tracks; | |
312 | strcpy(t->id, id); | |
313 | t->fd = -1; | |
314 | tracks = t; | |
315 | /* The initial input buffer will be the sample format. */ | |
316 | t->buffer = (void *)&t->format; | |
317 | t->size = sizeof t->format; | |
318 | } | |
319 | return t; | |
320 | } | |
321 | ||
1674096e | 322 | /** @brief Remove track @p id (but do not destroy it) */ |
460b9539 | 323 | static struct track *removetrack(const char *id) { |
324 | struct track *t, **tt; | |
325 | ||
326 | D(("removetrack %s", id)); | |
327 | for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next) | |
328 | ; | |
329 | if(t) | |
330 | *tt = t->next; | |
331 | return t; | |
332 | } | |
333 | ||
1674096e | 334 | /** @brief Destroy a track */ |
460b9539 | 335 | static void destroy(struct track *t) { |
336 | D(("destroy %s", t->id)); | |
337 | if(t->fd != -1) xclose(t->fd); | |
338 | if(t->buffer != (void *)&t->format) free(t->buffer); | |
339 | free(t); | |
340 | } | |
341 | ||
1674096e | 342 | /** @brief Notice a new connection */ |
460b9539 | 343 | static void acquire(struct track *t, int fd) { |
344 | D(("acquire %s %d", t->id, fd)); | |
345 | if(t->fd != -1) | |
346 | xclose(t->fd); | |
347 | t->fd = fd; | |
348 | nonblock(fd); | |
349 | } | |
350 | ||
1674096e | 351 | /** @brief Return true if A and B denote identical libao formats, else false */ |
352 | static int formats_equal(const ao_sample_format *a, | |
353 | const ao_sample_format *b) { | |
354 | return (a->bits == b->bits | |
355 | && a->rate == b->rate | |
356 | && a->channels == b->channels | |
357 | && a->byte_format == b->byte_format); | |
358 | } | |
359 | ||
360 | /** @brief Compute arguments to sox */ | |
361 | static void soxargs(const char ***pp, char **qq, ao_sample_format *ao) { | |
362 | int n; | |
363 | ||
364 | *(*pp)++ = "-t.raw"; | |
365 | *(*pp)++ = "-s"; | |
366 | *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1; | |
367 | *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1; | |
368 | /* sox 12.17.9 insists on -b etc; CVS sox insists on -<n> etc; both are | |
369 | * deployed! */ | |
370 | switch(config->sox_generation) { | |
371 | case 0: | |
372 | if(ao->bits != 8 | |
373 | && ao->byte_format != AO_FMT_NATIVE | |
374 | && ao->byte_format != MACHINE_AO_FMT) { | |
375 | *(*pp)++ = "-x"; | |
376 | } | |
377 | switch(ao->bits) { | |
378 | case 8: *(*pp)++ = "-b"; break; | |
379 | case 16: *(*pp)++ = "-w"; break; | |
380 | case 32: *(*pp)++ = "-l"; break; | |
381 | case 64: *(*pp)++ = "-d"; break; | |
382 | default: fatal(0, "cannot handle sample size %d", (int)ao->bits); | |
383 | } | |
384 | break; | |
385 | case 1: | |
386 | switch(ao->byte_format) { | |
387 | case AO_FMT_NATIVE: break; | |
388 | case AO_FMT_BIG: *(*pp)++ = "-B"; break; | |
389 | case AO_FMT_LITTLE: *(*pp)++ = "-L"; break; | |
390 | } | |
391 | *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1; | |
392 | break; | |
393 | } | |
394 | } | |
395 | ||
396 | /** @brief Enable format translation | |
397 | * | |
398 | * If necessary, replaces a tracks inbound file descriptor with one connected | |
399 | * to a sox invocation, which performs the required translation. | |
400 | */ | |
401 | static void enable_translation(struct track *t) { | |
0763e1f4 | 402 | if((backend->flags & FIXED_FORMAT) |
403 | && !formats_equal(&t->format, &config->sample_format)) { | |
1674096e | 404 | char argbuf[1024], *q = argbuf; |
405 | const char *av[18], **pp = av; | |
406 | int soxpipe[2]; | |
407 | pid_t soxkid; | |
408 | ||
409 | *pp++ = "sox"; | |
410 | soxargs(&pp, &q, &t->format); | |
411 | *pp++ = "-"; | |
412 | soxargs(&pp, &q, &config->sample_format); | |
413 | *pp++ = "-"; | |
414 | *pp++ = 0; | |
415 | if(debugging) { | |
416 | for(pp = av; *pp; pp++) | |
417 | D(("sox arg[%d] = %s", pp - av, *pp)); | |
418 | D(("end args")); | |
419 | } | |
420 | xpipe(soxpipe); | |
421 | soxkid = xfork(); | |
422 | if(soxkid == 0) { | |
423 | signal(SIGPIPE, SIG_DFL); | |
424 | xdup2(t->fd, 0); | |
425 | xdup2(soxpipe[1], 1); | |
426 | fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK); | |
427 | close(soxpipe[0]); | |
428 | close(soxpipe[1]); | |
429 | close(t->fd); | |
430 | execvp("sox", (char **)av); | |
431 | _exit(1); | |
432 | } | |
433 | D(("forking sox for format conversion (kid = %d)", soxkid)); | |
434 | close(t->fd); | |
435 | close(soxpipe[1]); | |
436 | t->fd = soxpipe[0]; | |
437 | t->format = config->sample_format; | |
1674096e | 438 | } |
439 | } | |
440 | ||
441 | /** @brief Read data into a sample buffer | |
442 | * @param t Pointer to track | |
443 | * @return 0 on success, -1 on EOF | |
444 | * | |
445 | * This is effectively the read callback on @c t->fd. | |
446 | */ | |
460b9539 | 447 | static int fill(struct track *t) { |
448 | size_t where, left; | |
449 | int n; | |
450 | ||
451 | D(("fill %s: eof=%d used=%zu size=%zu got_format=%d", | |
452 | t->id, t->eof, t->used, t->size, t->got_format)); | |
453 | if(t->eof) return -1; | |
454 | if(t->used < t->size) { | |
455 | /* there is room left in the buffer */ | |
456 | where = (t->start + t->used) % t->size; | |
457 | if(t->got_format) { | |
458 | /* We are reading audio data, get as much as we can */ | |
459 | if(where >= t->start) left = t->size - where; | |
460 | else left = t->start - where; | |
461 | } else | |
462 | /* We are still waiting for the format, only get that */ | |
463 | left = sizeof (ao_sample_format) - t->used; | |
464 | do { | |
465 | n = read(t->fd, t->buffer + where, left); | |
466 | } while(n < 0 && errno == EINTR); | |
467 | if(n < 0) { | |
468 | if(errno != EAGAIN) fatal(errno, "error reading sample stream"); | |
469 | return 0; | |
470 | } | |
471 | if(n == 0) { | |
472 | D(("fill %s: eof detected", t->id)); | |
473 | t->eof = 1; | |
474 | return -1; | |
475 | } | |
476 | t->used += n; | |
477 | if(!t->got_format && t->used >= sizeof (ao_sample_format)) { | |
478 | assert(t->used == sizeof (ao_sample_format)); | |
479 | /* Check that our assumptions are met. */ | |
480 | if(t->format.bits & 7) | |
481 | fatal(0, "bits per sample not a multiple of 8"); | |
1674096e | 482 | /* If the input format is unsuitable, arrange to translate it */ |
483 | enable_translation(t); | |
460b9539 | 484 | /* Make a new buffer for audio data. */ |
485 | t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS; | |
486 | t->buffer = xmalloc(t->size); | |
487 | t->used = 0; | |
488 | t->got_format = 1; | |
489 | D(("got format for %s", t->id)); | |
490 | } | |
491 | } | |
492 | return 0; | |
493 | } | |
494 | ||
1674096e | 495 | /** @brief Close the sound device */ |
460b9539 | 496 | static void idle(void) { |
460b9539 | 497 | D(("idle")); |
b5a99ad0 | 498 | if(backend->deactivate) |
499 | backend->deactivate(); | |
e83d0967 | 500 | idled = 1; |
9d5da576 | 501 | ready = 0; |
460b9539 | 502 | } |
503 | ||
1674096e | 504 | /** @brief Abandon the current track */ |
460b9539 | 505 | static void abandon(void) { |
506 | struct speaker_message sm; | |
507 | ||
508 | D(("abandon")); | |
509 | memset(&sm, 0, sizeof sm); | |
510 | sm.type = SM_FINISHED; | |
511 | strcpy(sm.id, playing->id); | |
512 | speaker_send(1, &sm, 0); | |
513 | removetrack(playing->id); | |
514 | destroy(playing); | |
515 | playing = 0; | |
516 | forceplay = 0; | |
517 | } | |
518 | ||
8023f60b | 519 | #if API_ALSA |
1674096e | 520 | /** @brief Log ALSA parameters */ |
1c6e6a61 | 521 | static void log_params(snd_pcm_hw_params_t *hwparams, |
522 | snd_pcm_sw_params_t *swparams) { | |
523 | snd_pcm_uframes_t f; | |
524 | unsigned u; | |
525 | ||
0c207c37 | 526 | return; /* too verbose */ |
1c6e6a61 | 527 | if(hwparams) { |
528 | /* TODO */ | |
529 | } | |
530 | if(swparams) { | |
531 | snd_pcm_sw_params_get_silence_size(swparams, &f); | |
532 | info("sw silence_size=%lu", (unsigned long)f); | |
533 | snd_pcm_sw_params_get_silence_threshold(swparams, &f); | |
534 | info("sw silence_threshold=%lu", (unsigned long)f); | |
535 | snd_pcm_sw_params_get_sleep_min(swparams, &u); | |
536 | info("sw sleep_min=%lu", (unsigned long)u); | |
537 | snd_pcm_sw_params_get_start_threshold(swparams, &f); | |
538 | info("sw start_threshold=%lu", (unsigned long)f); | |
539 | snd_pcm_sw_params_get_stop_threshold(swparams, &f); | |
540 | info("sw stop_threshold=%lu", (unsigned long)f); | |
541 | snd_pcm_sw_params_get_xfer_align(swparams, &f); | |
542 | info("sw xfer_align=%lu", (unsigned long)f); | |
543 | } | |
544 | } | |
8023f60b | 545 | #endif |
1c6e6a61 | 546 | |
1674096e | 547 | /** @brief Enable sound output |
548 | * | |
549 | * Makes sure the sound device is open and has the right sample format. Return | |
550 | * 0 on success and -1 on error. | |
551 | */ | |
460b9539 | 552 | static int activate(void) { |
460b9539 | 553 | /* If we don't know the format yet we cannot start. */ |
554 | if(!playing->got_format) { | |
555 | D((" - not got format for %s", playing->id)); | |
556 | return -1; | |
557 | } | |
29601377 | 558 | return backend->activate(); |
460b9539 | 559 | } |
560 | ||
561 | /* Check to see whether the current track has finished playing */ | |
562 | static void maybe_finished(void) { | |
563 | if(playing | |
564 | && playing->eof | |
565 | && (!playing->got_format | |
566 | || playing->used < bytes_per_frame(&playing->format))) | |
567 | abandon(); | |
568 | } | |
569 | ||
e83d0967 RK |
570 | static void fork_cmd(void) { |
571 | pid_t cmdpid; | |
9d5da576 | 572 | int pfd[2]; |
e83d0967 | 573 | if(cmdfd != -1) close(cmdfd); |
9d5da576 | 574 | xpipe(pfd); |
e83d0967 RK |
575 | cmdpid = xfork(); |
576 | if(!cmdpid) { | |
1674096e | 577 | signal(SIGPIPE, SIG_DFL); |
9d5da576 | 578 | xdup2(pfd[0], 0); |
579 | close(pfd[0]); | |
580 | close(pfd[1]); | |
581 | execl("/bin/sh", "sh", "-c", config->speaker_command, (char *)0); | |
582 | fatal(errno, "error execing /bin/sh"); | |
583 | } | |
584 | close(pfd[0]); | |
e83d0967 RK |
585 | cmdfd = pfd[1]; |
586 | D(("forked cmd %d, fd = %d", cmdpid, cmdfd)); | |
9d5da576 | 587 | } |
588 | ||
460b9539 | 589 | static void play(size_t frames) { |
3c68b773 | 590 | size_t avail_frames, avail_bytes, written_frames; |
9d5da576 | 591 | ssize_t written_bytes; |
460b9539 | 592 | |
7f9d5847 | 593 | /* Make sure the output device is activated */ |
460b9539 | 594 | if(activate()) { |
595 | if(playing) | |
596 | forceplay = frames; | |
597 | else | |
598 | forceplay = 0; /* Must have called abandon() */ | |
599 | return; | |
600 | } | |
601 | D(("play: play %zu/%zu%s %dHz %db %dc", frames, playing->used / bpf, | |
602 | playing->eof ? " EOF" : "", | |
603 | playing->format.rate, | |
604 | playing->format.bits, | |
605 | playing->format.channels)); | |
606 | /* If we haven't got enough bytes yet wait until we have. Exception: when | |
607 | * we are at eof. */ | |
608 | if(playing->used < frames * bpf && !playing->eof) { | |
609 | forceplay = frames; | |
610 | return; | |
611 | } | |
612 | /* We have got enough data so don't force play again */ | |
613 | forceplay = 0; | |
614 | /* Figure out how many frames there are available to write */ | |
615 | if(playing->start + playing->used > playing->size) | |
7f9d5847 | 616 | /* The ring buffer is currently wrapped, only play up to the wrap point */ |
460b9539 | 617 | avail_bytes = playing->size - playing->start; |
618 | else | |
7f9d5847 | 619 | /* The ring buffer is not wrapped, can play the lot */ |
460b9539 | 620 | avail_bytes = playing->used; |
7f9d5847 | 621 | avail_frames = avail_bytes / bpf; |
622 | /* Only play up to the requested amount */ | |
623 | if(avail_frames > frames) | |
624 | avail_frames = frames; | |
625 | if(!avail_frames) | |
626 | return; | |
3c68b773 | 627 | /* Play it, Sam */ |
628 | written_frames = backend->play(avail_frames); | |
544a9ec1 | 629 | written_bytes = written_frames * bpf; |
e83d0967 RK |
630 | /* written_bytes and written_frames had better both be set and correct by |
631 | * this point */ | |
460b9539 | 632 | playing->start += written_bytes; |
633 | playing->used -= written_bytes; | |
634 | playing->played += written_frames; | |
635 | /* If the pointer is at the end of the buffer (or the buffer is completely | |
636 | * empty) wrap it back to the start. */ | |
637 | if(!playing->used || playing->start == playing->size) | |
638 | playing->start = 0; | |
639 | frames -= written_frames; | |
640 | } | |
641 | ||
642 | /* Notify the server what we're up to. */ | |
643 | static void report(void) { | |
644 | struct speaker_message sm; | |
645 | ||
646 | if(playing && playing->buffer != (void *)&playing->format) { | |
647 | memset(&sm, 0, sizeof sm); | |
648 | sm.type = paused ? SM_PAUSED : SM_PLAYING; | |
649 | strcpy(sm.id, playing->id); | |
650 | sm.data = playing->played / playing->format.rate; | |
651 | speaker_send(1, &sm, 0); | |
652 | } | |
653 | time(&last_report); | |
654 | } | |
655 | ||
9d5da576 | 656 | static void reap(int __attribute__((unused)) sig) { |
e83d0967 | 657 | pid_t cmdpid; |
9d5da576 | 658 | int st; |
659 | ||
660 | do | |
e83d0967 RK |
661 | cmdpid = waitpid(-1, &st, WNOHANG); |
662 | while(cmdpid > 0); | |
9d5da576 | 663 | signal(SIGCHLD, reap); |
664 | } | |
665 | ||
460b9539 | 666 | static int addfd(int fd, int events) { |
667 | if(fdno < NFDS) { | |
668 | fds[fdno].fd = fd; | |
669 | fds[fdno].events = events; | |
670 | return fdno++; | |
671 | } else | |
672 | return -1; | |
673 | } | |
674 | ||
572d74ba | 675 | #if API_ALSA |
676 | /** @brief ALSA backend initialization */ | |
677 | static void alsa_init(void) { | |
678 | info("selected ALSA backend"); | |
679 | } | |
29601377 | 680 | |
681 | /** @brief ALSA backend activation */ | |
682 | static int alsa_activate(void) { | |
683 | /* If we need to change format then close the current device. */ | |
684 | if(pcm && !formats_equal(&playing->format, &pcm_format)) | |
685 | idle(); | |
686 | if(!pcm) { | |
687 | snd_pcm_hw_params_t *hwparams; | |
688 | snd_pcm_sw_params_t *swparams; | |
689 | snd_pcm_uframes_t pcm_bufsize; | |
690 | int err; | |
691 | int sample_format = 0; | |
692 | unsigned rate; | |
693 | ||
694 | D(("snd_pcm_open")); | |
695 | if((err = snd_pcm_open(&pcm, | |
696 | config->device, | |
697 | SND_PCM_STREAM_PLAYBACK, | |
698 | SND_PCM_NONBLOCK))) { | |
699 | error(0, "error from snd_pcm_open: %d", err); | |
700 | goto error; | |
701 | } | |
702 | snd_pcm_hw_params_alloca(&hwparams); | |
703 | D(("set up hw params")); | |
704 | if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0) | |
705 | fatal(0, "error from snd_pcm_hw_params_any: %d", err); | |
706 | if((err = snd_pcm_hw_params_set_access(pcm, hwparams, | |
707 | SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) | |
708 | fatal(0, "error from snd_pcm_hw_params_set_access: %d", err); | |
709 | switch(playing->format.bits) { | |
710 | case 8: | |
711 | sample_format = SND_PCM_FORMAT_S8; | |
712 | break; | |
713 | case 16: | |
714 | switch(playing->format.byte_format) { | |
715 | case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break; | |
716 | case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break; | |
717 | case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break; | |
718 | error(0, "unrecognized byte format %d", playing->format.byte_format); | |
719 | goto fatal; | |
720 | } | |
721 | break; | |
722 | default: | |
723 | error(0, "unsupported sample size %d", playing->format.bits); | |
724 | goto fatal; | |
725 | } | |
726 | if((err = snd_pcm_hw_params_set_format(pcm, hwparams, | |
727 | sample_format)) < 0) { | |
728 | error(0, "error from snd_pcm_hw_params_set_format (%d): %d", | |
729 | sample_format, err); | |
730 | goto fatal; | |
731 | } | |
732 | rate = playing->format.rate; | |
733 | if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) { | |
734 | error(0, "error from snd_pcm_hw_params_set_rate (%d): %d", | |
735 | playing->format.rate, err); | |
736 | goto fatal; | |
737 | } | |
738 | if(rate != (unsigned)playing->format.rate) | |
739 | info("want rate %d, got %u", playing->format.rate, rate); | |
740 | if((err = snd_pcm_hw_params_set_channels(pcm, hwparams, | |
741 | playing->format.channels)) < 0) { | |
742 | error(0, "error from snd_pcm_hw_params_set_channels (%d): %d", | |
743 | playing->format.channels, err); | |
744 | goto fatal; | |
745 | } | |
746 | bufsize = 3 * FRAMES; | |
747 | pcm_bufsize = bufsize; | |
748 | if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams, | |
749 | &pcm_bufsize)) < 0) | |
750 | fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d", | |
751 | 3 * FRAMES, err); | |
752 | if(pcm_bufsize != 3 * FRAMES && pcm_bufsize != last_pcm_bufsize) | |
753 | info("asked for PCM buffer of %d frames, got %d", | |
754 | 3 * FRAMES, (int)pcm_bufsize); | |
755 | last_pcm_bufsize = pcm_bufsize; | |
756 | if((err = snd_pcm_hw_params(pcm, hwparams)) < 0) | |
757 | fatal(0, "error calling snd_pcm_hw_params: %d", err); | |
758 | D(("set up sw params")); | |
759 | snd_pcm_sw_params_alloca(&swparams); | |
760 | if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0) | |
761 | fatal(0, "error calling snd_pcm_sw_params_current: %d", err); | |
762 | if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0) | |
763 | fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d", | |
764 | FRAMES, err); | |
765 | if((err = snd_pcm_sw_params(pcm, swparams)) < 0) | |
766 | fatal(0, "error calling snd_pcm_sw_params: %d", err); | |
767 | pcm_format = playing->format; | |
768 | bpf = bytes_per_frame(&pcm_format); | |
769 | D(("acquired audio device")); | |
770 | log_params(hwparams, swparams); | |
771 | ready = 1; | |
772 | } | |
773 | return 0; | |
774 | fatal: | |
775 | abandon(); | |
776 | error: | |
777 | /* We assume the error is temporary and that we'll retry in a bit. */ | |
778 | if(pcm) { | |
779 | snd_pcm_close(pcm); | |
780 | pcm = 0; | |
781 | } | |
782 | return -1; | |
783 | } | |
b5a99ad0 | 784 | |
7f9d5847 | 785 | /** @brief Play via ALSA */ |
786 | static size_t alsa_play(size_t frames) { | |
544a9ec1 | 787 | snd_pcm_sframes_t pcm_written_frames; |
788 | int err; | |
789 | ||
790 | pcm_written_frames = snd_pcm_writei(pcm, | |
791 | playing->buffer + playing->start, | |
792 | frames); | |
793 | D(("actually play %zu frames, wrote %d", | |
794 | frames, (int)pcm_written_frames)); | |
795 | if(pcm_written_frames < 0) { | |
796 | switch(pcm_written_frames) { | |
797 | case -EPIPE: /* underrun */ | |
798 | error(0, "snd_pcm_writei reports underrun"); | |
799 | if((err = snd_pcm_prepare(pcm)) < 0) | |
800 | fatal(0, "error calling snd_pcm_prepare: %d", err); | |
801 | return 0; | |
802 | case -EAGAIN: | |
803 | return 0; | |
804 | default: | |
805 | fatal(0, "error calling snd_pcm_writei: %d", | |
806 | (int)pcm_written_frames); | |
807 | } | |
808 | } else | |
809 | return pcm_written_frames; | |
7f9d5847 | 810 | } |
811 | ||
6ba5f1ea | 812 | static int alsa_slots, alsa_nslots = -1; |
813 | ||
814 | /** @brief Fill in poll fd array for ALSA */ | |
815 | static void alsa_beforepoll(void) { | |
816 | /* We send sample data to ALSA as fast as it can accept it, relying on | |
817 | * the fact that it has a relatively small buffer to minimize pause | |
818 | * latency. */ | |
819 | int retry = 3, err; | |
820 | ||
821 | alsa_slots = fdno; | |
822 | do { | |
823 | retry = 0; | |
824 | alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno); | |
825 | if((alsa_nslots <= 0 | |
826 | || !(fds[alsa_slots].events & POLLOUT)) | |
827 | && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) { | |
828 | error(0, "underrun detected after call to snd_pcm_poll_descriptors()"); | |
829 | if((err = snd_pcm_prepare(pcm))) | |
830 | fatal(0, "error calling snd_pcm_prepare: %d", err); | |
831 | } else | |
832 | break; | |
833 | } while(retry-- > 0); | |
834 | if(alsa_nslots >= 0) | |
835 | fdno += alsa_nslots; | |
836 | } | |
837 | ||
d62d6873 | 838 | /** @brief Process poll() results for ALSA */ |
839 | static int alsa_afterpoll(void) { | |
840 | int err; | |
841 | ||
842 | if(alsa_slots != -1) { | |
843 | unsigned short alsa_revents; | |
844 | ||
845 | if((err = snd_pcm_poll_descriptors_revents(pcm, | |
846 | &fds[alsa_slots], | |
847 | alsa_nslots, | |
848 | &alsa_revents)) < 0) | |
849 | fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err); | |
850 | if(alsa_revents & (POLLOUT | POLLERR)) | |
851 | play(3 * FRAMES); | |
852 | return 0; | |
853 | } else | |
854 | return 1; | |
855 | } | |
856 | ||
b5a99ad0 | 857 | /** @brief ALSA deactivation */ |
858 | static void alsa_deactivate(void) { | |
859 | if(pcm) { | |
860 | int err; | |
861 | ||
862 | if((err = snd_pcm_nonblock(pcm, 0)) < 0) | |
863 | fatal(0, "error calling snd_pcm_nonblock: %d", err); | |
864 | D(("draining pcm")); | |
865 | snd_pcm_drain(pcm); | |
866 | D(("closing pcm")); | |
867 | snd_pcm_close(pcm); | |
868 | pcm = 0; | |
869 | forceplay = 0; | |
870 | D(("released audio device")); | |
871 | } | |
872 | } | |
572d74ba | 873 | #endif |
874 | ||
875 | /** @brief Command backend initialization */ | |
876 | static void command_init(void) { | |
877 | info("selected command backend"); | |
878 | fork_cmd(); | |
879 | } | |
880 | ||
7f9d5847 | 881 | /** @brief Play to a subprocess */ |
882 | static size_t command_play(size_t frames) { | |
3c68b773 | 883 | size_t bytes = frames * bpf; |
884 | int written_bytes; | |
885 | ||
886 | written_bytes = write(cmdfd, playing->buffer + playing->start, bytes); | |
887 | D(("actually play %zu bytes, wrote %d", | |
888 | bytes, written_bytes)); | |
889 | if(written_bytes < 0) { | |
890 | switch(errno) { | |
891 | case EPIPE: | |
892 | error(0, "hmm, command died; trying another"); | |
893 | fork_cmd(); | |
894 | return 0; | |
895 | case EAGAIN: | |
896 | return 0; | |
897 | default: | |
898 | fatal(errno, "error writing to subprocess"); | |
899 | } | |
900 | } else | |
901 | return written_bytes / bpf; | |
7f9d5847 | 902 | } |
903 | ||
6ba5f1ea | 904 | static int cmdfd_slot; |
905 | ||
906 | /** @brief Update poll array for writing to subprocess */ | |
907 | static void command_beforepoll(void) { | |
908 | /* We send sample data to the subprocess as fast as it can accept it. | |
909 | * This isn't ideal as pause latency can be very high as a result. */ | |
910 | if(cmdfd >= 0) | |
911 | cmdfd_slot = addfd(cmdfd, POLLOUT); | |
912 | } | |
913 | ||
d62d6873 | 914 | /** @brief Process poll() results for subprocess play */ |
915 | static int command_afterpoll(void) { | |
916 | if(cmdfd_slot != -1) { | |
917 | if(fds[cmdfd_slot].revents & (POLLOUT | POLLERR)) | |
918 | play(3 * FRAMES); | |
919 | return 0; | |
920 | } else | |
921 | return -1; | |
922 | } | |
923 | ||
b5a99ad0 | 924 | /** @brief Command/network backend activation */ |
925 | static int generic_activate(void) { | |
29601377 | 926 | if(!ready) { |
29601377 | 927 | bufsize = 3 * FRAMES; |
928 | bpf = bytes_per_frame(&config->sample_format); | |
929 | D(("acquired audio device")); | |
930 | ready = 1; | |
931 | } | |
932 | return 0; | |
933 | } | |
934 | ||
572d74ba | 935 | /** @brief Network backend initialization */ |
936 | static void network_init(void) { | |
e83d0967 RK |
937 | struct addrinfo *res, *sres; |
938 | static const struct addrinfo pref = { | |
939 | 0, | |
940 | PF_INET, | |
941 | SOCK_DGRAM, | |
942 | IPPROTO_UDP, | |
943 | 0, | |
944 | 0, | |
945 | 0, | |
946 | 0 | |
947 | }; | |
948 | static const struct addrinfo prefbind = { | |
949 | AI_PASSIVE, | |
950 | PF_INET, | |
951 | SOCK_DGRAM, | |
952 | IPPROTO_UDP, | |
953 | 0, | |
954 | 0, | |
955 | 0, | |
956 | 0 | |
957 | }; | |
958 | static const int one = 1; | |
24d0936b RK |
959 | int sndbuf, target_sndbuf = 131072; |
960 | socklen_t len; | |
e83d0967 | 961 | char *sockname, *ssockname; |
572d74ba | 962 | |
963 | res = get_address(&config->broadcast, &pref, &sockname); | |
964 | if(!res) exit(-1); | |
965 | if(config->broadcast_from.n) { | |
966 | sres = get_address(&config->broadcast_from, &prefbind, &ssockname); | |
967 | if(!sres) exit(-1); | |
968 | } else | |
969 | sres = 0; | |
970 | if((bfd = socket(res->ai_family, | |
971 | res->ai_socktype, | |
972 | res->ai_protocol)) < 0) | |
973 | fatal(errno, "error creating broadcast socket"); | |
974 | if(setsockopt(bfd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0) | |
975 | fatal(errno, "error setting SO_BROADCAST on broadcast socket"); | |
976 | len = sizeof sndbuf; | |
977 | if(getsockopt(bfd, SOL_SOCKET, SO_SNDBUF, | |
978 | &sndbuf, &len) < 0) | |
979 | fatal(errno, "error getting SO_SNDBUF"); | |
980 | if(target_sndbuf > sndbuf) { | |
981 | if(setsockopt(bfd, SOL_SOCKET, SO_SNDBUF, | |
982 | &target_sndbuf, sizeof target_sndbuf) < 0) | |
983 | error(errno, "error setting SO_SNDBUF to %d", target_sndbuf); | |
984 | else | |
985 | info("changed socket send buffer size from %d to %d", | |
986 | sndbuf, target_sndbuf); | |
987 | } else | |
988 | info("default socket send buffer is %d", | |
989 | sndbuf); | |
990 | /* We might well want to set additional broadcast- or multicast-related | |
991 | * options here */ | |
992 | if(sres && bind(bfd, sres->ai_addr, sres->ai_addrlen) < 0) | |
993 | fatal(errno, "error binding broadcast socket to %s", ssockname); | |
994 | if(connect(bfd, res->ai_addr, res->ai_addrlen) < 0) | |
995 | fatal(errno, "error connecting broadcast socket to %s", sockname); | |
996 | /* Select an SSRC */ | |
997 | gcry_randomize(&rtp_id, sizeof rtp_id, GCRY_STRONG_RANDOM); | |
998 | info("selected network backend, sending to %s", sockname); | |
999 | if(config->sample_format.byte_format != AO_FMT_BIG) { | |
1000 | info("forcing big-endian sample format"); | |
1001 | config->sample_format.byte_format = AO_FMT_BIG; | |
1002 | } | |
1003 | } | |
1004 | ||
7f9d5847 | 1005 | /** @brief Play over the network */ |
1006 | static size_t network_play(size_t frames) { | |
3c68b773 | 1007 | struct rtp_header header; |
1008 | struct iovec vec[2]; | |
1009 | size_t bytes = frames * bpf, written_frames; | |
1010 | int written_bytes; | |
1011 | /* We transmit using RTP (RFC3550) and attempt to conform to the internet | |
1012 | * AVT profile (RFC3551). */ | |
1013 | ||
1014 | if(idled) { | |
1015 | /* There may have been a gap. Fix up the RTP time accordingly. */ | |
1016 | struct timeval now; | |
1017 | uint64_t delta; | |
1018 | uint64_t target_rtp_time; | |
1019 | ||
1020 | /* Find the current time */ | |
1021 | xgettimeofday(&now, 0); | |
1022 | /* Find the number of microseconds elapsed since rtp_time=0 */ | |
1023 | delta = tvsub_us(now, rtp_time_0); | |
1024 | assert(delta <= UINT64_MAX / 88200); | |
1025 | target_rtp_time = (delta * playing->format.rate | |
1026 | * playing->format.channels) / 1000000; | |
1027 | /* Overflows at ~6 years uptime with 44100Hz stereo */ | |
1028 | ||
1029 | /* rtp_time is the number of samples we've played. NB that we play | |
1030 | * RTP_AHEAD_MS ahead of ourselves, so it may legitimately be ahead of | |
1031 | * the value we deduce from time comparison. | |
1032 | * | |
1033 | * Suppose we have 1s track started at t=0, and another track begins to | |
1034 | * play at t=2s. Suppose RTP_AHEAD_MS=1000 and 44100Hz stereo. In that | |
1035 | * case we'll send 1s of audio as fast as we can, giving rtp_time=88200. | |
1036 | * rtp_time stops at this point. | |
1037 | * | |
1038 | * At t=2s we'll have calculated target_rtp_time=176400. In this case we | |
1039 | * set rtp_time=176400 and the player can correctly conclude that it | |
1040 | * should leave 1s between the tracks. | |
1041 | * | |
1042 | * Suppose instead that the second track arrives at t=0.5s, and that | |
1043 | * we've managed to transmit the whole of the first track already. We'll | |
1044 | * have target_rtp_time=44100. | |
1045 | * | |
1046 | * The desired behaviour is to play the second track back to back with | |
1047 | * first. In this case therefore we do not modify rtp_time. | |
1048 | * | |
1049 | * Is it ever right to reduce rtp_time? No; for that would imply | |
1050 | * transmitting packets with overlapping timestamp ranges, which does not | |
1051 | * make sense. | |
1052 | */ | |
1053 | if(target_rtp_time > rtp_time) { | |
1054 | /* More time has elapsed than we've transmitted samples. That implies | |
1055 | * we've been 'sending' silence. */ | |
1056 | info("advancing rtp_time by %"PRIu64" samples", | |
1057 | target_rtp_time - rtp_time); | |
1058 | rtp_time = target_rtp_time; | |
1059 | } else if(target_rtp_time < rtp_time) { | |
1060 | const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS | |
1061 | * config->sample_format.rate | |
1062 | * config->sample_format.channels | |
1063 | / 1000); | |
1064 | ||
1065 | if(target_rtp_time + samples_ahead < rtp_time) { | |
1066 | info("reversing rtp_time by %"PRIu64" samples", | |
1067 | rtp_time - target_rtp_time); | |
1068 | } | |
1069 | } | |
1070 | } | |
1071 | header.vpxcc = 2 << 6; /* V=2, P=0, X=0, CC=0 */ | |
1072 | header.seq = htons(rtp_seq++); | |
1073 | header.timestamp = htonl((uint32_t)rtp_time); | |
1074 | header.ssrc = rtp_id; | |
1075 | header.mpt = (idled ? 0x80 : 0x00) | 10; | |
1076 | /* 10 = L16 = 16-bit x 2 x 44100KHz. We ought to deduce this value from | |
1077 | * the sample rate (in a library somewhere so that configuration.c can rule | |
1078 | * out invalid rates). | |
1079 | */ | |
1080 | idled = 0; | |
1081 | if(bytes > NETWORK_BYTES - sizeof header) { | |
1082 | bytes = NETWORK_BYTES - sizeof header; | |
1083 | /* Always send a whole number of frames */ | |
1084 | bytes -= bytes % bpf; | |
1085 | } | |
1086 | /* "The RTP clock rate used for generating the RTP timestamp is independent | |
1087 | * of the number of channels and the encoding; it equals the number of | |
1088 | * sampling periods per second. For N-channel encodings, each sampling | |
1089 | * period (say, 1/8000 of a second) generates N samples. (This terminology | |
1090 | * is standard, but somewhat confusing, as the total number of samples | |
1091 | * generated per second is then the sampling rate times the channel | |
1092 | * count.)" | |
1093 | */ | |
1094 | vec[0].iov_base = (void *)&header; | |
1095 | vec[0].iov_len = sizeof header; | |
1096 | vec[1].iov_base = playing->buffer + playing->start; | |
1097 | vec[1].iov_len = bytes; | |
1098 | do { | |
1099 | written_bytes = writev(bfd, vec, 2); | |
1100 | } while(written_bytes < 0 && errno == EINTR); | |
1101 | if(written_bytes < 0) { | |
1102 | error(errno, "error transmitting audio data"); | |
1103 | ++audio_errors; | |
1104 | if(audio_errors == 10) | |
1105 | fatal(0, "too many audio errors"); | |
1106 | return 0; | |
1107 | } else | |
1108 | audio_errors /= 2; | |
1109 | written_bytes -= sizeof (struct rtp_header); | |
1110 | written_frames = written_bytes / bpf; | |
1111 | /* Advance RTP's notion of the time */ | |
1112 | rtp_time += written_frames * playing->format.channels; | |
1113 | return written_frames; | |
7f9d5847 | 1114 | } |
1115 | ||
6ba5f1ea | 1116 | static int bfd_slot; |
1117 | ||
1118 | /** @brief Set up poll array for network play */ | |
1119 | static void network_beforepoll(void) { | |
1120 | struct timeval now; | |
1121 | uint64_t target_us; | |
1122 | uint64_t target_rtp_time; | |
1123 | const int64_t samples_ahead = ((uint64_t)RTP_AHEAD_MS | |
1124 | * config->sample_format.rate | |
1125 | * config->sample_format.channels | |
1126 | / 1000); | |
1127 | ||
1128 | /* If we're starting then initialize the base time */ | |
1129 | if(!rtp_time) | |
1130 | xgettimeofday(&rtp_time_0, 0); | |
1131 | /* We send audio data whenever we get RTP_AHEAD seconds or more | |
1132 | * behind */ | |
1133 | xgettimeofday(&now, 0); | |
1134 | target_us = tvsub_us(now, rtp_time_0); | |
1135 | assert(target_us <= UINT64_MAX / 88200); | |
1136 | target_rtp_time = (target_us * config->sample_format.rate | |
1137 | * config->sample_format.channels) | |
1138 | / 1000000; | |
1139 | if((int64_t)(rtp_time - target_rtp_time) < samples_ahead) | |
1140 | bfd_slot = addfd(bfd, POLLOUT); | |
1141 | } | |
1142 | ||
d62d6873 | 1143 | /** @brief Process poll() results for network play */ |
1144 | static int network_afterpoll(void) { | |
1145 | if(bfd_slot != -1) { | |
1146 | if(fds[bfd_slot].revents & (POLLOUT | POLLERR)) | |
1147 | play(3 * FRAMES); | |
1148 | return 0; | |
1149 | } else | |
1150 | return 1; | |
1151 | } | |
1152 | ||
572d74ba | 1153 | /** @brief Table of speaker backends */ |
1154 | static const struct speaker_backend backends[] = { | |
1155 | #if API_ALSA | |
1156 | { | |
1157 | BACKEND_ALSA, | |
0763e1f4 | 1158 | 0, |
29601377 | 1159 | alsa_init, |
b5a99ad0 | 1160 | alsa_activate, |
7f9d5847 | 1161 | alsa_play, |
6ba5f1ea | 1162 | alsa_deactivate, |
d62d6873 | 1163 | alsa_beforepoll, |
1164 | alsa_afterpoll | |
572d74ba | 1165 | }, |
1166 | #endif | |
1167 | { | |
1168 | BACKEND_COMMAND, | |
0763e1f4 | 1169 | FIXED_FORMAT, |
29601377 | 1170 | command_init, |
b5a99ad0 | 1171 | generic_activate, |
7f9d5847 | 1172 | command_play, |
6ba5f1ea | 1173 | 0, /* deactivate */ |
d62d6873 | 1174 | command_beforepoll, |
1175 | command_afterpoll | |
572d74ba | 1176 | }, |
1177 | { | |
1178 | BACKEND_NETWORK, | |
0763e1f4 | 1179 | FIXED_FORMAT, |
29601377 | 1180 | network_init, |
b5a99ad0 | 1181 | generic_activate, |
7f9d5847 | 1182 | network_play, |
6ba5f1ea | 1183 | 0, /* deactivate */ |
d62d6873 | 1184 | network_beforepoll, |
1185 | network_afterpoll | |
572d74ba | 1186 | }, |
d62d6873 | 1187 | { -1, 0, 0, 0, 0, 0, 0, 0 } /* end of list */ |
572d74ba | 1188 | }; |
1189 | ||
1190 | int main(int argc, char **argv) { | |
6ba5f1ea | 1191 | int n, fd, stdin_slot, poke, timeout; |
572d74ba | 1192 | struct track *t; |
1193 | struct speaker_message sm; | |
460b9539 | 1194 | |
1195 | set_progname(argv); | |
460b9539 | 1196 | if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale"); |
1197 | while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) { | |
1198 | switch(n) { | |
1199 | case 'h': help(); | |
1200 | case 'V': version(); | |
1201 | case 'c': configfile = optarg; break; | |
1202 | case 'd': debugging = 1; break; | |
1203 | case 'D': debugging = 0; break; | |
1204 | default: fatal(0, "invalid option"); | |
1205 | } | |
1206 | } | |
1207 | if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1; | |
1208 | /* If stderr is a TTY then log there, otherwise to syslog. */ | |
1209 | if(!isatty(2)) { | |
1210 | openlog(progname, LOG_PID, LOG_DAEMON); | |
1211 | log_default = &log_syslog; | |
1212 | } | |
1213 | if(config_read()) fatal(0, "cannot read configuration"); | |
1214 | /* ignore SIGPIPE */ | |
1215 | signal(SIGPIPE, SIG_IGN); | |
9d5da576 | 1216 | /* reap kids */ |
1217 | signal(SIGCHLD, reap); | |
460b9539 | 1218 | /* set nice value */ |
1219 | xnice(config->nice_speaker); | |
1220 | /* change user */ | |
1221 | become_mortal(); | |
1222 | /* make sure we're not root, whatever the config says */ | |
1223 | if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root"); | |
572d74ba | 1224 | /* identify the backend used to play */ |
1225 | for(n = 0; backends[n].backend != -1; ++n) | |
1226 | if(backends[n].backend == config->speaker_backend) | |
1227 | break; | |
1228 | if(backends[n].backend == -1) | |
1229 | fatal(0, "unsupported backend %d", config->speaker_backend); | |
1230 | backend = &backends[n]; | |
1231 | /* backend-specific initialization */ | |
1232 | backend->init(); | |
460b9539 | 1233 | while(getppid() != 1) { |
1234 | fdno = 0; | |
1235 | /* Always ready for commands from the main server. */ | |
1236 | stdin_slot = addfd(0, POLLIN); | |
1237 | /* Try to read sample data for the currently playing track if there is | |
1238 | * buffer space. */ | |
1239 | if(playing && !playing->eof && playing->used < playing->size) { | |
1240 | playing->slot = addfd(playing->fd, POLLIN); | |
1241 | } else if(playing) | |
1242 | playing->slot = -1; | |
1243 | /* If forceplay is set then wait until it succeeds before waiting on the | |
1244 | * sound device. */ | |
9d5da576 | 1245 | alsa_slots = -1; |
e83d0967 RK |
1246 | cmdfd_slot = -1; |
1247 | bfd_slot = -1; | |
1248 | /* By default we will wait up to a second before thinking about current | |
1249 | * state. */ | |
1250 | timeout = 1000; | |
6ba5f1ea | 1251 | /* We'll break the poll as soon as the underlying sound device is ready for |
1252 | * more data */ | |
1253 | if(ready && !forceplay) | |
1254 | backend->beforepoll(); | |
460b9539 | 1255 | /* If any other tracks don't have a full buffer, try to read sample data |
1256 | * from them. */ | |
1257 | for(t = tracks; t; t = t->next) | |
1258 | if(t != playing) { | |
1259 | if(!t->eof && t->used < t->size) { | |
9d5da576 | 1260 | t->slot = addfd(t->fd, POLLIN | POLLHUP); |
460b9539 | 1261 | } else |
1262 | t->slot = -1; | |
1263 | } | |
e83d0967 RK |
1264 | /* Wait for something interesting to happen */ |
1265 | n = poll(fds, fdno, timeout); | |
460b9539 | 1266 | if(n < 0) { |
1267 | if(errno == EINTR) continue; | |
1268 | fatal(errno, "error calling poll"); | |
1269 | } | |
1270 | /* Play some sound before doing anything else */ | |
d62d6873 | 1271 | poke = backend->afterpoll(); |
e83d0967 | 1272 | if(poke) { |
460b9539 | 1273 | /* Some attempt to play must have failed */ |
1274 | if(playing && !paused) | |
1275 | play(forceplay); | |
1276 | else | |
1277 | forceplay = 0; /* just in case */ | |
1278 | } | |
1279 | /* Perhaps we have a command to process */ | |
1280 | if(fds[stdin_slot].revents & POLLIN) { | |
1281 | n = speaker_recv(0, &sm, &fd); | |
1282 | if(n > 0) | |
1283 | switch(sm.type) { | |
1284 | case SM_PREPARE: | |
1285 | D(("SM_PREPARE %s %d", sm.id, fd)); | |
1286 | if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor"); | |
1287 | t = findtrack(sm.id, 1); | |
1288 | acquire(t, fd); | |
1289 | break; | |
1290 | case SM_PLAY: | |
1291 | D(("SM_PLAY %s %d", sm.id, fd)); | |
1292 | if(playing) fatal(0, "got SM_PLAY but already playing something"); | |
1293 | t = findtrack(sm.id, 1); | |
1294 | if(fd != -1) acquire(t, fd); | |
1295 | playing = t; | |
8023f60b | 1296 | play(bufsize); |
460b9539 | 1297 | report(); |
1298 | break; | |
1299 | case SM_PAUSE: | |
1300 | D(("SM_PAUSE")); | |
1301 | paused = 1; | |
1302 | report(); | |
1303 | break; | |
1304 | case SM_RESUME: | |
1305 | D(("SM_RESUME")); | |
1306 | if(paused) { | |
1307 | paused = 0; | |
1308 | if(playing) | |
8023f60b | 1309 | play(bufsize); |
460b9539 | 1310 | } |
1311 | report(); | |
1312 | break; | |
1313 | case SM_CANCEL: | |
1314 | D(("SM_CANCEL %s", sm.id)); | |
1315 | t = removetrack(sm.id); | |
1316 | if(t) { | |
1317 | if(t == playing) { | |
1318 | sm.type = SM_FINISHED; | |
1319 | strcpy(sm.id, playing->id); | |
1320 | speaker_send(1, &sm, 0); | |
1321 | playing = 0; | |
1322 | } | |
1323 | destroy(t); | |
1324 | } else | |
1325 | error(0, "SM_CANCEL for unknown track %s", sm.id); | |
1326 | report(); | |
1327 | break; | |
1328 | case SM_RELOAD: | |
1329 | D(("SM_RELOAD")); | |
1330 | if(config_read()) error(0, "cannot read configuration"); | |
1331 | info("reloaded configuration"); | |
1332 | break; | |
1333 | default: | |
1334 | error(0, "unknown message type %d", sm.type); | |
1335 | } | |
1336 | } | |
1337 | /* Read in any buffered data */ | |
1338 | for(t = tracks; t; t = t->next) | |
9d5da576 | 1339 | if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP))) |
460b9539 | 1340 | fill(t); |
1341 | /* We might be able to play now */ | |
9d5da576 | 1342 | if(ready && forceplay && playing && !paused) |
460b9539 | 1343 | play(forceplay); |
1344 | /* Maybe we finished playing a track somewhere in the above */ | |
1345 | maybe_finished(); | |
1346 | /* If we don't need the sound device for now then close it for the benefit | |
1347 | * of anyone else who wants it. */ | |
9d5da576 | 1348 | if((!playing || paused) && ready) |
460b9539 | 1349 | idle(); |
1350 | /* If we've not reported out state for a second do so now. */ | |
1351 | if(time(0) > last_report) | |
1352 | report(); | |
1353 | } | |
1354 | info("stopped (parent terminated)"); | |
1355 | exit(0); | |
1356 | } | |
1357 | ||
1358 | /* | |
1359 | Local Variables: | |
1360 | c-basic-offset:2 | |
1361 | comment-column:40 | |
1362 | fill-column:79 | |
1363 | indent-tabs-mode:nil | |
1364 | End: | |
1365 | */ |