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