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"
43 #if HAVE_PTHREAD_CANCEL
47 #ifndef HAVE_PTHREAD_CANCEL
48 #define HAVE_PTHREAD_CANCEL 0
51 #ifndef IPV6_ADD_MEMBERSHIP
52 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
53 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
56 #define UDP_TX_BUF_SIZE 32768
57 #define UDP_MAX_PKT_SIZE 65536
68 struct sockaddr_storage dest_addr;
72 /* Circular Buffer variables for use in UDP receive code */
73 int circular_buffer_size;
75 int circular_buffer_error;
76 #if HAVE_PTHREAD_CANCEL
77 pthread_t circular_buffer_thread;
78 pthread_mutex_t mutex;
82 uint8_t tmp[UDP_MAX_PKT_SIZE+4];
89 #define OFFSET(x) offsetof(UDPContext, x)
90 #define D AV_OPT_FLAG_DECODING_PARAM
91 #define E AV_OPT_FLAG_ENCODING_PARAM
92 static const AVOption options[] = {
93 {"buffer_size", "Socket buffer size in bytes", OFFSET(buffer_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
94 {"localport", "Set local port to bind to", OFFSET(local_port), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
95 {"localaddr", "Choose local IP address", OFFSET(local_addr), AV_OPT_TYPE_STRING, {.str = ""}, 0, 0, D|E },
96 {"pkt_size", "Set size of UDP packets", OFFSET(packet_size), AV_OPT_TYPE_INT, {.i64 = 1472}, 0, INT_MAX, D|E },
97 {"reuse", "Explicitly allow or disallow reusing UDP sockets", OFFSET(reuse_socket), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
98 {"ttl", "Set the time to live value (for multicast only)", OFFSET(ttl), AV_OPT_TYPE_INT, {.i64 = 16}, 0, INT_MAX, E },
99 {"connect", "Should connect() be called on socket", OFFSET(is_connected), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
100 /* TODO 'sources', 'block' option */
101 {"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 },
102 {"overrun_nonfatal", "Survive in case of UDP receiving circular buffer overrun", OFFSET(overrun_nonfatal), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
103 {"timeout", "In read mode: if no data arrived in more than this time interval, raise error", OFFSET(timeout), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D },
107 static const AVClass udp_context_class = {
109 .item_name = av_default_item_name,
111 .version = LIBAVUTIL_VERSION_INT,
114 static void log_net_error(void *ctx, int level, const char* prefix)
117 av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
118 av_log(ctx, level, "%s: %s\n", prefix, errbuf);
121 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
122 struct sockaddr *addr)
124 #ifdef IP_MULTICAST_TTL
125 if (addr->sa_family == AF_INET) {
126 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
127 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
132 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
133 if (addr->sa_family == AF_INET6) {
134 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
135 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
143 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
145 #ifdef IP_ADD_MEMBERSHIP
146 if (addr->sa_family == AF_INET) {
149 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
150 mreq.imr_interface.s_addr= INADDR_ANY;
151 if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
152 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
157 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
158 if (addr->sa_family == AF_INET6) {
159 struct ipv6_mreq mreq6;
161 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
162 mreq6.ipv6mr_interface= 0;
163 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
164 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
172 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
174 #ifdef IP_DROP_MEMBERSHIP
175 if (addr->sa_family == AF_INET) {
178 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
179 mreq.imr_interface.s_addr= INADDR_ANY;
180 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
181 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
186 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
187 if (addr->sa_family == AF_INET6) {
188 struct ipv6_mreq mreq6;
190 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
191 mreq6.ipv6mr_interface= 0;
192 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
193 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
201 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
202 int type, int family, int flags)
204 struct addrinfo hints = { 0 }, *res = 0;
207 const char *node = 0, *service = "0";
210 snprintf(sport, sizeof(sport), "%d", port);
213 if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
216 hints.ai_socktype = type;
217 hints.ai_family = family;
218 hints.ai_flags = flags;
219 if ((error = getaddrinfo(node, service, &hints, &res))) {
221 av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
227 static int udp_set_multicast_sources(int sockfd, struct sockaddr *addr,
228 int addr_len, char **sources,
229 int nb_sources, int include)
231 #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE) && !defined(_WIN32)
232 /* These ones are available in the microsoft SDK, but don't seem to work
233 * as on linux, so just prefer the v4-only approach there for now. */
235 for (i = 0; i < nb_sources; i++) {
236 struct group_source_req mreqs;
237 int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
238 struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
239 SOCK_DGRAM, AF_UNSPEC,
242 return AVERROR(ENOENT);
244 mreqs.gsr_interface = 0;
245 memcpy(&mreqs.gsr_group, addr, addr_len);
246 memcpy(&mreqs.gsr_source, sourceaddr->ai_addr, sourceaddr->ai_addrlen);
247 freeaddrinfo(sourceaddr);
249 if (setsockopt(sockfd, level,
250 include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
251 (const void *)&mreqs, sizeof(mreqs)) < 0) {
253 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
255 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
256 return ff_neterrno();
259 #elif HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
261 if (addr->sa_family != AF_INET) {
262 av_log(NULL, AV_LOG_ERROR,
263 "Setting multicast sources only supported for IPv4\n");
264 return AVERROR(EINVAL);
266 for (i = 0; i < nb_sources; i++) {
267 struct ip_mreq_source mreqs;
268 struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
269 SOCK_DGRAM, AF_UNSPEC,
272 return AVERROR(ENOENT);
273 if (sourceaddr->ai_addr->sa_family != AF_INET) {
274 freeaddrinfo(sourceaddr);
275 av_log(NULL, AV_LOG_ERROR, "%s is of incorrect protocol family\n",
277 return AVERROR(EINVAL);
280 mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
281 mreqs.imr_interface.s_addr = INADDR_ANY;
282 mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)sourceaddr->ai_addr)->sin_addr.s_addr;
283 freeaddrinfo(sourceaddr);
285 if (setsockopt(sockfd, IPPROTO_IP,
286 include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
287 (const void *)&mreqs, sizeof(mreqs)) < 0) {
289 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
291 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
292 return ff_neterrno();
296 return AVERROR(ENOSYS);
300 static int udp_set_url(struct sockaddr_storage *addr,
301 const char *hostname, int port)
303 struct addrinfo *res0;
306 res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
307 if (res0 == 0) return AVERROR(EIO);
308 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
309 addr_len = res0->ai_addrlen;
315 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
316 socklen_t *addr_len, const char *localaddr)
319 struct addrinfo *res0 = NULL, *res = NULL;
320 int family = AF_UNSPEC;
322 if (((struct sockaddr *) &s->dest_addr)->sa_family)
323 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
324 res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
325 SOCK_DGRAM, family, AI_PASSIVE);
328 for (res = res0; res; res=res->ai_next) {
329 udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
330 if (udp_fd != -1) break;
331 log_net_error(NULL, AV_LOG_ERROR, "socket");
337 memcpy(addr, res->ai_addr, res->ai_addrlen);
338 *addr_len = res->ai_addrlen;
352 static int udp_port(struct sockaddr_storage *addr, int addr_len)
354 char sbuf[sizeof(int)*3+1];
357 if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
358 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
362 return strtol(sbuf, NULL, 10);
367 * If no filename is given to av_open_input_file because you want to
368 * get the local port first, then you must call this function to set
369 * the remote server address.
371 * url syntax: udp://host:port[?option=val...]
372 * option: 'ttl=n' : set the ttl value (for multicast only)
373 * 'localport=n' : set the local port
374 * 'pkt_size=n' : set max packet size
375 * 'reuse=1' : enable reusing the socket
376 * 'overrun_nonfatal=1': survive in case of circular buffer overrun
378 * @param h media file context
379 * @param uri of the remote server
380 * @return zero if no error.
382 int ff_udp_set_remote_url(URLContext *h, const char *uri)
384 UDPContext *s = h->priv_data;
385 char hostname[256], buf[10];
389 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
391 /* set the destination address */
392 s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
393 if (s->dest_addr_len < 0) {
396 s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
397 p = strchr(uri, '?');
399 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
400 int was_connected = s->is_connected;
401 s->is_connected = strtol(buf, NULL, 10);
402 if (s->is_connected && !was_connected) {
403 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
406 log_net_error(h, AV_LOG_ERROR, "connect");
417 * Return the local port used by the UDP connection
418 * @param h media file context
419 * @return the local port number
421 int ff_udp_get_local_port(URLContext *h)
423 UDPContext *s = h->priv_data;
424 return s->local_port;
428 * Return the udp file handle for select() usage to wait for several RTP
429 * streams at the same time.
430 * @param h media file context
432 static int udp_get_file_handle(URLContext *h)
434 UDPContext *s = h->priv_data;
438 #if HAVE_PTHREAD_CANCEL
439 static void *circular_buffer_task( void *_URLContext)
441 URLContext *h = _URLContext;
442 UDPContext *s = h->priv_data;
445 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
446 pthread_mutex_lock(&s->mutex);
447 if (ff_socket_nonblock(s->udp_fd, 0) < 0) {
448 av_log(h, AV_LOG_ERROR, "Failed to set blocking mode");
449 s->circular_buffer_error = AVERROR(EIO);
455 pthread_mutex_unlock(&s->mutex);
456 /* Blocking operations are always cancellation points;
457 see "General Information" / "Thread Cancelation Overview"
459 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);
460 len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
461 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
462 pthread_mutex_lock(&s->mutex);
464 if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
465 s->circular_buffer_error = ff_neterrno();
470 AV_WL32(s->tmp, len);
472 if(av_fifo_space(s->fifo) < len + 4) {
474 if (s->overrun_nonfatal) {
475 av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
476 "Surviving due to overrun_nonfatal option\n");
479 av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
480 "To avoid, increase fifo_size URL option. "
481 "To survive in such case, use overrun_nonfatal option\n");
482 s->circular_buffer_error = AVERROR(EIO);
486 av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
487 pthread_cond_signal(&s->cond);
491 pthread_cond_signal(&s->cond);
492 pthread_mutex_unlock(&s->mutex);
497 /* put it in UDP context */
498 /* return non zero if error */
499 static int udp_open(URLContext *h, const char *uri, int flags)
501 char hostname[1024], localaddr[1024] = "";
502 int port, udp_fd = -1, tmp, bind_ret = -1;
503 UDPContext *s = h->priv_data;
507 struct sockaddr_storage my_addr;
509 int reuse_specified = 0;
510 int i, include = 0, num_sources = 0;
515 is_output = !(flags & AVIO_FLAG_READ);
516 if (!s->buffer_size) /* if not set explicitly */
517 s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
519 p = strchr(uri, '?');
521 if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
523 s->reuse_socket = strtol(buf, &endptr, 10);
524 /* assume if no digits were found it is a request to enable it */
529 if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
531 s->overrun_nonfatal = strtol(buf, &endptr, 10);
532 /* assume if no digits were found it is a request to enable it */
534 s->overrun_nonfatal = 1;
535 if (!HAVE_PTHREAD_CANCEL)
536 av_log(h, AV_LOG_WARNING,
537 "'overrun_nonfatal' option was set but it is not supported "
538 "on this build (pthread support is required)\n");
540 if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
541 s->ttl = strtol(buf, NULL, 10);
543 if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
544 s->local_port = strtol(buf, NULL, 10);
546 if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
547 s->packet_size = strtol(buf, NULL, 10);
549 if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
550 s->buffer_size = strtol(buf, NULL, 10);
552 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
553 s->is_connected = strtol(buf, NULL, 10);
555 if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
556 s->circular_buffer_size = strtol(buf, NULL, 10);
557 if (!HAVE_PTHREAD_CANCEL)
558 av_log(h, AV_LOG_WARNING,
559 "'circular_buffer_size' option was set but it is not supported "
560 "on this build (pthread support is required)\n");
562 if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
563 av_strlcpy(localaddr, buf, sizeof(localaddr));
565 if (av_find_info_tag(buf, sizeof(buf), "sources", p))
567 if (include || av_find_info_tag(buf, sizeof(buf), "block", p)) {
572 char *next = strchr(source_start, ',');
575 sources[num_sources] = av_strdup(source_start);
576 if (!sources[num_sources])
578 source_start = next + 1;
580 if (num_sources >= FF_ARRAY_ELEMS(sources) || !next)
584 if (!is_output && av_find_info_tag(buf, sizeof(buf), "timeout", p))
585 s->timeout = strtol(buf, NULL, 10);
587 /* handling needed to support options picking from both AVOption and URL */
588 s->circular_buffer_size *= 188;
589 h->max_packet_size = s->packet_size;
590 h->rw_timeout = s->timeout;
592 /* fill the dest addr */
593 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
595 /* XXX: fix av_url_split */
596 if (hostname[0] == '\0' || hostname[0] == '?') {
597 /* only accepts null hostname if input */
598 if (!(flags & AVIO_FLAG_READ))
601 if (ff_udp_set_remote_url(h, uri) < 0)
605 if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
606 s->local_port = port;
607 udp_fd = udp_socket_create(s, &my_addr, &len, localaddr[0] ? localaddr : s->local_addr);
611 /* Follow the requested reuse option, unless it's multicast in which
612 * case enable reuse unless explicitly disabled.
614 if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
616 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
620 /* If multicast, try binding the multicast address first, to avoid
621 * receiving UDP packets from other sources aimed at the same UDP
622 * port. This fails on windows. This makes sending to the same address
623 * using sendto() fail, so only do it if we're opened in read-only mode. */
624 if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
625 bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
627 /* bind to the local address if not multicast or if the multicast
629 /* the bind is needed to give a port to the socket now */
630 if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
631 log_net_error(h, AV_LOG_ERROR, "bind failed");
635 len = sizeof(my_addr);
636 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
637 s->local_port = udp_port(&my_addr, len);
639 if (s->is_multicast) {
640 if (h->flags & AVIO_FLAG_WRITE) {
642 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
645 if (h->flags & AVIO_FLAG_READ) {
647 if (num_sources == 0 || !include) {
648 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
652 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 0) < 0)
655 } else if (include && num_sources) {
656 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 1) < 0)
659 av_log(NULL, AV_LOG_ERROR, "invalid udp settings: inclusive multicast but no sources given\n");
666 /* limit the tx buf size to limit latency */
667 tmp = s->buffer_size;
668 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
669 log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
673 /* set udp recv buffer size to the largest possible udp packet size to
674 * avoid losing data on OSes that set this too low by default. */
675 tmp = s->buffer_size;
676 if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
677 log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
679 /* make the socket non-blocking */
680 ff_socket_nonblock(udp_fd, 1);
682 if (s->is_connected) {
683 if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
684 log_net_error(h, AV_LOG_ERROR, "connect");
689 for (i = 0; i < num_sources; i++)
690 av_freep(&sources[i]);
694 #if HAVE_PTHREAD_CANCEL
695 if (!is_output && s->circular_buffer_size) {
698 /* start the task going */
699 s->fifo = av_fifo_alloc(s->circular_buffer_size);
700 ret = pthread_mutex_init(&s->mutex, NULL);
702 av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
705 ret = pthread_cond_init(&s->cond, NULL);
707 av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
710 ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
712 av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
715 s->thread_started = 1;
720 #if HAVE_PTHREAD_CANCEL
722 pthread_cond_destroy(&s->cond);
724 pthread_mutex_destroy(&s->mutex);
729 av_fifo_free(s->fifo);
730 for (i = 0; i < num_sources; i++)
731 av_freep(&sources[i]);
735 static int udp_read(URLContext *h, uint8_t *buf, int size)
737 UDPContext *s = h->priv_data;
739 int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
741 #if HAVE_PTHREAD_CANCEL
743 pthread_mutex_lock(&s->mutex);
745 avail = av_fifo_size(s->fifo);
746 if (avail) { // >=size) {
749 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
752 av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
756 av_fifo_generic_read(s->fifo, buf, avail, NULL);
757 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
758 pthread_mutex_unlock(&s->mutex);
760 } else if(s->circular_buffer_error){
761 int err = s->circular_buffer_error;
762 pthread_mutex_unlock(&s->mutex);
764 } else if(nonblock) {
765 pthread_mutex_unlock(&s->mutex);
766 return AVERROR(EAGAIN);
769 /* FIXME: using the monotonic clock would be better,
770 but it does not exist on all supported platforms. */
771 int64_t t = av_gettime() + 100000;
772 struct timespec tv = { .tv_sec = t / 1000000,
773 .tv_nsec = (t % 1000000) * 1000 };
774 if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0) {
775 pthread_mutex_unlock(&s->mutex);
776 return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
784 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
785 ret = ff_network_wait_fd(s->udp_fd, 0);
789 ret = recv(s->udp_fd, buf, size, 0);
791 return ret < 0 ? ff_neterrno() : ret;
794 static int udp_write(URLContext *h, const uint8_t *buf, int size)
796 UDPContext *s = h->priv_data;
799 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
800 ret = ff_network_wait_fd(s->udp_fd, 1);
805 if (!s->is_connected) {
806 ret = sendto (s->udp_fd, buf, size, 0,
807 (struct sockaddr *) &s->dest_addr,
810 ret = send(s->udp_fd, buf, size, 0);
812 return ret < 0 ? ff_neterrno() : ret;
815 static int udp_close(URLContext *h)
817 UDPContext *s = h->priv_data;
820 if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
821 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
822 closesocket(s->udp_fd);
823 #if HAVE_PTHREAD_CANCEL
824 if (s->thread_started) {
825 pthread_cancel(s->circular_buffer_thread);
826 ret = pthread_join(s->circular_buffer_thread, NULL);
828 av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
829 pthread_mutex_destroy(&s->mutex);
830 pthread_cond_destroy(&s->cond);
833 av_fifo_free(s->fifo);
837 URLProtocol ff_udp_protocol = {
839 .url_open = udp_open,
840 .url_read = udp_read,
841 .url_write = udp_write,
842 .url_close = udp_close,
843 .url_get_file_handle = udp_get_file_handle,
844 .priv_data_size = sizeof(UDPContext),
845 .priv_data_class = &udp_context_class,
846 .flags = URL_PROTOCOL_FLAG_NETWORK,