OSDN Git Service

Merge remote-tracking branch 'qatar/master'
[coroid/ffmpeg_saccubus.git] / 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 <unistd.h>
34 #include "internal.h"
35 #include "network.h"
36 #include "os_support.h"
37 #include "url.h"
38
39 #if HAVE_PTHREADS
40 #include <pthread.h>
41 #endif
42
43 #include <sys/time.h>
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 typedef struct {
51     int udp_fd;
52     int ttl;
53     int buffer_size;
54     int is_multicast;
55     int local_port;
56     int reuse_socket;
57     struct sockaddr_storage dest_addr;
58     int dest_addr_len;
59     int is_connected;
60
61     /* Circular Buffer variables for use in UDP receive code */
62     int circular_buffer_size;
63     AVFifoBuffer *fifo;
64     int circular_buffer_error;
65 #if HAVE_PTHREADS
66     pthread_t circular_buffer_thread;
67 #endif
68 } UDPContext;
69
70 #define UDP_TX_BUF_SIZE 32768
71 #define UDP_MAX_PKT_SIZE 65536
72
73 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
74                                  struct sockaddr *addr)
75 {
76 #ifdef IP_MULTICAST_TTL
77     if (addr->sa_family == AF_INET) {
78         if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
79             av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL): %s\n", strerror(errno));
80             return -1;
81         }
82     }
83 #endif
84 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
85     if (addr->sa_family == AF_INET6) {
86         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
87             av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS): %s\n", strerror(errno));
88             return -1;
89         }
90     }
91 #endif
92     return 0;
93 }
94
95 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
96 {
97 #ifdef IP_ADD_MEMBERSHIP
98     if (addr->sa_family == AF_INET) {
99         struct ip_mreq mreq;
100
101         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
102         mreq.imr_interface.s_addr= INADDR_ANY;
103         if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
104             av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno));
105             return -1;
106         }
107     }
108 #endif
109 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
110     if (addr->sa_family == AF_INET6) {
111         struct ipv6_mreq mreq6;
112
113         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
114         mreq6.ipv6mr_interface= 0;
115         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
116             av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP): %s\n", strerror(errno));
117             return -1;
118         }
119     }
120 #endif
121     return 0;
122 }
123
124 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
125 {
126 #ifdef IP_DROP_MEMBERSHIP
127     if (addr->sa_family == AF_INET) {
128         struct ip_mreq mreq;
129
130         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
131         mreq.imr_interface.s_addr= INADDR_ANY;
132         if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
133             av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP): %s\n", strerror(errno));
134             return -1;
135         }
136     }
137 #endif
138 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
139     if (addr->sa_family == AF_INET6) {
140         struct ipv6_mreq mreq6;
141
142         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
143         mreq6.ipv6mr_interface= 0;
144         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
145             av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP): %s\n", strerror(errno));
146             return -1;
147         }
148     }
149 #endif
150     return 0;
151 }
152
153 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
154                                          int type, int family, int flags)
155 {
156     struct addrinfo hints, *res = 0;
157     int error;
158     char sport[16];
159     const char *node = 0, *service = "0";
160
161     if (port > 0) {
162         snprintf(sport, sizeof(sport), "%d", port);
163         service = sport;
164     }
165     if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
166         node = hostname;
167     }
168     memset(&hints, 0, sizeof(hints));
169     hints.ai_socktype = type;
170     hints.ai_family   = family;
171     hints.ai_flags = flags;
172     if ((error = getaddrinfo(node, service, &hints, &res))) {
173         res = NULL;
174         av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
175     }
176
177     return res;
178 }
179
180 static int udp_set_url(struct sockaddr_storage *addr,
181                        const char *hostname, int port)
182 {
183     struct addrinfo *res0;
184     int addr_len;
185
186     res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
187     if (res0 == 0) return AVERROR(EIO);
188     memcpy(addr, res0->ai_addr, res0->ai_addrlen);
189     addr_len = res0->ai_addrlen;
190     freeaddrinfo(res0);
191
192     return addr_len;
193 }
194
195 static int udp_socket_create(UDPContext *s,
196                              struct sockaddr_storage *addr, int *addr_len)
197 {
198     int udp_fd = -1;
199     struct addrinfo *res0 = NULL, *res = NULL;
200     int family = AF_UNSPEC;
201
202     if (((struct sockaddr *) &s->dest_addr)->sa_family)
203         family = ((struct sockaddr *) &s->dest_addr)->sa_family;
204     res0 = udp_resolve_host(0, s->local_port, SOCK_DGRAM, family, AI_PASSIVE);
205     if (res0 == 0)
206         goto fail;
207     for (res = res0; res; res=res->ai_next) {
208         udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
209         if (udp_fd > 0) break;
210         av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno));
211     }
212
213     if (udp_fd < 0)
214         goto fail;
215
216     memcpy(addr, res->ai_addr, res->ai_addrlen);
217     *addr_len = res->ai_addrlen;
218
219     freeaddrinfo(res0);
220
221     return udp_fd;
222
223  fail:
224     if (udp_fd >= 0)
225         closesocket(udp_fd);
226     if(res0)
227         freeaddrinfo(res0);
228     return -1;
229 }
230
231 static int udp_port(struct sockaddr_storage *addr, int addr_len)
232 {
233     char sbuf[sizeof(int)*3+1];
234
235     if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0,  sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) {
236         av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno));
237         return -1;
238     }
239
240     return strtol(sbuf, NULL, 10);
241 }
242
243
244 /**
245  * If no filename is given to av_open_input_file because you want to
246  * get the local port first, then you must call this function to set
247  * the remote server address.
248  *
249  * url syntax: udp://host:port[?option=val...]
250  * option: 'ttl=n'       : set the ttl value (for multicast only)
251  *         'localport=n' : set the local port
252  *         'pkt_size=n'  : set max packet size
253  *         'reuse=1'     : enable reusing the socket
254  *
255  * @param h media file context
256  * @param uri of the remote server
257  * @return zero if no error.
258  */
259 int ff_udp_set_remote_url(URLContext *h, const char *uri)
260 {
261     UDPContext *s = h->priv_data;
262     char hostname[256], buf[10];
263     int port;
264     const char *p;
265
266     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
267
268     /* set the destination address */
269     s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
270     if (s->dest_addr_len < 0) {
271         return AVERROR(EIO);
272     }
273     s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
274     p = strchr(uri, '?');
275     if (p) {
276         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
277             int was_connected = s->is_connected;
278             s->is_connected = strtol(buf, NULL, 10);
279             if (s->is_connected && !was_connected) {
280                 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
281                             s->dest_addr_len)) {
282                     s->is_connected = 0;
283                     av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
284                     return AVERROR(EIO);
285                 }
286             }
287         }
288     }
289
290     return 0;
291 }
292
293 /**
294  * Return the local port used by the UDP connection
295  * @param h media file context
296  * @return the local port number
297  */
298 int ff_udp_get_local_port(URLContext *h)
299 {
300     UDPContext *s = h->priv_data;
301     return s->local_port;
302 }
303
304 /**
305  * Return the udp file handle for select() usage to wait for several RTP
306  * streams at the same time.
307  * @param h media file context
308  */
309 static int udp_get_file_handle(URLContext *h)
310 {
311     UDPContext *s = h->priv_data;
312     return s->udp_fd;
313 }
314
315 static void *circular_buffer_task( void *_URLContext)
316 {
317     URLContext *h = _URLContext;
318     UDPContext *s = h->priv_data;
319     fd_set rfds;
320     struct timeval tv;
321
322     for(;;) {
323         int left;
324         int ret;
325         int len;
326
327         if (url_interrupt_cb()) {
328             s->circular_buffer_error = EINTR;
329             return NULL;
330         }
331
332         FD_ZERO(&rfds);
333         FD_SET(s->udp_fd, &rfds);
334         tv.tv_sec = 1;
335         tv.tv_usec = 0;
336         ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv);
337         if (ret < 0) {
338             if (ff_neterrno() == AVERROR(EINTR))
339                 continue;
340             s->circular_buffer_error = EIO;
341             return NULL;
342         }
343
344         if (!(ret > 0 && FD_ISSET(s->udp_fd, &rfds)))
345             continue;
346
347         /* How much do we have left to the end of the buffer */
348         /* Whats the minimum we can read so that we dont comletely fill the buffer */
349         left = av_fifo_space(s->fifo);
350         left = FFMIN(left, s->fifo->end - s->fifo->wptr);
351
352         /* No Space left, error, what do we do now */
353         if( !left) {
354             av_log(h, AV_LOG_ERROR, "circular_buffer: OVERRUN\n");
355             s->circular_buffer_error = EIO;
356             return NULL;
357         }
358
359         len = recv(s->udp_fd, s->fifo->wptr, left, 0);
360         if (len < 0) {
361             if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
362                 s->circular_buffer_error = EIO;
363                 return NULL;
364             }
365         }
366         s->fifo->wptr += len;
367         if (s->fifo->wptr >= s->fifo->end)
368             s->fifo->wptr = s->fifo->buffer;
369         s->fifo->wndx += len;
370     }
371
372     return NULL;
373 }
374
375 /* put it in UDP context */
376 /* return non zero if error */
377 static int udp_open(URLContext *h, const char *uri, int flags)
378 {
379     char hostname[1024];
380     int port, udp_fd = -1, tmp, bind_ret = -1;
381     UDPContext *s = NULL;
382     int is_output;
383     const char *p;
384     char buf[256];
385     struct sockaddr_storage my_addr;
386     int len;
387     int reuse_specified = 0;
388
389     h->is_streamed = 1;
390     h->max_packet_size = 1472;
391
392     is_output = !(flags & AVIO_FLAG_READ);
393
394     s = av_mallocz(sizeof(UDPContext));
395     if (!s)
396         return AVERROR(ENOMEM);
397
398     h->priv_data = s;
399     s->ttl = 16;
400     s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
401
402     s->circular_buffer_size = 7*188*4096;
403
404     p = strchr(uri, '?');
405     if (p) {
406         if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
407             char *endptr = NULL;
408             s->reuse_socket = strtol(buf, &endptr, 10);
409             /* assume if no digits were found it is a request to enable it */
410             if (buf == endptr)
411                 s->reuse_socket = 1;
412             reuse_specified = 1;
413         }
414         if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
415             s->ttl = strtol(buf, NULL, 10);
416         }
417         if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
418             s->local_port = strtol(buf, NULL, 10);
419         }
420         if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
421             h->max_packet_size = strtol(buf, NULL, 10);
422         }
423         if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
424             s->buffer_size = strtol(buf, NULL, 10);
425         }
426         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
427             s->is_connected = strtol(buf, NULL, 10);
428         }
429         if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
430             s->circular_buffer_size = strtol(buf, NULL, 10)*188;
431         }
432     }
433
434     /* fill the dest addr */
435     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
436
437     /* XXX: fix av_url_split */
438     if (hostname[0] == '\0' || hostname[0] == '?') {
439         /* only accepts null hostname if input */
440         if (!(flags & AVIO_FLAG_READ))
441             goto fail;
442     } else {
443         if (ff_udp_set_remote_url(h, uri) < 0)
444             goto fail;
445     }
446
447     if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
448         s->local_port = port;
449     udp_fd = udp_socket_create(s, &my_addr, &len);
450     if (udp_fd < 0)
451         goto fail;
452
453     /* Follow the requested reuse option, unless it's multicast in which
454      * case enable reuse unless explicitely disabled.
455      */
456     if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
457         s->reuse_socket = 1;
458         if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
459             goto fail;
460     }
461
462     /* the bind is needed to give a port to the socket now */
463     /* if multicast, try the multicast address bind first */
464     if (s->is_multicast && (h->flags & AVIO_FLAG_READ)) {
465         bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
466     }
467     /* bind to the local address if not multicast or if the multicast
468      * bind failed */
469     if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0)
470         goto fail;
471
472     len = sizeof(my_addr);
473     getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
474     s->local_port = udp_port(&my_addr, len);
475
476     if (s->is_multicast) {
477         if (!(h->flags & AVIO_FLAG_READ)) {
478             /* output */
479             if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
480                 goto fail;
481         } else {
482             /* input */
483             if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
484                 goto fail;
485         }
486     }
487
488     if (is_output) {
489         /* limit the tx buf size to limit latency */
490         tmp = s->buffer_size;
491         if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
492             av_log(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF): %s\n", strerror(errno));
493             goto fail;
494         }
495     } else {
496         /* set udp recv buffer size to the largest possible udp packet size to
497          * avoid losing data on OSes that set this too low by default. */
498         tmp = s->buffer_size;
499         if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
500             av_log(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF): %s\n", strerror(errno));
501         }
502         /* make the socket non-blocking */
503         ff_socket_nonblock(udp_fd, 1);
504     }
505     if (s->is_connected) {
506         if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
507             av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
508             goto fail;
509         }
510     }
511
512     s->udp_fd = udp_fd;
513
514 #if HAVE_PTHREADS
515     if (!is_output && s->circular_buffer_size) {
516         /* start the task going */
517         s->fifo = av_fifo_alloc(s->circular_buffer_size);
518         if (pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h)) {
519             av_log(h, AV_LOG_ERROR, "pthread_create failed\n");
520             goto fail;
521         }
522     }
523 #endif
524
525     return 0;
526  fail:
527     if (udp_fd >= 0)
528         closesocket(udp_fd);
529     av_fifo_free(s->fifo);
530     av_free(s);
531     return AVERROR(EIO);
532 }
533
534 static int udp_read(URLContext *h, uint8_t *buf, int size)
535 {
536     UDPContext *s = h->priv_data;
537     int ret;
538     int avail;
539     fd_set rfds;
540     struct timeval tv;
541
542     if (s->fifo) {
543
544         do {
545             avail = av_fifo_size(s->fifo);
546             if (avail) { // >=size) {
547
548                 // Maximum amount available
549                 size = FFMIN( avail, size);
550                 av_fifo_generic_read(s->fifo, buf, size, NULL);
551                 return size;
552             }
553             else {
554                 FD_ZERO(&rfds);
555                 FD_SET(s->udp_fd, &rfds);
556                 tv.tv_sec = 1;
557                 tv.tv_usec = 0;
558                 ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv);
559                 if (ret<0)
560                     return ret;
561             }
562         } while( 1);
563     }
564
565     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
566         ret = ff_network_wait_fd(s->udp_fd, 0);
567         if (ret < 0)
568             return ret;
569     }
570     ret = recv(s->udp_fd, buf, size, 0);
571
572     return ret < 0 ? ff_neterrno() : ret;
573 }
574
575 static int udp_write(URLContext *h, const uint8_t *buf, int size)
576 {
577     UDPContext *s = h->priv_data;
578     int ret;
579
580     if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
581         ret = ff_network_wait_fd(s->udp_fd, 1);
582         if (ret < 0)
583             return ret;
584     }
585
586     if (!s->is_connected) {
587         ret = sendto (s->udp_fd, buf, size, 0,
588                       (struct sockaddr *) &s->dest_addr,
589                       s->dest_addr_len);
590     } else
591         ret = send(s->udp_fd, buf, size, 0);
592
593     return ret < 0 ? ff_neterrno() : ret;
594 }
595
596 static int udp_close(URLContext *h)
597 {
598     UDPContext *s = h->priv_data;
599
600     if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
601         udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
602     closesocket(s->udp_fd);
603     av_fifo_free(s->fifo);
604     av_free(s);
605     return 0;
606 }
607
608 URLProtocol ff_udp_protocol = {
609     .name                = "udp",
610     .url_open            = udp_open,
611     .url_read            = udp_read,
612     .url_write           = udp_write,
613     .url_close           = udp_close,
614     .url_get_file_handle = udp_get_file_handle,
615 };