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;
76 volatile int exit_thread;
78 uint8_t tmp[UDP_MAX_PKT_SIZE+4];
82 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
83 struct sockaddr *addr)
85 #ifdef IP_MULTICAST_TTL
86 if (addr->sa_family == AF_INET) {
87 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
88 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL): %s\n", strerror(errno));
93 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
94 if (addr->sa_family == AF_INET6) {
95 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
96 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS): %s\n", strerror(errno));
104 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
106 #ifdef IP_ADD_MEMBERSHIP
107 if (addr->sa_family == AF_INET) {
110 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
111 mreq.imr_interface.s_addr= INADDR_ANY;
112 if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
113 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno));
118 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
119 if (addr->sa_family == AF_INET6) {
120 struct ipv6_mreq mreq6;
122 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
123 mreq6.ipv6mr_interface= 0;
124 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
125 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP): %s\n", strerror(errno));
133 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
135 #ifdef IP_DROP_MEMBERSHIP
136 if (addr->sa_family == AF_INET) {
139 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
140 mreq.imr_interface.s_addr= INADDR_ANY;
141 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
142 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP): %s\n", strerror(errno));
147 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
148 if (addr->sa_family == AF_INET6) {
149 struct ipv6_mreq mreq6;
151 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
152 mreq6.ipv6mr_interface= 0;
153 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
154 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP): %s\n", strerror(errno));
162 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
163 int type, int family, int flags)
165 struct addrinfo hints, *res = 0;
168 const char *node = 0, *service = "0";
171 snprintf(sport, sizeof(sport), "%d", port);
174 if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
177 memset(&hints, 0, sizeof(hints));
178 hints.ai_socktype = type;
179 hints.ai_family = family;
180 hints.ai_flags = flags;
181 if ((error = getaddrinfo(node, service, &hints, &res))) {
183 av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
189 static int udp_set_url(struct sockaddr_storage *addr,
190 const char *hostname, int port)
192 struct addrinfo *res0;
195 res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
196 if (res0 == 0) return AVERROR(EIO);
197 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
198 addr_len = res0->ai_addrlen;
204 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
205 int *addr_len, const char *localaddr)
208 struct addrinfo *res0 = NULL, *res = NULL;
209 int family = AF_UNSPEC;
211 if (((struct sockaddr *) &s->dest_addr)->sa_family)
212 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
213 res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
214 SOCK_DGRAM, family, AI_PASSIVE);
217 for (res = res0; res; res=res->ai_next) {
218 udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
219 if (udp_fd > 0) break;
220 av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno));
226 memcpy(addr, res->ai_addr, res->ai_addrlen);
227 *addr_len = res->ai_addrlen;
241 static int udp_port(struct sockaddr_storage *addr, int addr_len)
243 char sbuf[sizeof(int)*3+1];
245 if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) {
246 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno));
250 return strtol(sbuf, NULL, 10);
255 * If no filename is given to av_open_input_file because you want to
256 * get the local port first, then you must call this function to set
257 * the remote server address.
259 * url syntax: udp://host:port[?option=val...]
260 * option: 'ttl=n' : set the ttl value (for multicast only)
261 * 'localport=n' : set the local port
262 * 'pkt_size=n' : set max packet size
263 * 'reuse=1' : enable reusing the socket
264 * 'overrun_nonfatal=1': survive in case of circular buffer overrun
266 * @param h media file context
267 * @param uri of the remote server
268 * @return zero if no error.
270 int ff_udp_set_remote_url(URLContext *h, const char *uri)
272 UDPContext *s = h->priv_data;
273 char hostname[256], buf[10];
277 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
279 /* set the destination address */
280 s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
281 if (s->dest_addr_len < 0) {
284 s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
285 p = strchr(uri, '?');
287 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
288 int was_connected = s->is_connected;
289 s->is_connected = strtol(buf, NULL, 10);
290 if (s->is_connected && !was_connected) {
291 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
294 av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
305 * Return the local port used by the UDP connection
306 * @param h media file context
307 * @return the local port number
309 int ff_udp_get_local_port(URLContext *h)
311 UDPContext *s = h->priv_data;
312 return s->local_port;
316 * Return the udp file handle for select() usage to wait for several RTP
317 * streams at the same time.
318 * @param h media file context
320 static int udp_get_file_handle(URLContext *h)
322 UDPContext *s = h->priv_data;
327 static void *circular_buffer_task( void *_URLContext)
329 URLContext *h = _URLContext;
330 UDPContext *s = h->priv_data;
334 while(!s->exit_thread) {
339 if (ff_check_interrupt(&h->interrupt_callback)) {
340 s->circular_buffer_error = AVERROR(EINTR);
345 FD_SET(s->udp_fd, &rfds);
348 ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv);
350 if (ff_neterrno() == AVERROR(EINTR))
352 s->circular_buffer_error = AVERROR(EIO);
356 if (!(ret > 0 && FD_ISSET(s->udp_fd, &rfds)))
359 /* How much do we have left to the end of the buffer */
360 /* Whats the minimum we can read so that we dont comletely fill the buffer */
361 left = av_fifo_space(s->fifo);
363 len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
365 if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
366 s->circular_buffer_error = AVERROR(EIO);
371 AV_WL32(s->tmp, len);
374 if (s->overrun_nonfatal) {
375 av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
376 "Surviving due to overrun_nonfatal option\n");
379 av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
380 "To avoid, increase fifo_size URL option. "
381 "To survive in such case, use overrun_nonfatal option\n");
382 s->circular_buffer_error = AVERROR(EIO);
386 pthread_mutex_lock(&s->mutex);
387 av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
388 pthread_cond_signal(&s->cond);
389 pthread_mutex_unlock(&s->mutex);
393 pthread_mutex_lock(&s->mutex);
394 pthread_cond_signal(&s->cond);
395 pthread_mutex_unlock(&s->mutex);
400 /* put it in UDP context */
401 /* return non zero if error */
402 static int udp_open(URLContext *h, const char *uri, int flags)
404 char hostname[1024], localaddr[1024] = "";
405 int port, udp_fd = -1, tmp, bind_ret = -1;
406 UDPContext *s = h->priv_data;
410 struct sockaddr_storage my_addr;
412 int reuse_specified = 0;
415 h->max_packet_size = 1472;
417 is_output = !(flags & AVIO_FLAG_READ);
420 s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
422 s->circular_buffer_size = 7*188*4096;
424 p = strchr(uri, '?');
426 if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
428 s->reuse_socket = strtol(buf, &endptr, 10);
429 /* assume if no digits were found it is a request to enable it */
434 if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
436 s->overrun_nonfatal = strtol(buf, &endptr, 10);
437 /* assume if no digits were found it is a request to enable it */
439 s->overrun_nonfatal = 1;
441 if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
442 s->ttl = strtol(buf, NULL, 10);
444 if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
445 s->local_port = strtol(buf, NULL, 10);
447 if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
448 h->max_packet_size = strtol(buf, NULL, 10);
450 if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
451 s->buffer_size = strtol(buf, NULL, 10);
453 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
454 s->is_connected = strtol(buf, NULL, 10);
456 if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
457 s->circular_buffer_size = strtol(buf, NULL, 10)*188;
459 if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
460 av_strlcpy(localaddr, buf, sizeof(localaddr));
464 /* fill the dest addr */
465 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
467 /* XXX: fix av_url_split */
468 if (hostname[0] == '\0' || hostname[0] == '?') {
469 /* only accepts null hostname if input */
470 if (!(flags & AVIO_FLAG_READ))
473 if (ff_udp_set_remote_url(h, uri) < 0)
477 if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
478 s->local_port = port;
479 udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
483 /* Follow the requested reuse option, unless it's multicast in which
484 * case enable reuse unless explicitly disabled.
486 if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
488 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
492 /* If multicast, try binding the multicast address first, to avoid
493 * receiving UDP packets from other sources aimed at the same UDP
494 * port. This fails on windows. This makes sending to the same address
495 * using sendto() fail, so only do it if we're opened in read-only mode. */
496 if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
497 bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
499 /* bind to the local address if not multicast or if the multicast
501 /* the bind is needed to give a port to the socket now */
502 if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
503 av_log(h, AV_LOG_ERROR, "bind failed: %s\n", strerror(errno));
507 len = sizeof(my_addr);
508 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
509 s->local_port = udp_port(&my_addr, len);
511 if (s->is_multicast) {
512 if (h->flags & AVIO_FLAG_WRITE) {
514 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
517 if (h->flags & AVIO_FLAG_READ) {
519 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
525 /* limit the tx buf size to limit latency */
526 tmp = s->buffer_size;
527 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
528 av_log(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF): %s\n", strerror(errno));
532 /* set udp recv buffer size to the largest possible udp packet size to
533 * avoid losing data on OSes that set this too low by default. */
534 tmp = s->buffer_size;
535 if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
536 av_log(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF): %s\n", strerror(errno));
538 /* make the socket non-blocking */
539 ff_socket_nonblock(udp_fd, 1);
541 if (s->is_connected) {
542 if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
543 av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
551 if (!is_output && s->circular_buffer_size) {
554 /* start the task going */
555 s->fifo = av_fifo_alloc(s->circular_buffer_size);
556 ret = pthread_mutex_init(&s->mutex, NULL);
558 av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
561 ret = pthread_cond_init(&s->cond, NULL);
563 av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
566 ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
568 av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
571 s->thread_started = 1;
578 pthread_cond_destroy(&s->cond);
580 pthread_mutex_destroy(&s->mutex);
585 av_fifo_free(s->fifo);
589 static int udp_read(URLContext *h, uint8_t *buf, int size)
591 UDPContext *s = h->priv_data;
597 pthread_mutex_lock(&s->mutex);
599 avail = av_fifo_size(s->fifo);
600 if (avail) { // >=size) {
602 pthread_mutex_unlock(&s->mutex);
604 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
607 av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
611 av_fifo_generic_read(s->fifo, buf, avail, NULL);
612 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
614 } else if(s->circular_buffer_error){
615 pthread_mutex_unlock(&s->mutex);
616 return s->circular_buffer_error;
617 } else if(h->flags & AVIO_FLAG_NONBLOCK) {
618 pthread_mutex_unlock(&s->mutex);
619 return AVERROR(EAGAIN);
622 pthread_cond_wait(&s->cond, &s->mutex);
628 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
629 ret = ff_network_wait_fd(s->udp_fd, 0);
633 ret = recv(s->udp_fd, buf, size, 0);
635 return ret < 0 ? ff_neterrno() : ret;
638 static int udp_write(URLContext *h, const uint8_t *buf, int size)
640 UDPContext *s = h->priv_data;
643 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
644 ret = ff_network_wait_fd(s->udp_fd, 1);
649 if (!s->is_connected) {
650 ret = sendto (s->udp_fd, buf, size, 0,
651 (struct sockaddr *) &s->dest_addr,
654 ret = send(s->udp_fd, buf, size, 0);
656 return ret < 0 ? ff_neterrno() : ret;
659 static int udp_close(URLContext *h)
661 UDPContext *s = h->priv_data;
664 if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
665 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
666 closesocket(s->udp_fd);
667 av_fifo_free(s->fifo);
669 if (s->thread_started) {
671 ret = pthread_join(s->circular_buffer_thread, NULL);
673 av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
676 pthread_mutex_destroy(&s->mutex);
677 pthread_cond_destroy(&s->cond);
682 URLProtocol ff_udp_protocol = {
684 .url_open = udp_open,
685 .url_read = udp_read,
686 .url_write = udp_write,
687 .url_close = udp_close,
688 .url_get_file_handle = udp_get_file_handle,
689 .priv_data_size = sizeof(UDPContext),
690 .flags = URL_PROTOCOL_FLAG_NETWORK,