]> git.sesse.net Git - ffmpeg/blob - libavformat/udp.c
Merge remote-tracking branch 'qatar/master'
[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 FFmpeg.
6  *
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.
11  *
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.
16  *
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
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/fifo.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/avstring.h"
35 #include "internal.h"
36 #include "network.h"
37 #include "os_support.h"
38 #include "url.h"
39
40 #if HAVE_PTHREAD_CANCEL
41 #include <pthread.h>
42 #endif
43
44 #ifndef IPV6_ADD_MEMBERSHIP
45 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
46 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
47 #endif
48
49 #define UDP_TX_BUF_SIZE 32768
50 #define UDP_MAX_PKT_SIZE 65536
51
52 typedef struct {
53     int udp_fd;
54     int ttl;
55     int buffer_size;
56     int is_multicast;
57     int local_port;
58     int reuse_socket;
59     int overrun_nonfatal;
60     struct sockaddr_storage dest_addr;
61     int dest_addr_len;
62     int is_connected;
63
64     /* Circular Buffer variables for use in UDP receive code */
65     int circular_buffer_size;
66     AVFifoBuffer *fifo;
67     int circular_buffer_error;
68 #if HAVE_PTHREAD_CANCEL
69     pthread_t circular_buffer_thread;
70     pthread_mutex_t mutex;
71     pthread_cond_t cond;
72     int thread_started;
73 #endif
74     uint8_t tmp[UDP_MAX_PKT_SIZE+4];
75     int remaining_in_dg;
76 } UDPContext;
77
78 static void log_net_error(void *ctx, int level, const char* prefix)
79 {
80     char errbuf[100];
81     av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
82     av_log(ctx, level, "%s: %s\n", prefix, errbuf);
83 }
84
85 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
86                                  struct sockaddr *addr)
87 {
88 #ifdef IP_MULTICAST_TTL
89     if (addr->sa_family == AF_INET) {
90         if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
91             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
92             return -1;
93         }
94     }
95 #endif
96 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
97     if (addr->sa_family == AF_INET6) {
98         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
99             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
100             return -1;
101         }
102     }
103 #endif
104     return 0;
105 }
106
107 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
108 {
109 #ifdef IP_ADD_MEMBERSHIP
110     if (addr->sa_family == AF_INET) {
111         struct ip_mreq mreq;
112
113         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
114         mreq.imr_interface.s_addr= INADDR_ANY;
115         if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
116             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
117             return -1;
118         }
119     }
120 #endif
121 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
122     if (addr->sa_family == AF_INET6) {
123         struct ipv6_mreq mreq6;
124
125         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
126         mreq6.ipv6mr_interface= 0;
127         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
128             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
129             return -1;
130         }
131     }
132 #endif
133     return 0;
134 }
135
136 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
137 {
138 #ifdef IP_DROP_MEMBERSHIP
139     if (addr->sa_family == AF_INET) {
140         struct ip_mreq mreq;
141
142         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
143         mreq.imr_interface.s_addr= INADDR_ANY;
144         if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
145             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
146             return -1;
147         }
148     }
149 #endif
150 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
151     if (addr->sa_family == AF_INET6) {
152         struct ipv6_mreq mreq6;
153
154         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
155         mreq6.ipv6mr_interface= 0;
156         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
157             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
158             return -1;
159         }
160     }
161 #endif
162     return 0;
163 }
164
165 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
166                                          int type, int family, int flags)
167 {
168     struct addrinfo hints = { 0 }, *res = 0;
169     int error;
170     char sport[16];
171     const char *node = 0, *service = "0";
172
173     if (port > 0) {
174         snprintf(sport, sizeof(sport), "%d", port);
175         service = sport;
176     }
177     if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
178         node = hostname;
179     }
180     hints.ai_socktype = type;
181     hints.ai_family   = family;
182     hints.ai_flags = flags;
183     if ((error = getaddrinfo(node, service, &hints, &res))) {
184         res = NULL;
185         av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
186     }
187
188     return res;
189 }
190
191 static int udp_set_multicast_sources(int sockfd, struct sockaddr *addr,
192                                      int addr_len, char **sources,
193                                      int nb_sources, int include)
194 {
195 #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE) && !defined(_WIN32)
196     /* These ones are available in the microsoft SDK, but don't seem to work
197      * as on linux, so just prefer the v4-only approach there for now. */
198     int i;
199     for (i = 0; i < nb_sources; i++) {
200         struct group_source_req mreqs;
201         int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
202         struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
203                                                        SOCK_DGRAM, AF_UNSPEC,
204                                                        AI_NUMERICHOST);
205         if (!sourceaddr)
206             return AVERROR(ENOENT);
207
208         mreqs.gsr_interface = 0;
209         memcpy(&mreqs.gsr_group, addr, addr_len);
210         memcpy(&mreqs.gsr_source, sourceaddr->ai_addr, sourceaddr->ai_addrlen);
211         freeaddrinfo(sourceaddr);
212
213         if (setsockopt(sockfd, level,
214                        include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
215                        (const void *)&mreqs, sizeof(mreqs)) < 0) {
216             if (include)
217                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
218             else
219                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
220             return ff_neterrno();
221         }
222     }
223 #elif HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
224     int i;
225     if (addr->sa_family != AF_INET) {
226         av_log(NULL, AV_LOG_ERROR,
227                "Setting multicast sources only supported for IPv4\n");
228         return AVERROR(EINVAL);
229     }
230     for (i = 0; i < nb_sources; i++) {
231         struct ip_mreq_source mreqs;
232         struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
233                                                        SOCK_DGRAM, AF_UNSPEC,
234                                                        AI_NUMERICHOST);
235         if (!sourceaddr)
236             return AVERROR(ENOENT);
237         if (sourceaddr->ai_addr->sa_family != AF_INET) {
238             freeaddrinfo(sourceaddr);
239             av_log(NULL, AV_LOG_ERROR, "%s is of incorrect protocol family\n",
240                    sources[i]);
241             return AVERROR(EINVAL);
242         }
243
244         mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
245         mreqs.imr_interface.s_addr = INADDR_ANY;
246         mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)sourceaddr->ai_addr)->sin_addr.s_addr;
247         freeaddrinfo(sourceaddr);
248
249         if (setsockopt(sockfd, IPPROTO_IP,
250                        include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
251                        (const void *)&mreqs, sizeof(mreqs)) < 0) {
252             if (include)
253                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
254             else
255                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
256             return ff_neterrno();
257         }
258     }
259 #else
260     return AVERROR(ENOSYS);
261 #endif
262     return 0;
263 }
264 static int udp_set_url(struct sockaddr_storage *addr,
265                        const char *hostname, int port)
266 {
267     struct addrinfo *res0;
268     int addr_len;
269
270     res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
271     if (res0 == 0) return AVERROR(EIO);
272     memcpy(addr, res0->ai_addr, res0->ai_addrlen);
273     addr_len = res0->ai_addrlen;
274     freeaddrinfo(res0);
275
276     return addr_len;
277 }
278
279 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
280                              int *addr_len, const char *localaddr)
281 {
282     int udp_fd = -1;
283     struct addrinfo *res0 = NULL, *res = NULL;
284     int family = AF_UNSPEC;
285
286     if (((struct sockaddr *) &s->dest_addr)->sa_family)
287         family = ((struct sockaddr *) &s->dest_addr)->sa_family;
288     res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
289                             SOCK_DGRAM, family, AI_PASSIVE);
290     if (res0 == 0)
291         goto fail;
292     for (res = res0; res; res=res->ai_next) {
293         udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
294         if (udp_fd != -1) break;
295         log_net_error(NULL, AV_LOG_ERROR, "socket");
296     }
297
298     if (udp_fd < 0)
299         goto fail;
300
301     memcpy(addr, res->ai_addr, res->ai_addrlen);
302     *addr_len = res->ai_addrlen;
303
304     freeaddrinfo(res0);
305
306     return udp_fd;
307
308  fail:
309     if (udp_fd >= 0)
310         closesocket(udp_fd);
311     if(res0)
312         freeaddrinfo(res0);
313     return -1;
314 }
315
316 static int udp_port(struct sockaddr_storage *addr, int addr_len)
317 {
318     char sbuf[sizeof(int)*3+1];
319     int error;
320
321     if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0,  sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
322         av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
323         return -1;
324     }
325
326     return strtol(sbuf, NULL, 10);
327 }
328
329
330 /**
331  * If no filename is given to av_open_input_file because you want to
332  * get the local port first, then you must call this function to set
333  * the remote server address.
334  *
335  * url syntax: udp://host:port[?option=val...]
336  * option: 'ttl=n'       : set the ttl value (for multicast only)
337  *         'localport=n' : set the local port
338  *         'pkt_size=n'  : set max packet size
339  *         'reuse=1'     : enable reusing the socket
340  *         'overrun_nonfatal=1': survive in case of circular buffer overrun
341  *
342  * @param h media file context
343  * @param uri of the remote server
344  * @return zero if no error.
345  */
346 int ff_udp_set_remote_url(URLContext *h, const char *uri)
347 {
348     UDPContext *s = h->priv_data;
349     char hostname[256], buf[10];
350     int port;
351     const char *p;
352
353     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
354
355     /* set the destination address */
356     s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
357     if (s->dest_addr_len < 0) {
358         return AVERROR(EIO);
359     }
360     s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
361     p = strchr(uri, '?');
362     if (p) {
363         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
364             int was_connected = s->is_connected;
365             s->is_connected = strtol(buf, NULL, 10);
366             if (s->is_connected && !was_connected) {
367                 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
368                             s->dest_addr_len)) {
369                     s->is_connected = 0;
370                     log_net_error(h, AV_LOG_ERROR, "connect");
371                     return AVERROR(EIO);
372                 }
373             }
374         }
375     }
376
377     return 0;
378 }
379
380 /**
381  * Return the local port used by the UDP connection
382  * @param h media file context
383  * @return the local port number
384  */
385 int ff_udp_get_local_port(URLContext *h)
386 {
387     UDPContext *s = h->priv_data;
388     return s->local_port;
389 }
390
391 /**
392  * Return the udp file handle for select() usage to wait for several RTP
393  * streams at the same time.
394  * @param h media file context
395  */
396 static int udp_get_file_handle(URLContext *h)
397 {
398     UDPContext *s = h->priv_data;
399     return s->udp_fd;
400 }
401
402 #if HAVE_PTHREAD_CANCEL
403 static void *circular_buffer_task( void *_URLContext)
404 {
405     URLContext *h = _URLContext;
406     UDPContext *s = h->priv_data;
407     int old_cancelstate;
408
409     pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
410     ff_socket_nonblock(s->udp_fd, 0);
411     pthread_mutex_lock(&s->mutex);
412     while(1) {
413         int len;
414
415         pthread_mutex_unlock(&s->mutex);
416         /* Blocking operations are always cancellation points;
417            see "General Information" / "Thread Cancelation Overview"
418            in Single Unix. */
419         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);
420         len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
421         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
422         pthread_mutex_lock(&s->mutex);
423         if (len < 0) {
424             if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
425                 s->circular_buffer_error = ff_neterrno();
426                 goto end;
427             }
428             continue;
429         }
430         AV_WL32(s->tmp, len);
431
432         if(av_fifo_space(s->fifo) < len + 4) {
433             /* No Space left */
434             if (s->overrun_nonfatal) {
435                 av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
436                         "Surviving due to overrun_nonfatal option\n");
437                 continue;
438             } else {
439                 av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
440                         "To avoid, increase fifo_size URL option. "
441                         "To survive in such case, use overrun_nonfatal option\n");
442                 s->circular_buffer_error = AVERROR(EIO);
443                 goto end;
444             }
445         }
446         av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
447         pthread_cond_signal(&s->cond);
448     }
449
450 end:
451     pthread_cond_signal(&s->cond);
452     pthread_mutex_unlock(&s->mutex);
453     return NULL;
454 }
455 #endif
456
457 /* put it in UDP context */
458 /* return non zero if error */
459 static int udp_open(URLContext *h, const char *uri, int flags)
460 {
461     char hostname[1024], localaddr[1024] = "";
462     int port, udp_fd = -1, tmp, bind_ret = -1;
463     UDPContext *s = h->priv_data;
464     int is_output;
465     const char *p;
466     char buf[256];
467     struct sockaddr_storage my_addr;
468     int len;
469     int reuse_specified = 0;
470     int i, include = 0, num_sources = 0;
471     char *sources[32];
472
473     h->is_streamed = 1;
474     h->max_packet_size = 1472;
475
476     is_output = !(flags & AVIO_FLAG_READ);
477
478     s->ttl = 16;
479     s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
480
481     s->circular_buffer_size = 7*188*4096;
482
483     p = strchr(uri, '?');
484     if (p) {
485         if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
486             char *endptr = NULL;
487             s->reuse_socket = strtol(buf, &endptr, 10);
488             /* assume if no digits were found it is a request to enable it */
489             if (buf == endptr)
490                 s->reuse_socket = 1;
491             reuse_specified = 1;
492         }
493         if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
494             char *endptr = NULL;
495             s->overrun_nonfatal = strtol(buf, &endptr, 10);
496             /* assume if no digits were found it is a request to enable it */
497             if (buf == endptr)
498                 s->overrun_nonfatal = 1;
499         }
500         if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
501             s->ttl = strtol(buf, NULL, 10);
502         }
503         if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
504             s->local_port = strtol(buf, NULL, 10);
505         }
506         if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
507             h->max_packet_size = strtol(buf, NULL, 10);
508         }
509         if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
510             s->buffer_size = strtol(buf, NULL, 10);
511         }
512         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
513             s->is_connected = strtol(buf, NULL, 10);
514         }
515         if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
516             s->circular_buffer_size = strtol(buf, NULL, 10)*188;
517         }
518         if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
519             av_strlcpy(localaddr, buf, sizeof(localaddr));
520         }
521         if (av_find_info_tag(buf, sizeof(buf), "sources", p))
522             include = 1;
523         if (include || av_find_info_tag(buf, sizeof(buf), "block", p)) {
524             char *source_start;
525
526             source_start = buf;
527             while (1) {
528                 char *next = strchr(source_start, ',');
529                 if (next)
530                     *next = '\0';
531                 sources[num_sources] = av_strdup(source_start);
532                 if (!sources[num_sources])
533                     goto fail;
534                 source_start = next + 1;
535                 num_sources++;
536                 if (num_sources >= FF_ARRAY_ELEMS(sources) || !next)
537                     break;
538             }
539         }
540     }
541
542     /* fill the dest addr */
543     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
544
545     /* XXX: fix av_url_split */
546     if (hostname[0] == '\0' || hostname[0] == '?') {
547         /* only accepts null hostname if input */
548         if (!(flags & AVIO_FLAG_READ))
549             goto fail;
550     } else {
551         if (ff_udp_set_remote_url(h, uri) < 0)
552             goto fail;
553     }
554
555     if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
556         s->local_port = port;
557     udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
558     if (udp_fd < 0)
559         goto fail;
560
561     /* Follow the requested reuse option, unless it's multicast in which
562      * case enable reuse unless explicitly disabled.
563      */
564     if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
565         s->reuse_socket = 1;
566         if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
567             goto fail;
568     }
569
570     /* If multicast, try binding the multicast address first, to avoid
571      * receiving UDP packets from other sources aimed at the same UDP
572      * port. This fails on windows. This makes sending to the same address
573      * using sendto() fail, so only do it if we're opened in read-only mode. */
574     if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
575         bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
576     }
577     /* bind to the local address if not multicast or if the multicast
578      * bind failed */
579     /* the bind is needed to give a port to the socket now */
580     if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
581         log_net_error(h, AV_LOG_ERROR, "bind failed");
582         goto fail;
583     }
584
585     len = sizeof(my_addr);
586     getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
587     s->local_port = udp_port(&my_addr, len);
588
589     if (s->is_multicast) {
590         if (h->flags & AVIO_FLAG_WRITE) {
591             /* output */
592             if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
593                 goto fail;
594         }
595         if (h->flags & AVIO_FLAG_READ) {
596             /* input */
597             if (num_sources == 0 || !include) {
598                 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
599                     goto fail;
600
601                 if (num_sources) {
602                     if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 0) < 0)
603                         goto fail;
604                 }
605             } else if (include && num_sources) {
606                 if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 1) < 0)
607                     goto fail;
608             } else {
609                 av_log(NULL, AV_LOG_ERROR, "invalid udp settings: inclusive multicast but no sources given\n");
610                 goto fail;
611             }
612         }
613     }
614
615     if (is_output) {
616         /* limit the tx buf size to limit latency */
617         tmp = s->buffer_size;
618         if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
619             log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
620             goto fail;
621         }
622     } else {
623         /* set udp recv buffer size to the largest possible udp packet size to
624          * avoid losing data on OSes that set this too low by default. */
625         tmp = s->buffer_size;
626         if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
627             log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
628         }
629         /* make the socket non-blocking */
630         ff_socket_nonblock(udp_fd, 1);
631     }
632     if (s->is_connected) {
633         if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
634             log_net_error(h, AV_LOG_ERROR, "connect");
635             goto fail;
636         }
637     }
638
639     for (i = 0; i < num_sources; i++)
640         av_freep(&sources[i]);
641
642     s->udp_fd = udp_fd;
643
644 #if HAVE_PTHREAD_CANCEL
645     if (!is_output && s->circular_buffer_size) {
646         int ret;
647
648         /* start the task going */
649         s->fifo = av_fifo_alloc(s->circular_buffer_size);
650         ret = pthread_mutex_init(&s->mutex, NULL);
651         if (ret != 0) {
652             av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
653             goto fail;
654         }
655         ret = pthread_cond_init(&s->cond, NULL);
656         if (ret != 0) {
657             av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
658             goto cond_fail;
659         }
660         ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
661         if (ret != 0) {
662             av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
663             goto thread_fail;
664         }
665         s->thread_started = 1;
666     }
667 #endif
668
669     return 0;
670 #if HAVE_PTHREAD_CANCEL
671  thread_fail:
672     pthread_cond_destroy(&s->cond);
673  cond_fail:
674     pthread_mutex_destroy(&s->mutex);
675 #endif
676  fail:
677     if (udp_fd >= 0)
678         closesocket(udp_fd);
679     av_fifo_free(s->fifo);
680     for (i = 0; i < num_sources; i++)
681         av_freep(&sources[i]);
682     return AVERROR(EIO);
683 }
684
685 static int udp_read(URLContext *h, uint8_t *buf, int size)
686 {
687     UDPContext *s = h->priv_data;
688     int ret;
689     int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
690
691 #if HAVE_PTHREAD_CANCEL
692     if (s->fifo) {
693         pthread_mutex_lock(&s->mutex);
694         do {
695             avail = av_fifo_size(s->fifo);
696             if (avail) { // >=size) {
697                 uint8_t tmp[4];
698
699                 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
700                 avail= AV_RL32(tmp);
701                 if(avail > size){
702                     av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
703                     avail= size;
704                 }
705
706                 av_fifo_generic_read(s->fifo, buf, avail, NULL);
707                 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
708                 pthread_mutex_unlock(&s->mutex);
709                 return avail;
710             } else if(s->circular_buffer_error){
711                 int err = s->circular_buffer_error;
712                 pthread_mutex_unlock(&s->mutex);
713                 return err;
714             } else if(nonblock) {
715                 pthread_mutex_unlock(&s->mutex);
716                 return AVERROR(EAGAIN);
717             }
718             else {
719                 /* FIXME: using the monotonic clock would be better,
720                    but it does not exist on all supported platforms. */
721                 int64_t t = av_gettime() + 100000;
722                 struct timespec tv = { .tv_sec  =  t / 1000000,
723                                        .tv_nsec = (t % 1000000) * 1000 };
724                 if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0)
725                     return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
726                 nonblock = 1;
727             }
728         } while( 1);
729     }
730 #endif
731
732     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
733         ret = ff_network_wait_fd(s->udp_fd, 0);
734         if (ret < 0)
735             return ret;
736     }
737     ret = recv(s->udp_fd, buf, size, 0);
738
739     return ret < 0 ? ff_neterrno() : ret;
740 }
741
742 static int udp_write(URLContext *h, const uint8_t *buf, int size)
743 {
744     UDPContext *s = h->priv_data;
745     int ret;
746
747     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
748         ret = ff_network_wait_fd(s->udp_fd, 1);
749         if (ret < 0)
750             return ret;
751     }
752
753     if (!s->is_connected) {
754         ret = sendto (s->udp_fd, buf, size, 0,
755                       (struct sockaddr *) &s->dest_addr,
756                       s->dest_addr_len);
757     } else
758         ret = send(s->udp_fd, buf, size, 0);
759
760     return ret < 0 ? ff_neterrno() : ret;
761 }
762
763 static int udp_close(URLContext *h)
764 {
765     UDPContext *s = h->priv_data;
766     int ret;
767
768     if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
769         udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
770     closesocket(s->udp_fd);
771 #if HAVE_PTHREAD_CANCEL
772     if (s->thread_started) {
773         pthread_cancel(s->circular_buffer_thread);
774         ret = pthread_join(s->circular_buffer_thread, NULL);
775         if (ret != 0)
776             av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
777     }
778
779     pthread_mutex_destroy(&s->mutex);
780     pthread_cond_destroy(&s->cond);
781 #endif
782     av_fifo_free(s->fifo);
783     return 0;
784 }
785
786 URLProtocol ff_udp_protocol = {
787     .name                = "udp",
788     .url_open            = udp_open,
789     .url_read            = udp_read,
790     .url_write           = udp_write,
791     .url_close           = udp_close,
792     .url_get_file_handle = udp_get_file_handle,
793     .priv_data_size      = sizeof(UDPContext),
794     .flags               = URL_PROTOCOL_FLAG_NETWORK,
795 };