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 _DEFAULT_SOURCE
28 #define _BSD_SOURCE /* Needed for using struct ip_mreq with recent glibc */
31 #include "avio_internal.h"
32 #include "libavutil/avassert.h"
33 #include "libavutil/parseutils.h"
34 #include "libavutil/fifo.h"
35 #include "libavutil/intreadwrite.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/log.h"
39 #include "libavutil/time.h"
42 #include "os_support.h"
47 #include "TargetConditionals.h"
53 /* On many Linux systems, udplite.h is missing but the kernel supports UDP-Lite.
54 * So, we provide a fallback here.
56 #define UDPLITE_SEND_CSCOV 10
57 #define UDPLITE_RECV_CSCOV 11
60 #ifndef IPPROTO_UDPLITE
61 #define IPPROTO_UDPLITE 136
64 #if HAVE_PTHREAD_CANCEL
68 #ifndef IPV6_ADD_MEMBERSHIP
69 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
70 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
73 #define UDP_TX_BUF_SIZE 32768
74 #define UDP_RX_BUF_SIZE 393216
75 #define UDP_MAX_PKT_SIZE 65536
76 #define UDP_HEADER_SIZE 8
78 typedef struct UDPContext {
90 struct sockaddr_storage dest_addr;
94 /* Circular Buffer variables for use in UDP receive code */
95 int circular_buffer_size;
97 int circular_buffer_error;
98 int64_t bitrate; /* number of bits to send per second */
101 #if HAVE_PTHREAD_CANCEL
102 pthread_t circular_buffer_thread;
103 pthread_mutex_t mutex;
107 uint8_t tmp[UDP_MAX_PKT_SIZE+4];
111 struct sockaddr_storage local_addr_storage;
114 IPSourceFilters filters;
117 #define OFFSET(x) offsetof(UDPContext, x)
118 #define D AV_OPT_FLAG_DECODING_PARAM
119 #define E AV_OPT_FLAG_ENCODING_PARAM
120 static const AVOption options[] = {
121 { "buffer_size", "System data size (in bytes)", OFFSET(buffer_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
122 { "bitrate", "Bits to send per second", OFFSET(bitrate), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, .flags = E },
123 { "burst_bits", "Max length of bursts in bits (when using bitrate)", OFFSET(burst_bits), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, .flags = E },
124 { "localport", "Local port", OFFSET(local_port), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, D|E },
125 { "local_port", "Local port", OFFSET(local_port), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, .flags = D|E },
126 { "localaddr", "Local address", OFFSET(localaddr), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = D|E },
127 { "udplite_coverage", "choose UDPLite head size which should be validated by checksum", OFFSET(udplite_coverage), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, D|E },
128 { "pkt_size", "Maximum UDP packet size", OFFSET(pkt_size), AV_OPT_TYPE_INT, { .i64 = 1472 }, -1, INT_MAX, .flags = D|E },
129 { "reuse", "explicitly allow reusing UDP sockets", OFFSET(reuse_socket), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D|E },
130 { "reuse_socket", "explicitly allow reusing UDP sockets", OFFSET(reuse_socket), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, .flags = D|E },
131 { "broadcast", "explicitly allow or disallow broadcast destination", OFFSET(is_broadcast), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
132 { "ttl", "Time to live (multicast only)", OFFSET(ttl), AV_OPT_TYPE_INT, { .i64 = 16 }, 0, INT_MAX, E },
133 { "connect", "set if connect() should be called on socket", OFFSET(is_connected), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = D|E },
134 { "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 },
135 { "overrun_nonfatal", "survive in case of UDP receiving circular buffer overrun", OFFSET(overrun_nonfatal), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, D },
136 { "timeout", "set raise error timeout (only in read mode)", OFFSET(timeout), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
137 { "sources", "Source list", OFFSET(sources), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = D|E },
138 { "block", "Block list", OFFSET(block), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = D|E },
142 static const AVClass udp_class = {
144 .item_name = av_default_item_name,
146 .version = LIBAVUTIL_VERSION_INT,
149 static const AVClass udplite_context_class = {
150 .class_name = "udplite",
151 .item_name = av_default_item_name,
153 .version = LIBAVUTIL_VERSION_INT,
156 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
157 struct sockaddr *addr)
159 #ifdef IP_MULTICAST_TTL
160 if (addr->sa_family == AF_INET) {
161 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
162 ff_log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
167 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
168 if (addr->sa_family == AF_INET6) {
169 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
170 ff_log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
178 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr,struct sockaddr *local_addr)
180 #ifdef IP_ADD_MEMBERSHIP
181 if (addr->sa_family == AF_INET) {
184 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
186 mreq.imr_interface= ((struct sockaddr_in *)local_addr)->sin_addr;
188 mreq.imr_interface.s_addr= INADDR_ANY;
189 if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
190 ff_log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
195 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
196 if (addr->sa_family == AF_INET6) {
197 struct ipv6_mreq mreq6;
199 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
200 //TODO: Interface index should be looked up from local_addr
201 mreq6.ipv6mr_interface= 0;
202 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
203 ff_log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
211 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr,struct sockaddr *local_addr)
213 #ifdef IP_DROP_MEMBERSHIP
214 if (addr->sa_family == AF_INET) {
217 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
219 mreq.imr_interface= ((struct sockaddr_in *)local_addr)->sin_addr;
221 mreq.imr_interface.s_addr= INADDR_ANY;
222 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
223 ff_log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
228 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
229 if (addr->sa_family == AF_INET6) {
230 struct ipv6_mreq mreq6;
232 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
233 //TODO: Interface index should be looked up from local_addr
234 mreq6.ipv6mr_interface= 0;
235 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
236 ff_log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
244 static int udp_set_multicast_sources(URLContext *h,
245 int sockfd, struct sockaddr *addr,
246 int addr_len, struct sockaddr_storage *local_addr,
247 struct sockaddr_storage *sources,
248 int nb_sources, int include)
251 if (addr->sa_family != AF_INET) {
252 #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE)
253 /* For IPv4 prefer the old approach, as that alone works reliably on
254 * Windows and it also supports supplying the interface based on its
257 for (i = 0; i < nb_sources; i++) {
258 struct group_source_req mreqs;
259 int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
261 //TODO: Interface index should be looked up from local_addr
262 mreqs.gsr_interface = 0;
263 memcpy(&mreqs.gsr_group, addr, addr_len);
264 memcpy(&mreqs.gsr_source, &sources[i], sizeof(*sources));
266 if (setsockopt(sockfd, level,
267 include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
268 (const void *)&mreqs, sizeof(mreqs)) < 0) {
270 ff_log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
272 ff_log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
273 return ff_neterrno();
278 av_log(h, AV_LOG_ERROR,
279 "Setting multicast sources only supported for IPv4\n");
280 return AVERROR(EINVAL);
283 #if HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
284 for (i = 0; i < nb_sources; i++) {
285 struct ip_mreq_source mreqs;
286 if (sources[i].ss_family != AF_INET) {
287 av_log(h, AV_LOG_ERROR, "Source/block address %d is of incorrect protocol family\n", i + 1);
288 return AVERROR(EINVAL);
291 mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
293 mreqs.imr_interface= ((struct sockaddr_in *)local_addr)->sin_addr;
295 mreqs.imr_interface.s_addr= INADDR_ANY;
296 mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)&sources[i])->sin_addr.s_addr;
298 if (setsockopt(sockfd, IPPROTO_IP,
299 include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
300 (const void *)&mreqs, sizeof(mreqs)) < 0) {
302 ff_log_net_error(h, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
304 ff_log_net_error(h, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
305 return ff_neterrno();
309 return AVERROR(ENOSYS);
313 static int udp_set_url(URLContext *h,
314 struct sockaddr_storage *addr,
315 const char *hostname, int port)
317 struct addrinfo *res0;
320 res0 = ff_ip_resolve_host(h, hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
321 if (!res0) return AVERROR(EIO);
322 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
323 addr_len = res0->ai_addrlen;
329 static int udp_socket_create(URLContext *h, struct sockaddr_storage *addr,
330 socklen_t *addr_len, const char *localaddr)
332 UDPContext *s = h->priv_data;
334 struct addrinfo *res0, *res;
335 int family = AF_UNSPEC;
337 if (((struct sockaddr *) &s->dest_addr)->sa_family)
338 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
339 res0 = ff_ip_resolve_host(h, (localaddr && localaddr[0]) ? localaddr : NULL,
341 SOCK_DGRAM, family, AI_PASSIVE);
344 for (res = res0; res; res=res->ai_next) {
345 if (s->udplite_coverage)
346 udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, IPPROTO_UDPLITE);
348 udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, 0);
349 if (udp_fd != -1) break;
350 ff_log_net_error(NULL, AV_LOG_ERROR, "socket");
356 memcpy(addr, res->ai_addr, res->ai_addrlen);
357 *addr_len = res->ai_addrlen;
371 static int udp_port(struct sockaddr_storage *addr, int addr_len)
373 char sbuf[sizeof(int)*3+1];
376 if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
377 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
381 return strtol(sbuf, NULL, 10);
386 * If no filename is given to av_open_input_file because you want to
387 * get the local port first, then you must call this function to set
388 * the remote server address.
390 * url syntax: udp://host:port[?option=val...]
391 * option: 'ttl=n' : set the ttl value (for multicast only)
392 * 'localport=n' : set the local port
393 * 'pkt_size=n' : set max packet size
394 * 'reuse=1' : enable reusing the socket
395 * 'overrun_nonfatal=1': survive in case of circular buffer overrun
397 * @param h media file context
398 * @param uri of the remote server
399 * @return zero if no error.
401 int ff_udp_set_remote_url(URLContext *h, const char *uri)
403 UDPContext *s = h->priv_data;
404 char hostname[256], buf[10];
408 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
410 /* set the destination address */
411 s->dest_addr_len = udp_set_url(h, &s->dest_addr, hostname, port);
412 if (s->dest_addr_len < 0) {
415 s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
416 p = strchr(uri, '?');
418 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
419 int was_connected = s->is_connected;
420 s->is_connected = strtol(buf, NULL, 10);
421 if (s->is_connected && !was_connected) {
422 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
425 ff_log_net_error(h, AV_LOG_ERROR, "connect");
436 * Return the local port used by the UDP connection
437 * @param h media file context
438 * @return the local port number
440 int ff_udp_get_local_port(URLContext *h)
442 UDPContext *s = h->priv_data;
443 return s->local_port;
447 * Return the udp file handle for select() usage to wait for several RTP
448 * streams at the same time.
449 * @param h media file context
451 static int udp_get_file_handle(URLContext *h)
453 UDPContext *s = h->priv_data;
457 #if HAVE_PTHREAD_CANCEL
458 static void *circular_buffer_task_rx( void *_URLContext)
460 URLContext *h = _URLContext;
461 UDPContext *s = h->priv_data;
464 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
465 pthread_mutex_lock(&s->mutex);
466 if (ff_socket_nonblock(s->udp_fd, 0) < 0) {
467 av_log(h, AV_LOG_ERROR, "Failed to set blocking mode");
468 s->circular_buffer_error = AVERROR(EIO);
473 struct sockaddr_storage addr;
474 socklen_t addr_len = sizeof(addr);
476 pthread_mutex_unlock(&s->mutex);
477 /* Blocking operations are always cancellation points;
478 see "General Information" / "Thread Cancelation Overview"
480 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);
481 len = recvfrom(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0, (struct sockaddr *)&addr, &addr_len);
482 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
483 pthread_mutex_lock(&s->mutex);
485 if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
486 s->circular_buffer_error = ff_neterrno();
491 if (ff_ip_check_source_lists(&addr, &s->filters))
493 AV_WL32(s->tmp, len);
495 if(av_fifo_space(s->fifo) < len + 4) {
497 if (s->overrun_nonfatal) {
498 av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
499 "Surviving due to overrun_nonfatal option\n");
502 av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
503 "To avoid, increase fifo_size URL option. "
504 "To survive in such case, use overrun_nonfatal option\n");
505 s->circular_buffer_error = AVERROR(EIO);
509 av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
510 pthread_cond_signal(&s->cond);
514 pthread_cond_signal(&s->cond);
515 pthread_mutex_unlock(&s->mutex);
519 static void *circular_buffer_task_tx( void *_URLContext)
521 URLContext *h = _URLContext;
522 UDPContext *s = h->priv_data;
523 int64_t target_timestamp = av_gettime_relative();
524 int64_t start_timestamp = av_gettime_relative();
525 int64_t sent_bits = 0;
526 int64_t burst_interval = s->bitrate ? (s->burst_bits * 1000000 / s->bitrate) : 0;
527 int64_t max_delay = s->bitrate ? ((int64_t)h->max_packet_size * 8 * 1000000 / s->bitrate + 1) : 0;
529 pthread_mutex_lock(&s->mutex);
531 if (ff_socket_nonblock(s->udp_fd, 0) < 0) {
532 av_log(h, AV_LOG_ERROR, "Failed to set blocking mode");
533 s->circular_buffer_error = AVERROR(EIO);
543 len=av_fifo_size(s->fifo);
548 if (pthread_cond_wait(&s->cond, &s->mutex) < 0) {
551 len=av_fifo_size(s->fifo);
554 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
557 av_assert0(len >= 0);
558 av_assert0(len <= sizeof(s->tmp));
560 av_fifo_generic_read(s->fifo, s->tmp, len, NULL);
562 pthread_mutex_unlock(&s->mutex);
565 timestamp = av_gettime_relative();
566 if (timestamp < target_timestamp) {
567 int64_t delay = target_timestamp - timestamp;
568 if (delay > max_delay) {
570 start_timestamp = timestamp + delay;
575 if (timestamp - burst_interval > target_timestamp) {
576 start_timestamp = timestamp - burst_interval;
580 sent_bits += len * 8;
581 target_timestamp = start_timestamp + sent_bits * 1000000 / s->bitrate;
588 if (!s->is_connected) {
589 ret = sendto (s->udp_fd, p, len, 0,
590 (struct sockaddr *) &s->dest_addr,
593 ret = send(s->udp_fd, p, len, 0);
599 if (ret != AVERROR(EAGAIN) && ret != AVERROR(EINTR)) {
600 pthread_mutex_lock(&s->mutex);
601 s->circular_buffer_error = ret;
602 pthread_mutex_unlock(&s->mutex);
608 pthread_mutex_lock(&s->mutex);
612 pthread_mutex_unlock(&s->mutex);
619 /* put it in UDP context */
620 /* return non zero if error */
621 static int udp_open(URLContext *h, const char *uri, int flags)
623 char hostname[1024], localaddr[1024] = "";
624 int port, udp_fd = -1, tmp, bind_ret = -1, dscp = -1;
625 UDPContext *s = h->priv_data;
629 struct sockaddr_storage my_addr;
634 is_output = !(flags & AVIO_FLAG_READ);
635 if (s->buffer_size < 0)
636 s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_RX_BUF_SIZE;
639 if (ff_ip_parse_sources(h, s->sources, &s->filters) < 0)
644 if (ff_ip_parse_blocks(h, s->block, &s->filters) < 0)
649 h->max_packet_size = s->pkt_size;
651 p = strchr(uri, '?');
653 if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
655 s->reuse_socket = strtol(buf, &endptr, 10);
656 /* assume if no digits were found it is a request to enable it */
660 if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
662 s->overrun_nonfatal = strtol(buf, &endptr, 10);
663 /* assume if no digits were found it is a request to enable it */
665 s->overrun_nonfatal = 1;
666 if (!HAVE_PTHREAD_CANCEL)
667 av_log(h, AV_LOG_WARNING,
668 "'overrun_nonfatal' option was set but it is not supported "
669 "on this build (pthread support is required)\n");
671 if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
672 s->ttl = strtol(buf, NULL, 10);
674 if (av_find_info_tag(buf, sizeof(buf), "udplite_coverage", p)) {
675 s->udplite_coverage = strtol(buf, NULL, 10);
677 if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
678 s->local_port = strtol(buf, NULL, 10);
680 if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
681 s->pkt_size = strtol(buf, NULL, 10);
683 if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
684 s->buffer_size = strtol(buf, NULL, 10);
686 if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
687 s->is_connected = strtol(buf, NULL, 10);
689 if (av_find_info_tag(buf, sizeof(buf), "dscp", p)) {
690 dscp = strtol(buf, NULL, 10);
692 if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
693 s->circular_buffer_size = strtol(buf, NULL, 10);
694 if (!HAVE_PTHREAD_CANCEL)
695 av_log(h, AV_LOG_WARNING,
696 "'circular_buffer_size' option was set but it is not supported "
697 "on this build (pthread support is required)\n");
699 if (av_find_info_tag(buf, sizeof(buf), "bitrate", p)) {
700 s->bitrate = strtoll(buf, NULL, 10);
701 if (!HAVE_PTHREAD_CANCEL)
702 av_log(h, AV_LOG_WARNING,
703 "'bitrate' option was set but it is not supported "
704 "on this build (pthread support is required)\n");
706 if (av_find_info_tag(buf, sizeof(buf), "burst_bits", p)) {
707 s->burst_bits = strtoll(buf, NULL, 10);
709 if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
710 av_strlcpy(localaddr, buf, sizeof(localaddr));
712 if (av_find_info_tag(buf, sizeof(buf), "sources", p)) {
713 if (ff_ip_parse_sources(h, buf, &s->filters) < 0)
716 if (av_find_info_tag(buf, sizeof(buf), "block", p)) {
717 if (ff_ip_parse_blocks(h, buf, &s->filters) < 0)
720 if (!is_output && av_find_info_tag(buf, sizeof(buf), "timeout", p))
721 s->timeout = strtol(buf, NULL, 10);
722 if (is_output && av_find_info_tag(buf, sizeof(buf), "broadcast", p))
723 s->is_broadcast = strtol(buf, NULL, 10);
725 /* handling needed to support options picking from both AVOption and URL */
726 s->circular_buffer_size *= 188;
727 if (flags & AVIO_FLAG_WRITE) {
728 h->max_packet_size = s->pkt_size;
730 h->max_packet_size = UDP_MAX_PKT_SIZE;
732 h->rw_timeout = s->timeout;
734 /* fill the dest addr */
735 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
737 /* XXX: fix av_url_split */
738 if (hostname[0] == '\0' || hostname[0] == '?') {
739 /* only accepts null hostname if input */
740 if (!(flags & AVIO_FLAG_READ))
743 if (ff_udp_set_remote_url(h, uri) < 0)
747 if ((s->is_multicast || s->local_port <= 0) && (h->flags & AVIO_FLAG_READ))
748 s->local_port = port;
751 udp_fd = udp_socket_create(h, &my_addr, &len, localaddr);
753 udp_fd = udp_socket_create(h, &my_addr, &len, s->localaddr);
757 s->local_addr_storage=my_addr; //store for future multicast join
759 /* Follow the requested reuse option, unless it's multicast in which
760 * case enable reuse unless explicitly disabled.
762 if (s->reuse_socket > 0 || (s->is_multicast && s->reuse_socket < 0)) {
764 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
768 if (s->is_broadcast) {
770 if (setsockopt (udp_fd, SOL_SOCKET, SO_BROADCAST, &(s->is_broadcast), sizeof(s->is_broadcast)) != 0)
775 /* Set the checksum coverage for UDP-Lite (RFC 3828) for sending and receiving.
776 * The receiver coverage has to be less than or equal to the sender coverage.
777 * Otherwise, the receiver will drop all packets.
779 if (s->udplite_coverage) {
780 if (setsockopt (udp_fd, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, &(s->udplite_coverage), sizeof(s->udplite_coverage)) != 0)
781 av_log(h, AV_LOG_WARNING, "socket option UDPLITE_SEND_CSCOV not available");
783 if (setsockopt (udp_fd, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, &(s->udplite_coverage), sizeof(s->udplite_coverage)) != 0)
784 av_log(h, AV_LOG_WARNING, "socket option UDPLITE_RECV_CSCOV not available");
789 if (setsockopt (udp_fd, IPPROTO_IP, IP_TOS, &dscp, sizeof(dscp)) != 0)
793 /* If multicast, try binding the multicast address first, to avoid
794 * receiving UDP packets from other sources aimed at the same UDP
795 * port. This fails on windows. This makes sending to the same address
796 * using sendto() fail, so only do it if we're opened in read-only mode. */
797 if (s->is_multicast && (h->flags & AVIO_FLAG_READ)) {
798 bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
800 /* bind to the local address if not multicast or if the multicast
802 /* the bind is needed to give a port to the socket now */
803 if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
804 ff_log_net_error(h, AV_LOG_ERROR, "bind failed");
808 len = sizeof(my_addr);
809 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
810 s->local_port = udp_port(&my_addr, len);
812 if (s->is_multicast) {
813 if (h->flags & AVIO_FLAG_WRITE) {
815 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
818 if (h->flags & AVIO_FLAG_READ) {
820 if (s->filters.nb_include_addrs) {
821 if (udp_set_multicast_sources(h, udp_fd,
822 (struct sockaddr *)&s->dest_addr,
823 s->dest_addr_len, &s->local_addr_storage,
824 s->filters.include_addrs,
825 s->filters.nb_include_addrs, 1) < 0)
828 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr,(struct sockaddr *)&s->local_addr_storage) < 0)
831 if (s->filters.nb_exclude_addrs) {
832 if (udp_set_multicast_sources(h, udp_fd,
833 (struct sockaddr *)&s->dest_addr,
834 s->dest_addr_len, &s->local_addr_storage,
835 s->filters.exclude_addrs,
836 s->filters.nb_exclude_addrs, 0) < 0)
843 /* limit the tx buf size to limit latency */
844 tmp = s->buffer_size;
845 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
846 ff_log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
850 /* set udp recv buffer size to the requested value (default 64K) */
851 tmp = s->buffer_size;
852 if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
853 ff_log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
856 if (getsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, &len) < 0) {
857 ff_log_net_error(h, AV_LOG_WARNING, "getsockopt(SO_RCVBUF)");
859 av_log(h, AV_LOG_DEBUG, "end receive buffer size reported is %d\n", tmp);
860 if(tmp < s->buffer_size)
861 av_log(h, AV_LOG_WARNING, "attempted to set receive buffer to size %d but it only ended up set as %d\n", s->buffer_size, tmp);
864 /* make the socket non-blocking */
865 ff_socket_nonblock(udp_fd, 1);
867 if (s->is_connected) {
868 if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
869 ff_log_net_error(h, AV_LOG_ERROR, "connect");
876 #if HAVE_PTHREAD_CANCEL
878 Create thread in case of:
879 1. Input and circular_buffer_size is set
880 2. Output and bitrate and circular_buffer_size is set
883 if (is_output && s->bitrate && !s->circular_buffer_size) {
884 /* Warn user in case of 'circular_buffer_size' is not set */
885 av_log(h, AV_LOG_WARNING,"'bitrate' option was set but 'circular_buffer_size' is not, but required\n");
888 if ((!is_output && s->circular_buffer_size) || (is_output && s->bitrate && s->circular_buffer_size)) {
891 /* start the task going */
892 s->fifo = av_fifo_alloc(s->circular_buffer_size);
893 ret = pthread_mutex_init(&s->mutex, NULL);
895 av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
898 ret = pthread_cond_init(&s->cond, NULL);
900 av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
903 ret = pthread_create(&s->circular_buffer_thread, NULL, is_output?circular_buffer_task_tx:circular_buffer_task_rx, h);
905 av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
908 s->thread_started = 1;
913 #if HAVE_PTHREAD_CANCEL
915 pthread_cond_destroy(&s->cond);
917 pthread_mutex_destroy(&s->mutex);
922 av_fifo_freep(&s->fifo);
923 ff_ip_reset_filters(&s->filters);
927 static int udplite_open(URLContext *h, const char *uri, int flags)
929 UDPContext *s = h->priv_data;
931 // set default checksum coverage
932 s->udplite_coverage = UDP_HEADER_SIZE;
934 return udp_open(h, uri, flags);
937 static int udp_read(URLContext *h, uint8_t *buf, int size)
939 UDPContext *s = h->priv_data;
941 struct sockaddr_storage addr;
942 socklen_t addr_len = sizeof(addr);
943 #if HAVE_PTHREAD_CANCEL
944 int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
947 pthread_mutex_lock(&s->mutex);
949 avail = av_fifo_size(s->fifo);
950 if (avail) { // >=size) {
953 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
956 av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
960 av_fifo_generic_read(s->fifo, buf, avail, NULL);
961 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
962 pthread_mutex_unlock(&s->mutex);
964 } else if(s->circular_buffer_error){
965 int err = s->circular_buffer_error;
966 pthread_mutex_unlock(&s->mutex);
968 } else if(nonblock) {
969 pthread_mutex_unlock(&s->mutex);
970 return AVERROR(EAGAIN);
973 /* FIXME: using the monotonic clock would be better,
974 but it does not exist on all supported platforms. */
975 int64_t t = av_gettime() + 100000;
976 struct timespec tv = { .tv_sec = t / 1000000,
977 .tv_nsec = (t % 1000000) * 1000 };
978 int err = pthread_cond_timedwait(&s->cond, &s->mutex, &tv);
980 pthread_mutex_unlock(&s->mutex);
981 return AVERROR(err == ETIMEDOUT ? EAGAIN : err);
989 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
990 ret = ff_network_wait_fd(s->udp_fd, 0);
994 ret = recvfrom(s->udp_fd, buf, size, 0, (struct sockaddr *)&addr, &addr_len);
996 return ff_neterrno();
997 if (ff_ip_check_source_lists(&addr, &s->filters))
998 return AVERROR(EINTR);
1002 static int udp_write(URLContext *h, const uint8_t *buf, int size)
1004 UDPContext *s = h->priv_data;
1007 #if HAVE_PTHREAD_CANCEL
1011 pthread_mutex_lock(&s->mutex);
1014 Return error if last tx failed.
1015 Here we can't know on which packet error was, but it needs to know that error exists.
1017 if (s->circular_buffer_error<0) {
1018 int err=s->circular_buffer_error;
1019 pthread_mutex_unlock(&s->mutex);
1023 if(av_fifo_space(s->fifo) < size + 4) {
1024 /* What about a partial packet tx ? */
1025 pthread_mutex_unlock(&s->mutex);
1026 return AVERROR(ENOMEM);
1029 av_fifo_generic_write(s->fifo, tmp, 4, NULL); /* size of packet */
1030 av_fifo_generic_write(s->fifo, (uint8_t *)buf, size, NULL); /* the data */
1031 pthread_cond_signal(&s->cond);
1032 pthread_mutex_unlock(&s->mutex);
1036 if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
1037 ret = ff_network_wait_fd(s->udp_fd, 1);
1042 if (!s->is_connected) {
1043 ret = sendto (s->udp_fd, buf, size, 0,
1044 (struct sockaddr *) &s->dest_addr,
1047 ret = send(s->udp_fd, buf, size, 0);
1049 return ret < 0 ? ff_neterrno() : ret;
1052 static int udp_close(URLContext *h)
1054 UDPContext *s = h->priv_data;
1056 #if HAVE_PTHREAD_CANCEL
1057 // Request close once writing is finished
1058 if (s->thread_started && !(h->flags & AVIO_FLAG_READ)) {
1059 pthread_mutex_lock(&s->mutex);
1061 pthread_cond_signal(&s->cond);
1062 pthread_mutex_unlock(&s->mutex);
1066 if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
1067 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr,(struct sockaddr *)&s->local_addr_storage);
1068 #if HAVE_PTHREAD_CANCEL
1069 if (s->thread_started) {
1071 // Cancel only read, as write has been signaled as success to the user
1072 if (h->flags & AVIO_FLAG_READ) {
1074 /* recvfrom() is not a cancellation point for win32, so we shutdown
1075 * the socket and abort pending IO, subsequent recvfrom() calls
1076 * will fail with WSAESHUTDOWN causing the thread to exit. */
1077 shutdown(s->udp_fd, SD_RECEIVE);
1078 CancelIoEx((HANDLE)(SOCKET)s->udp_fd, NULL);
1080 pthread_cancel(s->circular_buffer_thread);
1083 ret = pthread_join(s->circular_buffer_thread, NULL);
1085 av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
1086 pthread_mutex_destroy(&s->mutex);
1087 pthread_cond_destroy(&s->cond);
1090 closesocket(s->udp_fd);
1091 av_fifo_freep(&s->fifo);
1092 ff_ip_reset_filters(&s->filters);
1096 const URLProtocol ff_udp_protocol = {
1098 .url_open = udp_open,
1099 .url_read = udp_read,
1100 .url_write = udp_write,
1101 .url_close = udp_close,
1102 .url_get_file_handle = udp_get_file_handle,
1103 .priv_data_size = sizeof(UDPContext),
1104 .priv_data_class = &udp_class,
1105 .flags = URL_PROTOCOL_FLAG_NETWORK,
1108 const URLProtocol ff_udplite_protocol = {
1110 .url_open = udplite_open,
1111 .url_read = udp_read,
1112 .url_write = udp_write,
1113 .url_close = udp_close,
1114 .url_get_file_handle = udp_get_file_handle,
1115 .priv_data_size = sizeof(UDPContext),
1116 .priv_data_class = &udplite_context_class,
1117 .flags = URL_PROTOCOL_FLAG_NETWORK,