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