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"
38 #include "os_support.h"
47 #ifndef IPV6_ADD_MEMBERSHIP
48 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
49 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
52 #define UDP_TX_BUF_SIZE 32768
53 #define UDP_MAX_PKT_SIZE 65536
63 struct sockaddr_storage dest_addr;
67 /* Circular Buffer variables for use in UDP receive code */
68 int circular_buffer_size;
70 int circular_buffer_error;
72 pthread_t circular_buffer_thread;
73 pthread_mutex_t mutex;
77 uint8_t tmp[UDP_MAX_PKT_SIZE+4];
81 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
82 struct sockaddr *addr)
84 #ifdef IP_MULTICAST_TTL
85 if (addr->sa_family == AF_INET) {
86 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
87 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL): %s\n", strerror(errno));
92 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
93 if (addr->sa_family == AF_INET6) {
94 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
95 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS): %s\n", strerror(errno));
103 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
105 #ifdef IP_ADD_MEMBERSHIP
106 if (addr->sa_family == AF_INET) {
109 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
110 mreq.imr_interface.s_addr= INADDR_ANY;
111 if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
112 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno));
117 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
118 if (addr->sa_family == AF_INET6) {
119 struct ipv6_mreq mreq6;
121 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
122 mreq6.ipv6mr_interface= 0;
123 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
124 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP): %s\n", strerror(errno));
132 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
134 #ifdef IP_DROP_MEMBERSHIP
135 if (addr->sa_family == AF_INET) {
138 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
139 mreq.imr_interface.s_addr= INADDR_ANY;
140 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
141 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP): %s\n", strerror(errno));
146 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
147 if (addr->sa_family == AF_INET6) {
148 struct ipv6_mreq mreq6;
150 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
151 mreq6.ipv6mr_interface= 0;
152 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
153 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP): %s\n", strerror(errno));
161 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
162 int type, int family, int flags)
164 struct addrinfo hints = { 0 }, *res = 0;
167 const char *node = 0, *service = "0";
170 snprintf(sport, sizeof(sport), "%d", port);
173 if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
176 hints.ai_socktype = type;
177 hints.ai_family = family;
178 hints.ai_flags = flags;
179 if ((error = getaddrinfo(node, service, &hints, &res))) {
181 av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
187 static int udp_set_url(struct sockaddr_storage *addr,
188 const char *hostname, int port)
190 struct addrinfo *res0;
193 res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
194 if (res0 == 0) return AVERROR(EIO);
195 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
196 addr_len = res0->ai_addrlen;
202 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
203 int *addr_len, const char *localaddr)
206 struct addrinfo *res0 = NULL, *res = NULL;
207 int family = AF_UNSPEC;
209 if (((struct sockaddr *) &s->dest_addr)->sa_family)
210 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
211 res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
212 SOCK_DGRAM, family, AI_PASSIVE);
215 for (res = res0; res; res=res->ai_next) {
216 udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
217 if (udp_fd > 0) break;
218 av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno));
224 memcpy(addr, res->ai_addr, res->ai_addrlen);
225 *addr_len = res->ai_addrlen;
239 static int udp_port(struct sockaddr_storage *addr, int addr_len)
241 char sbuf[sizeof(int)*3+1];
243 if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) {
244 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno));
248 return strtol(sbuf, NULL, 10);
253 * If no filename is given to av_open_input_file because you want to
254 * get the local port first, then you must call this function to set
255 * the remote server address.
257 * url syntax: udp://host:port[?option=val...]
258 * option: 'ttl=n' : set the ttl value (for multicast only)
259 * 'localport=n' : set the local port
260 * 'pkt_size=n' : set max packet size
261 * 'reuse=1' : enable reusing the socket
262 * 'overrun_nonfatal=1': survive in case of circular buffer overrun
264 * @param h media file context
265 * @param uri of the remote server
266 * @return zero if no error.
268 int ff_udp_set_remote_url(URLContext *h, const char *uri)
270 UDPContext *s = h->priv_data;
271 char hostname[256], buf[10];
275 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
277 /* set the destination address */
278 s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
279 if (s->dest_addr_len < 0) {
282 s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
283 p = strchr(uri, '?');
285 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
286 int was_connected = s->is_connected;
287 s->is_connected = strtol(buf, NULL, 10);
288 if (s->is_connected && !was_connected) {
289 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
292 av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
303 * Return the local port used by the UDP connection
304 * @param h media file context
305 * @return the local port number
307 int ff_udp_get_local_port(URLContext *h)
309 UDPContext *s = h->priv_data;
310 return s->local_port;
314 * Return the udp file handle for select() usage to wait for several RTP
315 * streams at the same time.
316 * @param h media file context
318 static int udp_get_file_handle(URLContext *h)
320 UDPContext *s = h->priv_data;
325 static void *circular_buffer_task( void *_URLContext)
327 URLContext *h = _URLContext;
328 UDPContext *s = h->priv_data;
331 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
332 ff_socket_nonblock(s->udp_fd, 0);
333 pthread_mutex_lock(&s->mutex);
337 pthread_mutex_unlock(&s->mutex);
338 /* Blocking operations are always cancellation points;
339 see "General Information" / "Thread Cancelation Overview"
341 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);
342 len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
343 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
344 pthread_mutex_lock(&s->mutex);
346 if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
347 s->circular_buffer_error = ff_neterrno();
352 AV_WL32(s->tmp, len);
354 if(av_fifo_space(s->fifo) < len + 4) {
356 if (s->overrun_nonfatal) {
357 av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
358 "Surviving due to overrun_nonfatal option\n");
361 av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
362 "To avoid, increase fifo_size URL option. "
363 "To survive in such case, use overrun_nonfatal option\n");
364 s->circular_buffer_error = AVERROR(EIO);
368 av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
369 pthread_cond_signal(&s->cond);
373 pthread_cond_signal(&s->cond);
374 pthread_mutex_unlock(&s->mutex);
379 /* put it in UDP context */
380 /* return non zero if error */
381 static int udp_open(URLContext *h, const char *uri, int flags)
383 char hostname[1024], localaddr[1024] = "";
384 int port, udp_fd = -1, tmp, bind_ret = -1;
385 UDPContext *s = h->priv_data;
389 struct sockaddr_storage my_addr;
391 int reuse_specified = 0;
394 h->max_packet_size = 1472;
396 is_output = !(flags & AVIO_FLAG_READ);
399 s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
401 s->circular_buffer_size = 7*188*4096;
403 p = strchr(uri, '?');
405 if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
407 s->reuse_socket = strtol(buf, &endptr, 10);
408 /* assume if no digits were found it is a request to enable it */
413 if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
415 s->overrun_nonfatal = strtol(buf, &endptr, 10);
416 /* assume if no digits were found it is a request to enable it */
418 s->overrun_nonfatal = 1;
420 if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
421 s->ttl = strtol(buf, NULL, 10);
423 if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
424 s->local_port = strtol(buf, NULL, 10);
426 if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
427 h->max_packet_size = strtol(buf, NULL, 10);
429 if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
430 s->buffer_size = strtol(buf, NULL, 10);
432 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
433 s->is_connected = strtol(buf, NULL, 10);
435 if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
436 s->circular_buffer_size = strtol(buf, NULL, 10)*188;
438 if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
439 av_strlcpy(localaddr, buf, sizeof(localaddr));
443 /* fill the dest addr */
444 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
446 /* XXX: fix av_url_split */
447 if (hostname[0] == '\0' || hostname[0] == '?') {
448 /* only accepts null hostname if input */
449 if (!(flags & AVIO_FLAG_READ))
452 if (ff_udp_set_remote_url(h, uri) < 0)
456 if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
457 s->local_port = port;
458 udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
462 /* Follow the requested reuse option, unless it's multicast in which
463 * case enable reuse unless explicitly disabled.
465 if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
467 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
471 /* If multicast, try binding the multicast address first, to avoid
472 * receiving UDP packets from other sources aimed at the same UDP
473 * port. This fails on windows. This makes sending to the same address
474 * using sendto() fail, so only do it if we're opened in read-only mode. */
475 if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
476 bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
478 /* bind to the local address if not multicast or if the multicast
480 /* the bind is needed to give a port to the socket now */
481 if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
482 av_log(h, AV_LOG_ERROR, "bind failed: %s\n", strerror(errno));
486 len = sizeof(my_addr);
487 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
488 s->local_port = udp_port(&my_addr, len);
490 if (s->is_multicast) {
491 if (h->flags & AVIO_FLAG_WRITE) {
493 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
496 if (h->flags & AVIO_FLAG_READ) {
498 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
504 /* limit the tx buf size to limit latency */
505 tmp = s->buffer_size;
506 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
507 av_log(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF): %s\n", strerror(errno));
511 /* set udp recv buffer size to the largest possible udp packet size to
512 * avoid losing data on OSes that set this too low by default. */
513 tmp = s->buffer_size;
514 if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
515 av_log(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF): %s\n", strerror(errno));
517 /* make the socket non-blocking */
518 ff_socket_nonblock(udp_fd, 1);
520 if (s->is_connected) {
521 if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
522 av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
530 if (!is_output && s->circular_buffer_size) {
533 /* start the task going */
534 s->fifo = av_fifo_alloc(s->circular_buffer_size);
535 ret = pthread_mutex_init(&s->mutex, NULL);
537 av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
540 ret = pthread_cond_init(&s->cond, NULL);
542 av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
545 ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
547 av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
550 s->thread_started = 1;
557 pthread_cond_destroy(&s->cond);
559 pthread_mutex_destroy(&s->mutex);
564 av_fifo_free(s->fifo);
568 static int udp_read(URLContext *h, uint8_t *buf, int size)
570 UDPContext *s = h->priv_data;
572 int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
576 pthread_mutex_lock(&s->mutex);
578 avail = av_fifo_size(s->fifo);
579 if (avail) { // >=size) {
582 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
585 av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
589 av_fifo_generic_read(s->fifo, buf, avail, NULL);
590 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
591 pthread_mutex_unlock(&s->mutex);
593 } else if(s->circular_buffer_error){
594 int err = s->circular_buffer_error;
595 pthread_mutex_unlock(&s->mutex);
597 } else if(nonblock) {
598 pthread_mutex_unlock(&s->mutex);
599 return AVERROR(EAGAIN);
602 /* FIXME: using the monotonic clock would be better,
603 but it does not exist on all supported platforms. */
604 int64_t t = av_gettime() + 100000;
605 struct timespec tv = { .tv_sec = t / 1000000,
606 .tv_nsec = (t % 1000000) * 1000 };
607 if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0)
608 return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
615 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
616 ret = ff_network_wait_fd(s->udp_fd, 0);
620 ret = recv(s->udp_fd, buf, size, 0);
622 return ret < 0 ? ff_neterrno() : ret;
625 static int udp_write(URLContext *h, const uint8_t *buf, int size)
627 UDPContext *s = h->priv_data;
630 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
631 ret = ff_network_wait_fd(s->udp_fd, 1);
636 if (!s->is_connected) {
637 ret = sendto (s->udp_fd, buf, size, 0,
638 (struct sockaddr *) &s->dest_addr,
641 ret = send(s->udp_fd, buf, size, 0);
643 return ret < 0 ? ff_neterrno() : ret;
646 static int udp_close(URLContext *h)
648 UDPContext *s = h->priv_data;
651 if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
652 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
653 closesocket(s->udp_fd);
654 av_fifo_free(s->fifo);
656 if (s->thread_started) {
657 pthread_cancel(s->circular_buffer_thread);
658 ret = pthread_join(s->circular_buffer_thread, NULL);
660 av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
663 pthread_mutex_destroy(&s->mutex);
664 pthread_cond_destroy(&s->cond);
669 URLProtocol ff_udp_protocol = {
671 .url_open = udp_open,
672 .url_read = udp_read,
673 .url_write = udp_write,
674 .url_close = udp_close,
675 .url_get_file_handle = udp_get_file_handle,
676 .priv_data_size = sizeof(UDPContext),
677 .flags = URL_PROTOCOL_FLAG_NETWORK,