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