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