chiark / gitweb /
4785d62ae2ffdcc668f54111e0cf1d6161703436
[disorder] / lib / uaudio-rtp.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2009 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 3 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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU 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, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file lib/uaudio-rtp.c
19  * @brief Support for RTP network play backend */
20 #include "common.h"
21
22 #include <errno.h>
23 #include <ifaddrs.h>
24 #include <net/if.h>
25 #include <gcrypt.h>
26 #include <unistd.h>
27 #include <time.h>
28
29 #include "uaudio.h"
30 #include "mem.h"
31 #include "log.h"
32 #include "syscalls.h"
33 #include "rtp.h"
34 #include "addr.h"
35 #include "ifreq.h"
36 #include "timeval.h"
37
38 /** @brief Bytes to send per network packet
39  *
40  * This is the maximum number of bytes we pass to write(2); to determine actual
41  * packet sizes, add a UDP header and an IP header (and a link layer header if
42  * it's the link layer size you care about).
43  *
44  * Don't make this too big or arithmetic will start to overflow.
45  */
46 #define NETWORK_BYTES (1500-8/*UDP*/-40/*IP*/-8/*conservatism*/)
47
48 /** @brief RTP payload type */
49 static int rtp_payload;
50
51 /** @brief RTP output socket */
52 static int rtp_fd;
53
54 /** @brief RTP SSRC */
55 static uint32_t rtp_id;
56
57 /** @brief RTP sequence number */
58 static uint16_t rtp_sequence;
59
60 /** @brief RTP timestamp
61  *
62  * This is the timestamp that will be used on the next outbound packet.
63  *
64  * The timestamp in the packet header is only 32 bits wide.  With 44100Hz
65  * stereo, that only gives about half a day before wrapping, which is not
66  * particularly convenient for certain debugging purposes.  Therefore the
67  * timestamp is maintained as a 64-bit integer, giving around six million years
68  * before wrapping, and truncated to 32 bits when transmitting.
69  */
70 static uint64_t rtp_timestamp;
71
72 /** @brief Actual time corresponding to @ref rtp_timestamp
73  *
74  * This is the time, on this machine, at which the sample at @ref rtp_timestamp
75  * ought to be sent, interpreted as the time the last packet was sent plus the
76  * time length of the packet. */
77 static struct timeval rtp_timeval;
78
79 /** @brief Set when we (re-)activate, to provoke timestamp resync */
80 static int rtp_reactivated;
81
82 /** @brief Network error count
83  *
84  * If too many errors occur in too short a time, we give up.
85  */
86 static int rtp_errors;
87
88 /** @brief Delay threshold in microseconds
89  *
90  * rtp_play() never attempts to introduce a delay shorter than this.
91  */
92 static int64_t rtp_delay_threshold;
93
94 static const char *const rtp_options[] = {
95   "rtp-destination",
96   "rtp-destination-port",
97   "rtp-source",
98   "rtp-source-port",
99   "multicast-ttl",
100   "multicast-loop",
101   "rtp-delay-threshold",
102   NULL
103 };
104
105 static size_t rtp_play(void *buffer, size_t nsamples) {
106   struct rtp_header header;
107   struct iovec vec[2];
108   struct timeval now;
109   
110   /* We do as much work as possible before checking what time it is */
111   /* Fill out header */
112   header.vpxcc = 2 << 6;              /* V=2, P=0, X=0, CC=0 */
113   header.seq = htons(rtp_sequence++);
114   header.ssrc = rtp_id;
115   header.mpt = (rtp_reactivated ? 0x80 : 0x00) | rtp_payload;
116 #if !WORDS_BIGENDIAN
117   /* Convert samples to network byte order */
118   uint16_t *u = buffer, *const limit = u + nsamples;
119   while(u < limit) {
120     *u = htons(*u);
121     ++u;
122   }
123 #endif
124   vec[0].iov_base = (void *)&header;
125   vec[0].iov_len = sizeof header;
126   vec[1].iov_base = buffer;
127   vec[1].iov_len = nsamples * uaudio_sample_size;
128 retry:
129   xgettimeofday(&now, NULL);
130   if(rtp_reactivated) {
131     /* We've been deactivated for some unknown interval.  We need to advance
132      * rtp_timestamp to account for the dead air. */
133     /* On the first run through we'll set the start time. */
134     if(!rtp_timeval.tv_sec)
135       rtp_timeval = now;
136     /* See how much time we missed.
137      *
138      * This will be 0 on the first run through, in which case we'll not modify
139      * anything.
140      *
141      * It'll be negative in the (rare) situation where the deactivation
142      * interval is shorter than the last packet we sent.  In this case we wait
143      * for that much time and then return having sent no samples, which will
144      * cause uaudio_play_thread_fn() to retry.
145      *
146      * In the normal case it will be positive.
147      */
148     const int64_t delay = tvsub_us(now, rtp_timeval); /* microseconds */
149     if(delay < 0) {
150       usleep(-delay);
151       goto retry;
152     }
153     /* Advance the RTP timestamp to the present.  With 44.1KHz stereo this will
154      * overflow the intermediate value with a delay of a bit over 6 years.
155      * This seems acceptable. */
156     uint64_t update = (delay * uaudio_rate * uaudio_channels) / 1000000;
157     /* Don't throw off channel synchronization */
158     update -= update % uaudio_channels;
159     /* We log nontrivial changes */
160     if(update)
161       info("advancing rtp_time by %"PRIu64" samples", update);
162       rtp_timestamp += update;
163     rtp_timeval = now;
164     rtp_reactivated = 0;
165   } else {
166     /* Chances are we've been called right on the heels of the previous packet.
167      * If we just sent packets as fast as we got audio data we'd get way ahead
168      * of the player and some buffer somewhere would fill (or at least become
169      * unreasonably large).
170      *
171      * First find out how far ahead of the target time we are.
172      */
173     const int64_t ahead = tvsub_us(now, rtp_timeval); /* microseconds */
174     /* Only delay at all if we are nontrivially ahead. */
175     if(ahead > rtp_delay_threshold) {
176       /* Don't delay by the full amount */
177       usleep(ahead - rtp_delay_threshold / 2);
178       /* Refetch time (so we don't get out of step with reality) */
179       xgettimeofday(&now, NULL);
180     }
181   }
182   header.timestamp = htonl((uint32_t)rtp_timestamp);
183   int written_bytes;
184   do {
185     written_bytes = writev(rtp_fd, vec, 2);
186   } while(written_bytes < 0 && errno == EINTR);
187   if(written_bytes < 0) {
188     error(errno, "error transmitting audio data");
189     ++rtp_errors;
190     if(rtp_errors == 10)
191       fatal(0, "too many audio tranmission errors");
192     return 0;
193   } else
194     rtp_errors /= 2;                    /* gradual decay */
195   written_bytes -= sizeof (struct rtp_header);
196   size_t written_samples = written_bytes / uaudio_sample_size;
197   /* rtp_timestamp and rtp_timestamp are supposed to refer to the first sample
198    * of the next packet */
199   rtp_timestamp += written_samples;
200   const unsigned usec = (rtp_timeval.tv_usec
201                          + 1000000 * written_samples / (uaudio_rate
202                                                             * uaudio_channels));
203   /* ...will only overflow 32 bits if one packet is more than about half an
204    * hour long, which is not plausible. */
205   rtp_timeval.tv_sec += usec / 1000000;
206   rtp_timeval.tv_usec = usec % 1000000;
207   return written_samples;
208 }
209
210 static void rtp_open(void) {
211   struct addrinfo *res, *sres;
212   static const struct addrinfo pref = {
213     .ai_flags = 0,
214     .ai_family = PF_INET,
215     .ai_socktype = SOCK_DGRAM,
216     .ai_protocol = IPPROTO_UDP,
217   };
218   static const struct addrinfo prefbind = {
219     .ai_flags = AI_PASSIVE,
220     .ai_family = PF_INET,
221     .ai_socktype = SOCK_DGRAM,
222     .ai_protocol = IPPROTO_UDP,
223   };
224   static const int one = 1;
225   int sndbuf, target_sndbuf = 131072;
226   socklen_t len;
227   char *sockname, *ssockname;
228   struct stringlist dst, src;
229   const char *delay;
230   
231   /* Get configuration */
232   dst.n = 2;
233   dst.s = xcalloc(2, sizeof *dst.s);
234   dst.s[0] = uaudio_get("rtp-destination");
235   dst.s[1] = uaudio_get("rtp-destination-port");
236   src.n = 2;
237   src.s = xcalloc(2, sizeof *dst.s);
238   src.s[0] = uaudio_get("rtp-source");
239   src.s[1] = uaudio_get("rtp-source-port");
240   if(!dst.s[0])
241     fatal(0, "'rtp-destination' not set");
242   if(!dst.s[1])
243     fatal(0, "'rtp-destination-port' not set");
244   if(src.s[0]) {
245     if(!src.s[1])
246       fatal(0, "'rtp-source-port' not set");
247     src.n = 2;
248   } else
249     src.n = 0;
250   if((delay = uaudio_get("rtp-delay-threshold")))
251     rtp_delay_threshold = atoi(delay);
252   else
253     rtp_delay_threshold = 1000;         /* microseconds */
254
255   /* Resolve addresses */
256   res = get_address(&dst, &pref, &sockname);
257   if(!res) exit(-1);
258   if(src.n) {
259     sres = get_address(&src, &prefbind, &ssockname);
260     if(!sres) exit(-1);
261   } else
262     sres = 0;
263   /* Create the socket */
264   if((rtp_fd = socket(res->ai_family,
265                       res->ai_socktype,
266                       res->ai_protocol)) < 0)
267     fatal(errno, "error creating broadcast socket");
268   if(multicast(res->ai_addr)) {
269     /* Enable multicast options */
270     const char *ttls = uaudio_get("multicast-ttl");
271     const int ttl = ttls ? atoi(ttls) : 1;
272     const char *loops = uaudio_get("multicast-loop");
273     const int loop = loops ? !strcmp(loops, "yes") : 1;
274     switch(res->ai_family) {
275     case PF_INET: {
276       if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
277                     &ttl, sizeof ttl) < 0)
278         fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
279       if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
280                     &loop, sizeof loop) < 0)
281         fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
282       break;
283     }
284     case PF_INET6: {
285       if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
286                     &ttl, sizeof ttl) < 0)
287         fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
288       if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
289                     &loop, sizeof loop) < 0)
290         fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
291       break;
292     }
293     default:
294       fatal(0, "unsupported address family %d", res->ai_family);
295     }
296     info("multicasting on %s TTL=%d loop=%s", 
297          sockname, ttl, loop ? "yes" : "no");
298   } else {
299     struct ifaddrs *ifs;
300
301     if(getifaddrs(&ifs) < 0)
302       fatal(errno, "error calling getifaddrs");
303     while(ifs) {
304       /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
305        * still a null pointer.  It turns out that there's a subsequent entry
306        * for he same interface which _does_ have ifa_broadaddr though... */
307       if((ifs->ifa_flags & IFF_BROADCAST)
308          && ifs->ifa_broadaddr
309          && sockaddr_equal(ifs->ifa_broadaddr, res->ai_addr))
310         break;
311       ifs = ifs->ifa_next;
312     }
313     if(ifs) {
314       if(setsockopt(rtp_fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
315         fatal(errno, "error setting SO_BROADCAST on broadcast socket");
316       info("broadcasting on %s (%s)", sockname, ifs->ifa_name);
317     } else
318       info("unicasting on %s", sockname);
319   }
320   /* Enlarge the socket buffer */
321   len = sizeof sndbuf;
322   if(getsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
323                 &sndbuf, &len) < 0)
324     fatal(errno, "error getting SO_SNDBUF");
325   if(target_sndbuf > sndbuf) {
326     if(setsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
327                   &target_sndbuf, sizeof target_sndbuf) < 0)
328       error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
329     else
330       info("changed socket send buffer size from %d to %d",
331            sndbuf, target_sndbuf);
332   } else
333     info("default socket send buffer is %d",
334          sndbuf);
335   /* We might well want to set additional broadcast- or multicast-related
336    * options here */
337   if(sres && bind(rtp_fd, sres->ai_addr, sres->ai_addrlen) < 0)
338     fatal(errno, "error binding broadcast socket to %s", ssockname);
339   if(connect(rtp_fd, res->ai_addr, res->ai_addrlen) < 0)
340     fatal(errno, "error connecting broadcast socket to %s", sockname);
341   /* Various fields are required to have random initial values by RFC3550.  The
342    * packet contents are highly public so there's no point asking for very
343    * strong randomness. */
344   gcry_create_nonce(&rtp_id, sizeof rtp_id);
345   gcry_create_nonce(&rtp_sequence, sizeof rtp_sequence);
346   gcry_create_nonce(&rtp_timestamp, sizeof rtp_timestamp);
347   /* rtp_play() will spot this and choose an initial value */
348   rtp_timeval.tv_sec = 0;
349 }
350
351 static void rtp_start(uaudio_callback *callback,
352                       void *userdata) {
353   /* We only support L16 (but we do stereo and mono and will convert sign) */
354   if(uaudio_channels == 2
355      && uaudio_bits == 16
356      && uaudio_rate == 44100)
357     rtp_payload = 10;
358   else if(uaudio_channels == 1
359      && uaudio_bits == 16
360      && uaudio_rate == 44100)
361     rtp_payload = 11;
362   else
363     fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
364           uaudio_bits, uaudio_rate, uaudio_channels); 
365   rtp_open();
366   uaudio_thread_start(callback,
367                       userdata,
368                       rtp_play,
369                       256 / uaudio_sample_size,
370                       (NETWORK_BYTES - sizeof(struct rtp_header))
371                       / uaudio_sample_size);
372 }
373
374 static void rtp_stop(void) {
375   uaudio_thread_stop();
376   close(rtp_fd);
377   rtp_fd = -1;
378 }
379
380 static void rtp_activate(void) {
381   rtp_reactivated = 1;
382   uaudio_thread_activate();
383 }
384
385 static void rtp_deactivate(void) {
386   uaudio_thread_deactivate();
387 }
388
389 const struct uaudio uaudio_rtp = {
390   .name = "rtp",
391   .options = rtp_options,
392   .start = rtp_start,
393   .stop = rtp_stop,
394   .activate = rtp_activate,
395   .deactivate = rtp_deactivate
396 };
397
398 /*
399 Local Variables:
400 c-basic-offset:2
401 comment-column:40
402 fill-column:79
403 indent-tabs-mode:nil
404 End:
405 */