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