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
62 struct sockaddr_storage dest_addr;
66 /* Circular Buffer variables for use in UDP receive code */
67 int circular_buffer_size;
69 int circular_buffer_error;
71 pthread_t circular_buffer_thread;
72 pthread_mutex_t mutex;
75 uint8_t tmp[UDP_MAX_PKT_SIZE+4];
79 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
80 struct sockaddr *addr)
82 #ifdef IP_MULTICAST_TTL
83 if (addr->sa_family == AF_INET) {
84 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
85 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL): %s\n", strerror(errno));
90 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
91 if (addr->sa_family == AF_INET6) {
92 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
93 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS): %s\n", strerror(errno));
101 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
103 #ifdef IP_ADD_MEMBERSHIP
104 if (addr->sa_family == AF_INET) {
107 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
108 mreq.imr_interface.s_addr= INADDR_ANY;
109 if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
110 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno));
115 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
116 if (addr->sa_family == AF_INET6) {
117 struct ipv6_mreq mreq6;
119 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
120 mreq6.ipv6mr_interface= 0;
121 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
122 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP): %s\n", strerror(errno));
130 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
132 #ifdef IP_DROP_MEMBERSHIP
133 if (addr->sa_family == AF_INET) {
136 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
137 mreq.imr_interface.s_addr= INADDR_ANY;
138 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
139 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP): %s\n", strerror(errno));
144 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
145 if (addr->sa_family == AF_INET6) {
146 struct ipv6_mreq mreq6;
148 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
149 mreq6.ipv6mr_interface= 0;
150 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
151 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP): %s\n", strerror(errno));
159 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
160 int type, int family, int flags)
162 struct addrinfo hints, *res = 0;
165 const char *node = 0, *service = "0";
168 snprintf(sport, sizeof(sport), "%d", port);
171 if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
174 memset(&hints, 0, sizeof(hints));
175 hints.ai_socktype = type;
176 hints.ai_family = family;
177 hints.ai_flags = flags;
178 if ((error = getaddrinfo(node, service, &hints, &res))) {
180 av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
186 static int udp_set_url(struct sockaddr_storage *addr,
187 const char *hostname, int port)
189 struct addrinfo *res0;
192 res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
193 if (res0 == 0) return AVERROR(EIO);
194 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
195 addr_len = res0->ai_addrlen;
201 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
202 int *addr_len, const char *localaddr)
205 struct addrinfo *res0 = NULL, *res = NULL;
206 int family = AF_UNSPEC;
208 if (((struct sockaddr *) &s->dest_addr)->sa_family)
209 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
210 res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
211 SOCK_DGRAM, family, AI_PASSIVE);
214 for (res = res0; res; res=res->ai_next) {
215 udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
216 if (udp_fd > 0) break;
217 av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno));
223 memcpy(addr, res->ai_addr, res->ai_addrlen);
224 *addr_len = res->ai_addrlen;
238 static int udp_port(struct sockaddr_storage *addr, int addr_len)
240 char sbuf[sizeof(int)*3+1];
242 if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) {
243 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno));
247 return strtol(sbuf, NULL, 10);
252 * If no filename is given to av_open_input_file because you want to
253 * get the local port first, then you must call this function to set
254 * the remote server address.
256 * url syntax: udp://host:port[?option=val...]
257 * option: 'ttl=n' : set the ttl value (for multicast only)
258 * 'localport=n' : set the local port
259 * 'pkt_size=n' : set max packet size
260 * 'reuse=1' : enable reusing the socket
262 * @param h media file context
263 * @param uri of the remote server
264 * @return zero if no error.
266 int ff_udp_set_remote_url(URLContext *h, const char *uri)
268 UDPContext *s = h->priv_data;
269 char hostname[256], buf[10];
273 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
275 /* set the destination address */
276 s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
277 if (s->dest_addr_len < 0) {
280 s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
281 p = strchr(uri, '?');
283 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
284 int was_connected = s->is_connected;
285 s->is_connected = strtol(buf, NULL, 10);
286 if (s->is_connected && !was_connected) {
287 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
290 av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
301 * Return the local port used by the UDP connection
302 * @param h media file context
303 * @return the local port number
305 int ff_udp_get_local_port(URLContext *h)
307 UDPContext *s = h->priv_data;
308 return s->local_port;
312 * Return the udp file handle for select() usage to wait for several RTP
313 * streams at the same time.
314 * @param h media file context
316 static int udp_get_file_handle(URLContext *h)
318 UDPContext *s = h->priv_data;
323 static void *circular_buffer_task( void *_URLContext)
325 URLContext *h = _URLContext;
326 UDPContext *s = h->priv_data;
335 if (ff_check_interrupt(&h->interrupt_callback)) {
336 s->circular_buffer_error = EINTR;
341 FD_SET(s->udp_fd, &rfds);
344 ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv);
346 if (ff_neterrno() == AVERROR(EINTR))
348 s->circular_buffer_error = EIO;
352 if (!(ret > 0 && FD_ISSET(s->udp_fd, &rfds)))
355 /* How much do we have left to the end of the buffer */
356 /* Whats the minimum we can read so that we dont comletely fill the buffer */
357 left = av_fifo_space(s->fifo);
359 /* No Space left, error, what do we do now */
360 if(left < UDP_MAX_PKT_SIZE + 4) {
361 av_log(h, AV_LOG_ERROR, "circular_buffer: OVERRUN\n");
362 s->circular_buffer_error = EIO;
365 left = FFMIN(left, s->fifo->end - s->fifo->wptr);
366 len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
368 if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
369 s->circular_buffer_error = EIO;
374 AV_WL32(s->tmp, len);
375 pthread_mutex_lock(&s->mutex);
376 av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
377 pthread_cond_signal(&s->cond);
378 pthread_mutex_unlock(&s->mutex);
382 pthread_mutex_lock(&s->mutex);
383 pthread_cond_signal(&s->cond);
384 pthread_mutex_unlock(&s->mutex);
389 /* put it in UDP context */
390 /* return non zero if error */
391 static int udp_open(URLContext *h, const char *uri, int flags)
393 char hostname[1024], localaddr[1024] = "";
394 int port, udp_fd = -1, tmp, bind_ret = -1;
395 UDPContext *s = h->priv_data;
399 struct sockaddr_storage my_addr;
401 int reuse_specified = 0;
404 h->max_packet_size = 1472;
406 is_output = !(flags & AVIO_FLAG_READ);
409 s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
411 s->circular_buffer_size = 7*188*4096;
413 p = strchr(uri, '?');
415 if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
417 s->reuse_socket = strtol(buf, &endptr, 10);
418 /* assume if no digits were found it is a request to enable it */
423 if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
424 s->ttl = strtol(buf, NULL, 10);
426 if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
427 s->local_port = strtol(buf, NULL, 10);
429 if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
430 h->max_packet_size = strtol(buf, NULL, 10);
432 if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
433 s->buffer_size = strtol(buf, NULL, 10);
435 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
436 s->is_connected = strtol(buf, NULL, 10);
438 if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
439 s->circular_buffer_size = strtol(buf, NULL, 10)*188;
441 if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
442 av_strlcpy(localaddr, buf, sizeof(localaddr));
446 /* fill the dest addr */
447 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
449 /* XXX: fix av_url_split */
450 if (hostname[0] == '\0' || hostname[0] == '?') {
451 /* only accepts null hostname if input */
452 if (!(flags & AVIO_FLAG_READ))
455 if (ff_udp_set_remote_url(h, uri) < 0)
459 if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
460 s->local_port = port;
461 udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
465 /* Follow the requested reuse option, unless it's multicast in which
466 * case enable reuse unless explicitly disabled.
468 if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
470 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
474 /* the bind is needed to give a port to the socket now */
475 /* if multicast, try the multicast address bind first */
476 if (s->is_multicast && (h->flags & AVIO_FLAG_READ)) {
477 bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
479 /* bind to the local address if not multicast or if the multicast
481 if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0)
484 len = sizeof(my_addr);
485 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
486 s->local_port = udp_port(&my_addr, len);
488 if (s->is_multicast) {
489 if (!(h->flags & AVIO_FLAG_READ)) {
491 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
495 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
501 /* limit the tx buf size to limit latency */
502 tmp = s->buffer_size;
503 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
504 av_log(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF): %s\n", strerror(errno));
508 /* set udp recv buffer size to the largest possible udp packet size to
509 * avoid losing data on OSes that set this too low by default. */
510 tmp = s->buffer_size;
511 if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
512 av_log(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF): %s\n", strerror(errno));
514 /* make the socket non-blocking */
515 ff_socket_nonblock(udp_fd, 1);
517 if (s->is_connected) {
518 if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
519 av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
527 if (!is_output && s->circular_buffer_size) {
528 /* start the task going */
529 s->fifo = av_fifo_alloc(s->circular_buffer_size);
530 pthread_mutex_init(&s->mutex, NULL);
531 pthread_cond_init(&s->cond, NULL);
532 if (pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h)) {
533 av_log(h, AV_LOG_ERROR, "pthread_create failed\n");
543 av_fifo_free(s->fifo);
547 static int udp_read(URLContext *h, uint8_t *buf, int size)
549 UDPContext *s = h->priv_data;
555 pthread_mutex_lock(&s->mutex);
557 avail = av_fifo_size(s->fifo);
558 if (avail) { // >=size) {
560 pthread_mutex_unlock(&s->mutex);
562 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
565 av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
569 av_fifo_generic_read(s->fifo, buf, avail, NULL);
570 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
572 } else if(s->circular_buffer_error){
573 pthread_mutex_unlock(&s->mutex);
574 return s->circular_buffer_error;
575 } else if(h->flags & AVIO_FLAG_NONBLOCK) {
576 pthread_mutex_unlock(&s->mutex);
577 return AVERROR(EAGAIN);
580 pthread_cond_wait(&s->cond, &s->mutex);
586 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
587 ret = ff_network_wait_fd(s->udp_fd, 0);
591 ret = recv(s->udp_fd, buf, size, 0);
593 return ret < 0 ? ff_neterrno() : ret;
596 static int udp_write(URLContext *h, const uint8_t *buf, int size)
598 UDPContext *s = h->priv_data;
601 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
602 ret = ff_network_wait_fd(s->udp_fd, 1);
607 if (!s->is_connected) {
608 ret = sendto (s->udp_fd, buf, size, 0,
609 (struct sockaddr *) &s->dest_addr,
612 ret = send(s->udp_fd, buf, size, 0);
614 return ret < 0 ? ff_neterrno() : ret;
617 static int udp_close(URLContext *h)
619 UDPContext *s = h->priv_data;
621 if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
622 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
623 closesocket(s->udp_fd);
624 av_fifo_free(s->fifo);
626 pthread_mutex_destroy(&s->mutex);
627 pthread_cond_destroy(&s->cond);
632 URLProtocol ff_udp_protocol = {
634 .url_open = udp_open,
635 .url_read = udp_read,
636 .url_write = udp_write,
637 .url_close = udp_close,
638 .url_get_file_handle = udp_get_file_handle,
639 .priv_data_size = sizeof(UDPContext),