]> git.sesse.net Git - ffmpeg/blob - libavformat/udp.c
Merge commit 'f3fdef108eb06b1e71b29152bf6822519e787efe'
[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 _DEFAULT_SOURCE
28 #define _BSD_SOURCE     /* Needed for using struct ip_mreq with recent glibc */
29
30 #include "avformat.h"
31 #include "avio_internal.h"
32 #include "libavutil/parseutils.h"
33 #include "libavutil/fifo.h"
34 #include "libavutil/intreadwrite.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/opt.h"
37 #include "libavutil/log.h"
38 #include "libavutil/time.h"
39 #include "internal.h"
40 #include "network.h"
41 #include "os_support.h"
42 #include "url.h"
43
44 #if HAVE_UDPLITE_H
45 #include "udplite.h"
46 #else
47 /* On many Linux systems, udplite.h is missing but the kernel supports UDP-Lite.
48  * So, we provide a fallback here.
49  */
50 #define UDPLITE_SEND_CSCOV                               10
51 #define UDPLITE_RECV_CSCOV                               11
52 #endif
53
54 #ifndef IPPROTO_UDPLITE
55 #define IPPROTO_UDPLITE                                  136
56 #endif
57
58 #if HAVE_PTHREAD_CANCEL
59 #include <pthread.h>
60 #endif
61
62 #ifndef HAVE_PTHREAD_CANCEL
63 #define HAVE_PTHREAD_CANCEL 0
64 #endif
65
66 #ifndef IPV6_ADD_MEMBERSHIP
67 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
68 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
69 #endif
70
71 #define UDP_TX_BUF_SIZE 32768
72 #define UDP_MAX_PKT_SIZE 65536
73 #define UDP_HEADER_SIZE 8
74
75 typedef struct UDPContext {
76     const AVClass *class;
77     int udp_fd;
78     int ttl;
79     int udplite_coverage;
80     int buffer_size;
81     int pkt_size;
82     int is_multicast;
83     int is_broadcast;
84     int local_port;
85     int reuse_socket;
86     int overrun_nonfatal;
87     struct sockaddr_storage dest_addr;
88     int dest_addr_len;
89     int is_connected;
90
91     /* Circular Buffer variables for use in UDP receive code */
92     int circular_buffer_size;
93     AVFifoBuffer *fifo;
94     int circular_buffer_error;
95 #if HAVE_PTHREAD_CANCEL
96     pthread_t circular_buffer_thread;
97     pthread_mutex_t mutex;
98     pthread_cond_t cond;
99     int thread_started;
100 #endif
101     uint8_t tmp[UDP_MAX_PKT_SIZE+4];
102     int remaining_in_dg;
103     char *localaddr;
104     int timeout;
105     struct sockaddr_storage local_addr_storage;
106     char *sources;
107     char *block;
108 } UDPContext;
109
110 #define OFFSET(x) offsetof(UDPContext, x)
111 #define D AV_OPT_FLAG_DECODING_PARAM
112 #define E AV_OPT_FLAG_ENCODING_PARAM
113 static const AVOption options[] = {
114     { "buffer_size",    "System data size (in bytes)",                     OFFSET(buffer_size),    AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
115     { "localport",      "Local port",                                      OFFSET(local_port),     AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, D|E },
116     { "local_port",     "Local port",                                      OFFSET(local_port),     AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
117     { "localaddr",      "Local address",                                   OFFSET(localaddr),      AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
118     { "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 },
119     { "pkt_size",       "Maximum UDP packet size",                         OFFSET(pkt_size),       AV_OPT_TYPE_INT,    { .i64 = 1472 },  -1, INT_MAX, .flags = D|E },
120     { "reuse",          "explicitly allow reusing UDP sockets",            OFFSET(reuse_socket),   AV_OPT_TYPE_BOOL,   { .i64 = -1 },    -1, 1,       D|E },
121     { "reuse_socket",   "explicitly allow reusing UDP sockets",            OFFSET(reuse_socket),   AV_OPT_TYPE_BOOL,   { .i64 = -1 },    -1, 1,       .flags = D|E },
122     { "broadcast", "explicitly allow or disallow broadcast destination",   OFFSET(is_broadcast),   AV_OPT_TYPE_BOOL,   { .i64 = 0  },     0, 1,       E },
123     { "ttl",            "Time to live (multicast only)",                   OFFSET(ttl),            AV_OPT_TYPE_INT,    { .i64 = 16 },     0, INT_MAX, E },
124     { "connect",        "set if connect() should be called on socket",     OFFSET(is_connected),   AV_OPT_TYPE_BOOL,   { .i64 =  0 },     0, 1,       .flags = D|E },
125     { "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 },
126     { "overrun_nonfatal", "survive in case of UDP receiving circular buffer overrun", OFFSET(overrun_nonfatal), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1,    D },
127     { "timeout",        "set raise error timeout (only in read mode)",     OFFSET(timeout),        AV_OPT_TYPE_INT,    { .i64 = 0 },      0, INT_MAX, D },
128     { "sources",        "Source list",                                     OFFSET(sources),        AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
129     { "block",          "Block list",                                      OFFSET(block),          AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
130     { NULL }
131 };
132
133 static const AVClass udp_class = {
134     .class_name = "udp",
135     .item_name  = av_default_item_name,
136     .option     = options,
137     .version    = LIBAVUTIL_VERSION_INT,
138 };
139
140 static const AVClass udplite_context_class = {
141     .class_name     = "udplite",
142     .item_name      = av_default_item_name,
143     .option         = options,
144     .version        = LIBAVUTIL_VERSION_INT,
145 };
146
147 static void log_net_error(void *ctx, int level, const char* prefix)
148 {
149     char errbuf[100];
150     av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
151     av_log(ctx, level, "%s: %s\n", prefix, errbuf);
152 }
153
154 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
155                                  struct sockaddr *addr)
156 {
157 #ifdef IP_MULTICAST_TTL
158     if (addr->sa_family == AF_INET) {
159         if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
160             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
161             return -1;
162         }
163     }
164 #endif
165 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
166     if (addr->sa_family == AF_INET6) {
167         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
168             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
169             return -1;
170         }
171     }
172 #endif
173     return 0;
174 }
175
176 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr,struct sockaddr *local_addr)
177 {
178 #ifdef IP_ADD_MEMBERSHIP
179     if (addr->sa_family == AF_INET) {
180         struct ip_mreq mreq;
181
182         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
183         if (local_addr)
184             mreq.imr_interface= ((struct sockaddr_in *)local_addr)->sin_addr;
185         else
186             mreq.imr_interface.s_addr= INADDR_ANY;
187         if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
188             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
189             return -1;
190         }
191     }
192 #endif
193 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
194     if (addr->sa_family == AF_INET6) {
195         struct ipv6_mreq mreq6;
196
197         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
198         mreq6.ipv6mr_interface= 0;
199         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
200             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
201             return -1;
202         }
203     }
204 #endif
205     return 0;
206 }
207
208 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr,struct sockaddr *local_addr)
209 {
210 #ifdef IP_DROP_MEMBERSHIP
211     if (addr->sa_family == AF_INET) {
212         struct ip_mreq mreq;
213
214         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
215         if (local_addr)
216             mreq.imr_interface= ((struct sockaddr_in *)local_addr)->sin_addr;
217         else
218             mreq.imr_interface.s_addr= INADDR_ANY;
219         if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
220             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
221             return -1;
222         }
223     }
224 #endif
225 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
226     if (addr->sa_family == AF_INET6) {
227         struct ipv6_mreq mreq6;
228
229         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
230         mreq6.ipv6mr_interface= 0;
231         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
232             log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
233             return -1;
234         }
235     }
236 #endif
237     return 0;
238 }
239
240 static struct addrinfo *udp_resolve_host(URLContext *h,
241                                          const char *hostname, int port,
242                                          int type, int family, int flags)
243 {
244     struct addrinfo hints = { 0 }, *res = 0;
245     int error;
246     char sport[16];
247     const char *node = 0, *service = "0";
248
249     if (port > 0) {
250         snprintf(sport, sizeof(sport), "%d", port);
251         service = sport;
252     }
253     if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
254         node = hostname;
255     }
256     hints.ai_socktype = type;
257     hints.ai_family   = family;
258     hints.ai_flags = flags;
259     if ((error = getaddrinfo(node, service, &hints, &res))) {
260         res = NULL;
261         av_log(h, AV_LOG_ERROR, "getaddrinfo(%s, %s): %s\n",
262                node ? node : "unknown",
263                service ? service : "unknown",
264                gai_strerror(error));
265     }
266
267     return res;
268 }
269
270 static int udp_set_multicast_sources(URLContext *h,
271                                      int sockfd, struct sockaddr *addr,
272                                      int addr_len, char **sources,
273                                      int nb_sources, int include)
274 {
275 #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE) && !defined(_WIN32)
276     /* These ones are available in the microsoft SDK, but don't seem to work
277      * as on linux, so just prefer the v4-only approach there for now. */
278     int i;
279     for (i = 0; i < nb_sources; i++) {
280         struct group_source_req mreqs;
281         int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
282         struct addrinfo *sourceaddr = udp_resolve_host(h, sources[i], 0,
283                                                        SOCK_DGRAM, AF_UNSPEC,
284                                                        0);
285         if (!sourceaddr)
286             return AVERROR(ENOENT);
287
288         mreqs.gsr_interface = 0;
289         memcpy(&mreqs.gsr_group, addr, addr_len);
290         memcpy(&mreqs.gsr_source, sourceaddr->ai_addr, sourceaddr->ai_addrlen);
291         freeaddrinfo(sourceaddr);
292
293         if (setsockopt(sockfd, level,
294                        include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
295                        (const void *)&mreqs, sizeof(mreqs)) < 0) {
296             if (include)
297                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
298             else
299                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
300             return ff_neterrno();
301         }
302     }
303 #elif HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
304     int i;
305     if (addr->sa_family != AF_INET) {
306         av_log(NULL, AV_LOG_ERROR,
307                "Setting multicast sources only supported for IPv4\n");
308         return AVERROR(EINVAL);
309     }
310     for (i = 0; i < nb_sources; i++) {
311         struct ip_mreq_source mreqs;
312         struct addrinfo *sourceaddr = udp_resolve_host(h, sources[i], 0,
313                                                        SOCK_DGRAM, AF_UNSPEC,
314                                                        0);
315         if (!sourceaddr)
316             return AVERROR(ENOENT);
317         if (sourceaddr->ai_addr->sa_family != AF_INET) {
318             freeaddrinfo(sourceaddr);
319             av_log(NULL, AV_LOG_ERROR, "%s is of incorrect protocol family\n",
320                    sources[i]);
321             return AVERROR(EINVAL);
322         }
323
324         mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
325         mreqs.imr_interface.s_addr = INADDR_ANY;
326         mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)sourceaddr->ai_addr)->sin_addr.s_addr;
327         freeaddrinfo(sourceaddr);
328
329         if (setsockopt(sockfd, IPPROTO_IP,
330                        include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
331                        (const void *)&mreqs, sizeof(mreqs)) < 0) {
332             if (include)
333                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
334             else
335                 log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
336             return ff_neterrno();
337         }
338     }
339 #else
340     return AVERROR(ENOSYS);
341 #endif
342     return 0;
343 }
344 static int udp_set_url(URLContext *h,
345                        struct sockaddr_storage *addr,
346                        const char *hostname, int port)
347 {
348     struct addrinfo *res0;
349     int addr_len;
350
351     res0 = udp_resolve_host(h, hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
352     if (!res0) return AVERROR(EIO);
353     memcpy(addr, res0->ai_addr, res0->ai_addrlen);
354     addr_len = res0->ai_addrlen;
355     freeaddrinfo(res0);
356
357     return addr_len;
358 }
359
360 static int udp_socket_create(URLContext *h, struct sockaddr_storage *addr,
361                              socklen_t *addr_len, const char *localaddr)
362 {
363     UDPContext *s = h->priv_data;
364     int udp_fd = -1;
365     struct addrinfo *res0, *res;
366     int family = AF_UNSPEC;
367
368     if (((struct sockaddr *) &s->dest_addr)->sa_family)
369         family = ((struct sockaddr *) &s->dest_addr)->sa_family;
370     res0 = udp_resolve_host(h, (localaddr && localaddr[0]) ? localaddr : NULL,
371                             s->local_port,
372                             SOCK_DGRAM, family, AI_PASSIVE);
373     if (!res0)
374         goto fail;
375     for (res = res0; res; res=res->ai_next) {
376         if (s->udplite_coverage)
377             udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, IPPROTO_UDPLITE);
378         else
379             udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, 0);
380         if (udp_fd != -1) break;
381         log_net_error(NULL, AV_LOG_ERROR, "socket");
382     }
383
384     if (udp_fd < 0)
385         goto fail;
386
387     memcpy(addr, res->ai_addr, res->ai_addrlen);
388     *addr_len = res->ai_addrlen;
389
390     freeaddrinfo(res0);
391
392     return udp_fd;
393
394  fail:
395     if (udp_fd >= 0)
396         closesocket(udp_fd);
397     if(res0)
398         freeaddrinfo(res0);
399     return -1;
400 }
401
402 static int udp_port(struct sockaddr_storage *addr, int addr_len)
403 {
404     char sbuf[sizeof(int)*3+1];
405     int error;
406
407     if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0,  sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
408         av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
409         return -1;
410     }
411
412     return strtol(sbuf, NULL, 10);
413 }
414
415
416 /**
417  * If no filename is given to av_open_input_file because you want to
418  * get the local port first, then you must call this function to set
419  * the remote server address.
420  *
421  * url syntax: udp://host:port[?option=val...]
422  * option: 'ttl=n'       : set the ttl value (for multicast only)
423  *         'localport=n' : set the local port
424  *         'pkt_size=n'  : set max packet size
425  *         'reuse=1'     : enable reusing the socket
426  *         'overrun_nonfatal=1': survive in case of circular buffer overrun
427  *
428  * @param h media file context
429  * @param uri of the remote server
430  * @return zero if no error.
431  */
432 int ff_udp_set_remote_url(URLContext *h, const char *uri)
433 {
434     UDPContext *s = h->priv_data;
435     char hostname[256], buf[10];
436     int port;
437     const char *p;
438
439     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
440
441     /* set the destination address */
442     s->dest_addr_len = udp_set_url(h, &s->dest_addr, hostname, port);
443     if (s->dest_addr_len < 0) {
444         return AVERROR(EIO);
445     }
446     s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
447     p = strchr(uri, '?');
448     if (p) {
449         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
450             int was_connected = s->is_connected;
451             s->is_connected = strtol(buf, NULL, 10);
452             if (s->is_connected && !was_connected) {
453                 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
454                             s->dest_addr_len)) {
455                     s->is_connected = 0;
456                     log_net_error(h, AV_LOG_ERROR, "connect");
457                     return AVERROR(EIO);
458                 }
459             }
460         }
461     }
462
463     return 0;
464 }
465
466 /**
467  * Return the local port used by the UDP connection
468  * @param h media file context
469  * @return the local port number
470  */
471 int ff_udp_get_local_port(URLContext *h)
472 {
473     UDPContext *s = h->priv_data;
474     return s->local_port;
475 }
476
477 /**
478  * Return the udp file handle for select() usage to wait for several RTP
479  * streams at the same time.
480  * @param h media file context
481  */
482 static int udp_get_file_handle(URLContext *h)
483 {
484     UDPContext *s = h->priv_data;
485     return s->udp_fd;
486 }
487
488 #if HAVE_PTHREAD_CANCEL
489 static void *circular_buffer_task( void *_URLContext)
490 {
491     URLContext *h = _URLContext;
492     UDPContext *s = h->priv_data;
493     int old_cancelstate;
494
495     pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
496     pthread_mutex_lock(&s->mutex);
497     if (ff_socket_nonblock(s->udp_fd, 0) < 0) {
498         av_log(h, AV_LOG_ERROR, "Failed to set blocking mode");
499         s->circular_buffer_error = AVERROR(EIO);
500         goto end;
501     }
502     while(1) {
503         int len;
504
505         pthread_mutex_unlock(&s->mutex);
506         /* Blocking operations are always cancellation points;
507            see "General Information" / "Thread Cancelation Overview"
508            in Single Unix. */
509         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);
510         len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
511         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
512         pthread_mutex_lock(&s->mutex);
513         if (len < 0) {
514             if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
515                 s->circular_buffer_error = ff_neterrno();
516                 goto end;
517             }
518             continue;
519         }
520         AV_WL32(s->tmp, len);
521
522         if(av_fifo_space(s->fifo) < len + 4) {
523             /* No Space left */
524             if (s->overrun_nonfatal) {
525                 av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
526                         "Surviving due to overrun_nonfatal option\n");
527                 continue;
528             } else {
529                 av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
530                         "To avoid, increase fifo_size URL option. "
531                         "To survive in such case, use overrun_nonfatal option\n");
532                 s->circular_buffer_error = AVERROR(EIO);
533                 goto end;
534             }
535         }
536         av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
537         pthread_cond_signal(&s->cond);
538     }
539
540 end:
541     pthread_cond_signal(&s->cond);
542     pthread_mutex_unlock(&s->mutex);
543     return NULL;
544 }
545 #endif
546
547 static int parse_source_list(char *buf, char **sources, int *num_sources,
548                              int max_sources)
549 {
550     char *source_start;
551
552     source_start = buf;
553     while (1) {
554         char *next = strchr(source_start, ',');
555         if (next)
556             *next = '\0';
557         sources[*num_sources] = av_strdup(source_start);
558         if (!sources[*num_sources])
559             return AVERROR(ENOMEM);
560         source_start = next + 1;
561         (*num_sources)++;
562         if (*num_sources >= max_sources || !next)
563             break;
564     }
565     return 0;
566 }
567
568 /* put it in UDP context */
569 /* return non zero if error */
570 static int udp_open(URLContext *h, const char *uri, int flags)
571 {
572     char hostname[1024], localaddr[1024] = "";
573     int port, udp_fd = -1, tmp, bind_ret = -1, dscp = -1;
574     UDPContext *s = h->priv_data;
575     int is_output;
576     const char *p;
577     char buf[256];
578     struct sockaddr_storage my_addr;
579     socklen_t len;
580     int i, num_include_sources = 0, num_exclude_sources = 0;
581     char *include_sources[32], *exclude_sources[32];
582
583     h->is_streamed = 1;
584
585     is_output = !(flags & AVIO_FLAG_READ);
586     if (s->buffer_size < 0)
587         s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
588
589     if (s->sources) {
590         if (parse_source_list(s->sources, include_sources,
591                               &num_include_sources,
592                               FF_ARRAY_ELEMS(include_sources)))
593             goto fail;
594     }
595
596     if (s->block) {
597         if (parse_source_list(s->block, exclude_sources, &num_exclude_sources,
598                               FF_ARRAY_ELEMS(exclude_sources)))
599             goto fail;
600     }
601
602     if (s->pkt_size > 0)
603         h->max_packet_size = s->pkt_size;
604
605     p = strchr(uri, '?');
606     if (p) {
607         if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
608             char *endptr = NULL;
609             s->reuse_socket = strtol(buf, &endptr, 10);
610             /* assume if no digits were found it is a request to enable it */
611             if (buf == endptr)
612                 s->reuse_socket = 1;
613         }
614         if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
615             char *endptr = NULL;
616             s->overrun_nonfatal = strtol(buf, &endptr, 10);
617             /* assume if no digits were found it is a request to enable it */
618             if (buf == endptr)
619                 s->overrun_nonfatal = 1;
620             if (!HAVE_PTHREAD_CANCEL)
621                 av_log(h, AV_LOG_WARNING,
622                        "'overrun_nonfatal' option was set but it is not supported "
623                        "on this build (pthread support is required)\n");
624         }
625         if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
626             s->ttl = strtol(buf, NULL, 10);
627         }
628         if (av_find_info_tag(buf, sizeof(buf), "udplite_coverage", p)) {
629             s->udplite_coverage = strtol(buf, NULL, 10);
630         }
631         if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
632             s->local_port = strtol(buf, NULL, 10);
633         }
634         if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
635             s->pkt_size = strtol(buf, NULL, 10);
636         }
637         if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
638             s->buffer_size = strtol(buf, NULL, 10);
639         }
640         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
641             s->is_connected = strtol(buf, NULL, 10);
642         }
643         if (av_find_info_tag(buf, sizeof(buf), "dscp", p)) {
644             dscp = strtol(buf, NULL, 10);
645         }
646         if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
647             s->circular_buffer_size = strtol(buf, NULL, 10);
648             if (!HAVE_PTHREAD_CANCEL)
649                 av_log(h, AV_LOG_WARNING,
650                        "'circular_buffer_size' option was set but it is not supported "
651                        "on this build (pthread support is required)\n");
652         }
653         if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
654             av_strlcpy(localaddr, buf, sizeof(localaddr));
655         }
656         if (av_find_info_tag(buf, sizeof(buf), "sources", p)) {
657             if (parse_source_list(buf, include_sources, &num_include_sources,
658                                   FF_ARRAY_ELEMS(include_sources)))
659                 goto fail;
660         }
661         if (av_find_info_tag(buf, sizeof(buf), "block", p)) {
662             if (parse_source_list(buf, exclude_sources, &num_exclude_sources,
663                                   FF_ARRAY_ELEMS(exclude_sources)))
664                 goto fail;
665         }
666         if (!is_output && av_find_info_tag(buf, sizeof(buf), "timeout", p))
667             s->timeout = strtol(buf, NULL, 10);
668         if (is_output && av_find_info_tag(buf, sizeof(buf), "broadcast", p))
669             s->is_broadcast = strtol(buf, NULL, 10);
670     }
671     /* handling needed to support options picking from both AVOption and URL */
672     s->circular_buffer_size *= 188;
673     if (flags & AVIO_FLAG_WRITE) {
674         h->max_packet_size = s->pkt_size;
675     } else {
676         h->max_packet_size = UDP_MAX_PKT_SIZE;
677     }
678     h->rw_timeout = s->timeout;
679
680     /* fill the dest addr */
681     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
682
683     /* XXX: fix av_url_split */
684     if (hostname[0] == '\0' || hostname[0] == '?') {
685         /* only accepts null hostname if input */
686         if (!(flags & AVIO_FLAG_READ))
687             goto fail;
688     } else {
689         if (ff_udp_set_remote_url(h, uri) < 0)
690             goto fail;
691     }
692
693     if ((s->is_multicast || s->local_port <= 0) && (h->flags & AVIO_FLAG_READ))
694         s->local_port = port;
695
696     if (localaddr[0])
697         udp_fd = udp_socket_create(h, &my_addr, &len, localaddr);
698     else
699         udp_fd = udp_socket_create(h, &my_addr, &len, s->localaddr);
700     if (udp_fd < 0)
701         goto fail;
702
703     s->local_addr_storage=my_addr; //store for future multicast join
704
705     /* Follow the requested reuse option, unless it's multicast in which
706      * case enable reuse unless explicitly disabled.
707      */
708     if (s->reuse_socket > 0 || (s->is_multicast && s->reuse_socket < 0)) {
709         s->reuse_socket = 1;
710         if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
711             goto fail;
712     }
713
714     if (s->is_broadcast) {
715 #ifdef SO_BROADCAST
716         if (setsockopt (udp_fd, SOL_SOCKET, SO_BROADCAST, &(s->is_broadcast), sizeof(s->is_broadcast)) != 0)
717 #endif
718            goto fail;
719     }
720
721     /* Set the checksum coverage for UDP-Lite (RFC 3828) for sending and receiving.
722      * The receiver coverage has to be less than or equal to the sender coverage.
723      * Otherwise, the receiver will drop all packets.
724      */
725     if (s->udplite_coverage) {
726         if (setsockopt (udp_fd, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, &(s->udplite_coverage), sizeof(s->udplite_coverage)) != 0)
727             av_log(h, AV_LOG_WARNING, "socket option UDPLITE_SEND_CSCOV not available");
728
729         if (setsockopt (udp_fd, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, &(s->udplite_coverage), sizeof(s->udplite_coverage)) != 0)
730             av_log(h, AV_LOG_WARNING, "socket option UDPLITE_RECV_CSCOV not available");
731     }
732
733     if (dscp >= 0) {
734         dscp <<= 2;
735         if (setsockopt (udp_fd, IPPROTO_IP, IP_TOS, &dscp, sizeof(dscp)) != 0)
736             goto fail;
737     }
738
739     /* If multicast, try binding the multicast address first, to avoid
740      * receiving UDP packets from other sources aimed at the same UDP
741      * port. This fails on windows. This makes sending to the same address
742      * using sendto() fail, so only do it if we're opened in read-only mode. */
743     if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
744         bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
745     }
746     /* bind to the local address if not multicast or if the multicast
747      * bind failed */
748     /* the bind is needed to give a port to the socket now */
749     if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
750         log_net_error(h, AV_LOG_ERROR, "bind failed");
751         goto fail;
752     }
753
754     len = sizeof(my_addr);
755     getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
756     s->local_port = udp_port(&my_addr, len);
757
758     if (s->is_multicast) {
759         if (h->flags & AVIO_FLAG_WRITE) {
760             /* output */
761             if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
762                 goto fail;
763         }
764         if (h->flags & AVIO_FLAG_READ) {
765             /* input */
766             if (num_include_sources && num_exclude_sources) {
767                 av_log(h, AV_LOG_ERROR, "Simultaneously including and excluding multicast sources is not supported\n");
768                 goto fail;
769             }
770             if (num_include_sources) {
771                 if (udp_set_multicast_sources(h, udp_fd,
772                                               (struct sockaddr *)&s->dest_addr,
773                                               s->dest_addr_len,
774                                               include_sources,
775                                               num_include_sources, 1) < 0)
776                     goto fail;
777             } else {
778                 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr,(struct sockaddr *)&s->local_addr_storage) < 0)
779                     goto fail;
780             }
781             if (num_exclude_sources) {
782                 if (udp_set_multicast_sources(h, udp_fd,
783                                               (struct sockaddr *)&s->dest_addr,
784                                               s->dest_addr_len,
785                                               exclude_sources,
786                                               num_exclude_sources, 0) < 0)
787                     goto fail;
788             }
789         }
790     }
791
792     if (is_output) {
793         /* limit the tx buf size to limit latency */
794         tmp = s->buffer_size;
795         if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
796             log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
797             goto fail;
798         }
799     } else {
800         /* set udp recv buffer size to the requested value (default 64K) */
801         tmp = s->buffer_size;
802         if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
803             log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
804         }
805         len = sizeof(tmp);
806         if (getsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, &len) < 0) {
807             log_net_error(h, AV_LOG_WARNING, "getsockopt(SO_RCVBUF)");
808         } else {
809             av_log(h, AV_LOG_DEBUG, "end receive buffer size reported is %d\n", tmp);
810             if(tmp < s->buffer_size)
811                 av_log(h, AV_LOG_WARNING, "attempted to set receive buffer to size %d but it only ended up set as %d", s->buffer_size, tmp);
812         }
813
814         /* make the socket non-blocking */
815         ff_socket_nonblock(udp_fd, 1);
816     }
817     if (s->is_connected) {
818         if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
819             log_net_error(h, AV_LOG_ERROR, "connect");
820             goto fail;
821         }
822     }
823
824     for (i = 0; i < num_include_sources; i++)
825         av_freep(&include_sources[i]);
826     for (i = 0; i < num_exclude_sources; i++)
827         av_freep(&exclude_sources[i]);
828
829     s->udp_fd = udp_fd;
830
831 #if HAVE_PTHREAD_CANCEL
832     if (!is_output && s->circular_buffer_size) {
833         int ret;
834
835         /* start the task going */
836         s->fifo = av_fifo_alloc(s->circular_buffer_size);
837         ret = pthread_mutex_init(&s->mutex, NULL);
838         if (ret != 0) {
839             av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
840             goto fail;
841         }
842         ret = pthread_cond_init(&s->cond, NULL);
843         if (ret != 0) {
844             av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
845             goto cond_fail;
846         }
847         ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
848         if (ret != 0) {
849             av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
850             goto thread_fail;
851         }
852         s->thread_started = 1;
853     }
854 #endif
855
856     return 0;
857 #if HAVE_PTHREAD_CANCEL
858  thread_fail:
859     pthread_cond_destroy(&s->cond);
860  cond_fail:
861     pthread_mutex_destroy(&s->mutex);
862 #endif
863  fail:
864     if (udp_fd >= 0)
865         closesocket(udp_fd);
866     av_fifo_freep(&s->fifo);
867     for (i = 0; i < num_include_sources; i++)
868         av_freep(&include_sources[i]);
869     for (i = 0; i < num_exclude_sources; i++)
870         av_freep(&exclude_sources[i]);
871     return AVERROR(EIO);
872 }
873
874 static int udplite_open(URLContext *h, const char *uri, int flags)
875 {
876     UDPContext *s = h->priv_data;
877
878     // set default checksum coverage
879     s->udplite_coverage = UDP_HEADER_SIZE;
880
881     return udp_open(h, uri, flags);
882 }
883
884 static int udp_read(URLContext *h, uint8_t *buf, int size)
885 {
886     UDPContext *s = h->priv_data;
887     int ret;
888 #if HAVE_PTHREAD_CANCEL
889     int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
890
891     if (s->fifo) {
892         pthread_mutex_lock(&s->mutex);
893         do {
894             avail = av_fifo_size(s->fifo);
895             if (avail) { // >=size) {
896                 uint8_t tmp[4];
897
898                 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
899                 avail= AV_RL32(tmp);
900                 if(avail > size){
901                     av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
902                     avail= size;
903                 }
904
905                 av_fifo_generic_read(s->fifo, buf, avail, NULL);
906                 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
907                 pthread_mutex_unlock(&s->mutex);
908                 return avail;
909             } else if(s->circular_buffer_error){
910                 int err = s->circular_buffer_error;
911                 pthread_mutex_unlock(&s->mutex);
912                 return err;
913             } else if(nonblock) {
914                 pthread_mutex_unlock(&s->mutex);
915                 return AVERROR(EAGAIN);
916             }
917             else {
918                 /* FIXME: using the monotonic clock would be better,
919                    but it does not exist on all supported platforms. */
920                 int64_t t = av_gettime() + 100000;
921                 struct timespec tv = { .tv_sec  =  t / 1000000,
922                                        .tv_nsec = (t % 1000000) * 1000 };
923                 if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0) {
924                     pthread_mutex_unlock(&s->mutex);
925                     return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
926                 }
927                 nonblock = 1;
928             }
929         } while( 1);
930     }
931 #endif
932
933     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
934         ret = ff_network_wait_fd(s->udp_fd, 0);
935         if (ret < 0)
936             return ret;
937     }
938     ret = recv(s->udp_fd, buf, size, 0);
939
940     return ret < 0 ? ff_neterrno() : ret;
941 }
942
943 static int udp_write(URLContext *h, const uint8_t *buf, int size)
944 {
945     UDPContext *s = h->priv_data;
946     int ret;
947
948     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
949         ret = ff_network_wait_fd(s->udp_fd, 1);
950         if (ret < 0)
951             return ret;
952     }
953
954     if (!s->is_connected) {
955         ret = sendto (s->udp_fd, buf, size, 0,
956                       (struct sockaddr *) &s->dest_addr,
957                       s->dest_addr_len);
958     } else
959         ret = send(s->udp_fd, buf, size, 0);
960
961     return ret < 0 ? ff_neterrno() : ret;
962 }
963
964 static int udp_close(URLContext *h)
965 {
966     UDPContext *s = h->priv_data;
967
968     if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
969         udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr,(struct sockaddr *)&s->local_addr_storage);
970     closesocket(s->udp_fd);
971 #if HAVE_PTHREAD_CANCEL
972     if (s->thread_started) {
973         int ret;
974         pthread_cancel(s->circular_buffer_thread);
975         ret = pthread_join(s->circular_buffer_thread, NULL);
976         if (ret != 0)
977             av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
978         pthread_mutex_destroy(&s->mutex);
979         pthread_cond_destroy(&s->cond);
980     }
981 #endif
982     av_fifo_freep(&s->fifo);
983     return 0;
984 }
985
986 const URLProtocol ff_udp_protocol = {
987     .name                = "udp",
988     .url_open            = udp_open,
989     .url_read            = udp_read,
990     .url_write           = udp_write,
991     .url_close           = udp_close,
992     .url_get_file_handle = udp_get_file_handle,
993     .priv_data_size      = sizeof(UDPContext),
994     .priv_data_class     = &udp_class,
995     .flags               = URL_PROTOCOL_FLAG_NETWORK,
996 };
997
998 const URLProtocol ff_udplite_protocol = {
999     .name                = "udplite",
1000     .url_open            = udplite_open,
1001     .url_read            = udp_read,
1002     .url_write           = udp_write,
1003     .url_close           = udp_close,
1004     .url_get_file_handle = udp_get_file_handle,
1005     .priv_data_size      = sizeof(UDPContext),
1006     .priv_data_class     = &udplite_context_class,
1007     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1008 };