OSDN Git Service

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