chiark / gitweb /
Start rationalizing network address configuration.
[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 <sys/socket.h>
24 #include <ifaddrs.h>
25 #include <net/if.h>
26 #include <arpa/inet.h>
27 #include <netinet/in.h>
28 #include <gcrypt.h>
29 #include <unistd.h>
30 #include <time.h>
31 #include <sys/uio.h>
32
33 #include "uaudio.h"
34 #include "mem.h"
35 #include "log.h"
36 #include "syscalls.h"
37 #include "rtp.h"
38 #include "addr.h"
39 #include "ifreq.h"
40 #include "timeval.h"
41 #include "configuration.h"
42
43 /** @brief Bytes to send per network packet
44  *
45  * This is the maximum number of bytes we pass to write(2); to determine actual
46  * packet sizes, add a UDP header and an IP header (and a link layer header if
47  * it's the link layer size you care about).
48  *
49  * Don't make this too big or arithmetic will start to overflow.
50  */
51 #define NETWORK_BYTES (1500-8/*UDP*/-40/*IP*/-8/*conservatism*/)
52
53 /** @brief RTP payload type */
54 static int rtp_payload;
55
56 /** @brief RTP output socket */
57 static int rtp_fd;
58
59 /** @brief RTP SSRC */
60 static uint32_t rtp_id;
61
62 /** @brief RTP sequence number */
63 static uint16_t rtp_sequence;
64
65 /** @brief Network error count
66  *
67  * If too many errors occur in too short a time, we give up.
68  */
69 static int rtp_errors;
70
71 /** @brief Delay threshold in microseconds
72  *
73  * rtp_play() never attempts to introduce a delay shorter than this.
74  */
75 static int64_t rtp_delay_threshold;
76
77 static const char *const rtp_options[] = {
78   "rtp-destination",
79   "rtp-destination-port",
80   "rtp-source",
81   "rtp-source-port",
82   "multicast-ttl",
83   "multicast-loop",
84   "delay-threshold",
85   NULL
86 };
87
88 static void rtp_get_netconfig(const char *af,
89                               const char *addr,
90                               const char *port,
91                               struct netaddress *na) {
92   char *vec[3];
93   
94   vec[0] = uaudio_get(af, NULL);
95   vec[1] = uaudio_get(addr, NULL);
96   vec[2] = uaudio_get(port, NULL);
97   if(!*vec)
98     na->af = -1;
99   else
100     if(netaddress_parse(na, 3, vec))
101       fatal(0, "invalid RTP address");
102 }
103
104 static void rtp_set_netconfig(const char *af,
105                               const char *addr,
106                               const char *port,
107                               const struct netaddress *na) {
108   uaudio_set(af, NULL);
109   uaudio_set(addr, NULL);
110   uaudio_set(port, NULL);
111   if(na->af != -1) {
112     int nvec;
113     char **vec;
114
115     netaddress_format(na, &nvec, &vec);
116     if(nvec > 0) {
117       uaudio_set(af, vec[0]);
118       xfree(vec[0]);
119     }
120     if(nvec > 1) {
121       uaudio_set(addr, vec[1]);
122       xfree(vec[1]);
123     }
124     if(nvec > 2) {
125       uaudio_set(port, vec[2]);
126       xfree(vec[2]);
127     }
128     xfree(vec);
129   }
130 }
131
132 static size_t rtp_play(void *buffer, size_t nsamples) {
133   struct rtp_header header;
134   struct iovec vec[2];
135   
136   /* We do as much work as possible before checking what time it is */
137   /* Fill out header */
138   header.vpxcc = 2 << 6;              /* V=2, P=0, X=0, CC=0 */
139   header.seq = htons(rtp_sequence++);
140   header.ssrc = rtp_id;
141   header.mpt = (uaudio_schedule_reactivated ? 0x80 : 0x00) | rtp_payload;
142 #if !WORDS_BIGENDIAN
143   /* Convert samples to network byte order */
144   uint16_t *u = buffer, *const limit = u + nsamples;
145   while(u < limit) {
146     *u = htons(*u);
147     ++u;
148   }
149 #endif
150   vec[0].iov_base = (void *)&header;
151   vec[0].iov_len = sizeof header;
152   vec[1].iov_base = buffer;
153   vec[1].iov_len = nsamples * uaudio_sample_size;
154   uaudio_schedule_synchronize();
155   header.timestamp = htonl((uint32_t)uaudio_schedule_timestamp);
156   int written_bytes;
157   do {
158     written_bytes = writev(rtp_fd, vec, 2);
159   } while(written_bytes < 0 && errno == EINTR);
160   if(written_bytes < 0) {
161     error(errno, "error transmitting audio data");
162     ++rtp_errors;
163     if(rtp_errors == 10)
164       fatal(0, "too many audio tranmission errors");
165     return 0;
166   } else
167     rtp_errors /= 2;                    /* gradual decay */
168   written_bytes -= sizeof (struct rtp_header);
169   const size_t written_samples = written_bytes / uaudio_sample_size;
170   uaudio_schedule_update(written_samples);
171   return written_samples;
172 }
173
174 static void rtp_open(void) {
175   struct addrinfo *res, *sres;
176   static const int one = 1;
177   int sndbuf, target_sndbuf = 131072;
178   socklen_t len;
179   struct netaddress dst[1], src[1];
180   
181   /* Get configuration */
182   rtp_get_netconfig("rtp-destination-af",
183                     "rtp-destination",
184                     "rtp-destination-port",
185                     dst);
186   rtp_get_netconfig("rtp-source-af",
187                     "rtp-source",
188                     "rtp-source-port",
189                     src);
190   rtp_delay_threshold = atoi(uaudio_get("rtp-delay-threshold", "1000"));
191   /* ...microseconds */
192
193   /* Resolve addresses */
194   res = netaddress_resolve(dst, 0, IPPROTO_UDP);
195   if(!res)
196     exit(-1);
197   if(src->af != -1) {
198     sres = netaddress_resolve(src, 1, IPPROTO_UDP);
199     if(!sres)
200       exit(-1);
201   } else
202     sres = 0;
203   /* Create the socket */
204   if((rtp_fd = socket(res->ai_family,
205                       res->ai_socktype,
206                       res->ai_protocol)) < 0)
207     fatal(errno, "error creating broadcast socket");
208   if(multicast(res->ai_addr)) {
209     /* Enable multicast options */
210     const int ttl = atoi(uaudio_get("multicast-ttl", "1"));
211     const int loop = !strcmp(uaudio_get("multicast-loop", "yes"), "yes");
212     switch(res->ai_family) {
213     case PF_INET: {
214       if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_TTL,
215                     &ttl, sizeof ttl) < 0)
216         fatal(errno, "error setting IP_MULTICAST_TTL on multicast socket");
217       if(setsockopt(rtp_fd, IPPROTO_IP, IP_MULTICAST_LOOP,
218                     &loop, sizeof loop) < 0)
219         fatal(errno, "error setting IP_MULTICAST_LOOP on multicast socket");
220       break;
221     }
222     case PF_INET6: {
223       if(setsockopt(rtp_fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
224                     &ttl, sizeof ttl) < 0)
225         fatal(errno, "error setting IPV6_MULTICAST_HOPS on multicast socket");
226       if(setsockopt(rtp_fd, IPPROTO_IP, IPV6_MULTICAST_LOOP,
227                     &loop, sizeof loop) < 0)
228         fatal(errno, "error setting IPV6_MULTICAST_LOOP on multicast socket");
229       break;
230     }
231     default:
232       fatal(0, "unsupported address family %d", res->ai_family);
233     }
234     info("multicasting on %s TTL=%d loop=%s", 
235          format_sockaddr(res->ai_addr), ttl, loop ? "yes" : "no");
236   } else {
237     struct ifaddrs *ifs;
238
239     if(getifaddrs(&ifs) < 0)
240       fatal(errno, "error calling getifaddrs");
241     while(ifs) {
242       /* (At least on Darwin) IFF_BROADCAST might be set but ifa_broadaddr
243        * still a null pointer.  It turns out that there's a subsequent entry
244        * for he same interface which _does_ have ifa_broadaddr though... */
245       if((ifs->ifa_flags & IFF_BROADCAST)
246          && ifs->ifa_broadaddr
247          && sockaddr_equal(ifs->ifa_broadaddr, res->ai_addr))
248         break;
249       ifs = ifs->ifa_next;
250     }
251     if(ifs) {
252       if(setsockopt(rtp_fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) < 0)
253         fatal(errno, "error setting SO_BROADCAST on broadcast socket");
254       info("broadcasting on %s (%s)", 
255            format_sockaddr(res->ai_addr), ifs->ifa_name);
256     } else
257       info("unicasting on %s", format_sockaddr(res->ai_addr));
258   }
259   /* Enlarge the socket buffer */
260   len = sizeof sndbuf;
261   if(getsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
262                 &sndbuf, &len) < 0)
263     fatal(errno, "error getting SO_SNDBUF");
264   if(target_sndbuf > sndbuf) {
265     if(setsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF,
266                   &target_sndbuf, sizeof target_sndbuf) < 0)
267       error(errno, "error setting SO_SNDBUF to %d", target_sndbuf);
268     else
269       info("changed socket send buffer size from %d to %d",
270            sndbuf, target_sndbuf);
271   } else
272     info("default socket send buffer is %d",
273          sndbuf);
274   /* We might well want to set additional broadcast- or multicast-related
275    * options here */
276   if(sres && bind(rtp_fd, sres->ai_addr, sres->ai_addrlen) < 0)
277     fatal(errno, "error binding broadcast socket to %s", 
278           format_sockaddr(sres->ai_addr));
279   if(connect(rtp_fd, res->ai_addr, res->ai_addrlen) < 0)
280     fatal(errno, "error connecting broadcast socket to %s", 
281           format_sockaddr(res->ai_addr));
282 }
283
284 static void rtp_start(uaudio_callback *callback,
285                       void *userdata) {
286   /* We only support L16 (but we do stereo and mono and will convert sign) */
287   if(uaudio_channels == 2
288      && uaudio_bits == 16
289      && uaudio_rate == 44100)
290     rtp_payload = 10;
291   else if(uaudio_channels == 1
292      && uaudio_bits == 16
293      && uaudio_rate == 44100)
294     rtp_payload = 11;
295   else
296     fatal(0, "asked for %d/%d/%d 16/44100/1 and 16/44100/2",
297           uaudio_bits, uaudio_rate, uaudio_channels); 
298   /* Various fields are required to have random initial values by RFC3550.  The
299    * packet contents are highly public so there's no point asking for very
300    * strong randomness. */
301   gcry_create_nonce(&rtp_id, sizeof rtp_id);
302   gcry_create_nonce(&rtp_sequence, sizeof rtp_sequence);
303   rtp_open();
304   uaudio_schedule_init();
305   uaudio_thread_start(callback,
306                       userdata,
307                       rtp_play,
308                       256 / uaudio_sample_size,
309                       (NETWORK_BYTES - sizeof(struct rtp_header))
310                       / uaudio_sample_size,
311                       0);
312 }
313
314 static void rtp_stop(void) {
315   uaudio_thread_stop();
316   close(rtp_fd);
317   rtp_fd = -1;
318 }
319
320 static void rtp_activate(void) {
321   uaudio_schedule_reactivated = 1;
322   uaudio_thread_activate();
323 }
324
325 static void rtp_deactivate(void) {
326   uaudio_thread_deactivate();
327 }
328
329 static void rtp_configure(void) {
330   char buffer[64];
331
332   rtp_set_netconfig("rtp-destination-af",
333                     "rtp-destination",
334                     "rtp-destination-port", &config->broadcast);
335   rtp_set_netconfig("rtp-source-af",
336                     "rtp-source",
337                     "rtp-source-port", &config->broadcast_from);
338   snprintf(buffer, sizeof buffer, "%ld", config->multicast_ttl);
339   uaudio_set("multicast-ttl", buffer);
340   uaudio_set("multicast-loop", config->multicast_loop ? "yes" : "no");
341   snprintf(buffer, sizeof buffer, "%ld", config->rtp_delay_threshold);
342   uaudio_set("delay-threshold", buffer);
343 }
344
345 const struct uaudio uaudio_rtp = {
346   .name = "rtp",
347   .options = rtp_options,
348   .start = rtp_start,
349   .stop = rtp_stop,
350   .activate = rtp_activate,
351   .deactivate = rtp_deactivate,
352   .configure = rtp_configure,
353 };
354
355 /*
356 Local Variables:
357 c-basic-offset:2
358 comment-column:40
359 fill-column:79
360 indent-tabs-mode:nil
361 End:
362 */