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"
39 #include "os_support.h"
42 #if HAVE_PTHREAD_CANCEL
46 #ifndef HAVE_PTHREAD_CANCEL
47 #define HAVE_PTHREAD_CANCEL 0
50 #ifndef IPV6_ADD_MEMBERSHIP
51 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
52 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
55 #define UDP_TX_BUF_SIZE 32768
56 #define UDP_MAX_PKT_SIZE 65536
67 struct sockaddr_storage dest_addr;
71 /* Circular Buffer variables for use in UDP receive code */
72 int circular_buffer_size;
74 int circular_buffer_error;
75 #if HAVE_PTHREAD_CANCEL
76 pthread_t circular_buffer_thread;
77 pthread_mutex_t mutex;
81 uint8_t tmp[UDP_MAX_PKT_SIZE+4];
88 #define OFFSET(x) offsetof(UDPContext, x)
89 #define D AV_OPT_FLAG_DECODING_PARAM
90 #define E AV_OPT_FLAG_ENCODING_PARAM
91 static const AVOption options[] = {
92 {"buffer_size", "Socket buffer size in bytes", OFFSET(buffer_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
93 {"localport", "Set local port to bind to", OFFSET(local_port), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
94 {"localaddr", "Choose local IP address", OFFSET(local_addr), AV_OPT_TYPE_STRING, {.str = ""}, 0, 0, D|E },
95 {"pkt_size", "Set size of UDP packets", OFFSET(packet_size), AV_OPT_TYPE_INT, {.i64 = 1472}, 0, INT_MAX, D|E },
96 {"reuse", "Explicitly allow or disallow reusing UDP sockets", OFFSET(reuse_socket), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
97 {"ttl", "Set the time to live value (for multicast only)", OFFSET(ttl), AV_OPT_TYPE_INT, {.i64 = 16}, 0, INT_MAX, E },
98 {"connect", "Should connect() be called on socket", OFFSET(is_connected), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
99 /* TODO 'sources', 'block' option */
100 {"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 },
101 {"overrun_nonfatal", "Survive in case of UDP receiving circular buffer overrun", OFFSET(overrun_nonfatal), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
102 {"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 },
106 static const AVClass udp_context_class = {
108 .item_name = av_default_item_name,
110 .version = LIBAVUTIL_VERSION_INT,
113 static void log_net_error(void *ctx, int level, const char* prefix)
116 av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
117 av_log(ctx, level, "%s: %s\n", prefix, errbuf);
120 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
121 struct sockaddr *addr)
123 #ifdef IP_MULTICAST_TTL
124 if (addr->sa_family == AF_INET) {
125 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
126 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
131 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
132 if (addr->sa_family == AF_INET6) {
133 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
134 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
142 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
144 #ifdef IP_ADD_MEMBERSHIP
145 if (addr->sa_family == AF_INET) {
148 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
149 mreq.imr_interface.s_addr= INADDR_ANY;
150 if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
151 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
156 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
157 if (addr->sa_family == AF_INET6) {
158 struct ipv6_mreq mreq6;
160 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
161 mreq6.ipv6mr_interface= 0;
162 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
163 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
171 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
173 #ifdef IP_DROP_MEMBERSHIP
174 if (addr->sa_family == AF_INET) {
177 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
178 mreq.imr_interface.s_addr= INADDR_ANY;
179 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
180 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
185 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
186 if (addr->sa_family == AF_INET6) {
187 struct ipv6_mreq mreq6;
189 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
190 mreq6.ipv6mr_interface= 0;
191 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
192 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
200 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
201 int type, int family, int flags)
203 struct addrinfo hints = { 0 }, *res = 0;
206 const char *node = 0, *service = "0";
209 snprintf(sport, sizeof(sport), "%d", port);
212 if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
215 hints.ai_socktype = type;
216 hints.ai_family = family;
217 hints.ai_flags = flags;
218 if ((error = getaddrinfo(node, service, &hints, &res))) {
220 av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
226 static int udp_set_multicast_sources(int sockfd, struct sockaddr *addr,
227 int addr_len, char **sources,
228 int nb_sources, int include)
230 #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE) && !defined(_WIN32)
231 /* These ones are available in the microsoft SDK, but don't seem to work
232 * as on linux, so just prefer the v4-only approach there for now. */
234 for (i = 0; i < nb_sources; i++) {
235 struct group_source_req mreqs;
236 int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
237 struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
238 SOCK_DGRAM, AF_UNSPEC,
241 return AVERROR(ENOENT);
243 mreqs.gsr_interface = 0;
244 memcpy(&mreqs.gsr_group, addr, addr_len);
245 memcpy(&mreqs.gsr_source, sourceaddr->ai_addr, sourceaddr->ai_addrlen);
246 freeaddrinfo(sourceaddr);
248 if (setsockopt(sockfd, level,
249 include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
250 (const void *)&mreqs, sizeof(mreqs)) < 0) {
252 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
254 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
255 return ff_neterrno();
258 #elif HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
260 if (addr->sa_family != AF_INET) {
261 av_log(NULL, AV_LOG_ERROR,
262 "Setting multicast sources only supported for IPv4\n");
263 return AVERROR(EINVAL);
265 for (i = 0; i < nb_sources; i++) {
266 struct ip_mreq_source mreqs;
267 struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
268 SOCK_DGRAM, AF_UNSPEC,
271 return AVERROR(ENOENT);
272 if (sourceaddr->ai_addr->sa_family != AF_INET) {
273 freeaddrinfo(sourceaddr);
274 av_log(NULL, AV_LOG_ERROR, "%s is of incorrect protocol family\n",
276 return AVERROR(EINVAL);
279 mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
280 mreqs.imr_interface.s_addr = INADDR_ANY;
281 mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)sourceaddr->ai_addr)->sin_addr.s_addr;
282 freeaddrinfo(sourceaddr);
284 if (setsockopt(sockfd, IPPROTO_IP,
285 include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
286 (const void *)&mreqs, sizeof(mreqs)) < 0) {
288 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
290 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
291 return ff_neterrno();
295 return AVERROR(ENOSYS);
299 static int udp_set_url(struct sockaddr_storage *addr,
300 const char *hostname, int port)
302 struct addrinfo *res0;
305 res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
306 if (res0 == 0) return AVERROR(EIO);
307 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
308 addr_len = res0->ai_addrlen;
314 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
315 int *addr_len, const char *localaddr)
318 struct addrinfo *res0 = NULL, *res = NULL;
319 int family = AF_UNSPEC;
321 if (((struct sockaddr *) &s->dest_addr)->sa_family)
322 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
323 res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
324 SOCK_DGRAM, family, AI_PASSIVE);
327 for (res = res0; res; res=res->ai_next) {
328 udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
329 if (udp_fd != -1) break;
330 log_net_error(NULL, AV_LOG_ERROR, "socket");
336 memcpy(addr, res->ai_addr, res->ai_addrlen);
337 *addr_len = res->ai_addrlen;
351 static int udp_port(struct sockaddr_storage *addr, int addr_len)
353 char sbuf[sizeof(int)*3+1];
356 if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
357 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
361 return strtol(sbuf, NULL, 10);
366 * If no filename is given to av_open_input_file because you want to
367 * get the local port first, then you must call this function to set
368 * the remote server address.
370 * url syntax: udp://host:port[?option=val...]
371 * option: 'ttl=n' : set the ttl value (for multicast only)
372 * 'localport=n' : set the local port
373 * 'pkt_size=n' : set max packet size
374 * 'reuse=1' : enable reusing the socket
375 * 'overrun_nonfatal=1': survive in case of circular buffer overrun
377 * @param h media file context
378 * @param uri of the remote server
379 * @return zero if no error.
381 int ff_udp_set_remote_url(URLContext *h, const char *uri)
383 UDPContext *s = h->priv_data;
384 char hostname[256], buf[10];
388 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
390 /* set the destination address */
391 s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
392 if (s->dest_addr_len < 0) {
395 s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
396 p = strchr(uri, '?');
398 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
399 int was_connected = s->is_connected;
400 s->is_connected = strtol(buf, NULL, 10);
401 if (s->is_connected && !was_connected) {
402 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
405 log_net_error(h, AV_LOG_ERROR, "connect");
416 * Return the local port used by the UDP connection
417 * @param h media file context
418 * @return the local port number
420 int ff_udp_get_local_port(URLContext *h)
422 UDPContext *s = h->priv_data;
423 return s->local_port;
427 * Return the udp file handle for select() usage to wait for several RTP
428 * streams at the same time.
429 * @param h media file context
431 static int udp_get_file_handle(URLContext *h)
433 UDPContext *s = h->priv_data;
437 #if HAVE_PTHREAD_CANCEL
438 static void *circular_buffer_task( void *_URLContext)
440 URLContext *h = _URLContext;
441 UDPContext *s = h->priv_data;
444 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
445 ff_socket_nonblock(s->udp_fd, 0);
446 pthread_mutex_lock(&s->mutex);
450 pthread_mutex_unlock(&s->mutex);
451 /* Blocking operations are always cancellation points;
452 see "General Information" / "Thread Cancelation Overview"
454 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);
455 len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
456 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
457 pthread_mutex_lock(&s->mutex);
459 if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
460 s->circular_buffer_error = ff_neterrno();
465 AV_WL32(s->tmp, len);
467 if(av_fifo_space(s->fifo) < len + 4) {
469 if (s->overrun_nonfatal) {
470 av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
471 "Surviving due to overrun_nonfatal option\n");
474 av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
475 "To avoid, increase fifo_size URL option. "
476 "To survive in such case, use overrun_nonfatal option\n");
477 s->circular_buffer_error = AVERROR(EIO);
481 av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
482 pthread_cond_signal(&s->cond);
486 pthread_cond_signal(&s->cond);
487 pthread_mutex_unlock(&s->mutex);
492 /* put it in UDP context */
493 /* return non zero if error */
494 static int udp_open(URLContext *h, const char *uri, int flags)
496 char hostname[1024], localaddr[1024] = "";
497 int port, udp_fd = -1, tmp, bind_ret = -1;
498 UDPContext *s = h->priv_data;
502 struct sockaddr_storage my_addr;
504 int reuse_specified = 0;
505 int i, include = 0, num_sources = 0;
510 is_output = !(flags & AVIO_FLAG_READ);
511 if (!s->buffer_size) /* if not set explicitly */
512 s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
514 p = strchr(uri, '?');
516 if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
518 s->reuse_socket = strtol(buf, &endptr, 10);
519 /* assume if no digits were found it is a request to enable it */
524 if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
526 s->overrun_nonfatal = strtol(buf, &endptr, 10);
527 /* assume if no digits were found it is a request to enable it */
529 s->overrun_nonfatal = 1;
530 if (!HAVE_PTHREAD_CANCEL)
531 av_log(h, AV_LOG_WARNING,
532 "'overrun_nonfatal' option was set but it is not supported "
533 "on this build (pthread support is required)\n");
535 if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
536 s->ttl = strtol(buf, NULL, 10);
538 if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
539 s->local_port = strtol(buf, NULL, 10);
541 if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
542 s->packet_size = strtol(buf, NULL, 10);
544 if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
545 s->buffer_size = strtol(buf, NULL, 10);
547 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
548 s->is_connected = strtol(buf, NULL, 10);
550 if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
551 s->circular_buffer_size = strtol(buf, NULL, 10);
552 if (!HAVE_PTHREAD_CANCEL)
553 av_log(h, AV_LOG_WARNING,
554 "'circular_buffer_size' option was set but it is not supported "
555 "on this build (pthread support is required)\n");
557 if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
558 av_strlcpy(localaddr, buf, sizeof(localaddr));
560 if (av_find_info_tag(buf, sizeof(buf), "sources", p))
562 if (include || av_find_info_tag(buf, sizeof(buf), "block", p)) {
567 char *next = strchr(source_start, ',');
570 sources[num_sources] = av_strdup(source_start);
571 if (!sources[num_sources])
573 source_start = next + 1;
575 if (num_sources >= FF_ARRAY_ELEMS(sources) || !next)
579 if (!is_output && av_find_info_tag(buf, sizeof(buf), "timeout", p))
580 s->timeout = strtol(buf, NULL, 10);
582 /* handling needed to support options picking from both AVOption and URL */
583 s->circular_buffer_size *= 188;
584 h->max_packet_size = s->packet_size;
585 h->rw_timeout = s->timeout;
587 /* fill the dest addr */
588 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
590 /* XXX: fix av_url_split */
591 if (hostname[0] == '\0' || hostname[0] == '?') {
592 /* only accepts null hostname if input */
593 if (!(flags & AVIO_FLAG_READ))
596 if (ff_udp_set_remote_url(h, uri) < 0)
600 if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
601 s->local_port = port;
602 udp_fd = udp_socket_create(s, &my_addr, &len, localaddr[0] ? localaddr : s->local_addr);
606 /* Follow the requested reuse option, unless it's multicast in which
607 * case enable reuse unless explicitly disabled.
609 if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
611 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
615 /* If multicast, try binding the multicast address first, to avoid
616 * receiving UDP packets from other sources aimed at the same UDP
617 * port. This fails on windows. This makes sending to the same address
618 * using sendto() fail, so only do it if we're opened in read-only mode. */
619 if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
620 bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
622 /* bind to the local address if not multicast or if the multicast
624 /* the bind is needed to give a port to the socket now */
625 if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
626 log_net_error(h, AV_LOG_ERROR, "bind failed");
630 len = sizeof(my_addr);
631 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
632 s->local_port = udp_port(&my_addr, len);
634 if (s->is_multicast) {
635 if (h->flags & AVIO_FLAG_WRITE) {
637 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
640 if (h->flags & AVIO_FLAG_READ) {
642 if (num_sources == 0 || !include) {
643 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
647 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 0) < 0)
650 } else if (include && num_sources) {
651 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 1) < 0)
654 av_log(NULL, AV_LOG_ERROR, "invalid udp settings: inclusive multicast but no sources given\n");
661 /* limit the tx buf size to limit latency */
662 tmp = s->buffer_size;
663 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
664 log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
668 /* set udp recv buffer size to the largest possible udp packet size to
669 * avoid losing data on OSes that set this too low by default. */
670 tmp = s->buffer_size;
671 if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
672 log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
674 /* make the socket non-blocking */
675 ff_socket_nonblock(udp_fd, 1);
677 if (s->is_connected) {
678 if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
679 log_net_error(h, AV_LOG_ERROR, "connect");
684 for (i = 0; i < num_sources; i++)
685 av_freep(&sources[i]);
689 #if HAVE_PTHREAD_CANCEL
690 if (!is_output && s->circular_buffer_size) {
693 /* start the task going */
694 s->fifo = av_fifo_alloc(s->circular_buffer_size);
695 ret = pthread_mutex_init(&s->mutex, NULL);
697 av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
700 ret = pthread_cond_init(&s->cond, NULL);
702 av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
705 ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
707 av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
710 s->thread_started = 1;
715 #if HAVE_PTHREAD_CANCEL
717 pthread_cond_destroy(&s->cond);
719 pthread_mutex_destroy(&s->mutex);
724 av_fifo_free(s->fifo);
725 for (i = 0; i < num_sources; i++)
726 av_freep(&sources[i]);
730 static int udp_read(URLContext *h, uint8_t *buf, int size)
732 UDPContext *s = h->priv_data;
734 int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
736 #if HAVE_PTHREAD_CANCEL
738 pthread_mutex_lock(&s->mutex);
740 avail = av_fifo_size(s->fifo);
741 if (avail) { // >=size) {
744 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
747 av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
751 av_fifo_generic_read(s->fifo, buf, avail, NULL);
752 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
753 pthread_mutex_unlock(&s->mutex);
755 } else if(s->circular_buffer_error){
756 int err = s->circular_buffer_error;
757 pthread_mutex_unlock(&s->mutex);
759 } else if(nonblock) {
760 pthread_mutex_unlock(&s->mutex);
761 return AVERROR(EAGAIN);
764 /* FIXME: using the monotonic clock would be better,
765 but it does not exist on all supported platforms. */
766 int64_t t = av_gettime() + 100000;
767 struct timespec tv = { .tv_sec = t / 1000000,
768 .tv_nsec = (t % 1000000) * 1000 };
769 if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0) {
770 pthread_mutex_unlock(&s->mutex);
771 return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
779 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
780 ret = ff_network_wait_fd(s->udp_fd, 0);
784 ret = recv(s->udp_fd, buf, size, 0);
786 return ret < 0 ? ff_neterrno() : ret;
789 static int udp_write(URLContext *h, const uint8_t *buf, int size)
791 UDPContext *s = h->priv_data;
794 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
795 ret = ff_network_wait_fd(s->udp_fd, 1);
800 if (!s->is_connected) {
801 ret = sendto (s->udp_fd, buf, size, 0,
802 (struct sockaddr *) &s->dest_addr,
805 ret = send(s->udp_fd, buf, size, 0);
807 return ret < 0 ? ff_neterrno() : ret;
810 static int udp_close(URLContext *h)
812 UDPContext *s = h->priv_data;
815 if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
816 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
817 closesocket(s->udp_fd);
818 #if HAVE_PTHREAD_CANCEL
819 if (s->thread_started) {
820 pthread_cancel(s->circular_buffer_thread);
821 ret = pthread_join(s->circular_buffer_thread, NULL);
823 av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
824 pthread_mutex_destroy(&s->mutex);
825 pthread_cond_destroy(&s->cond);
828 av_fifo_free(s->fifo);
832 URLProtocol ff_udp_protocol = {
834 .url_open = udp_open,
835 .url_read = udp_read,
836 .url_write = udp_write,
837 .url_close = udp_close,
838 .url_get_file_handle = udp_get_file_handle,
839 .priv_data_size = sizeof(UDPContext),
840 .priv_data_class = &udp_context_class,
841 .flags = URL_PROTOCOL_FLAG_NETWORK,