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"
41 #if HAVE_PTHREAD_CANCEL
45 #ifndef IPV6_ADD_MEMBERSHIP
46 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
47 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
50 #define UDP_TX_BUF_SIZE 32768
51 #define UDP_MAX_PKT_SIZE 65536
61 struct sockaddr_storage dest_addr;
65 /* Circular Buffer variables for use in UDP receive code */
66 int circular_buffer_size;
68 int circular_buffer_error;
69 #if HAVE_PTHREAD_CANCEL
70 pthread_t circular_buffer_thread;
71 pthread_mutex_t mutex;
75 uint8_t tmp[UDP_MAX_PKT_SIZE+4];
79 static void log_net_error(void *ctx, int level, const char* prefix)
82 av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
83 av_log(ctx, level, "%s: %s\n", prefix, errbuf);
86 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
87 struct sockaddr *addr)
89 #ifdef IP_MULTICAST_TTL
90 if (addr->sa_family == AF_INET) {
91 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
92 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
97 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
98 if (addr->sa_family == AF_INET6) {
99 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
100 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
108 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
110 #ifdef IP_ADD_MEMBERSHIP
111 if (addr->sa_family == AF_INET) {
114 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
115 mreq.imr_interface.s_addr= INADDR_ANY;
116 if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
117 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
122 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
123 if (addr->sa_family == AF_INET6) {
124 struct ipv6_mreq mreq6;
126 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
127 mreq6.ipv6mr_interface= 0;
128 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
129 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
137 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
139 #ifdef IP_DROP_MEMBERSHIP
140 if (addr->sa_family == AF_INET) {
143 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
144 mreq.imr_interface.s_addr= INADDR_ANY;
145 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
146 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
151 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
152 if (addr->sa_family == AF_INET6) {
153 struct ipv6_mreq mreq6;
155 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
156 mreq6.ipv6mr_interface= 0;
157 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
158 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
166 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
167 int type, int family, int flags)
169 struct addrinfo hints = { 0 }, *res = 0;
172 const char *node = 0, *service = "0";
175 snprintf(sport, sizeof(sport), "%d", port);
178 if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
181 hints.ai_socktype = type;
182 hints.ai_family = family;
183 hints.ai_flags = flags;
184 if ((error = getaddrinfo(node, service, &hints, &res))) {
186 av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
192 static int udp_set_url(struct sockaddr_storage *addr,
193 const char *hostname, int port)
195 struct addrinfo *res0;
198 res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
199 if (res0 == 0) return AVERROR(EIO);
200 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
201 addr_len = res0->ai_addrlen;
207 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
208 int *addr_len, const char *localaddr)
211 struct addrinfo *res0 = NULL, *res = NULL;
212 int family = AF_UNSPEC;
214 if (((struct sockaddr *) &s->dest_addr)->sa_family)
215 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
216 res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
217 SOCK_DGRAM, family, AI_PASSIVE);
220 for (res = res0; res; res=res->ai_next) {
221 udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
222 if (udp_fd != -1) break;
223 log_net_error(NULL, AV_LOG_ERROR, "socket");
229 memcpy(addr, res->ai_addr, res->ai_addrlen);
230 *addr_len = res->ai_addrlen;
244 static int udp_port(struct sockaddr_storage *addr, int addr_len)
246 char sbuf[sizeof(int)*3+1];
249 if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
250 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
254 return strtol(sbuf, NULL, 10);
259 * If no filename is given to av_open_input_file because you want to
260 * get the local port first, then you must call this function to set
261 * the remote server address.
263 * url syntax: udp://host:port[?option=val...]
264 * option: 'ttl=n' : set the ttl value (for multicast only)
265 * 'localport=n' : set the local port
266 * 'pkt_size=n' : set max packet size
267 * 'reuse=1' : enable reusing the socket
268 * 'overrun_nonfatal=1': survive in case of circular buffer overrun
270 * @param h media file context
271 * @param uri of the remote server
272 * @return zero if no error.
274 int ff_udp_set_remote_url(URLContext *h, const char *uri)
276 UDPContext *s = h->priv_data;
277 char hostname[256], buf[10];
281 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
283 /* set the destination address */
284 s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
285 if (s->dest_addr_len < 0) {
288 s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
289 p = strchr(uri, '?');
291 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
292 int was_connected = s->is_connected;
293 s->is_connected = strtol(buf, NULL, 10);
294 if (s->is_connected && !was_connected) {
295 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
298 log_net_error(h, AV_LOG_ERROR, "connect");
309 * Return the local port used by the UDP connection
310 * @param h media file context
311 * @return the local port number
313 int ff_udp_get_local_port(URLContext *h)
315 UDPContext *s = h->priv_data;
316 return s->local_port;
320 * Return the udp file handle for select() usage to wait for several RTP
321 * streams at the same time.
322 * @param h media file context
324 static int udp_get_file_handle(URLContext *h)
326 UDPContext *s = h->priv_data;
330 #if HAVE_PTHREAD_CANCEL
331 static void *circular_buffer_task( void *_URLContext)
333 URLContext *h = _URLContext;
334 UDPContext *s = h->priv_data;
337 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
338 ff_socket_nonblock(s->udp_fd, 0);
339 pthread_mutex_lock(&s->mutex);
343 pthread_mutex_unlock(&s->mutex);
344 /* Blocking operations are always cancellation points;
345 see "General Information" / "Thread Cancelation Overview"
347 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);
348 len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
349 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
350 pthread_mutex_lock(&s->mutex);
352 if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
353 s->circular_buffer_error = ff_neterrno();
358 AV_WL32(s->tmp, len);
360 if(av_fifo_space(s->fifo) < len + 4) {
362 if (s->overrun_nonfatal) {
363 av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
364 "Surviving due to overrun_nonfatal option\n");
367 av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
368 "To avoid, increase fifo_size URL option. "
369 "To survive in such case, use overrun_nonfatal option\n");
370 s->circular_buffer_error = AVERROR(EIO);
374 av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
375 pthread_cond_signal(&s->cond);
379 pthread_cond_signal(&s->cond);
380 pthread_mutex_unlock(&s->mutex);
385 /* put it in UDP context */
386 /* return non zero if error */
387 static int udp_open(URLContext *h, const char *uri, int flags)
389 char hostname[1024], localaddr[1024] = "";
390 int port, udp_fd = -1, tmp, bind_ret = -1;
391 UDPContext *s = h->priv_data;
395 struct sockaddr_storage my_addr;
397 int reuse_specified = 0;
400 h->max_packet_size = 1472;
402 is_output = !(flags & AVIO_FLAG_READ);
405 s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
407 s->circular_buffer_size = 7*188*4096;
409 p = strchr(uri, '?');
411 if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
413 s->reuse_socket = strtol(buf, &endptr, 10);
414 /* assume if no digits were found it is a request to enable it */
419 if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
421 s->overrun_nonfatal = strtol(buf, &endptr, 10);
422 /* assume if no digits were found it is a request to enable it */
424 s->overrun_nonfatal = 1;
426 if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
427 s->ttl = strtol(buf, NULL, 10);
429 if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
430 s->local_port = strtol(buf, NULL, 10);
432 if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
433 h->max_packet_size = strtol(buf, NULL, 10);
435 if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
436 s->buffer_size = strtol(buf, NULL, 10);
438 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
439 s->is_connected = strtol(buf, NULL, 10);
441 if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
442 s->circular_buffer_size = strtol(buf, NULL, 10)*188;
444 if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
445 av_strlcpy(localaddr, buf, sizeof(localaddr));
449 /* fill the dest addr */
450 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
452 /* XXX: fix av_url_split */
453 if (hostname[0] == '\0' || hostname[0] == '?') {
454 /* only accepts null hostname if input */
455 if (!(flags & AVIO_FLAG_READ))
458 if (ff_udp_set_remote_url(h, uri) < 0)
462 if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
463 s->local_port = port;
464 udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
468 /* Follow the requested reuse option, unless it's multicast in which
469 * case enable reuse unless explicitly disabled.
471 if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
473 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
477 /* If multicast, try binding the multicast address first, to avoid
478 * receiving UDP packets from other sources aimed at the same UDP
479 * port. This fails on windows. This makes sending to the same address
480 * using sendto() fail, so only do it if we're opened in read-only mode. */
481 if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
482 bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
484 /* bind to the local address if not multicast or if the multicast
486 /* the bind is needed to give a port to the socket now */
487 if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
488 log_net_error(h, AV_LOG_ERROR, "bind failed");
492 len = sizeof(my_addr);
493 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
494 s->local_port = udp_port(&my_addr, len);
496 if (s->is_multicast) {
497 if (h->flags & AVIO_FLAG_WRITE) {
499 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
502 if (h->flags & AVIO_FLAG_READ) {
504 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
510 /* limit the tx buf size to limit latency */
511 tmp = s->buffer_size;
512 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
513 log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
517 /* set udp recv buffer size to the largest possible udp packet size to
518 * avoid losing data on OSes that set this too low by default. */
519 tmp = s->buffer_size;
520 if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
521 log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
523 /* make the socket non-blocking */
524 ff_socket_nonblock(udp_fd, 1);
526 if (s->is_connected) {
527 if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
528 log_net_error(h, AV_LOG_ERROR, "connect");
535 #if HAVE_PTHREAD_CANCEL
536 if (!is_output && s->circular_buffer_size) {
539 /* start the task going */
540 s->fifo = av_fifo_alloc(s->circular_buffer_size);
541 ret = pthread_mutex_init(&s->mutex, NULL);
543 av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
546 ret = pthread_cond_init(&s->cond, NULL);
548 av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
551 ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
553 av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
556 s->thread_started = 1;
561 #if HAVE_PTHREAD_CANCEL
563 pthread_cond_destroy(&s->cond);
565 pthread_mutex_destroy(&s->mutex);
570 av_fifo_free(s->fifo);
574 static int udp_read(URLContext *h, uint8_t *buf, int size)
576 UDPContext *s = h->priv_data;
578 int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
580 #if HAVE_PTHREAD_CANCEL
582 pthread_mutex_lock(&s->mutex);
584 avail = av_fifo_size(s->fifo);
585 if (avail) { // >=size) {
588 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
591 av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
595 av_fifo_generic_read(s->fifo, buf, avail, NULL);
596 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
597 pthread_mutex_unlock(&s->mutex);
599 } else if(s->circular_buffer_error){
600 int err = s->circular_buffer_error;
601 pthread_mutex_unlock(&s->mutex);
603 } else if(nonblock) {
604 pthread_mutex_unlock(&s->mutex);
605 return AVERROR(EAGAIN);
608 /* FIXME: using the monotonic clock would be better,
609 but it does not exist on all supported platforms. */
610 int64_t t = av_gettime() + 100000;
611 struct timespec tv = { .tv_sec = t / 1000000,
612 .tv_nsec = (t % 1000000) * 1000 };
613 if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0)
614 return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
621 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
622 ret = ff_network_wait_fd(s->udp_fd, 0);
626 ret = recv(s->udp_fd, buf, size, 0);
628 return ret < 0 ? ff_neterrno() : ret;
631 static int udp_write(URLContext *h, const uint8_t *buf, int size)
633 UDPContext *s = h->priv_data;
636 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
637 ret = ff_network_wait_fd(s->udp_fd, 1);
642 if (!s->is_connected) {
643 ret = sendto (s->udp_fd, buf, size, 0,
644 (struct sockaddr *) &s->dest_addr,
647 ret = send(s->udp_fd, buf, size, 0);
649 return ret < 0 ? ff_neterrno() : ret;
652 static int udp_close(URLContext *h)
654 UDPContext *s = h->priv_data;
657 if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
658 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
659 closesocket(s->udp_fd);
660 av_fifo_free(s->fifo);
661 #if HAVE_PTHREAD_CANCEL
662 if (s->thread_started) {
663 pthread_cancel(s->circular_buffer_thread);
664 ret = pthread_join(s->circular_buffer_thread, NULL);
666 av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
669 pthread_mutex_destroy(&s->mutex);
670 pthread_cond_destroy(&s->cond);
675 URLProtocol ff_udp_protocol = {
677 .url_open = udp_open,
678 .url_read = udp_read,
679 .url_write = udp_write,
680 .url_close = udp_close,
681 .url_get_file_handle = udp_get_file_handle,
682 .priv_data_size = sizeof(UDPContext),
683 .flags = URL_PROTOCOL_FLAG_NETWORK,