2 * UDP prototype streaming system
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #define _BSD_SOURCE /* Needed for using struct ip_mreq with recent glibc */
30 #include "avio_internal.h"
31 #include "libavutil/parseutils.h"
32 #include "libavutil/avstring.h"
35 #include "os_support.h"
38 #ifndef IPV6_ADD_MEMBERSHIP
39 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
40 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
43 typedef struct UDPContext {
50 struct sockaddr_storage dest_addr;
55 #define UDP_TX_BUF_SIZE 32768
56 #define UDP_MAX_PKT_SIZE 65536
58 static void log_net_error(void *ctx, int level, const char* prefix)
61 av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
62 av_log(ctx, level, "%s: %s\n", prefix, errbuf);
65 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
66 struct sockaddr *addr)
68 #ifdef IP_MULTICAST_TTL
69 if (addr->sa_family == AF_INET) {
70 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
71 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
76 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
77 if (addr->sa_family == AF_INET6) {
78 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
79 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
87 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
89 #ifdef IP_ADD_MEMBERSHIP
90 if (addr->sa_family == AF_INET) {
93 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
94 mreq.imr_interface.s_addr= INADDR_ANY;
95 if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
96 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
101 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
102 if (addr->sa_family == AF_INET6) {
103 struct ipv6_mreq mreq6;
105 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
106 mreq6.ipv6mr_interface= 0;
107 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
108 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
116 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
118 #ifdef IP_DROP_MEMBERSHIP
119 if (addr->sa_family == AF_INET) {
122 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
123 mreq.imr_interface.s_addr= INADDR_ANY;
124 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
125 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
130 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
131 if (addr->sa_family == AF_INET6) {
132 struct ipv6_mreq mreq6;
134 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
135 mreq6.ipv6mr_interface= 0;
136 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
137 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
145 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
146 int type, int family, int flags)
148 struct addrinfo hints = { 0 }, *res = 0;
151 const char *node = 0, *service = "0";
154 snprintf(sport, sizeof(sport), "%d", port);
157 if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
160 hints.ai_socktype = type;
161 hints.ai_family = family;
162 hints.ai_flags = flags;
163 if ((error = getaddrinfo(node, service, &hints, &res))) {
165 av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
171 static int udp_set_multicast_sources(int sockfd, struct sockaddr *addr,
172 int addr_len, char **sources,
173 int nb_sources, int include)
175 #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE) && !defined(_WIN32)
176 /* These ones are available in the microsoft SDK, but don't seem to work
177 * as on linux, so just prefer the v4-only approach there for now. */
179 for (i = 0; i < nb_sources; i++) {
180 struct group_source_req mreqs;
181 int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
182 struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
183 SOCK_DGRAM, AF_UNSPEC,
186 return AVERROR(ENOENT);
188 mreqs.gsr_interface = 0;
189 memcpy(&mreqs.gsr_group, addr, addr_len);
190 memcpy(&mreqs.gsr_source, sourceaddr->ai_addr, sourceaddr->ai_addrlen);
191 freeaddrinfo(sourceaddr);
193 if (setsockopt(sockfd, level,
194 include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
195 (const void *)&mreqs, sizeof(mreqs)) < 0) {
197 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
199 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
200 return ff_neterrno();
203 #elif HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
205 if (addr->sa_family != AF_INET) {
206 av_log(NULL, AV_LOG_ERROR,
207 "Setting multicast sources only supported for IPv4\n");
208 return AVERROR(EINVAL);
210 for (i = 0; i < nb_sources; i++) {
211 struct ip_mreq_source mreqs;
212 struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
213 SOCK_DGRAM, AF_UNSPEC,
216 return AVERROR(ENOENT);
217 if (sourceaddr->ai_addr->sa_family != AF_INET) {
218 freeaddrinfo(sourceaddr);
219 av_log(NULL, AV_LOG_ERROR, "%s is of incorrect protocol family\n",
221 return AVERROR(EINVAL);
224 mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
225 mreqs.imr_interface.s_addr = INADDR_ANY;
226 mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)sourceaddr->ai_addr)->sin_addr.s_addr;
227 freeaddrinfo(sourceaddr);
229 if (setsockopt(sockfd, IPPROTO_IP,
230 include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
231 (const void *)&mreqs, sizeof(mreqs)) < 0) {
233 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
235 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
236 return ff_neterrno();
240 return AVERROR(ENOSYS);
244 static int udp_set_url(struct sockaddr_storage *addr,
245 const char *hostname, int port)
247 struct addrinfo *res0;
250 res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
251 if (res0 == 0) return AVERROR(EIO);
252 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
253 addr_len = res0->ai_addrlen;
259 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
260 socklen_t *addr_len, const char *localaddr)
263 struct addrinfo *res0 = NULL, *res = NULL;
264 int family = AF_UNSPEC;
266 if (((struct sockaddr *) &s->dest_addr)->sa_family)
267 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
268 res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
269 SOCK_DGRAM, family, AI_PASSIVE);
272 for (res = res0; res; res=res->ai_next) {
273 udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, 0);
274 if (udp_fd != -1) break;
275 log_net_error(NULL, AV_LOG_ERROR, "socket");
281 memcpy(addr, res->ai_addr, res->ai_addrlen);
282 *addr_len = res->ai_addrlen;
296 static int udp_port(struct sockaddr_storage *addr, int addr_len)
298 char sbuf[sizeof(int)*3+1];
301 if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
302 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
306 return strtol(sbuf, NULL, 10);
311 * If no filename is given to av_open_input_file because you want to
312 * get the local port first, then you must call this function to set
313 * the remote server address.
315 * url syntax: udp://host:port[?option=val...]
316 * option: 'ttl=n' : set the ttl value (for multicast only)
317 * 'localport=n' : set the local port
318 * 'pkt_size=n' : set max packet size
319 * 'reuse=1' : enable reusing the socket
321 * @param h media file context
322 * @param uri of the remote server
323 * @return zero if no error.
325 int ff_udp_set_remote_url(URLContext *h, const char *uri)
327 UDPContext *s = h->priv_data;
328 char hostname[256], buf[10];
332 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
334 /* set the destination address */
335 s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
336 if (s->dest_addr_len < 0) {
339 s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
340 p = strchr(uri, '?');
342 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
343 int was_connected = s->is_connected;
344 s->is_connected = strtol(buf, NULL, 10);
345 if (s->is_connected && !was_connected) {
346 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
349 log_net_error(h, AV_LOG_ERROR, "connect");
360 * Return the local port used by the UDP connection
361 * @param h media file context
362 * @return the local port number
364 int ff_udp_get_local_port(URLContext *h)
366 UDPContext *s = h->priv_data;
367 return s->local_port;
371 * Return the udp file handle for select() usage to wait for several RTP
372 * streams at the same time.
373 * @param h media file context
375 static int udp_get_file_handle(URLContext *h)
377 UDPContext *s = h->priv_data;
381 static int parse_source_list(char *buf, char **sources, int *num_sources,
388 char *next = strchr(source_start, ',');
391 sources[*num_sources] = av_strdup(source_start);
392 if (!sources[*num_sources])
393 return AVERROR(ENOMEM);
394 source_start = next + 1;
396 if (*num_sources >= max_sources || !next)
402 /* put it in UDP context */
403 /* return non zero if error */
404 static int udp_open(URLContext *h, const char *uri, int flags)
406 char hostname[1024], localaddr[1024] = "";
407 int port, udp_fd = -1, tmp, bind_ret = -1;
408 UDPContext *s = h->priv_data;
412 struct sockaddr_storage my_addr;
414 int reuse_specified = 0;
415 int i, num_include_sources = 0, num_exclude_sources = 0;
416 char *include_sources[32], *exclude_sources[32];
419 h->max_packet_size = 1472;
421 is_output = !(flags & AVIO_FLAG_READ);
424 s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
426 p = strchr(uri, '?');
428 if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
430 s->reuse_socket = strtol(buf, &endptr, 10);
431 /* assume if no digits were found it is a request to enable it */
436 if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
437 s->ttl = strtol(buf, NULL, 10);
439 if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
440 s->local_port = strtol(buf, NULL, 10);
442 if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
443 h->max_packet_size = strtol(buf, NULL, 10);
445 if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
446 s->buffer_size = strtol(buf, NULL, 10);
448 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
449 s->is_connected = strtol(buf, NULL, 10);
451 if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
452 av_strlcpy(localaddr, buf, sizeof(localaddr));
454 if (av_find_info_tag(buf, sizeof(buf), "sources", p)) {
455 if (parse_source_list(buf, include_sources, &num_include_sources,
456 FF_ARRAY_ELEMS(include_sources)))
459 if (av_find_info_tag(buf, sizeof(buf), "block", p)) {
460 if (parse_source_list(buf, exclude_sources, &num_exclude_sources,
461 FF_ARRAY_ELEMS(exclude_sources)))
466 /* fill the dest addr */
467 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
469 /* XXX: fix av_url_split */
470 if (hostname[0] == '\0' || hostname[0] == '?') {
471 /* only accepts null hostname if input */
472 if (!(flags & AVIO_FLAG_READ))
475 if (ff_udp_set_remote_url(h, uri) < 0)
479 if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
480 s->local_port = port;
481 udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
485 /* Follow the requested reuse option, unless it's multicast in which
486 * case enable reuse unless explicitly disabled.
488 if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
490 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
494 /* If multicast, try binding the multicast address first, to avoid
495 * receiving UDP packets from other sources aimed at the same UDP
496 * port. This fails on windows. This makes sending to the same address
497 * using sendto() fail, so only do it if we're opened in read-only mode. */
498 if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
499 bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
501 /* bind to the local address if not multicast or if the multicast
503 /* the bind is needed to give a port to the socket now */
504 if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
505 log_net_error(h, AV_LOG_ERROR, "bind failed");
509 len = sizeof(my_addr);
510 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
511 s->local_port = udp_port(&my_addr, len);
513 if (s->is_multicast) {
514 if (h->flags & AVIO_FLAG_WRITE) {
516 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
519 if (h->flags & AVIO_FLAG_READ) {
521 if (num_include_sources && num_exclude_sources) {
522 av_log(h, AV_LOG_ERROR, "Simultaneously including and excluding multicast sources is not supported\n");
525 if (num_include_sources) {
526 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, include_sources, num_include_sources, 1) < 0)
529 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
532 if (num_exclude_sources) {
533 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, exclude_sources, num_exclude_sources, 0) < 0)
540 /* limit the tx buf size to limit latency */
541 tmp = s->buffer_size;
542 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
543 log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
547 /* set udp recv buffer size to the largest possible udp packet size to
548 * avoid losing data on OSes that set this too low by default. */
549 tmp = s->buffer_size;
550 if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
551 log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
553 /* make the socket non-blocking */
554 ff_socket_nonblock(udp_fd, 1);
556 if (s->is_connected) {
557 if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
558 log_net_error(h, AV_LOG_ERROR, "connect");
563 for (i = 0; i < num_include_sources; i++)
564 av_freep(&include_sources[i]);
565 for (i = 0; i < num_exclude_sources; i++)
566 av_freep(&exclude_sources[i]);
573 for (i = 0; i < num_include_sources; i++)
574 av_freep(&include_sources[i]);
575 for (i = 0; i < num_exclude_sources; i++)
576 av_freep(&exclude_sources[i]);
580 static int udp_read(URLContext *h, uint8_t *buf, int size)
582 UDPContext *s = h->priv_data;
585 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
586 ret = ff_network_wait_fd(s->udp_fd, 0);
590 ret = recv(s->udp_fd, buf, size, 0);
591 return ret < 0 ? ff_neterrno() : ret;
594 static int udp_write(URLContext *h, const uint8_t *buf, int size)
596 UDPContext *s = h->priv_data;
599 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
600 ret = ff_network_wait_fd(s->udp_fd, 1);
605 if (!s->is_connected) {
606 ret = sendto (s->udp_fd, buf, size, 0,
607 (struct sockaddr *) &s->dest_addr,
610 ret = send(s->udp_fd, buf, size, 0);
612 return ret < 0 ? ff_neterrno() : ret;
615 static int udp_close(URLContext *h)
617 UDPContext *s = h->priv_data;
619 if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
620 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
621 closesocket(s->udp_fd);
625 URLProtocol ff_udp_protocol = {
627 .url_open = udp_open,
628 .url_read = udp_read,
629 .url_write = udp_write,
630 .url_close = udp_close,
631 .url_get_file_handle = udp_get_file_handle,
632 .priv_data_size = sizeof(UDPContext),
633 .flags = URL_PROTOCOL_FLAG_NETWORK,