2 * UDP prototype streaming system
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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/fifo.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/log.h"
37 #include "libavutil/time.h"
40 #include "os_support.h"
46 /* On many Linux systems, udplite.h is missing but the kernel supports UDP-Lite.
47 * So, we provide a fallback here.
49 #define UDPLITE_SEND_CSCOV 10
50 #define UDPLITE_RECV_CSCOV 11
53 #ifndef IPPROTO_UDPLITE
54 #define IPPROTO_UDPLITE 136
57 #if HAVE_PTHREAD_CANCEL
61 #ifndef HAVE_PTHREAD_CANCEL
62 #define HAVE_PTHREAD_CANCEL 0
65 #ifndef IPV6_ADD_MEMBERSHIP
66 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
67 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
70 #define UDP_TX_BUF_SIZE 32768
71 #define UDP_MAX_PKT_SIZE 65536
72 #define UDP_HEADER_SIZE 8
74 typedef struct UDPContext {
86 struct sockaddr_storage dest_addr;
90 /* Circular Buffer variables for use in UDP receive code */
91 int circular_buffer_size;
93 int circular_buffer_error;
94 #if HAVE_PTHREAD_CANCEL
95 pthread_t circular_buffer_thread;
96 pthread_mutex_t mutex;
100 uint8_t tmp[UDP_MAX_PKT_SIZE+4];
104 struct sockaddr_storage local_addr_storage;
109 #define OFFSET(x) offsetof(UDPContext, x)
110 #define D AV_OPT_FLAG_DECODING_PARAM
111 #define E AV_OPT_FLAG_ENCODING_PARAM
112 static const AVOption options[] = {
113 { "buffer_size", "System data size (in bytes)", OFFSET(buffer_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
114 { "localport", "Local port", OFFSET(local_port), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, D|E },
115 { "local_port", "Local port", OFFSET(local_port), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
116 { "localaddr", "Local address", OFFSET(localaddr), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = D|E },
117 { "udplite_coverage", "choose UDPLite head size which should be validated by checksum", OFFSET(udplite_coverage), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
118 { "pkt_size", "set size of UDP packets", OFFSET(pkt_size), AV_OPT_TYPE_INT, { .i64 = 1472 }, -1, INT_MAX, D|E },
119 { "pkt_size", "Maximum UDP packet size", OFFSET(pkt_size), AV_OPT_TYPE_INT, { .i64 = 1472 }, -1, INT_MAX, .flags = D|E },
120 { "reuse", "explicitly allow reusing UDP sockets", OFFSET(reuse_socket), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D|E },
121 { "reuse_socket", "explicitly allow reusing UDP sockets", OFFSET(reuse_socket), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, .flags = D|E },
122 { "broadcast", "explicitly allow or disallow broadcast destination", OFFSET(is_broadcast), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
123 { "ttl", "Time to live (multicast only)", OFFSET(ttl), AV_OPT_TYPE_INT, { .i64 = 16 }, 0, INT_MAX, E },
124 { "connect", "set if connect() should be called on socket", OFFSET(is_connected), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = D|E },
125 { "fifo_size", "set the UDP receiving circular buffer size, expressed as a number of packets with size of 188 bytes", OFFSET(circular_buffer_size), AV_OPT_TYPE_INT, {.i64 = 7*4096}, 0, INT_MAX, D },
126 { "overrun_nonfatal", "survive in case of UDP receiving circular buffer overrun", OFFSET(overrun_nonfatal), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
127 { "timeout", "set raise error timeout (only in read mode)", OFFSET(timeout), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
128 { "sources", "Source list", OFFSET(sources), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = D|E },
129 { "block", "Block list", OFFSET(block), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = D|E },
133 static const AVClass udp_class = {
135 .item_name = av_default_item_name,
137 .version = LIBAVUTIL_VERSION_INT,
140 static const AVClass udplite_context_class = {
141 .class_name = "udplite",
142 .item_name = av_default_item_name,
144 .version = LIBAVUTIL_VERSION_INT,
147 static void log_net_error(void *ctx, int level, const char* prefix)
150 av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
151 av_log(ctx, level, "%s: %s\n", prefix, errbuf);
154 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
155 struct sockaddr *addr)
157 #ifdef IP_MULTICAST_TTL
158 if (addr->sa_family == AF_INET) {
159 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
160 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
165 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
166 if (addr->sa_family == AF_INET6) {
167 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
168 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
176 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr,struct sockaddr *local_addr)
178 #ifdef IP_ADD_MEMBERSHIP
179 if (addr->sa_family == AF_INET) {
182 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
184 mreq.imr_interface= ((struct sockaddr_in *)local_addr)->sin_addr;
186 mreq.imr_interface.s_addr= INADDR_ANY;
187 if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
188 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
193 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
194 if (addr->sa_family == AF_INET6) {
195 struct ipv6_mreq mreq6;
197 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
198 mreq6.ipv6mr_interface= 0;
199 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
200 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
208 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr,struct sockaddr *local_addr)
210 #ifdef IP_DROP_MEMBERSHIP
211 if (addr->sa_family == AF_INET) {
214 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
216 mreq.imr_interface= ((struct sockaddr_in *)local_addr)->sin_addr;
218 mreq.imr_interface.s_addr= INADDR_ANY;
219 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
220 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
225 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
226 if (addr->sa_family == AF_INET6) {
227 struct ipv6_mreq mreq6;
229 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
230 mreq6.ipv6mr_interface= 0;
231 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
232 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
240 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
241 int type, int family, int flags)
243 struct addrinfo hints = { 0 }, *res = 0;
246 const char *node = 0, *service = "0";
249 snprintf(sport, sizeof(sport), "%d", port);
252 if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
255 hints.ai_socktype = type;
256 hints.ai_family = family;
257 hints.ai_flags = flags;
258 if ((error = getaddrinfo(node, service, &hints, &res))) {
260 av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
266 static int udp_set_multicast_sources(int sockfd, struct sockaddr *addr,
267 int addr_len, char **sources,
268 int nb_sources, int include)
270 #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE) && !defined(_WIN32)
271 /* These ones are available in the microsoft SDK, but don't seem to work
272 * as on linux, so just prefer the v4-only approach there for now. */
274 for (i = 0; i < nb_sources; i++) {
275 struct group_source_req mreqs;
276 int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
277 struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
278 SOCK_DGRAM, AF_UNSPEC,
281 return AVERROR(ENOENT);
283 mreqs.gsr_interface = 0;
284 memcpy(&mreqs.gsr_group, addr, addr_len);
285 memcpy(&mreqs.gsr_source, sourceaddr->ai_addr, sourceaddr->ai_addrlen);
286 freeaddrinfo(sourceaddr);
288 if (setsockopt(sockfd, level,
289 include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
290 (const void *)&mreqs, sizeof(mreqs)) < 0) {
292 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
294 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
295 return ff_neterrno();
298 #elif HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
300 if (addr->sa_family != AF_INET) {
301 av_log(NULL, AV_LOG_ERROR,
302 "Setting multicast sources only supported for IPv4\n");
303 return AVERROR(EINVAL);
305 for (i = 0; i < nb_sources; i++) {
306 struct ip_mreq_source mreqs;
307 struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
308 SOCK_DGRAM, AF_UNSPEC,
311 return AVERROR(ENOENT);
312 if (sourceaddr->ai_addr->sa_family != AF_INET) {
313 freeaddrinfo(sourceaddr);
314 av_log(NULL, AV_LOG_ERROR, "%s is of incorrect protocol family\n",
316 return AVERROR(EINVAL);
319 mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
320 mreqs.imr_interface.s_addr = INADDR_ANY;
321 mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)sourceaddr->ai_addr)->sin_addr.s_addr;
322 freeaddrinfo(sourceaddr);
324 if (setsockopt(sockfd, IPPROTO_IP,
325 include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
326 (const void *)&mreqs, sizeof(mreqs)) < 0) {
328 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
330 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
331 return ff_neterrno();
335 return AVERROR(ENOSYS);
339 static int udp_set_url(struct sockaddr_storage *addr,
340 const char *hostname, int port)
342 struct addrinfo *res0;
345 res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
346 if (!res0) return AVERROR(EIO);
347 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
348 addr_len = res0->ai_addrlen;
354 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
355 socklen_t *addr_len, const char *localaddr)
358 struct addrinfo *res0, *res;
359 int family = AF_UNSPEC;
361 if (((struct sockaddr *) &s->dest_addr)->sa_family)
362 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
363 res0 = udp_resolve_host((localaddr && localaddr[0]) ? localaddr : NULL, s->local_port,
364 SOCK_DGRAM, family, AI_PASSIVE);
367 for (res = res0; res; res=res->ai_next) {
368 if (s->udplite_coverage)
369 udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, IPPROTO_UDPLITE);
371 udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, 0);
372 if (udp_fd != -1) break;
373 log_net_error(NULL, AV_LOG_ERROR, "socket");
379 memcpy(addr, res->ai_addr, res->ai_addrlen);
380 *addr_len = res->ai_addrlen;
394 static int udp_port(struct sockaddr_storage *addr, int addr_len)
396 char sbuf[sizeof(int)*3+1];
399 if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
400 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
404 return strtol(sbuf, NULL, 10);
409 * If no filename is given to av_open_input_file because you want to
410 * get the local port first, then you must call this function to set
411 * the remote server address.
413 * url syntax: udp://host:port[?option=val...]
414 * option: 'ttl=n' : set the ttl value (for multicast only)
415 * 'localport=n' : set the local port
416 * 'pkt_size=n' : set max packet size
417 * 'reuse=1' : enable reusing the socket
418 * 'overrun_nonfatal=1': survive in case of circular buffer overrun
420 * @param h media file context
421 * @param uri of the remote server
422 * @return zero if no error.
424 int ff_udp_set_remote_url(URLContext *h, const char *uri)
426 UDPContext *s = h->priv_data;
427 char hostname[256], buf[10];
431 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
433 /* set the destination address */
434 s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
435 if (s->dest_addr_len < 0) {
438 s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
439 p = strchr(uri, '?');
441 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
442 int was_connected = s->is_connected;
443 s->is_connected = strtol(buf, NULL, 10);
444 if (s->is_connected && !was_connected) {
445 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
448 log_net_error(h, AV_LOG_ERROR, "connect");
459 * Return the local port used by the UDP connection
460 * @param h media file context
461 * @return the local port number
463 int ff_udp_get_local_port(URLContext *h)
465 UDPContext *s = h->priv_data;
466 return s->local_port;
470 * Return the udp file handle for select() usage to wait for several RTP
471 * streams at the same time.
472 * @param h media file context
474 static int udp_get_file_handle(URLContext *h)
476 UDPContext *s = h->priv_data;
480 #if HAVE_PTHREAD_CANCEL
481 static void *circular_buffer_task( void *_URLContext)
483 URLContext *h = _URLContext;
484 UDPContext *s = h->priv_data;
487 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
488 pthread_mutex_lock(&s->mutex);
489 if (ff_socket_nonblock(s->udp_fd, 0) < 0) {
490 av_log(h, AV_LOG_ERROR, "Failed to set blocking mode");
491 s->circular_buffer_error = AVERROR(EIO);
497 pthread_mutex_unlock(&s->mutex);
498 /* Blocking operations are always cancellation points;
499 see "General Information" / "Thread Cancelation Overview"
501 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);
502 len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
503 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
504 pthread_mutex_lock(&s->mutex);
506 if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
507 s->circular_buffer_error = ff_neterrno();
512 AV_WL32(s->tmp, len);
514 if(av_fifo_space(s->fifo) < len + 4) {
516 if (s->overrun_nonfatal) {
517 av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
518 "Surviving due to overrun_nonfatal option\n");
521 av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
522 "To avoid, increase fifo_size URL option. "
523 "To survive in such case, use overrun_nonfatal option\n");
524 s->circular_buffer_error = AVERROR(EIO);
528 av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
529 pthread_cond_signal(&s->cond);
533 pthread_cond_signal(&s->cond);
534 pthread_mutex_unlock(&s->mutex);
539 static int parse_source_list(char *buf, char **sources, int *num_sources,
546 char *next = strchr(source_start, ',');
549 sources[*num_sources] = av_strdup(source_start);
550 if (!sources[*num_sources])
551 return AVERROR(ENOMEM);
552 source_start = next + 1;
554 if (*num_sources >= max_sources || !next)
560 /* put it in UDP context */
561 /* return non zero if error */
562 static int udp_open(URLContext *h, const char *uri, int flags)
564 char hostname[1024], localaddr[1024] = "";
565 int port, udp_fd = -1, tmp, bind_ret = -1, dscp = -1;
566 UDPContext *s = h->priv_data;
570 struct sockaddr_storage my_addr;
572 int i, num_include_sources = 0, num_exclude_sources = 0;
573 char *include_sources[32], *exclude_sources[32];
577 is_output = !(flags & AVIO_FLAG_READ);
578 if (s->buffer_size < 0)
579 s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
582 if (parse_source_list(s->sources, include_sources,
583 &num_include_sources,
584 FF_ARRAY_ELEMS(include_sources)))
589 if (parse_source_list(s->block, exclude_sources, &num_exclude_sources,
590 FF_ARRAY_ELEMS(exclude_sources)))
595 h->max_packet_size = s->pkt_size;
597 p = strchr(uri, '?');
599 if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
601 s->reuse_socket = strtol(buf, &endptr, 10);
602 /* assume if no digits were found it is a request to enable it */
606 if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
608 s->overrun_nonfatal = strtol(buf, &endptr, 10);
609 /* assume if no digits were found it is a request to enable it */
611 s->overrun_nonfatal = 1;
612 if (!HAVE_PTHREAD_CANCEL)
613 av_log(h, AV_LOG_WARNING,
614 "'overrun_nonfatal' option was set but it is not supported "
615 "on this build (pthread support is required)\n");
617 if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
618 s->ttl = strtol(buf, NULL, 10);
620 if (av_find_info_tag(buf, sizeof(buf), "udplite_coverage", p)) {
621 s->udplite_coverage = strtol(buf, NULL, 10);
623 if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
624 s->local_port = strtol(buf, NULL, 10);
626 if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
627 s->pkt_size = strtol(buf, NULL, 10);
629 if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
630 s->buffer_size = strtol(buf, NULL, 10);
632 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
633 s->is_connected = strtol(buf, NULL, 10);
635 if (av_find_info_tag(buf, sizeof(buf), "dscp", p)) {
636 dscp = strtol(buf, NULL, 10);
638 if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
639 s->circular_buffer_size = strtol(buf, NULL, 10);
640 if (!HAVE_PTHREAD_CANCEL)
641 av_log(h, AV_LOG_WARNING,
642 "'circular_buffer_size' option was set but it is not supported "
643 "on this build (pthread support is required)\n");
645 if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
646 av_strlcpy(localaddr, buf, sizeof(localaddr));
648 if (av_find_info_tag(buf, sizeof(buf), "sources", p)) {
649 if (parse_source_list(buf, include_sources, &num_include_sources,
650 FF_ARRAY_ELEMS(include_sources)))
653 if (av_find_info_tag(buf, sizeof(buf), "block", p)) {
654 if (parse_source_list(buf, exclude_sources, &num_exclude_sources,
655 FF_ARRAY_ELEMS(exclude_sources)))
658 if (!is_output && av_find_info_tag(buf, sizeof(buf), "timeout", p))
659 s->timeout = strtol(buf, NULL, 10);
660 if (is_output && av_find_info_tag(buf, sizeof(buf), "broadcast", p))
661 s->is_broadcast = strtol(buf, NULL, 10);
663 /* handling needed to support options picking from both AVOption and URL */
664 s->circular_buffer_size *= 188;
665 if (flags & AVIO_FLAG_WRITE) {
666 h->max_packet_size = s->pkt_size;
668 h->max_packet_size = UDP_MAX_PKT_SIZE;
670 h->rw_timeout = s->timeout;
672 /* fill the dest addr */
673 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
675 /* XXX: fix av_url_split */
676 if (hostname[0] == '\0' || hostname[0] == '?') {
677 /* only accepts null hostname if input */
678 if (!(flags & AVIO_FLAG_READ))
681 if (ff_udp_set_remote_url(h, uri) < 0)
685 if ((s->is_multicast || s->local_port <= 0) && (h->flags & AVIO_FLAG_READ))
686 s->local_port = port;
689 udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
691 udp_fd = udp_socket_create(s, &my_addr, &len, s->localaddr);
695 s->local_addr_storage=my_addr; //store for future multicast join
697 /* Follow the requested reuse option, unless it's multicast in which
698 * case enable reuse unless explicitly disabled.
700 if (s->reuse_socket > 0 || (s->is_multicast && s->reuse_socket < 0)) {
702 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
706 if (s->is_broadcast) {
708 if (setsockopt (udp_fd, SOL_SOCKET, SO_BROADCAST, &(s->is_broadcast), sizeof(s->is_broadcast)) != 0)
713 /* Set the checksum coverage for UDP-Lite (RFC 3828) for sending and receiving.
714 * The receiver coverage has to be less than or equal to the sender coverage.
715 * Otherwise, the receiver will drop all packets.
717 if (s->udplite_coverage) {
718 if (setsockopt (udp_fd, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, &(s->udplite_coverage), sizeof(s->udplite_coverage)) != 0)
719 av_log(h, AV_LOG_WARNING, "socket option UDPLITE_SEND_CSCOV not available");
721 if (setsockopt (udp_fd, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, &(s->udplite_coverage), sizeof(s->udplite_coverage)) != 0)
722 av_log(h, AV_LOG_WARNING, "socket option UDPLITE_RECV_CSCOV not available");
727 if (setsockopt (udp_fd, IPPROTO_IP, IP_TOS, &dscp, sizeof(dscp)) != 0)
731 /* If multicast, try binding the multicast address first, to avoid
732 * receiving UDP packets from other sources aimed at the same UDP
733 * port. This fails on windows. This makes sending to the same address
734 * using sendto() fail, so only do it if we're opened in read-only mode. */
735 if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
736 bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
738 /* bind to the local address if not multicast or if the multicast
740 /* the bind is needed to give a port to the socket now */
741 if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
742 log_net_error(h, AV_LOG_ERROR, "bind failed");
746 len = sizeof(my_addr);
747 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
748 s->local_port = udp_port(&my_addr, len);
750 if (s->is_multicast) {
751 if (h->flags & AVIO_FLAG_WRITE) {
753 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
756 if (h->flags & AVIO_FLAG_READ) {
758 if (num_include_sources && num_exclude_sources) {
759 av_log(h, AV_LOG_ERROR, "Simultaneously including and excluding multicast sources is not supported\n");
762 if (num_include_sources) {
763 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, include_sources, num_include_sources, 1) < 0)
766 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr,(struct sockaddr *)&s->local_addr_storage) < 0)
769 if (num_exclude_sources) {
770 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, exclude_sources, num_exclude_sources, 0) < 0)
777 /* limit the tx buf size to limit latency */
778 tmp = s->buffer_size;
779 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
780 log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
784 /* set udp recv buffer size to the requested value (default 64K) */
785 tmp = s->buffer_size;
786 if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
787 log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
790 if (getsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, &len) < 0) {
791 log_net_error(h, AV_LOG_WARNING, "getsockopt(SO_RCVBUF)");
793 av_log(h, AV_LOG_DEBUG, "end receive buffer size reported is %d\n", tmp);
794 if(tmp < s->buffer_size)
795 av_log(h, AV_LOG_WARNING, "attempted to set receive buffer to size %d but it only ended up set as %d", s->buffer_size, tmp);
798 /* make the socket non-blocking */
799 ff_socket_nonblock(udp_fd, 1);
801 if (s->is_connected) {
802 if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
803 log_net_error(h, AV_LOG_ERROR, "connect");
808 for (i = 0; i < num_include_sources; i++)
809 av_freep(&include_sources[i]);
810 for (i = 0; i < num_exclude_sources; i++)
811 av_freep(&exclude_sources[i]);
815 #if HAVE_PTHREAD_CANCEL
816 if (!is_output && s->circular_buffer_size) {
819 /* start the task going */
820 s->fifo = av_fifo_alloc(s->circular_buffer_size);
821 ret = pthread_mutex_init(&s->mutex, NULL);
823 av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
826 ret = pthread_cond_init(&s->cond, NULL);
828 av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
831 ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
833 av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
836 s->thread_started = 1;
841 #if HAVE_PTHREAD_CANCEL
843 pthread_cond_destroy(&s->cond);
845 pthread_mutex_destroy(&s->mutex);
850 av_fifo_freep(&s->fifo);
851 for (i = 0; i < num_include_sources; i++)
852 av_freep(&include_sources[i]);
853 for (i = 0; i < num_exclude_sources; i++)
854 av_freep(&exclude_sources[i]);
858 static int udplite_open(URLContext *h, const char *uri, int flags)
860 UDPContext *s = h->priv_data;
862 // set default checksum coverage
863 s->udplite_coverage = UDP_HEADER_SIZE;
865 return udp_open(h, uri, flags);
868 static int udp_read(URLContext *h, uint8_t *buf, int size)
870 UDPContext *s = h->priv_data;
872 #if HAVE_PTHREAD_CANCEL
873 int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
876 pthread_mutex_lock(&s->mutex);
878 avail = av_fifo_size(s->fifo);
879 if (avail) { // >=size) {
882 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
885 av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
889 av_fifo_generic_read(s->fifo, buf, avail, NULL);
890 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
891 pthread_mutex_unlock(&s->mutex);
893 } else if(s->circular_buffer_error){
894 int err = s->circular_buffer_error;
895 pthread_mutex_unlock(&s->mutex);
897 } else if(nonblock) {
898 pthread_mutex_unlock(&s->mutex);
899 return AVERROR(EAGAIN);
902 /* FIXME: using the monotonic clock would be better,
903 but it does not exist on all supported platforms. */
904 int64_t t = av_gettime() + 100000;
905 struct timespec tv = { .tv_sec = t / 1000000,
906 .tv_nsec = (t % 1000000) * 1000 };
907 if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0) {
908 pthread_mutex_unlock(&s->mutex);
909 return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
917 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
918 ret = ff_network_wait_fd(s->udp_fd, 0);
922 ret = recv(s->udp_fd, buf, size, 0);
924 return ret < 0 ? ff_neterrno() : ret;
927 static int udp_write(URLContext *h, const uint8_t *buf, int size)
929 UDPContext *s = h->priv_data;
932 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
933 ret = ff_network_wait_fd(s->udp_fd, 1);
938 if (!s->is_connected) {
939 ret = sendto (s->udp_fd, buf, size, 0,
940 (struct sockaddr *) &s->dest_addr,
943 ret = send(s->udp_fd, buf, size, 0);
945 return ret < 0 ? ff_neterrno() : ret;
948 static int udp_close(URLContext *h)
950 UDPContext *s = h->priv_data;
952 if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
953 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr,(struct sockaddr *)&s->local_addr_storage);
954 closesocket(s->udp_fd);
955 #if HAVE_PTHREAD_CANCEL
956 if (s->thread_started) {
958 pthread_cancel(s->circular_buffer_thread);
959 ret = pthread_join(s->circular_buffer_thread, NULL);
961 av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
962 pthread_mutex_destroy(&s->mutex);
963 pthread_cond_destroy(&s->cond);
966 av_fifo_freep(&s->fifo);
970 URLProtocol ff_udp_protocol = {
972 .url_open = udp_open,
973 .url_read = udp_read,
974 .url_write = udp_write,
975 .url_close = udp_close,
976 .url_get_file_handle = udp_get_file_handle,
977 .priv_data_size = sizeof(UDPContext),
978 .priv_data_class = &udp_class,
979 .flags = URL_PROTOCOL_FLAG_NETWORK,
982 URLProtocol ff_udplite_protocol = {
984 .url_open = udplite_open,
985 .url_read = udp_read,
986 .url_write = udp_write,
987 .url_close = udp_close,
988 .url_get_file_handle = udp_get_file_handle,
989 .priv_data_size = sizeof(UDPContext),
990 .priv_data_class = &udplite_context_class,
991 .flags = URL_PROTOCOL_FLAG_NETWORK,