chiark / gitweb /
non-server builds want alsa too now
[disorder] / clients / playrtp.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
21 #include <config.h>
22 #include "types.h"
23
24 #include <getopt.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <sys/socket.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netdb.h>
31 #include <pthread.h>
32 #include <locale.h>
33
34 #include "log.h"
35 #include "mem.h"
36 #include "configuration.h"
37 #include "addr.h"
38 #include "syscalls.h"
39 #include "rtp.h"
40 #include "defs.h"
41
42 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
43 # include <CoreAudio/AudioHardware.h>
44 #endif
45 #if API_ALSA
46 #include <alsa/asoundlib.h>
47 #endif
48
49 #define readahead linux_headers_are_borked
50
51 /** @brief RTP socket */
52 static int rtpfd;
53
54 /** @brief Output device */
55 static const char *device;
56
57 /** @brief Maximum samples per packet we'll support
58  *
59  * NB that two channels = two samples in this program.
60  */
61 #define MAXSAMPLES 2048
62
63 /** @brief Minimum low watermark
64  *
65  * We'll stop playing if there's only this many samples in the buffer. */
66 static unsigned minbuffer = 2 * 44100 / 10;  /* 0.2 seconds */
67
68 /** @brief Maximum sample size
69  *
70  * The maximum supported size (in bytes) of one sample. */
71 #define MAXSAMPLESIZE 2
72
73 /** @brief Buffer high watermark
74  *
75  * We'll only start playing when this many samples are available. */
76 static unsigned readahead = 2 * 2 * 44100;
77
78 /** @brief Maximum buffer size
79  *
80  * We'll stop reading from the network if we have this many samples. */
81 static unsigned maxbuffer;
82
83 /** @brief Number of samples to infill by in one go */
84 #define INFILL_SAMPLES (44100 * 2)      /* 1s */
85
86 /** @brief Received packet
87  *
88  * Packets are recorded in an ordered linked list. */
89 struct packet {
90   /** @brief Pointer to next packet
91    * The next packet might not be immediately next: if packets are dropped
92    * or mis-ordered there may be gaps at any given moment. */
93   struct packet *next;
94   /** @brief Number of samples in this packet */
95   uint32_t nsamples;
96   /** @brief Timestamp from RTP packet
97    *
98    * NB that "timestamps" are really sample counters.*/
99   uint32_t timestamp;
100 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
101   /** @brief Converted sample data */
102   float samples_float[MAXSAMPLES];
103 #else
104   /** @brief Raw sample data */
105   unsigned char samples_raw[MAXSAMPLES * MAXSAMPLESIZE];
106 #endif
107 };
108
109 /** @brief Total number of samples available */
110 static unsigned long nsamples;
111
112 /** @brief Linked list of packets
113  *
114  * In ascending order of timestamp.  Really this should be a heap for more
115  * efficient access. */
116 static struct packet *packets;
117
118 /** @brief Timestamp of next packet to play.
119  *
120  * This is set to the timestamp of the last packet, plus the number of
121  * samples it contained.  Only valid if @ref active is nonzero.
122  */
123 static uint32_t next_timestamp;
124
125 /** @brief True if actively playing
126  *
127  * This is true when playing and false when just buffering. */
128 static int active;
129
130 /** @brief Lock protecting @ref packets */
131 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
132
133 /** @brief Condition variable signalled whenever @ref packets is changed */
134 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
135
136 static const struct option options[] = {
137   { "help", no_argument, 0, 'h' },
138   { "version", no_argument, 0, 'V' },
139   { "debug", no_argument, 0, 'd' },
140   { "device", required_argument, 0, 'D' },
141   { "min", required_argument, 0, 'm' },
142   { "max", required_argument, 0, 'x' },
143   { "buffer", required_argument, 0, 'b' },
144   { 0, 0, 0, 0 }
145 };
146
147 /** @brief Return true iff a < b in sequence-space arithmetic */
148 static inline int lt(uint32_t a, uint32_t b) {
149   return (uint32_t)(a - b) & 0x80000000;
150 }
151
152 /** @brief Return true iff a >= b in sequence-space arithmetic */
153 static inline int ge(uint32_t a, uint32_t b) {
154   return !lt(a, b);
155 }
156
157 /** @brief Return true iff a > b in sequence-space arithmetic */
158 static inline int gt(uint32_t a, uint32_t b) {
159   return lt(b, a);
160 }
161
162 /** @brief Return true iff a <= b in sequence-space arithmetic */
163 static inline int le(uint32_t a, uint32_t b) {
164   return !lt(b, a);
165 }
166
167 /** @brief Drop the packet at the head of the queue */
168 static void drop_first_packet(void) {
169   struct packet *const p = packets;
170   packets = p->next;
171   nsamples -= p->nsamples;
172   free(p);
173   pthread_cond_broadcast(&cond);
174 }
175
176 /** @brief Background thread collecting samples
177  *
178  * This function collects samples, perhaps converts them to the target format,
179  * and adds them to the packet list. */
180 static void *listen_thread(void attribute((unused)) *arg) {
181   struct packet *p = 0, **pp;
182   int n;
183   union {
184     struct rtp_header header;
185     uint8_t bytes[sizeof(uint16_t) * MAXSAMPLES + sizeof (struct rtp_header)];
186   } packet;
187   const uint16_t *const samples = (uint16_t *)(packet.bytes
188                                                + sizeof (struct rtp_header));
189
190   for(;;) {
191     if(!p)
192       p = xmalloc(sizeof *p);
193     n = read(rtpfd, packet.bytes, sizeof packet.bytes);
194     if(n < 0) {
195       switch(errno) {
196       case EINTR:
197         continue;
198       default:
199         fatal(errno, "error reading from socket");
200       }
201     }
202     /* Ignore too-short packets */
203     if((size_t)n <= sizeof (struct rtp_header))
204       continue;
205     p->timestamp = ntohl(packet.header.timestamp);
206     /* Ignore packets in the past */
207     if(active && lt(p->timestamp, next_timestamp)) {
208       info("dropping old packet, timestamp=%"PRIx32" < %"PRIx32,
209            p->timestamp, next_timestamp);
210       continue;
211     }
212     /* Convert to target format */
213     switch(packet.header.mpt & 0x7F) {
214     case 10:
215       p->nsamples = (n - sizeof (struct rtp_header)) / sizeof(uint16_t);
216 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
217       /* Convert to what Core Audio expects */
218       {
219         size_t i;
220
221         for(i = 0; i < p->nsamples; ++n)
222           p->samples_float[i] = (int16_t)ntohs(samples[i]) * (0.5f / 32767);
223       }
224 #else
225       /* ALSA can do any necessary conversion itself (though it might be better
226        * to do any necessary conversion in the background) */
227       memcpy(p->samples_raw, samples, n - sizeof (struct rtp_header));
228 #endif
229       break;
230       /* TODO support other RFC3551 media types (when the speaker does) */
231     default:
232       fatal(0, "unsupported RTP payload type %d",
233             packet.header.mpt & 0x7F);
234     }
235     pthread_mutex_lock(&lock);
236     /* Stop reading if we've reached the maximum.
237      *
238      * This is rather unsatisfactory: it means that if packets get heavily
239      * out of order then we guarantee dropouts.  But for now... */
240     while(nsamples >= maxbuffer)
241       pthread_cond_wait(&cond, &lock);
242     for(pp = &packets;
243         *pp && lt((*pp)->timestamp, p->timestamp);
244         pp = &(*pp)->next)
245       ;
246     /* So now either !*pp or *pp >= p */
247     if(*pp && p->timestamp == (*pp)->timestamp) {
248       /* *pp == p; a duplicate.  Ideally we avoid the translation step here,
249        * but we'll worry about that another time. */
250       info("dropped a duplicated");
251     } else {
252       if(*pp)
253         info("receiving packets out of order");
254       p->next = *pp;
255       *pp = p;
256       nsamples += p->nsamples;
257       pthread_cond_broadcast(&cond);
258       p = 0;                            /* we've consumed this packet */
259     }
260     pthread_mutex_unlock(&lock);
261   }
262 }
263
264 #if HAVE_COREAUDIO_AUDIOHARDWARE_H
265 /** @brief Callback from Core Audio */
266 static OSStatus adioproc
267     (AudioDeviceID attribute((unused)) inDevice,
268      const AudioTimeStamp attribute((unused)) *inNow,
269      const AudioBufferList attribute((unused)) *inInputData,
270      const AudioTimeStamp attribute((unused)) *inInputTime,
271      AudioBufferList *outOutputData,
272      const AudioTimeStamp attribute((unused)) *inOutputTime,
273      void attribute((unused)) *inClientData) {
274   UInt32 nbuffers = outOutputData->mNumberBuffers;
275   AudioBuffer *ab = outOutputData->mBuffers;
276
277   pthread_mutex_lock(&lock);
278   while(nbuffers > 0) {
279     float *samplesOut = ab->mData;
280     size_t samplesOutLeft = ab->mDataByteSize / sizeof (float);
281     
282     while(samplesOutLeft > 0) {
283       if(packets) {
284         /* There's a packet */
285         const uint32_t packet_start = packets->timestamp;
286         const uint32_t packet_end = packets->timestamp + packets->nsamples;
287         
288         if(le(packet_end, next_timestamp)) {
289           /* This packet is in the past */
290           info("dropping buffered past packet %"PRIx32" < %"PRIx32,
291                packets->timestamp, next_timestamp);
292           continue;
293         }
294         if(ge(next_timestamp, packet_start)
295            && lt(next_timestamp, packet_end)) {
296           /* This packet is suitable */
297           const uint32_t offset = next_timestamp - packets->timestamp;
298           uint32_t samples_available = packet_end - next_timestamp;
299           if(samples_available > samplesOutLeft)
300             samples_available = samplesOutLeft;
301           memcpy(samplesOut,
302                  packets->samples_float + offset,
303                  samples_available * sizeof(float));
304           samplesOut += samples_available;
305           next_timestamp += samples_available;
306           if(ge(next_timestamp, packet_end))
307             drop_first_packet();
308           continue;
309         }
310       }
311       /* We didn't find a suitable packet (though there might still be
312        * unsuitable ones).  We infill with 0s. */
313       if(packets) {
314         /* There is a next packet, only infill up to that point */
315         uint32_t samples_available = packets->timestamp - next_timestamp;
316         
317         if(samples_available > samplesOutLeft)
318           samples_available = samplesOutLeft;
319         /* Convniently the buffer is 0 to start with */
320         next_timestamp += samples_available;
321         samplesOut += samples_available;
322         samplesOutLeft -= samples_available;
323         /* TODO log infill */
324       } else {
325         /* There's no next packet at all */
326         next_timestamp += samplesOutLeft;
327         samplesOut += samplesOutLeft;
328         samplesOutLeft = 0;
329         /* TODO log infill */
330       }
331     }
332     ++ab;
333     --nbuffers;
334   }
335   pthread_mutex_unlock(&lock);
336   return 0;
337 }
338 #endif
339
340 /** @brief Play an RTP stream
341  *
342  * This is the guts of the program.  It is responsible for:
343  * - starting the listening thread
344  * - opening the audio device
345  * - reading ahead to build up a buffer
346  * - arranging for audio to be played
347  * - detecting when the buffer has got too small and re-buffering
348  */
349 static void play_rtp(void) {
350   pthread_t ltid;
351
352   /* We receive and convert audio data in a background thread */
353   pthread_create(&ltid, 0, listen_thread, 0);
354 #if API_ALSA
355   {
356     snd_pcm_t *pcm;
357     snd_pcm_hw_params_t *hwparams;
358     snd_pcm_sw_params_t *swparams;
359     /* Only support one format for now */
360     const int sample_format = SND_PCM_FORMAT_S16_BE;
361     unsigned rate = 44100;
362     const int channels = 2;
363     const int samplesize = channels * sizeof(uint16_t);
364     snd_pcm_uframes_t pcm_bufsize = MAXSAMPLES * samplesize * 3;
365     /* If we can write more than this many samples we'll get a wakeup */
366     const int avail_min = 256;
367     snd_pcm_sframes_t frames_written;
368     size_t samples_written;
369     int prepared = 1;
370     int err;
371     int infilling = 0, escape = 0;
372     time_t logged, now;
373     uint32_t packet_start, packet_end;
374
375     /* Open ALSA */
376     if((err = snd_pcm_open(&pcm,
377                            device ? device : "default",
378                            SND_PCM_STREAM_PLAYBACK,
379                            SND_PCM_NONBLOCK)))
380       fatal(0, "error from snd_pcm_open: %d", err);
381     /* Set up 'hardware' parameters */
382     snd_pcm_hw_params_alloca(&hwparams);
383     if((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
384       fatal(0, "error from snd_pcm_hw_params_any: %d", err);
385     if((err = snd_pcm_hw_params_set_access(pcm, hwparams,
386                                            SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
387       fatal(0, "error from snd_pcm_hw_params_set_access: %d", err);
388     if((err = snd_pcm_hw_params_set_format(pcm, hwparams,
389                                            sample_format)) < 0)
390       fatal(0, "error from snd_pcm_hw_params_set_format (%d): %d",
391             sample_format, err);
392     if((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0)
393       fatal(0, "error from snd_pcm_hw_params_set_rate (%d): %d",
394             rate, err);
395     if((err = snd_pcm_hw_params_set_channels(pcm, hwparams,
396                                              channels)) < 0)
397       fatal(0, "error from snd_pcm_hw_params_set_channels (%d): %d",
398             channels, err);
399     if((err = snd_pcm_hw_params_set_buffer_size_near(pcm, hwparams,
400                                                      &pcm_bufsize)) < 0)
401       fatal(0, "error from snd_pcm_hw_params_set_buffer_size (%d): %d",
402             MAXSAMPLES * samplesize * 3, err);
403     if((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
404       fatal(0, "error calling snd_pcm_hw_params: %d", err);
405     /* Set up 'software' parameters */
406     snd_pcm_sw_params_alloca(&swparams);
407     if((err = snd_pcm_sw_params_current(pcm, swparams)) < 0)
408       fatal(0, "error calling snd_pcm_sw_params_current: %d", err);
409     if((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0)
410       fatal(0, "error calling snd_pcm_sw_params_set_avail_min %d: %d",
411             avail_min, err);
412     if((err = snd_pcm_sw_params(pcm, swparams)) < 0)
413       fatal(0, "error calling snd_pcm_sw_params: %d", err);
414
415     /* Ready to go */
416
417     time(&logged);
418     pthread_mutex_lock(&lock);
419     for(;;) {
420       /* Wait for the buffer to fill up a bit */
421       logged = now;
422       info("%lu samples in buffer (%lus)", nsamples,
423            nsamples / (44100 * 2));
424       info("Buffering...");
425       while(nsamples < readahead)
426         pthread_cond_wait(&cond, &lock);
427       if(!prepared) {
428         if((err = snd_pcm_prepare(pcm)))
429           fatal(0, "error calling snd_pcm_prepare: %d", err);
430         prepared = 1;
431       }
432       /* Start at the first available packet */
433       next_timestamp = packets->timestamp;
434       active = 1;
435       infilling = 0;
436       escape = 0;
437       logged = now;
438       info("%lu samples in buffer (%lus)", nsamples,
439            nsamples / (44100 * 2));
440       info("Playing...");
441       /* Wait until the buffer empties out */
442       while(nsamples >= minbuffer && !escape) {
443         time(&now);
444         if(now > logged + 10) {
445           logged = now;
446           info("%lu samples in buffer (%lus)", nsamples,
447                nsamples / (44100 * 2));
448         }
449         if(packets
450            && ge(next_timestamp, packets->timestamp + packets->nsamples)) {
451           info("dropping buffered past packet %"PRIx32" < %"PRIx32,
452                packets->timestamp, next_timestamp);
453           drop_first_packet();
454           continue;
455         }
456         /* Wait for ALSA to ask us for more data */
457         pthread_mutex_unlock(&lock);
458         write(2, ".", 1);               /* TODO remove me sometime */
459         switch(err = snd_pcm_wait(pcm, -1)) {
460         case 0:
461           info("snd_pcm_wait timed out");
462           break;
463         case 1:
464           break;
465         default:
466           fatal(0, "snd_pcm_wait returned %d", err);
467         }
468         pthread_mutex_lock(&lock);
469         /* ALSA is ready for more data */
470         packet_start = packets->timestamp;
471         packet_end = packets->timestamp + packets->nsamples;
472         if(ge(next_timestamp, packet_start)
473            && lt(next_timestamp, packet_end)) {
474           /* The target timestamp is somewhere in this packet */
475           const uint32_t offset = next_timestamp - packets->timestamp;
476           const uint32_t samples_available = (packets->timestamp + packets->nsamples) - next_timestamp;
477           const size_t frames_available = samples_available / 2;
478
479           frames_written = snd_pcm_writei(pcm,
480                                           packets->samples_raw + offset,
481                                           frames_available);
482           if(frames_written < 0) {
483             switch(frames_written) {
484             case -EAGAIN:
485               info("snd_pcm_wait() returned but we got -EAGAIN!");
486               break;
487             case -EPIPE:
488               error(0, "error calling snd_pcm_writei: %ld",
489                     (long)frames_written);
490               escape = 1;
491               break;
492             default:
493               fatal(0, "error calling snd_pcm_writei: %ld",
494                     (long)frames_written);
495             }
496           } else {
497             samples_written = frames_written * 2;
498             next_timestamp += samples_written;
499             if(ge(next_timestamp, packet_end))
500               drop_first_packet();
501             infilling = 0;
502           }
503         } else {
504           /* We don't have anything to play!  We'd better play some 0s. */
505           static const uint16_t zeros[INFILL_SAMPLES];
506           size_t samples_available = INFILL_SAMPLES, frames_available;
507
508           /* If the maximum infill would take us past the start of the next
509            * packet then we truncate the infill to the right amount. */
510           if(lt(packets->timestamp,
511                 next_timestamp + samples_available))
512             samples_available = packets->timestamp - next_timestamp;
513           if((int)samples_available < 0) {
514             info("packets->timestamp: %"PRIx32"  next_timestamp: %"PRIx32"  next+max: %"PRIx32"  available: %"PRIx32,
515                  packets->timestamp, next_timestamp,
516                  next_timestamp + INFILL_SAMPLES, samples_available);
517           }
518           frames_available = samples_available / 2;
519           if(!infilling) {
520             info("Infilling %d samples, next=%"PRIx32" packet=[%"PRIx32",%"PRIx32"]",
521                  samples_available, next_timestamp,
522                  packets->timestamp, packets->timestamp + packets->nsamples);
523             //infilling++;
524           }
525           frames_written = snd_pcm_writei(pcm,
526                                           zeros,
527                                           frames_available);
528           if(frames_written < 0) {
529             switch(frames_written) {
530             case -EAGAIN:
531               info("snd_pcm_wait() returned but we got -EAGAIN!");
532               break;
533             case -EPIPE:
534               error(0, "error calling snd_pcm_writei: %ld",
535                     (long)frames_written);
536               escape = 1;
537               break;
538             default:
539               fatal(0, "error calling snd_pcm_writei: %ld",
540                     (long)frames_written);
541             }
542           } else {
543             samples_written = frames_written * 2;
544             next_timestamp += samples_written;
545           }
546         }
547       }
548       active = 0;
549       /* We stop playing for a bit until the buffer re-fills */
550       pthread_mutex_unlock(&lock);
551       if((err = snd_pcm_nonblock(pcm, 0)))
552         fatal(0, "error calling snd_pcm_nonblock: %d", err);
553       if(escape) {
554         if((err = snd_pcm_drop(pcm)))
555           fatal(0, "error calling snd_pcm_drop: %d", err);
556         escape = 0;
557       } else
558         if((err = snd_pcm_drain(pcm)))
559           fatal(0, "error calling snd_pcm_drain: %d", err);
560       if((err = snd_pcm_nonblock(pcm, 1)))
561         fatal(0, "error calling snd_pcm_nonblock: %d", err);
562       prepared = 0;
563       pthread_mutex_lock(&lock);
564     }
565
566   }
567 #elif HAVE_COREAUDIO_AUDIOHARDWARE_H
568   {
569     OSStatus status;
570     UInt32 propertySize;
571     AudioDeviceID adid;
572     AudioStreamBasicDescription asbd;
573
574     /* If this looks suspiciously like libao's macosx driver there's an
575      * excellent reason for that... */
576
577     /* TODO report errors as strings not numbers */
578     propertySize = sizeof adid;
579     status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
580                                       &propertySize, &adid);
581     if(status)
582       fatal(0, "AudioHardwareGetProperty: %d", (int)status);
583     if(adid == kAudioDeviceUnknown)
584       fatal(0, "no output device");
585     propertySize = sizeof asbd;
586     status = AudioDeviceGetProperty(adid, 0, false,
587                                     kAudioDevicePropertyStreamFormat,
588                                     &propertySize, &asbd);
589     if(status)
590       fatal(0, "AudioHardwareGetProperty: %d", (int)status);
591     D(("mSampleRate       %f", asbd.mSampleRate));
592     D(("mFormatID         %08lx", asbd.mFormatID));
593     D(("mFormatFlags      %08lx", asbd.mFormatFlags));
594     D(("mBytesPerPacket   %08lx", asbd.mBytesPerPacket));
595     D(("mFramesPerPacket  %08lx", asbd.mFramesPerPacket));
596     D(("mBytesPerFrame    %08lx", asbd.mBytesPerFrame));
597     D(("mChannelsPerFrame %08lx", asbd.mChannelsPerFrame));
598     D(("mBitsPerChannel   %08lx", asbd.mBitsPerChannel));
599     D(("mReserved         %08lx", asbd.mReserved));
600     if(asbd.mFormatID != kAudioFormatLinearPCM)
601       fatal(0, "audio device does not support kAudioFormatLinearPCM");
602     status = AudioDeviceAddIOProc(adid, adioproc, 0);
603     if(status)
604       fatal(0, "AudioDeviceAddIOProc: %d", (int)status);
605     pthread_mutex_lock(&lock);
606     for(;;) {
607       /* Wait for the buffer to fill up a bit */
608       while(nsamples < readahead)
609         pthread_cond_wait(&cond, &lock);
610       /* Start playing now */
611       status = AudioDeviceStart(adid, adioproc);
612       if(status)
613         fatal(0, "AudioDeviceStart: %d", (int)status);
614       /* Wait until the buffer empties out */
615       while(nsamples >= minbuffer)
616         pthread_cond_wait(&cond, &lock);
617       /* Stop playing for a bit until the buffer re-fills */
618       status = AudioDeviceStop(adid, adioproc);
619       if(status)
620         fatal(0, "AudioDeviceStop: %d", (int)status);
621       /* Go back round */
622     }
623   }
624 #else
625 # error No known audio API
626 #endif
627 }
628
629 /* display usage message and terminate */
630 static void help(void) {
631   xprintf("Usage:\n"
632           "  disorder-playrtp [OPTIONS] ADDRESS [PORT]\n"
633           "Options:\n"
634           "  --device, -D DEVICE     Output device\n"
635           "  --min, -m FRAMES        Buffer low water mark\n"
636           "  --buffer, -b FRAMES     Buffer high water mark\n"
637           "  --max, -x FRAMES        Buffer maximum size\n"
638           "  --help, -h              Display usage message\n"
639           "  --version, -V           Display version number\n"
640           );
641   xfclose(stdout);
642   exit(0);
643 }
644
645 /* display version number and terminate */
646 static void version(void) {
647   xprintf("disorder-playrtp version %s\n", disorder_version_string);
648   xfclose(stdout);
649   exit(0);
650 }
651
652 int main(int argc, char **argv) {
653   int n;
654   struct addrinfo *res;
655   struct stringlist sl;
656   char *sockname;
657
658   static const struct addrinfo prefs = {
659     AI_PASSIVE,
660     PF_INET,
661     SOCK_DGRAM,
662     IPPROTO_UDP,
663     0,
664     0,
665     0,
666     0
667   };
668
669   mem_init();
670   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
671   while((n = getopt_long(argc, argv, "hVdD:m:b:x:", options, 0)) >= 0) {
672     switch(n) {
673     case 'h': help();
674     case 'V': version();
675     case 'd': debugging = 1; break;
676     case 'D': device = optarg; break;
677     case 'm': minbuffer = 2 * atol(optarg); break;
678     case 'b': readahead = 2 * atol(optarg); break;
679     case 'x': maxbuffer = 2 * atol(optarg); break;
680     default: fatal(0, "invalid option");
681     }
682   }
683   if(!maxbuffer)
684     maxbuffer = 4 * readahead;
685   argc -= optind;
686   argv += optind;
687   if(argc < 1 || argc > 2)
688     fatal(0, "usage: disorder-playrtp [OPTIONS] ADDRESS [PORT]");
689   sl.n = argc;
690   sl.s = argv;
691   /* Listen for inbound audio data */
692   if(!(res = get_address(&sl, &prefs, &sockname)))
693     exit(1);
694   if((rtpfd = socket(res->ai_family,
695                      res->ai_socktype,
696                      res->ai_protocol)) < 0)
697     fatal(errno, "error creating socket");
698   if(bind(rtpfd, res->ai_addr, res->ai_addrlen) < 0)
699     fatal(errno, "error binding socket to %s", sockname);
700   play_rtp();
701   return 0;
702 }
703
704 /*
705 Local Variables:
706 c-basic-offset:2
707 comment-column:40
708 fill-column:79
709 indent-tabs-mode:nil
710 End:
711 */