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