]> git.sesse.net Git - ffmpeg/blob - libavformat/udp.c
7fc3843b466d56c7c102b7d03c657641af120343
[ffmpeg] / libavformat / udp.c
1 /*
2  * UDP prototype streaming system
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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.
11  *
12  * Libav 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.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * UDP protocol
25  */
26
27 #define _BSD_SOURCE     /* Needed for using struct ip_mreq with recent glibc */
28
29 #include "avformat.h"
30 #include "avio_internal.h"
31 #include "libavutil/parseutils.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/opt.h"
34 #include "internal.h"
35 #include "network.h"
36 #include "os_support.h"
37 #include "url.h"
38
39 #ifndef IPV6_ADD_MEMBERSHIP
40 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
41 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
42 #endif
43
44 typedef struct UDPContext {
45     const AVClass *class;
46     int udp_fd;
47     int ttl;
48     int buffer_size;
49     int pkt_size;
50     int is_multicast;
51     int local_port;
52     int reuse_socket;
53     struct sockaddr_storage dest_addr;
54     int dest_addr_len;
55     int is_connected;
56     char *localaddr;
57     char *sources;
58     char *block;
59 } UDPContext;
60
61 #define UDP_TX_BUF_SIZE 32768
62 #define UDP_MAX_PKT_SIZE 65536
63
64 #define OFFSET(x) offsetof(UDPContext, x)
65 #define D AV_OPT_FLAG_DECODING_PARAM
66 #define E AV_OPT_FLAG_ENCODING_PARAM
67 static const AVOption options[] = {
68     { "ttl",            "Time to live (in milliseconds, multicast only)",  OFFSET(ttl),            AV_OPT_TYPE_INT,    { .i64 = 16 },     0, INT_MAX, .flags = D|E },
69     { "buffer_size",    "System data size (in bytes)",                     OFFSET(buffer_size),    AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
70     { "local_port",     "Local port",                                      OFFSET(local_port),     AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
71     { "reuse_socket",   "Reuse socket",                                    OFFSET(reuse_socket),   AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, 1,       .flags = D|E },
72     { "connect",        "Connect socket",                                  OFFSET(is_connected),   AV_OPT_TYPE_INT,    { .i64 =  0 },     0, 1,       .flags = D|E },
73     { "pkt_size",       "Maximum packet size",                             OFFSET(pkt_size),       AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
74     { "localaddr",      "Local address",                                   OFFSET(localaddr),      AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
75     { "sources",        "Source list",                                     OFFSET(sources),        AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
76     { "block",          "Block list",                                      OFFSET(block),          AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
77     { NULL }
78 };
79
80 static const AVClass udp_class = {
81     .class_name = "udp",
82     .item_name  = av_default_item_name,
83     .option     = options,
84     .version    = LIBAVUTIL_VERSION_INT,
85 };
86
87 static void log_net_error(void *ctx, int level, const char* prefix)
88 {
89     char errbuf[100];
90     av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
91     av_log(ctx, level, "%s: %s\n", prefix, errbuf);
92 }
93
94 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
95                                  struct sockaddr *addr)
96 {
97 #ifdef IP_MULTICAST_TTL
98     if (addr->sa_family == AF_INET) {
99         if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
100             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
101             return -1;
102         }
103     }
104 #endif
105 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
106     if (addr->sa_family == AF_INET6) {
107         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
108             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
109             return -1;
110         }
111     }
112 #endif
113     return 0;
114 }
115
116 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
117 {
118 #ifdef IP_ADD_MEMBERSHIP
119     if (addr->sa_family == AF_INET) {
120         struct ip_mreq mreq;
121
122         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
123         mreq.imr_interface.s_addr= INADDR_ANY;
124         if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
125             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
126             return -1;
127         }
128     }
129 #endif
130 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
131     if (addr->sa_family == AF_INET6) {
132         struct ipv6_mreq mreq6;
133
134         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
135         mreq6.ipv6mr_interface= 0;
136         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
137             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
138             return -1;
139         }
140     }
141 #endif
142     return 0;
143 }
144
145 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
146 {
147 #ifdef IP_DROP_MEMBERSHIP
148     if (addr->sa_family == AF_INET) {
149         struct ip_mreq mreq;
150
151         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
152         mreq.imr_interface.s_addr= INADDR_ANY;
153         if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
154             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
155             return -1;
156         }
157     }
158 #endif
159 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
160     if (addr->sa_family == AF_INET6) {
161         struct ipv6_mreq mreq6;
162
163         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
164         mreq6.ipv6mr_interface= 0;
165         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
166             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
167             return -1;
168         }
169     }
170 #endif
171     return 0;
172 }
173
174 static struct addrinfo *udp_resolve_host(URLContext *h,
175                                          const char *hostname, int port,
176                                          int type, int family, int flags)
177 {
178     struct addrinfo hints = { 0 }, *res = 0;
179     int error;
180     char sport[16];
181     const char *node = 0, *service = "0";
182
183     if (port > 0) {
184         snprintf(sport, sizeof(sport), "%d", port);
185         service = sport;
186     }
187     if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
188         node = hostname;
189     }
190     hints.ai_socktype = type;
191     hints.ai_family   = family;
192     hints.ai_flags = flags;
193     if ((error = getaddrinfo(node, service, &hints, &res))) {
194         res = NULL;
195         av_log(h, AV_LOG_ERROR, "udp_resolve_host: %s\n",
196                gai_strerror(error));
197     }
198
199     return res;
200 }
201
202 static int udp_set_multicast_sources(URLContext *h,
203                                      int sockfd, struct sockaddr *addr,
204                                      int addr_len, char **sources,
205                                      int nb_sources, int include)
206 {
207 #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE) && !defined(_WIN32)
208     /* These ones are available in the microsoft SDK, but don't seem to work
209      * as on linux, so just prefer the v4-only approach there for now. */
210     int i;
211     for (i = 0; i < nb_sources; i++) {
212         struct group_source_req mreqs;
213         int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
214         struct addrinfo *sourceaddr = udp_resolve_host(h, sources[i], 0,
215                                                        SOCK_DGRAM, AF_UNSPEC,
216                                                        0);
217         if (!sourceaddr)
218             return AVERROR(ENOENT);
219
220         mreqs.gsr_interface = 0;
221         memcpy(&mreqs.gsr_group, addr, addr_len);
222         memcpy(&mreqs.gsr_source, sourceaddr->ai_addr, sourceaddr->ai_addrlen);
223         freeaddrinfo(sourceaddr);
224
225         if (setsockopt(sockfd, level,
226                        include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
227                        (const void *)&mreqs, sizeof(mreqs)) < 0) {
228             if (include)
229                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
230             else
231                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
232             return ff_neterrno();
233         }
234     }
235 #elif HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
236     int i;
237     if (addr->sa_family != AF_INET) {
238         av_log(NULL, AV_LOG_ERROR,
239                "Setting multicast sources only supported for IPv4\n");
240         return AVERROR(EINVAL);
241     }
242     for (i = 0; i < nb_sources; i++) {
243         struct ip_mreq_source mreqs;
244         struct addrinfo *sourceaddr = udp_resolve_host(h, sources[i], 0,
245                                                        SOCK_DGRAM, AF_UNSPEC,
246                                                        0);
247         if (!sourceaddr)
248             return AVERROR(ENOENT);
249         if (sourceaddr->ai_addr->sa_family != AF_INET) {
250             freeaddrinfo(sourceaddr);
251             av_log(NULL, AV_LOG_ERROR, "%s is of incorrect protocol family\n",
252                    sources[i]);
253             return AVERROR(EINVAL);
254         }
255
256         mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
257         mreqs.imr_interface.s_addr = INADDR_ANY;
258         mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)sourceaddr->ai_addr)->sin_addr.s_addr;
259         freeaddrinfo(sourceaddr);
260
261         if (setsockopt(sockfd, IPPROTO_IP,
262                        include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
263                        (const void *)&mreqs, sizeof(mreqs)) < 0) {
264             if (include)
265                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
266             else
267                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
268             return ff_neterrno();
269         }
270     }
271 #else
272     return AVERROR(ENOSYS);
273 #endif
274     return 0;
275 }
276 static int udp_set_url(URLContext *h,
277                        struct sockaddr_storage *addr,
278                        const char *hostname, int port)
279 {
280     struct addrinfo *res0;
281     int addr_len;
282
283     res0 = udp_resolve_host(h, hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
284     if (res0 == 0) return AVERROR(EIO);
285     memcpy(addr, res0->ai_addr, res0->ai_addrlen);
286     addr_len = res0->ai_addrlen;
287     freeaddrinfo(res0);
288
289     return addr_len;
290 }
291
292 static int udp_socket_create(URLContext *h, struct sockaddr_storage *addr,
293                              socklen_t *addr_len, const char *localaddr)
294 {
295     UDPContext *s = h->priv_data;
296     int udp_fd = -1;
297     struct addrinfo *res0 = NULL, *res = NULL;
298     int family = AF_UNSPEC;
299
300     if (((struct sockaddr *) &s->dest_addr)->sa_family)
301         family = ((struct sockaddr *) &s->dest_addr)->sa_family;
302     res0 = udp_resolve_host(h, (localaddr && localaddr[0]) ? localaddr : NULL,
303                             s->local_port,
304                             SOCK_DGRAM, family, AI_PASSIVE);
305     if (res0 == 0)
306         goto fail;
307     for (res = res0; res; res=res->ai_next) {
308         udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, 0);
309         if (udp_fd != -1) break;
310         log_net_error(NULL, AV_LOG_ERROR, "socket");
311     }
312
313     if (udp_fd < 0)
314         goto fail;
315
316     memcpy(addr, res->ai_addr, res->ai_addrlen);
317     *addr_len = res->ai_addrlen;
318
319     freeaddrinfo(res0);
320
321     return udp_fd;
322
323  fail:
324     if (udp_fd >= 0)
325         closesocket(udp_fd);
326     if(res0)
327         freeaddrinfo(res0);
328     return -1;
329 }
330
331 static int udp_port(struct sockaddr_storage *addr, int addr_len)
332 {
333     char sbuf[sizeof(int)*3+1];
334     int error;
335
336     if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0,  sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
337         av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
338         return -1;
339     }
340
341     return strtol(sbuf, NULL, 10);
342 }
343
344
345 /**
346  * If no filename is given to av_open_input_file because you want to
347  * get the local port first, then you must call this function to set
348  * the remote server address.
349  *
350  * url syntax: udp://host:port[?option=val...]
351  * option: 'ttl=n'       : set the ttl value (for multicast only)
352  *         'localport=n' : set the local port
353  *         'pkt_size=n'  : set max packet size
354  *         'reuse=1'     : enable reusing the socket
355  *
356  * @param h media file context
357  * @param uri of the remote server
358  * @return zero if no error.
359  */
360 int ff_udp_set_remote_url(URLContext *h, const char *uri)
361 {
362     UDPContext *s = h->priv_data;
363     char hostname[256], buf[10];
364     int port;
365     const char *p;
366
367     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
368
369     /* set the destination address */
370     s->dest_addr_len = udp_set_url(h, &s->dest_addr, hostname, port);
371     if (s->dest_addr_len < 0) {
372         return AVERROR(EIO);
373     }
374     s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
375     p = strchr(uri, '?');
376     if (p) {
377         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
378             int was_connected = s->is_connected;
379             s->is_connected = strtol(buf, NULL, 10);
380             if (s->is_connected && !was_connected) {
381                 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
382                             s->dest_addr_len)) {
383                     s->is_connected = 0;
384                     log_net_error(h, AV_LOG_ERROR, "connect");
385                     return AVERROR(EIO);
386                 }
387             }
388         }
389     }
390
391     return 0;
392 }
393
394 /**
395  * Return the local port used by the UDP connection
396  * @param h media file context
397  * @return the local port number
398  */
399 int ff_udp_get_local_port(URLContext *h)
400 {
401     UDPContext *s = h->priv_data;
402     return s->local_port;
403 }
404
405 /**
406  * Return the udp file handle for select() usage to wait for several RTP
407  * streams at the same time.
408  * @param h media file context
409  */
410 static int udp_get_file_handle(URLContext *h)
411 {
412     UDPContext *s = h->priv_data;
413     return s->udp_fd;
414 }
415
416 static int parse_source_list(char *buf, char **sources, int *num_sources,
417                              int max_sources)
418 {
419     char *source_start;
420
421     source_start = buf;
422     while (1) {
423         char *next = strchr(source_start, ',');
424         if (next)
425             *next = '\0';
426         sources[*num_sources] = av_strdup(source_start);
427         if (!sources[*num_sources])
428             return AVERROR(ENOMEM);
429         source_start = next + 1;
430         (*num_sources)++;
431         if (*num_sources >= max_sources || !next)
432             break;
433     }
434     return 0;
435 }
436
437 /* put it in UDP context */
438 /* return non zero if error */
439 static int udp_open(URLContext *h, const char *uri, int flags)
440 {
441     char hostname[1024], localaddr[1024] = "";
442     int port, udp_fd = -1, tmp, bind_ret = -1;
443     UDPContext *s = h->priv_data;
444     int is_output;
445     const char *p;
446     char buf[256];
447     struct sockaddr_storage my_addr;
448     socklen_t len;
449     int i, num_include_sources = 0, num_exclude_sources = 0;
450     char *include_sources[32], *exclude_sources[32];
451
452     h->is_streamed = 1;
453     h->max_packet_size = 1472;
454
455     is_output = !(flags & AVIO_FLAG_READ);
456
457     if (s->buffer_size < 0)
458         s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
459
460     if (s->sources) {
461         if (parse_source_list(s->sources, include_sources,
462                               &num_include_sources,
463                               FF_ARRAY_ELEMS(include_sources)))
464             goto fail;
465     }
466
467     if (s->block) {
468         if (parse_source_list(s->block, exclude_sources, &num_exclude_sources,
469                               FF_ARRAY_ELEMS(exclude_sources)))
470             goto fail;
471     }
472
473     if (s->pkt_size > 0)
474         h->max_packet_size = s->pkt_size;
475
476     p = strchr(uri, '?');
477     if (p) {
478         if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
479             char *endptr = NULL;
480             s->reuse_socket = strtol(buf, &endptr, 10);
481             /* assume if no digits were found it is a request to enable it */
482             if (buf == endptr)
483                 s->reuse_socket = 1;
484         }
485         if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
486             s->ttl = strtol(buf, NULL, 10);
487         }
488         if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
489             s->local_port = strtol(buf, NULL, 10);
490         }
491         if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
492             h->max_packet_size = strtol(buf, NULL, 10);
493         }
494         if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
495             s->buffer_size = strtol(buf, NULL, 10);
496         }
497         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
498             s->is_connected = strtol(buf, NULL, 10);
499         }
500         if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
501             av_strlcpy(localaddr, buf, sizeof(localaddr));
502         }
503         if (av_find_info_tag(buf, sizeof(buf), "sources", p)) {
504             if (parse_source_list(buf, include_sources, &num_include_sources,
505                                   FF_ARRAY_ELEMS(include_sources)))
506                 goto fail;
507         }
508         if (av_find_info_tag(buf, sizeof(buf), "block", p)) {
509             if (parse_source_list(buf, exclude_sources, &num_exclude_sources,
510                                   FF_ARRAY_ELEMS(exclude_sources)))
511                 goto fail;
512         }
513     }
514
515     /* fill the dest addr */
516     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
517
518     /* XXX: fix av_url_split */
519     if (hostname[0] == '\0' || hostname[0] == '?') {
520         /* only accepts null hostname if input */
521         if (!(flags & AVIO_FLAG_READ))
522             goto fail;
523     } else {
524         if (ff_udp_set_remote_url(h, uri) < 0)
525             goto fail;
526     }
527
528     if ((s->is_multicast || s->local_port < 0) && (h->flags & AVIO_FLAG_READ))
529         s->local_port = port;
530
531     if (localaddr[0])
532         udp_fd = udp_socket_create(h, &my_addr, &len, localaddr);
533     else
534         udp_fd = udp_socket_create(h, &my_addr, &len, s->localaddr);
535     if (udp_fd < 0)
536         goto fail;
537
538     /* Follow the requested reuse option, unless it's multicast in which
539      * case enable reuse unless explicitly disabled.
540      */
541     if (s->reuse_socket > 0 || (s->is_multicast && s->reuse_socket < 0)) {
542         s->reuse_socket = 1;
543         if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
544             goto fail;
545     }
546
547     /* If multicast, try binding the multicast address first, to avoid
548      * receiving UDP packets from other sources aimed at the same UDP
549      * port. This fails on windows. This makes sending to the same address
550      * using sendto() fail, so only do it if we're opened in read-only mode. */
551     if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
552         bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
553     }
554     /* bind to the local address if not multicast or if the multicast
555      * bind failed */
556     /* the bind is needed to give a port to the socket now */
557     if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
558         log_net_error(h, AV_LOG_ERROR, "bind failed");
559         goto fail;
560     }
561
562     len = sizeof(my_addr);
563     getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
564     s->local_port = udp_port(&my_addr, len);
565
566     if (s->is_multicast) {
567         if (h->flags & AVIO_FLAG_WRITE) {
568             /* output */
569             if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
570                 goto fail;
571         }
572         if (h->flags & AVIO_FLAG_READ) {
573             /* input */
574             if (num_include_sources && num_exclude_sources) {
575                 av_log(h, AV_LOG_ERROR, "Simultaneously including and excluding multicast sources is not supported\n");
576                 goto fail;
577             }
578             if (num_include_sources) {
579                 if (udp_set_multicast_sources(h, udp_fd,
580                                               (struct sockaddr *)&s->dest_addr,
581                                               s->dest_addr_len,
582                                               include_sources,
583                                               num_include_sources, 1) < 0)
584                     goto fail;
585             } else {
586                 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
587                     goto fail;
588             }
589             if (num_exclude_sources) {
590                 if (udp_set_multicast_sources(h, udp_fd,
591                                               (struct sockaddr *)&s->dest_addr,
592                                               s->dest_addr_len,
593                                               exclude_sources,
594                                               num_exclude_sources, 0) < 0)
595                     goto fail;
596             }
597         }
598     }
599
600     if (is_output) {
601         /* limit the tx buf size to limit latency */
602         tmp = s->buffer_size;
603         if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
604             log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
605             goto fail;
606         }
607     } else {
608         /* set udp recv buffer size to the largest possible udp packet size to
609          * avoid losing data on OSes that set this too low by default. */
610         tmp = s->buffer_size;
611         if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
612             log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
613         }
614         /* make the socket non-blocking */
615         ff_socket_nonblock(udp_fd, 1);
616     }
617     if (s->is_connected) {
618         if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
619             log_net_error(h, AV_LOG_ERROR, "connect");
620             goto fail;
621         }
622     }
623
624     for (i = 0; i < num_include_sources; i++)
625         av_freep(&include_sources[i]);
626     for (i = 0; i < num_exclude_sources; i++)
627         av_freep(&exclude_sources[i]);
628
629     s->udp_fd = udp_fd;
630     return 0;
631  fail:
632     if (udp_fd >= 0)
633         closesocket(udp_fd);
634     for (i = 0; i < num_include_sources; i++)
635         av_freep(&include_sources[i]);
636     for (i = 0; i < num_exclude_sources; i++)
637         av_freep(&exclude_sources[i]);
638     return AVERROR(EIO);
639 }
640
641 static int udp_read(URLContext *h, uint8_t *buf, int size)
642 {
643     UDPContext *s = h->priv_data;
644     int ret;
645
646     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
647         ret = ff_network_wait_fd(s->udp_fd, 0);
648         if (ret < 0)
649             return ret;
650     }
651     ret = recv(s->udp_fd, buf, size, 0);
652     return ret < 0 ? ff_neterrno() : ret;
653 }
654
655 static int udp_write(URLContext *h, const uint8_t *buf, int size)
656 {
657     UDPContext *s = h->priv_data;
658     int ret;
659
660     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
661         ret = ff_network_wait_fd(s->udp_fd, 1);
662         if (ret < 0)
663             return ret;
664     }
665
666     if (!s->is_connected) {
667         ret = sendto (s->udp_fd, buf, size, 0,
668                       (struct sockaddr *) &s->dest_addr,
669                       s->dest_addr_len);
670     } else
671         ret = send(s->udp_fd, buf, size, 0);
672
673     return ret < 0 ? ff_neterrno() : ret;
674 }
675
676 static int udp_close(URLContext *h)
677 {
678     UDPContext *s = h->priv_data;
679
680     if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
681         udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
682     closesocket(s->udp_fd);
683     return 0;
684 }
685
686 URLProtocol ff_udp_protocol = {
687     .name                = "udp",
688     .url_open            = udp_open,
689     .url_read            = udp_read,
690     .url_write           = udp_write,
691     .url_close           = udp_close,
692     .url_get_file_handle = udp_get_file_handle,
693     .priv_data_size      = sizeof(UDPContext),
694     .flags               = URL_PROTOCOL_FLAG_NETWORK,
695     .priv_data_class     = &udp_class,
696 };