chiark / gitweb /
1eb3a24043419ba3063d61739d50d8a2b7429943
[disorder] / server / speaker.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2005, 2006, 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
21 /* This program deliberately does not use the garbage collector even though it
22  * might be convenient to do so.  This is for two reasons.  Firstly some libao
23  * drivers are implemented using threads and we do not want to have to deal
24  * with potential interactions between threading and garbage collection.
25  * Secondly this process needs to be able to respond quickly and this is not
26  * compatible with the collector hanging the program even relatively
27  * briefly. */
28
29 #include <config.h>
30 #include "types.h"
31
32 #include <getopt.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <locale.h>
36 #include <syslog.h>
37 #include <unistd.h>
38 #include <errno.h>
39 #include <ao/ao.h>
40 #include <string.h>
41 #include <assert.h>
42 #include <sys/select.h>
43 #include <sys/wait.h>
44 #include <time.h>
45 #include <fcntl.h>
46 #include <poll.h>
47
48 #include "configuration.h"
49 #include "syscalls.h"
50 #include "log.h"
51 #include "defs.h"
52 #include "mem.h"
53 #include "speaker.h"
54 #include "user.h"
55
56 #if API_ALSA
57 #include <alsa/asoundlib.h>
58 #endif
59
60 #define BUFFER_SECONDS 5                /* How many seconds of input to
61                                          * buffer. */
62
63 #define FRAMES 4096                     /* Frame batch size */
64
65 #define NFDS 256                        /* Max FDs to poll for */
66
67 /* Known tracks are kept in a linked list.  We don't normally to have
68  * more than two - maybe three at the outside. */
69 static struct track {
70   struct track *next;                   /* next track */
71   int fd;                               /* input FD */
72   char id[24];                          /* ID */
73   size_t start, used;                   /* start + bytes used */
74   int eof;                              /* input is at EOF */
75   int got_format;                       /* got format yet? */
76   ao_sample_format format;              /* sample format */
77   unsigned long long played;            /* number of frames played */
78   char *buffer;                         /* sample buffer */
79   size_t size;                          /* sample buffer size */
80   int slot;                             /* poll array slot */
81 } *tracks, *playing;                    /* all tracks + playing track */
82
83 static time_t last_report;              /* when we last reported */
84 static int paused;                      /* pause status */
85 static ao_sample_format pcm_format;     /* current format if aodev != 0 */
86 static size_t bpf;                      /* bytes per frame */
87 static struct pollfd fds[NFDS];         /* if we need more than that */
88 static int fdno;                        /* fd number */
89 static size_t bufsize;                  /* buffer size */
90 #if API_ALSA
91 static snd_pcm_t *pcm;                  /* current pcm handle */
92 static snd_pcm_uframes_t last_pcm_bufsize; /* last seen buffer size */
93 #endif
94 static int ready;                       /* ready to send audio */
95 static int forceplay;                   /* frames to force play */
96 static int kidfd = -1;                  /* child process input */
97
98 static const struct option options[] = {
99   { "help", no_argument, 0, 'h' },
100   { "version", no_argument, 0, 'V' },
101   { "config", required_argument, 0, 'c' },
102   { "debug", no_argument, 0, 'd' },
103   { "no-debug", no_argument, 0, 'D' },
104   { 0, 0, 0, 0 }
105 };
106
107 /* Display usage message and terminate. */
108 static void help(void) {
109   xprintf("Usage:\n"
110           "  disorder-speaker [OPTIONS]\n"
111           "Options:\n"
112           "  --help, -h              Display usage message\n"
113           "  --version, -V           Display version number\n"
114           "  --config PATH, -c PATH  Set configuration file\n"
115           "  --debug, -d             Turn on debugging\n"
116           "\n"
117           "Speaker process for DisOrder.  Not intended to be run\n"
118           "directly.\n");
119   xfclose(stdout);
120   exit(0);
121 }
122
123 /* Display version number and terminate. */
124 static void version(void) {
125   xprintf("disorder-speaker version %s\n", disorder_version_string);
126   xfclose(stdout);
127   exit(0);
128 }
129
130 /* Return the number of bytes per frame in FORMAT. */
131 static size_t bytes_per_frame(const ao_sample_format *format) {
132   return format->channels * format->bits / 8;
133 }
134
135 /* Find track ID, maybe creating it if not found. */
136 static struct track *findtrack(const char *id, int create) {
137   struct track *t;
138
139   D(("findtrack %s %d", id, create));
140   for(t = tracks; t && strcmp(id, t->id); t = t->next)
141     ;
142   if(!t && create) {
143     t = xmalloc(sizeof *t);
144     t->next = tracks;
145     strcpy(t->id, id);
146     t->fd = -1;
147     tracks = t;
148     /* The initial input buffer will be the sample format. */
149     t->buffer = (void *)&t->format;
150     t->size = sizeof t->format;
151   }
152   return t;
153 }
154
155 /* Remove track ID (but do not destroy it). */
156 static struct track *removetrack(const char *id) {
157   struct track *t, **tt;
158
159   D(("removetrack %s", id));
160   for(tt = &tracks; (t = *tt) && strcmp(id, t->id); tt = &t->next)
161     ;
162   if(t)
163     *tt = t->next;
164   return t;
165 }
166
167 /* Destroy a track. */
168 static void destroy(struct track *t) {
169   D(("destroy %s", t->id));
170   if(t->fd != -1) xclose(t->fd);
171   if(t->buffer != (void *)&t->format) free(t->buffer);
172   free(t);
173 }
174
175 /* Notice a new FD. */
176 static void acquire(struct track *t, int fd) {
177   D(("acquire %s %d", t->id, fd));
178   if(t->fd != -1)
179     xclose(t->fd);
180   t->fd = fd;
181   nonblock(fd);
182 }
183
184 /* Read data into a sample buffer.  Return 0 on success, -1 on EOF. */
185 static int fill(struct track *t) {
186   size_t where, left;
187   int n;
188
189   D(("fill %s: eof=%d used=%zu size=%zu  got_format=%d",
190      t->id, t->eof, t->used, t->size, t->got_format));
191   if(t->eof) return -1;
192   if(t->used < t->size) {
193     /* there is room left in the buffer */
194     where = (t->start + t->used) % t->size;
195     if(t->got_format) {
196       /* We are reading audio data, get as much as we can */
197       if(where >= t->start) left = t->size - where;
198       else left = t->start - where;
199     } else
200       /* We are still waiting for the format, only get that */
201       left = sizeof (ao_sample_format) - t->used;
202     do {
203       n = read(t->fd, t->buffer + where, left);
204     } while(n < 0 && errno == EINTR);
205     if(n < 0) {
206       if(errno != EAGAIN) fatal(errno, "error reading sample stream");
207       return 0;
208     }
209     if(n == 0) {
210       D(("fill %s: eof detected", t->id));
211       t->eof = 1;
212       return -1;
213     }
214     t->used += n;
215     if(!t->got_format && t->used >= sizeof (ao_sample_format)) {
216       assert(t->used == sizeof (ao_sample_format));
217       /* Check that our assumptions are met. */
218       if(t->format.bits & 7)
219         fatal(0, "bits per sample not a multiple of 8");
220       /* Make a new buffer for audio data. */
221       t->size = bytes_per_frame(&t->format) * t->format.rate * BUFFER_SECONDS;
222       t->buffer = xmalloc(t->size);
223       t->used = 0;
224       t->got_format = 1;
225       D(("got format for %s", t->id));
226     }
227   }
228   return 0;
229 }
230
231 /* Return true if A and B denote identical libao formats, else false. */
232 static int formats_equal(const ao_sample_format *a,
233                          const ao_sample_format *b) {
234   return (a->bits == b->bits
235           && a->rate == b->rate
236           && a->channels == b->channels
237           && a->byte_format == b->byte_format);
238 }
239
240 /* Close the sound device. */
241 static void idle(void) {
242   D(("idle"));
243 #if API_ALSA
244   if(pcm) {
245     int  err;
246
247     if((err = snd_pcm_nonblock(pcm, 0)) < 0)
248       fatal(0, "error calling snd_pcm_nonblock: %d", err);
249     D(("draining pcm"));
250     snd_pcm_drain(pcm);
251     D(("closing pcm"));
252     snd_pcm_close(pcm);
253     pcm = 0;
254     forceplay = 0;
255     D(("released audio device"));
256   }
257 #endif
258   ready = 0;
259 }
260
261 /* Abandon the current track */
262 static void abandon(void) {
263   struct speaker_message sm;
264
265   D(("abandon"));
266   memset(&sm, 0, sizeof sm);
267   sm.type = SM_FINISHED;
268   strcpy(sm.id, playing->id);
269   speaker_send(1, &sm, 0);
270   removetrack(playing->id);
271   destroy(playing);
272   playing = 0;
273   forceplay = 0;
274 }
275
276 #if API_ALSA
277 static void log_params(snd_pcm_hw_params_t *hwparams,
278                        snd_pcm_sw_params_t *swparams) {
279   snd_pcm_uframes_t f;
280   unsigned u;
281
282   return;                               /* too verbose */
283   if(hwparams) {
284     /* TODO */
285   }
286   if(swparams) {
287     snd_pcm_sw_params_get_silence_size(swparams, &f);
288     info("sw silence_size=%lu", (unsigned long)f);
289     snd_pcm_sw_params_get_silence_threshold(swparams, &f);
290     info("sw silence_threshold=%lu", (unsigned long)f);
291     snd_pcm_sw_params_get_sleep_min(swparams, &u);
292     info("sw sleep_min=%lu", (unsigned long)u);
293     snd_pcm_sw_params_get_start_threshold(swparams, &f);
294     info("sw start_threshold=%lu", (unsigned long)f);
295     snd_pcm_sw_params_get_stop_threshold(swparams, &f);
296     info("sw stop_threshold=%lu", (unsigned long)f);
297     snd_pcm_sw_params_get_xfer_align(swparams, &f);
298     info("sw xfer_align=%lu", (unsigned long)f);
299   }
300 }
301 #endif
302
303 static void soxargs(const char ***pp, char **qq, ao_sample_format *ao)
304 {
305   int n;
306
307   *(*pp)++ = "-t.raw";
308   *(*pp)++ = "-s";
309   *(*pp)++ = *qq; n = sprintf(*qq, "-r%d", ao->rate); *qq += n + 1;
310   switch(ao->byte_format) {
311     case AO_FMT_NATIVE: break;
312     case AO_FMT_BIG: *(*pp)++ = "-B";
313     case AO_FMT_LITTLE: *(*pp)++ = "-L";
314   }
315   *(*pp)++ = *qq; n = sprintf(*qq, "-%d", ao->bits/8); *qq += n + 1;
316   *(*pp)++ = *qq; n = sprintf(*qq, "-c%d", ao->channels); *qq += n + 1;
317 }
318
319 /* Make sure the sound device is open and has the right sample format.  Return
320  * 0 on success and -1 on error. */
321 static int activate(void) {
322   /* If we don't know the format yet we cannot start. */
323   if(!playing->got_format) {
324     D((" - not got format for %s", playing->id));
325     return -1;
326   }
327   if(kidfd >= 0) {
328     if(!formats_equal(&playing->format, &config->sample_format)) {
329       char argbuf[1024], *q = argbuf;
330       const char *av[18], **pp = av;
331       int soxpipe[2];
332       pid_t soxkid;
333       *pp++ = "sox";
334       soxargs(&pp, &q, &playing->format);
335       *pp++ = "-";
336       soxargs(&pp, &q, &config->sample_format);
337       *pp++ = "-";
338       *pp++ = 0;
339       if(debugging) {
340         for(pp = av; *pp; pp++)
341           D(("sox arg[%d] = %s", pp - av, *pp));
342         D(("end args"));
343       }
344       xpipe(soxpipe);
345       soxkid = xfork();
346       if(soxkid == 0) {
347         xdup2(playing->fd, 0);
348         xdup2(soxpipe[1], 1);
349         fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK);
350         close(soxpipe[0]);
351         close(soxpipe[1]);
352         close(playing->fd);
353         execvp("sox", (char **)av);
354         _exit(1);
355       }
356       D(("forking sox for format conversion (kid = %d)", soxkid));
357       close(playing->fd);
358       close(soxpipe[1]);
359       playing->fd = soxpipe[0];
360       playing->format = config->sample_format;
361       ready = 0;
362     }
363     if(!ready) {
364       pcm_format = config->sample_format;
365       bufsize = 3 * FRAMES;
366       bpf = bytes_per_frame(&config->sample_format);
367       D(("acquired audio device"));
368       ready = 1;
369     }
370     return 0;
371   }
372 #if API_ALSA
373   /* If we need to change format then close the current device. */
374   if(pcm && !formats_equal(&playing->format, &pcm_format))
375      idle();
376   if(!pcm) {
377     snd_pcm_hw_params_t *hwparams;
378     snd_pcm_sw_params_t *swparams;
379     snd_pcm_uframes_t pcm_bufsize;
380     int err;
381     int sample_format = 0;
382     unsigned rate;
383
384     D(("snd_pcm_open"));
385     if((err = snd_pcm_open(&pcm,
386                            config->device,
387                            SND_PCM_STREAM_PLAYBACK,
388                            SND_PCM_NONBLOCK))) {
389       error(0, "error from snd_pcm_open: %d", err);
390       goto error;
391     }
392     snd_pcm_hw_params_alloca(&hwparams);
393     D(("set up hw params"));
394     if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
395       fatal(0, "error from snd_pcm_hw_params_any: %d", err);
396     if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
397                                            SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
398       fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
399     switch(playing->format.bits) {
400     case 8:
401       sample_format = SND_PCM_FORMAT_S8;
402       break;
403     case 16:
404       switch(playing->format.byte_format) {
405       case AO_FMT_NATIVE: sample_format = SND_PCM_FORMAT_S16; break;
406       case AO_FMT_LITTLE: sample_format = SND_PCM_FORMAT_S16_LE; break;
407       case AO_FMT_BIG: sample_format = SND_PCM_FORMAT_S16_BE; break;
408         error(0, "unrecognized byte format %d", playing->format.byte_format);
409         goto fatal;
410       }
411       break;
412     default:
413       error(0, "unsupported sample size %d", playing->format.bits);
414       goto fatal;
415     }
416     if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
417                                            sample_format)) < 0) {
418       error(0, "error from snd_pcm_hw_params_set_format (%d): %d",
419             sample_format, err);
420       goto fatal;
421     }
422     rate = playing->format.rate;
423     if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0) {
424       error(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
425             playing->format.rate, err);
426       goto fatal;
427     }
428     if(rate != (unsigned)playing->format.rate)
429       info("want rate %d, got %u", playing->format.rate, rate);
430     if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
431                                              playing->format.channels)) < 0) {
432       error(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
433             playing->format.channels, err);
434       goto fatal;
435     }
436     bufsize = 3 * FRAMES;
437     pcm_bufsize = bufsize;
438     if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
439                                                      &pcm_bufsize)) < 0)
440       fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
441             3 * FRAMES, err);
442     if(pcm_bufsize != 3 * FRAMES && pcm_bufsize != last_pcm_bufsize)
443       info("asked for PCM buffer of %d frames, got %d",
444            3 * FRAMES, (int)pcm_bufsize);
445     last_pcm_bufsize = pcm_bufsize;
446     if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
447       fatal(0, "error calling snd_pcm_hw_params: %d", err);
448     D(("set up sw params"));
449     snd_pcm_sw_params_alloca(&swparams);
450     if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
451       fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
452     if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, FRAMES)) < 0)
453       fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
454             FRAMES, err);
455     if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
456       fatal(0, "error calling snd_pcm_sw_params: %d", err);
457     pcm_format = playing->format;
458     bpf = bytes_per_frame(&pcm_format);
459     D(("acquired audio device"));
460     log_params(hwparams, swparams);
461     ready = 1;
462   }
463   return 0;
464 fatal:
465   abandon();
466 error:
467   /* We assume the error is temporary and that we'll retry in a bit. */
468   if(pcm) {
469     snd_pcm_close(pcm);
470     pcm = 0;
471   }
472 #endif
473   return -1;
474 }
475
476 /* Check to see whether the current track has finished playing */
477 static void maybe_finished(void) {
478   if(playing
479      && playing->eof
480      && (!playing->got_format
481          || playing->used < bytes_per_frame(&playing->format)))
482     abandon();
483 }
484
485 static void fork_kid(void) {
486   pid_t kid;
487   int pfd[2];
488   if(kidfd != -1) close(kidfd);
489   xpipe(pfd);
490   kid = xfork();
491   if(!kid) {
492     xdup2(pfd[0], 0);
493     close(pfd[0]);
494     close(pfd[1]);
495     execl("/bin/sh", "sh", "-c", config->speaker_command, (char *)0);
496     fatal(errno, "error execing /bin/sh");
497   }
498   close(pfd[0]);
499   kidfd = pfd[1];
500   D(("forked kid %d, fd = %d", kid, kidfd));
501 }
502
503 static void play(size_t frames) {
504   size_t avail_bytes, written_frames;
505   ssize_t written_bytes;
506
507   if(activate()) {
508     if(playing)
509       forceplay = frames;
510     else
511       forceplay = 0;                    /* Must have called abandon() */
512     return;
513   }
514   D(("play: play %zu/%zu%s %dHz %db %dc",  frames, playing->used / bpf,
515      playing->eof ? " EOF" : "",
516      playing->format.rate,
517      playing->format.bits,
518      playing->format.channels));
519   /* If we haven't got enough bytes yet wait until we have.  Exception: when
520    * we are at eof. */
521   if(playing->used < frames * bpf && !playing->eof) {
522     forceplay = frames;
523     return;
524   }
525   /* We have got enough data so don't force play again */
526   forceplay = 0;
527   /* Figure out how many frames there are available to write */
528   if(playing->start + playing->used > playing->size)
529     avail_bytes = playing->size - playing->start;
530   else
531     avail_bytes = playing->used;
532
533   if(kidfd == -1) {
534 #if API_ALSA
535     snd_pcm_sframes_t pcm_written_frames;
536     size_t avail_frames;
537     int err;
538
539     avail_frames = avail_bytes / bpf;
540     if(avail_frames > frames)
541       avail_frames = frames;
542     if(!avail_frames)
543       return;
544     pcm_written_frames = snd_pcm_writei(pcm,
545                                         playing->buffer + playing->start,
546                                         avail_frames);
547     D(("actually play %zu frames, wrote %d",
548        avail_frames, (int)pcm_written_frames));
549     if(pcm_written_frames < 0) {
550       switch(pcm_written_frames) {
551         case -EPIPE:                        /* underrun */
552           error(0, "snd_pcm_writei reports underrun");
553           if((err = snd_pcm_prepare(pcm)) < 0)
554             fatal(0, "error calling snd_pcm_prepare: %d", err);
555           return;
556         case -EAGAIN:
557           return;
558         default:
559           fatal(0, "error calling snd_pcm_writei: %d",
560                 (int)pcm_written_frames);
561       }
562     }
563     written_frames = pcm_written_frames;
564     written_bytes = written_frames * bpf;
565 #else
566     assert(!"reached");
567 #endif
568   } else {
569     if(avail_bytes > frames * bpf)
570       avail_bytes = frames * bpf;
571     written_bytes = write(kidfd, playing->buffer + playing->start,
572                           avail_bytes);
573     D(("actually play %zu bytes, wrote %d",
574        avail_bytes, (int)written_bytes));
575     if(written_bytes < 0) {
576       switch(errno) {
577         case EPIPE:
578           error(0, "hmm, kid died; trying another");
579           fork_kid();
580           return;
581         case EAGAIN:
582           return;
583       }
584     }
585     written_frames = written_bytes / bpf; /* good enough */
586   }
587   playing->start += written_bytes;
588   playing->used -= written_bytes;
589   playing->played += written_frames;
590   /* If the pointer is at the end of the buffer (or the buffer is completely
591    * empty) wrap it back to the start. */
592   if(!playing->used || playing->start == playing->size)
593     playing->start = 0;
594   frames -= written_frames;
595 }
596
597 /* Notify the server what we're up to. */
598 static void report(void) {
599   struct speaker_message sm;
600
601   if(playing && playing->buffer != (void *)&playing->format) {
602     memset(&sm, 0, sizeof sm);
603     sm.type = paused ? SM_PAUSED : SM_PLAYING;
604     strcpy(sm.id, playing->id);
605     sm.data = playing->played / playing->format.rate;
606     speaker_send(1, &sm, 0);
607   }
608   time(&last_report);
609 }
610
611 static void reap(int __attribute__((unused)) sig) {
612   pid_t kid;
613   int st;
614
615   do
616     kid = waitpid(-1, &st, WNOHANG);
617   while(kid > 0);
618   signal(SIGCHLD, reap);
619 }
620
621 static int addfd(int fd, int events) {
622   if(fdno < NFDS) {
623     fds[fdno].fd = fd;
624     fds[fdno].events = events;
625     return fdno++;
626   } else
627     return -1;
628 }
629
630 int main(int argc, char **argv) {
631   int n, fd, stdin_slot, alsa_slots, kid_slot;
632   struct track *t;
633   struct speaker_message sm;
634 #if API_ALSA
635   int alsa_nslots = -1, err;
636 #endif
637
638   set_progname(argv);
639   mem_init(0);
640   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
641   while((n = getopt_long(argc, argv, "hVc:dD", options, 0)) >= 0) {
642     switch(n) {
643     case 'h': help();
644     case 'V': version();
645     case 'c': configfile = optarg; break;
646     case 'd': debugging = 1; break;
647     case 'D': debugging = 0; break;
648     default: fatal(0, "invalid option");
649     }
650   }
651   if(getenv("DISORDER_DEBUG_SPEAKER")) debugging = 1;
652   /* If stderr is a TTY then log there, otherwise to syslog. */
653   if(!isatty(2)) {
654     openlog(progname, LOG_PID, LOG_DAEMON);
655     log_default = &log_syslog;
656   }
657   if(config_read()) fatal(0, "cannot read configuration");
658   /* ignore SIGPIPE */
659   signal(SIGPIPE, SIG_IGN);
660   /* reap kids */
661   signal(SIGCHLD, reap);
662   /* set nice value */
663   xnice(config->nice_speaker);
664   /* change user */
665   become_mortal();
666   /* make sure we're not root, whatever the config says */
667   if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
668   info("started");
669   if(config->speaker_command)
670     fork_kid();
671   else {
672 #if API_ALSA
673     /* ok */
674 #else
675     fatal(0, "invoked speaker but no speaker_command and no known sound API");
676  #endif
677   }
678   while(getppid() != 1) {
679     fdno = 0;
680     /* Always ready for commands from the main server. */
681     stdin_slot = addfd(0, POLLIN);
682     /* Try to read sample data for the currently playing track if there is
683      * buffer space. */
684     if(playing && !playing->eof && playing->used < playing->size) {
685       playing->slot = addfd(playing->fd, POLLIN);
686     } else if(playing)
687       playing->slot = -1;
688     /* If forceplay is set then wait until it succeeds before waiting on the
689      * sound device. */
690     alsa_slots = -1;
691     kid_slot = -1;
692     if(ready && !forceplay) {
693       if(kidfd >= 0)
694         kid_slot = addfd(kidfd, POLLOUT);
695       else {
696 #if API_ALSA
697         int retry = 3;
698         
699         alsa_slots = fdno;
700         do {
701           retry = 0;
702           alsa_nslots = snd_pcm_poll_descriptors(pcm, &fds[fdno], NFDS - fdno);
703           if((alsa_nslots <= 0
704               || !(fds[alsa_slots].events & POLLOUT))
705              && snd_pcm_state(pcm) == SND_PCM_STATE_XRUN) {
706             error(0, "underrun detected after call to snd_pcm_poll_descriptors()");
707             if((err = snd_pcm_prepare(pcm)))
708               fatal(0, "error calling snd_pcm_prepare: %d", err);
709           } else
710             break;
711         } while(retry-- > 0);
712         if(alsa_nslots >= 0)
713           fdno += alsa_nslots;
714 #endif
715       }
716     }
717     /* If any other tracks don't have a full buffer, try to read sample data
718      * from them. */
719     for(t = tracks; t; t = t->next)
720       if(t != playing) {
721         if(!t->eof && t->used < t->size) {
722           t->slot = addfd(t->fd,  POLLIN | POLLHUP);
723         } else
724           t->slot = -1;
725       }
726     /* Wait up to a second before thinking about current state */
727     n = poll(fds, fdno, 1000);
728     if(n < 0) {
729       if(errno == EINTR) continue;
730       fatal(errno, "error calling poll");
731     }
732     /* Play some sound before doing anything else */
733     if(alsa_slots != -1) {
734 #if API_ALSA
735       unsigned short alsa_revents;
736       
737       if((err = snd_pcm_poll_descriptors_revents(pcm,
738                                                  &fds[alsa_slots],
739                                                  alsa_nslots,
740                                                  &alsa_revents)) < 0)
741         fatal(0, "error calling snd_pcm_poll_descriptors_revents: %d", err);
742       if(alsa_revents & (POLLOUT | POLLERR))
743         play(3 * FRAMES);
744 #endif
745     } else if(kid_slot != -1) {
746       if(fds[kid_slot].revents & (POLLOUT | POLLERR))
747         play(3 * FRAMES);
748     } else {
749       /* Some attempt to play must have failed */
750       if(playing && !paused)
751         play(forceplay);
752       else
753         forceplay = 0;                  /* just in case */
754     }
755     /* Perhaps we have a command to process */
756     if(fds[stdin_slot].revents & POLLIN) {
757       n = speaker_recv(0, &sm, &fd);
758       if(n > 0)
759         switch(sm.type) {
760         case SM_PREPARE:
761           D(("SM_PREPARE %s %d", sm.id, fd));
762           if(fd == -1) fatal(0, "got SM_PREPARE but no file descriptor");
763           t = findtrack(sm.id, 1);
764           acquire(t, fd);
765           break;
766         case SM_PLAY:
767           D(("SM_PLAY %s %d", sm.id, fd));
768           if(playing) fatal(0, "got SM_PLAY but already playing something");
769           t = findtrack(sm.id, 1);
770           if(fd != -1) acquire(t, fd);
771           playing = t;
772           play(bufsize);
773           report();
774           break;
775         case SM_PAUSE:
776           D(("SM_PAUSE"));
777           paused = 1;
778           report();
779           break;
780         case SM_RESUME:
781           D(("SM_RESUME"));
782           if(paused) {
783             paused = 0;
784             if(playing)
785               play(bufsize);
786           }
787           report();
788           break;
789         case SM_CANCEL:
790           D(("SM_CANCEL %s",  sm.id));
791           t = removetrack(sm.id);
792           if(t) {
793             if(t == playing) {
794               sm.type = SM_FINISHED;
795               strcpy(sm.id, playing->id);
796               speaker_send(1, &sm, 0);
797               playing = 0;
798             }
799             destroy(t);
800           } else
801             error(0, "SM_CANCEL for unknown track %s", sm.id);
802           report();
803           break;
804         case SM_RELOAD:
805           D(("SM_RELOAD"));
806           if(config_read()) error(0, "cannot read configuration");
807           info("reloaded configuration");
808           break;
809         default:
810           error(0, "unknown message type %d", sm.type);
811         }
812     }
813     /* Read in any buffered data */
814     for(t = tracks; t; t = t->next)
815       if(t->slot != -1 && (fds[t->slot].revents & (POLLIN | POLLHUP)))
816          fill(t);
817     /* We might be able to play now */
818     if(ready && forceplay && playing && !paused)
819       play(forceplay);
820     /* Maybe we finished playing a track somewhere in the above */
821     maybe_finished();
822     /* If we don't need the sound device for now then close it for the benefit
823      * of anyone else who wants it. */
824     if((!playing || paused) && ready)
825       idle();
826     /* If we've not reported out state for a second do so now. */
827     if(time(0) > last_report)
828       report();
829   }
830   info("stopped (parent terminated)");
831   exit(0);
832 }
833
834 /*
835 Local Variables:
836 c-basic-offset:2
837 comment-column:40
838 fill-column:79
839 indent-tabs-mode:nil
840 End:
841 */