]> git.sesse.net Git - ffmpeg/blob - libavformat/udp.c
mpeg12dec: reset first_field with picture_structure changes.
[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_PTHREADS
42 #include <pthread.h>
43 #endif
44
45 #include <sys/time.h>
46
47 #ifndef IPV6_ADD_MEMBERSHIP
48 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
49 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
50 #endif
51
52 #define UDP_TX_BUF_SIZE 32768
53 #define UDP_MAX_PKT_SIZE 65536
54
55 typedef struct {
56     int udp_fd;
57     int ttl;
58     int buffer_size;
59     int is_multicast;
60     int local_port;
61     int reuse_socket;
62     struct sockaddr_storage dest_addr;
63     int dest_addr_len;
64     int is_connected;
65
66     /* Circular Buffer variables for use in UDP receive code */
67     int circular_buffer_size;
68     AVFifoBuffer *fifo;
69     int circular_buffer_error;
70 #if HAVE_PTHREADS
71     pthread_t circular_buffer_thread;
72 #endif
73     uint8_t tmp[UDP_MAX_PKT_SIZE+4];
74     int remaining_in_dg;
75 } UDPContext;
76
77 static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
78                                  struct sockaddr *addr)
79 {
80 #ifdef IP_MULTICAST_TTL
81     if (addr->sa_family == AF_INET) {
82         if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
83             av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL): %s\n", strerror(errno));
84             return -1;
85         }
86     }
87 #endif
88 #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
89     if (addr->sa_family == AF_INET6) {
90         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
91             av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS): %s\n", strerror(errno));
92             return -1;
93         }
94     }
95 #endif
96     return 0;
97 }
98
99 static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
100 {
101 #ifdef IP_ADD_MEMBERSHIP
102     if (addr->sa_family == AF_INET) {
103         struct ip_mreq mreq;
104
105         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
106         mreq.imr_interface.s_addr= INADDR_ANY;
107         if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
108             av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno));
109             return -1;
110         }
111     }
112 #endif
113 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
114     if (addr->sa_family == AF_INET6) {
115         struct ipv6_mreq mreq6;
116
117         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
118         mreq6.ipv6mr_interface= 0;
119         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
120             av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP): %s\n", strerror(errno));
121             return -1;
122         }
123     }
124 #endif
125     return 0;
126 }
127
128 static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
129 {
130 #ifdef IP_DROP_MEMBERSHIP
131     if (addr->sa_family == AF_INET) {
132         struct ip_mreq mreq;
133
134         mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
135         mreq.imr_interface.s_addr= INADDR_ANY;
136         if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
137             av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP): %s\n", strerror(errno));
138             return -1;
139         }
140     }
141 #endif
142 #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
143     if (addr->sa_family == AF_INET6) {
144         struct ipv6_mreq mreq6;
145
146         memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
147         mreq6.ipv6mr_interface= 0;
148         if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
149             av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP): %s\n", strerror(errno));
150             return -1;
151         }
152     }
153 #endif
154     return 0;
155 }
156
157 static struct addrinfo* udp_resolve_host(const char *hostname, int port,
158                                          int type, int family, int flags)
159 {
160     struct addrinfo hints, *res = 0;
161     int error;
162     char sport[16];
163     const char *node = 0, *service = "0";
164
165     if (port > 0) {
166         snprintf(sport, sizeof(sport), "%d", port);
167         service = sport;
168     }
169     if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
170         node = hostname;
171     }
172     memset(&hints, 0, sizeof(hints));
173     hints.ai_socktype = type;
174     hints.ai_family   = family;
175     hints.ai_flags = flags;
176     if ((error = getaddrinfo(node, service, &hints, &res))) {
177         res = NULL;
178         av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
179     }
180
181     return res;
182 }
183
184 static int udp_set_url(struct sockaddr_storage *addr,
185                        const char *hostname, int port)
186 {
187     struct addrinfo *res0;
188     int addr_len;
189
190     res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
191     if (res0 == 0) return AVERROR(EIO);
192     memcpy(addr, res0->ai_addr, res0->ai_addrlen);
193     addr_len = res0->ai_addrlen;
194     freeaddrinfo(res0);
195
196     return addr_len;
197 }
198
199 static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
200                              int *addr_len, const char *localaddr)
201 {
202     int udp_fd = -1;
203     struct addrinfo *res0 = NULL, *res = NULL;
204     int family = AF_UNSPEC;
205
206     if (((struct sockaddr *) &s->dest_addr)->sa_family)
207         family = ((struct sockaddr *) &s->dest_addr)->sa_family;
208     res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
209                             SOCK_DGRAM, family, AI_PASSIVE);
210     if (res0 == 0)
211         goto fail;
212     for (res = res0; res; res=res->ai_next) {
213         udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
214         if (udp_fd > 0) break;
215         av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno));
216     }
217
218     if (udp_fd < 0)
219         goto fail;
220
221     memcpy(addr, res->ai_addr, res->ai_addrlen);
222     *addr_len = res->ai_addrlen;
223
224     freeaddrinfo(res0);
225
226     return udp_fd;
227
228  fail:
229     if (udp_fd >= 0)
230         closesocket(udp_fd);
231     if(res0)
232         freeaddrinfo(res0);
233     return -1;
234 }
235
236 static int udp_port(struct sockaddr_storage *addr, int addr_len)
237 {
238     char sbuf[sizeof(int)*3+1];
239
240     if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0,  sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) {
241         av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno));
242         return -1;
243     }
244
245     return strtol(sbuf, NULL, 10);
246 }
247
248
249 /**
250  * If no filename is given to av_open_input_file because you want to
251  * get the local port first, then you must call this function to set
252  * the remote server address.
253  *
254  * url syntax: udp://host:port[?option=val...]
255  * option: 'ttl=n'       : set the ttl value (for multicast only)
256  *         'localport=n' : set the local port
257  *         'pkt_size=n'  : set max packet size
258  *         'reuse=1'     : enable reusing the socket
259  *
260  * @param h media file context
261  * @param uri of the remote server
262  * @return zero if no error.
263  */
264 int ff_udp_set_remote_url(URLContext *h, const char *uri)
265 {
266     UDPContext *s = h->priv_data;
267     char hostname[256], buf[10];
268     int port;
269     const char *p;
270
271     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
272
273     /* set the destination address */
274     s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
275     if (s->dest_addr_len < 0) {
276         return AVERROR(EIO);
277     }
278     s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
279     p = strchr(uri, '?');
280     if (p) {
281         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
282             int was_connected = s->is_connected;
283             s->is_connected = strtol(buf, NULL, 10);
284             if (s->is_connected && !was_connected) {
285                 if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
286                             s->dest_addr_len)) {
287                     s->is_connected = 0;
288                     av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
289                     return AVERROR(EIO);
290                 }
291             }
292         }
293     }
294
295     return 0;
296 }
297
298 /**
299  * Return the local port used by the UDP connection
300  * @param h media file context
301  * @return the local port number
302  */
303 int ff_udp_get_local_port(URLContext *h)
304 {
305     UDPContext *s = h->priv_data;
306     return s->local_port;
307 }
308
309 /**
310  * Return the udp file handle for select() usage to wait for several RTP
311  * streams at the same time.
312  * @param h media file context
313  */
314 static int udp_get_file_handle(URLContext *h)
315 {
316     UDPContext *s = h->priv_data;
317     return s->udp_fd;
318 }
319
320 static void *circular_buffer_task( void *_URLContext)
321 {
322     URLContext *h = _URLContext;
323     UDPContext *s = h->priv_data;
324     fd_set rfds;
325     struct timeval tv;
326
327     for(;;) {
328         int left;
329         int ret;
330         int len;
331
332         if (ff_check_interrupt(&h->interrupt_callback)) {
333             s->circular_buffer_error = EINTR;
334             return NULL;
335         }
336
337         FD_ZERO(&rfds);
338         FD_SET(s->udp_fd, &rfds);
339         tv.tv_sec = 1;
340         tv.tv_usec = 0;
341         ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv);
342         if (ret < 0) {
343             if (ff_neterrno() == AVERROR(EINTR))
344                 continue;
345             s->circular_buffer_error = EIO;
346             return NULL;
347         }
348
349         if (!(ret > 0 && FD_ISSET(s->udp_fd, &rfds)))
350             continue;
351
352         /* How much do we have left to the end of the buffer */
353         /* Whats the minimum we can read so that we dont comletely fill the buffer */
354         left = av_fifo_space(s->fifo);
355
356         /* No Space left, error, what do we do now */
357         if(left < UDP_MAX_PKT_SIZE + 4) {
358             av_log(h, AV_LOG_ERROR, "circular_buffer: OVERRUN\n");
359             s->circular_buffer_error = EIO;
360             return NULL;
361         }
362         left = FFMIN(left, s->fifo->end - s->fifo->wptr);
363         len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
364         if (len < 0) {
365             if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
366                 s->circular_buffer_error = EIO;
367                 return NULL;
368             }
369             continue;
370         }
371         AV_WL32(s->tmp, len);
372         av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
373     }
374
375     return NULL;
376 }
377
378 /* put it in UDP context */
379 /* return non zero if error */
380 static int udp_open(URLContext *h, const char *uri, int flags)
381 {
382     char hostname[1024], localaddr[1024] = "";
383     int port, udp_fd = -1, tmp, bind_ret = -1;
384     UDPContext *s = h->priv_data;
385     int is_output;
386     const char *p;
387     char buf[256];
388     struct sockaddr_storage my_addr;
389     int len;
390     int reuse_specified = 0;
391
392     h->is_streamed = 1;
393     h->max_packet_size = 1472;
394
395     is_output = !(flags & AVIO_FLAG_READ);
396
397     s->ttl = 16;
398     s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
399
400     s->circular_buffer_size = 7*188*4096;
401
402     p = strchr(uri, '?');
403     if (p) {
404         if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
405             char *endptr = NULL;
406             s->reuse_socket = strtol(buf, &endptr, 10);
407             /* assume if no digits were found it is a request to enable it */
408             if (buf == endptr)
409                 s->reuse_socket = 1;
410             reuse_specified = 1;
411         }
412         if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
413             s->ttl = strtol(buf, NULL, 10);
414         }
415         if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
416             s->local_port = strtol(buf, NULL, 10);
417         }
418         if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
419             h->max_packet_size = strtol(buf, NULL, 10);
420         }
421         if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
422             s->buffer_size = strtol(buf, NULL, 10);
423         }
424         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
425             s->is_connected = strtol(buf, NULL, 10);
426         }
427         if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
428             s->circular_buffer_size = strtol(buf, NULL, 10)*188;
429         }
430         if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
431             av_strlcpy(localaddr, buf, sizeof(localaddr));
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, localaddr);
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 explicitly 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     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                 uint8_t tmp[4];
548
549                 av_fifo_generic_read(s->fifo, tmp, 4, NULL);
550                 avail= AV_RL32(tmp);
551                 if(avail > size){
552                     av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
553                     avail= size;
554                 }
555
556                 av_fifo_generic_read(s->fifo, buf, avail, NULL);
557                 av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
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     return 0;
612 }
613
614 URLProtocol ff_udp_protocol = {
615     .name                = "udp",
616     .url_open            = udp_open,
617     .url_read            = udp_read,
618     .url_write           = udp_write,
619     .url_close           = udp_close,
620     .url_get_file_handle = udp_get_file_handle,
621     .priv_data_size      = sizeof(UDPContext),
622 };