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"
33 #include "libavutil/opt.h"
36 #include "os_support.h"
39 #ifndef IPV6_ADD_MEMBERSHIP
40 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
41 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
44 typedef struct UDPContext {
53 struct sockaddr_storage dest_addr;
61 #define UDP_TX_BUF_SIZE 32768
62 #define UDP_MAX_PKT_SIZE 65536
64 #define OFFSET(x) offsetof(UDPContext, x)
65 #define D AV_OPT_FLAG_DECODING_PARAM
66 #define E AV_OPT_FLAG_ENCODING_PARAM
67 static const AVOption options[] = {
68 { "ttl", "Time to live (in milliseconds, multicast only)", OFFSET(ttl), AV_OPT_TYPE_INT, { .i64 = 16 }, 0, INT_MAX, .flags = D|E },
69 { "buffer_size", "System data size (in bytes)", OFFSET(buffer_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
70 { "local_port", "Local port", OFFSET(local_port), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
71 { "reuse_socket", "Reuse socket", OFFSET(reuse_socket), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, .flags = D|E },
72 { "connect", "Connect socket", OFFSET(is_connected), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = D|E },
73 { "pkt_size", "Maximum packet size", OFFSET(pkt_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
74 { "localaddr", "Local address", OFFSET(localaddr), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = D|E },
75 { "sources", "Source list", OFFSET(sources), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = D|E },
76 { "block", "Block list", OFFSET(block), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = D|E },
80 static const AVClass udp_class = {
82 .item_name = av_default_item_name,
84 .version = LIBAVUTIL_VERSION_INT,
87 static void log_net_error(void *ctx, int level, const char* prefix)
90 av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
91 av_log(ctx, level, "%s: %s\n", prefix, errbuf);
94 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
95 struct sockaddr *addr)
97 #ifdef IP_MULTICAST_TTL
98 if (addr->sa_family == AF_INET) {
99 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
100 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
105 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
106 if (addr->sa_family == AF_INET6) {
107 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
108 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
116 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
118 #ifdef IP_ADD_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_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
125 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_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_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
137 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
145 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
147 #ifdef IP_DROP_MEMBERSHIP
148 if (addr->sa_family == AF_INET) {
151 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
152 mreq.imr_interface.s_addr= INADDR_ANY;
153 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
154 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
159 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
160 if (addr->sa_family == AF_INET6) {
161 struct ipv6_mreq mreq6;
163 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
164 mreq6.ipv6mr_interface= 0;
165 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
166 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
174 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
175 int type, int family, int flags)
177 struct addrinfo hints = { 0 }, *res = 0;
180 const char *node = 0, *service = "0";
183 snprintf(sport, sizeof(sport), "%d", port);
186 if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
189 hints.ai_socktype = type;
190 hints.ai_family = family;
191 hints.ai_flags = flags;
192 if ((error = getaddrinfo(node, service, &hints, &res))) {
194 av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
200 static int udp_set_multicast_sources(int sockfd, struct sockaddr *addr,
201 int addr_len, char **sources,
202 int nb_sources, int include)
204 #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE) && !defined(_WIN32)
205 /* These ones are available in the microsoft SDK, but don't seem to work
206 * as on linux, so just prefer the v4-only approach there for now. */
208 for (i = 0; i < nb_sources; i++) {
209 struct group_source_req mreqs;
210 int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
211 struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
212 SOCK_DGRAM, AF_UNSPEC,
215 return AVERROR(ENOENT);
217 mreqs.gsr_interface = 0;
218 memcpy(&mreqs.gsr_group, addr, addr_len);
219 memcpy(&mreqs.gsr_source, sourceaddr->ai_addr, sourceaddr->ai_addrlen);
220 freeaddrinfo(sourceaddr);
222 if (setsockopt(sockfd, level,
223 include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
224 (const void *)&mreqs, sizeof(mreqs)) < 0) {
226 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
228 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
229 return ff_neterrno();
232 #elif HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
234 if (addr->sa_family != AF_INET) {
235 av_log(NULL, AV_LOG_ERROR,
236 "Setting multicast sources only supported for IPv4\n");
237 return AVERROR(EINVAL);
239 for (i = 0; i < nb_sources; i++) {
240 struct ip_mreq_source mreqs;
241 struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
242 SOCK_DGRAM, AF_UNSPEC,
245 return AVERROR(ENOENT);
246 if (sourceaddr->ai_addr->sa_family != AF_INET) {
247 freeaddrinfo(sourceaddr);
248 av_log(NULL, AV_LOG_ERROR, "%s is of incorrect protocol family\n",
250 return AVERROR(EINVAL);
253 mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
254 mreqs.imr_interface.s_addr = INADDR_ANY;
255 mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)sourceaddr->ai_addr)->sin_addr.s_addr;
256 freeaddrinfo(sourceaddr);
258 if (setsockopt(sockfd, IPPROTO_IP,
259 include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
260 (const void *)&mreqs, sizeof(mreqs)) < 0) {
262 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
264 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
265 return ff_neterrno();
269 return AVERROR(ENOSYS);
273 static int udp_set_url(struct sockaddr_storage *addr,
274 const char *hostname, int port)
276 struct addrinfo *res0;
279 res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
280 if (res0 == 0) return AVERROR(EIO);
281 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
282 addr_len = res0->ai_addrlen;
288 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
289 socklen_t *addr_len, const char *localaddr)
292 struct addrinfo *res0 = NULL, *res = NULL;
293 int family = AF_UNSPEC;
295 if (((struct sockaddr *) &s->dest_addr)->sa_family)
296 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
297 res0 = udp_resolve_host((localaddr && localaddr[0]) ? localaddr : NULL, s->local_port,
298 SOCK_DGRAM, family, AI_PASSIVE);
301 for (res = res0; res; res=res->ai_next) {
302 udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, 0);
303 if (udp_fd != -1) break;
304 log_net_error(NULL, AV_LOG_ERROR, "socket");
310 memcpy(addr, res->ai_addr, res->ai_addrlen);
311 *addr_len = res->ai_addrlen;
325 static int udp_port(struct sockaddr_storage *addr, int addr_len)
327 char sbuf[sizeof(int)*3+1];
330 if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
331 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
335 return strtol(sbuf, NULL, 10);
340 * If no filename is given to av_open_input_file because you want to
341 * get the local port first, then you must call this function to set
342 * the remote server address.
344 * url syntax: udp://host:port[?option=val...]
345 * option: 'ttl=n' : set the ttl value (for multicast only)
346 * 'localport=n' : set the local port
347 * 'pkt_size=n' : set max packet size
348 * 'reuse=1' : enable reusing the socket
350 * @param h media file context
351 * @param uri of the remote server
352 * @return zero if no error.
354 int ff_udp_set_remote_url(URLContext *h, const char *uri)
356 UDPContext *s = h->priv_data;
357 char hostname[256], buf[10];
361 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
363 /* set the destination address */
364 s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
365 if (s->dest_addr_len < 0) {
368 s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
369 p = strchr(uri, '?');
371 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
372 int was_connected = s->is_connected;
373 s->is_connected = strtol(buf, NULL, 10);
374 if (s->is_connected && !was_connected) {
375 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
378 log_net_error(h, AV_LOG_ERROR, "connect");
389 * Return the local port used by the UDP connection
390 * @param h media file context
391 * @return the local port number
393 int ff_udp_get_local_port(URLContext *h)
395 UDPContext *s = h->priv_data;
396 return s->local_port;
400 * Return the udp file handle for select() usage to wait for several RTP
401 * streams at the same time.
402 * @param h media file context
404 static int udp_get_file_handle(URLContext *h)
406 UDPContext *s = h->priv_data;
410 static int parse_source_list(char *buf, char **sources, int *num_sources,
417 char *next = strchr(source_start, ',');
420 sources[*num_sources] = av_strdup(source_start);
421 if (!sources[*num_sources])
422 return AVERROR(ENOMEM);
423 source_start = next + 1;
425 if (*num_sources >= max_sources || !next)
431 /* put it in UDP context */
432 /* return non zero if error */
433 static int udp_open(URLContext *h, const char *uri, int flags)
435 char hostname[1024], localaddr[1024] = "";
436 int port, udp_fd = -1, tmp, bind_ret = -1;
437 UDPContext *s = h->priv_data;
441 struct sockaddr_storage my_addr;
443 int i, num_include_sources = 0, num_exclude_sources = 0;
444 char *include_sources[32], *exclude_sources[32];
447 h->max_packet_size = 1472;
449 is_output = !(flags & AVIO_FLAG_READ);
451 if (s->buffer_size < 0)
452 s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
455 if (parse_source_list(s->sources, include_sources,
456 &num_include_sources,
457 FF_ARRAY_ELEMS(include_sources)))
462 if (parse_source_list(s->block, exclude_sources, &num_exclude_sources,
463 FF_ARRAY_ELEMS(exclude_sources)))
468 h->max_packet_size = s->pkt_size;
470 p = strchr(uri, '?');
472 if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
474 s->reuse_socket = strtol(buf, &endptr, 10);
475 /* assume if no digits were found it is a request to enable it */
479 if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
480 s->ttl = strtol(buf, NULL, 10);
482 if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
483 s->local_port = strtol(buf, NULL, 10);
485 if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
486 h->max_packet_size = strtol(buf, NULL, 10);
488 if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
489 s->buffer_size = strtol(buf, NULL, 10);
491 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
492 s->is_connected = strtol(buf, NULL, 10);
494 if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
495 av_strlcpy(localaddr, buf, sizeof(localaddr));
497 if (av_find_info_tag(buf, sizeof(buf), "sources", p)) {
498 if (parse_source_list(buf, include_sources, &num_include_sources,
499 FF_ARRAY_ELEMS(include_sources)))
502 if (av_find_info_tag(buf, sizeof(buf), "block", p)) {
503 if (parse_source_list(buf, exclude_sources, &num_exclude_sources,
504 FF_ARRAY_ELEMS(exclude_sources)))
509 /* fill the dest addr */
510 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
512 /* XXX: fix av_url_split */
513 if (hostname[0] == '\0' || hostname[0] == '?') {
514 /* only accepts null hostname if input */
515 if (!(flags & AVIO_FLAG_READ))
518 if (ff_udp_set_remote_url(h, uri) < 0)
522 if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
523 s->local_port = port;
526 udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
528 udp_fd = udp_socket_create(s, &my_addr, &len, s->localaddr);
532 /* Follow the requested reuse option, unless it's multicast in which
533 * case enable reuse unless explicitly disabled.
535 if (s->reuse_socket > 0 || (s->is_multicast && s->reuse_socket < 0)) {
537 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
541 /* If multicast, try binding the multicast address first, to avoid
542 * receiving UDP packets from other sources aimed at the same UDP
543 * port. This fails on windows. This makes sending to the same address
544 * using sendto() fail, so only do it if we're opened in read-only mode. */
545 if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
546 bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
548 /* bind to the local address if not multicast or if the multicast
550 /* the bind is needed to give a port to the socket now */
551 if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
552 log_net_error(h, AV_LOG_ERROR, "bind failed");
556 len = sizeof(my_addr);
557 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
558 s->local_port = udp_port(&my_addr, len);
560 if (s->is_multicast) {
561 if (h->flags & AVIO_FLAG_WRITE) {
563 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
566 if (h->flags & AVIO_FLAG_READ) {
568 if (num_include_sources && num_exclude_sources) {
569 av_log(h, AV_LOG_ERROR, "Simultaneously including and excluding multicast sources is not supported\n");
572 if (num_include_sources) {
573 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, include_sources, num_include_sources, 1) < 0)
576 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
579 if (num_exclude_sources) {
580 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, exclude_sources, num_exclude_sources, 0) < 0)
587 /* limit the tx buf size to limit latency */
588 tmp = s->buffer_size;
589 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
590 log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
594 /* set udp recv buffer size to the largest possible udp packet size to
595 * avoid losing data on OSes that set this too low by default. */
596 tmp = s->buffer_size;
597 if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
598 log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
600 /* make the socket non-blocking */
601 ff_socket_nonblock(udp_fd, 1);
603 if (s->is_connected) {
604 if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
605 log_net_error(h, AV_LOG_ERROR, "connect");
610 for (i = 0; i < num_include_sources; i++)
611 av_freep(&include_sources[i]);
612 for (i = 0; i < num_exclude_sources; i++)
613 av_freep(&exclude_sources[i]);
620 for (i = 0; i < num_include_sources; i++)
621 av_freep(&include_sources[i]);
622 for (i = 0; i < num_exclude_sources; i++)
623 av_freep(&exclude_sources[i]);
627 static int udp_read(URLContext *h, uint8_t *buf, int size)
629 UDPContext *s = h->priv_data;
632 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
633 ret = ff_network_wait_fd(s->udp_fd, 0);
637 ret = recv(s->udp_fd, buf, size, 0);
638 return ret < 0 ? ff_neterrno() : ret;
641 static int udp_write(URLContext *h, const uint8_t *buf, int size)
643 UDPContext *s = h->priv_data;
646 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
647 ret = ff_network_wait_fd(s->udp_fd, 1);
652 if (!s->is_connected) {
653 ret = sendto (s->udp_fd, buf, size, 0,
654 (struct sockaddr *) &s->dest_addr,
657 ret = send(s->udp_fd, buf, size, 0);
659 return ret < 0 ? ff_neterrno() : ret;
662 static int udp_close(URLContext *h)
664 UDPContext *s = h->priv_data;
666 if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
667 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
668 closesocket(s->udp_fd);
672 URLProtocol ff_udp_protocol = {
674 .url_open = udp_open,
675 .url_read = udp_read,
676 .url_write = udp_write,
677 .url_close = udp_close,
678 .url_get_file_handle = udp_get_file_handle,
679 .priv_data_size = sizeof(UDPContext),
680 .flags = URL_PROTOCOL_FLAG_NETWORK,
681 .priv_data_class = &udp_class,