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