]> git.sesse.net Git - ffmpeg/blob - libavformat/rtpproto.c
rtpproto: Support nonblocking reads
[ffmpeg] / libavformat / rtpproto.c
1 /*
2  * RTP network protocol
3  * Copyright (c) 2002 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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  * RTP protocol
25  */
26
27 #include "libavutil/parseutils.h"
28 #include "libavutil/avstring.h"
29 #include "avformat.h"
30 #include "avio_internal.h"
31 #include "rtpdec.h"
32 #include "url.h"
33
34 #include <stdarg.h>
35 #include "internal.h"
36 #include "network.h"
37 #include "os_support.h"
38 #include <fcntl.h>
39 #if HAVE_POLL_H
40 #include <sys/poll.h>
41 #endif
42
43 typedef struct RTPContext {
44     URLContext *rtp_hd, *rtcp_hd;
45     int rtp_fd, rtcp_fd, nb_ssm_include_addrs, nb_ssm_exclude_addrs;
46     struct sockaddr_storage **ssm_include_addrs, **ssm_exclude_addrs;
47 } RTPContext;
48
49 /**
50  * If no filename is given to av_open_input_file because you want to
51  * get the local port first, then you must call this function to set
52  * the remote server address.
53  *
54  * @param h media file context
55  * @param uri of the remote server
56  * @return zero if no error.
57  */
58
59 int ff_rtp_set_remote_url(URLContext *h, const char *uri)
60 {
61     RTPContext *s = h->priv_data;
62     char hostname[256];
63     int port;
64
65     char buf[1024];
66     char path[1024];
67
68     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port,
69                  path, sizeof(path), uri);
70
71     ff_url_join(buf, sizeof(buf), "udp", NULL, hostname, port, "%s", path);
72     ff_udp_set_remote_url(s->rtp_hd, buf);
73
74     ff_url_join(buf, sizeof(buf), "udp", NULL, hostname, port + 1, "%s", path);
75     ff_udp_set_remote_url(s->rtcp_hd, buf);
76     return 0;
77 }
78
79 static struct addrinfo* rtp_resolve_host(const char *hostname, int port,
80                                          int type, int family, int flags)
81 {
82     struct addrinfo hints = { 0 }, *res = 0;
83     int error;
84     char service[16];
85
86     snprintf(service, sizeof(service), "%d", port);
87     hints.ai_socktype = type;
88     hints.ai_family   = family;
89     hints.ai_flags    = flags;
90     if ((error = getaddrinfo(hostname, service, &hints, &res))) {
91         res = NULL;
92         av_log(NULL, AV_LOG_ERROR, "rtp_resolve_host: %s\n", gai_strerror(error));
93     }
94
95     return res;
96 }
97
98 static int compare_addr(const struct sockaddr_storage *a,
99                         const struct sockaddr_storage *b)
100 {
101     if (a->ss_family != b->ss_family)
102         return 1;
103     if (a->ss_family == AF_INET) {
104         return (((const struct sockaddr_in *)a)->sin_addr.s_addr !=
105                 ((const struct sockaddr_in *)b)->sin_addr.s_addr);
106     }
107
108 #if defined(IPPROTO_IPV6)
109     if (a->ss_family == AF_INET6) {
110         const uint8_t *s6_addr_a = ((const struct sockaddr_in6 *)a)->sin6_addr.s6_addr;
111         const uint8_t *s6_addr_b = ((const struct sockaddr_in6 *)b)->sin6_addr.s6_addr;
112         return memcmp(s6_addr_a, s6_addr_b, 16);
113     }
114 #endif
115     return 1;
116 }
117
118 static int rtp_check_source_lists(RTPContext *s, struct sockaddr_storage *source_addr_ptr)
119 {
120     int i;
121     if (s->nb_ssm_exclude_addrs) {
122         for (i = 0; i < s->nb_ssm_exclude_addrs; i++) {
123             if (!compare_addr(source_addr_ptr, s->ssm_exclude_addrs[i]))
124                 return 1;
125         }
126     }
127     if (s->nb_ssm_include_addrs) {
128         for (i = 0; i < s->nb_ssm_include_addrs; i++) {
129             if (!compare_addr(source_addr_ptr, s->ssm_include_addrs[i]))
130                 return 0;
131         }
132         return 1;
133     }
134     return 0;
135 }
136
137 /**
138  * add option to url of the form:
139  * "http://host:port/path?option1=val1&option2=val2...
140  */
141
142 static av_printf_format(3, 4) void url_add_option(char *buf, int buf_size, const char *fmt, ...)
143 {
144     char buf1[1024];
145     va_list ap;
146
147     va_start(ap, fmt);
148     if (strchr(buf, '?'))
149         av_strlcat(buf, "&", buf_size);
150     else
151         av_strlcat(buf, "?", buf_size);
152     vsnprintf(buf1, sizeof(buf1), fmt, ap);
153     av_strlcat(buf, buf1, buf_size);
154     va_end(ap);
155 }
156
157 static void build_udp_url(char *buf, int buf_size,
158                           const char *hostname, int port,
159                           int local_port, int ttl,
160                           int max_packet_size, int connect,
161                           const char *include_sources,
162                           const char *exclude_sources)
163 {
164     ff_url_join(buf, buf_size, "udp", NULL, hostname, port, NULL);
165     if (local_port >= 0)
166         url_add_option(buf, buf_size, "localport=%d", local_port);
167     if (ttl >= 0)
168         url_add_option(buf, buf_size, "ttl=%d", ttl);
169     if (max_packet_size >=0)
170         url_add_option(buf, buf_size, "pkt_size=%d", max_packet_size);
171     if (connect)
172         url_add_option(buf, buf_size, "connect=1");
173     if (include_sources && include_sources[0])
174         url_add_option(buf, buf_size, "sources=%s", include_sources);
175     if (exclude_sources && exclude_sources[0])
176         url_add_option(buf, buf_size, "block=%s", exclude_sources);
177 }
178
179 static void rtp_parse_addr_list(URLContext *h, char *buf,
180                                 struct sockaddr_storage ***address_list_ptr,
181                                 int *address_list_size_ptr)
182 {
183     struct addrinfo *ai = NULL;
184     struct sockaddr_storage *source_addr;
185     char tmp = '\0', *p = buf, *next;
186
187     /* Resolve all of the IPs */
188
189     while (p && p[0]) {
190         next = strchr(p, ',');
191
192         if (next) {
193             tmp = *next;
194             *next = '\0';
195         }
196
197         ai = rtp_resolve_host(p, 0, SOCK_DGRAM, AF_UNSPEC, 0);
198         if (ai) {
199             source_addr = av_mallocz(sizeof(struct sockaddr_storage));
200             if (!source_addr)
201                 break;
202
203             memcpy(source_addr, ai->ai_addr, ai->ai_addrlen);
204             freeaddrinfo(ai);
205             dynarray_add(address_list_ptr, address_list_size_ptr, source_addr);
206         } else {
207             av_log(h, AV_LOG_WARNING, "Unable to resolve %s\n", p);
208         }
209
210         if (next) {
211             *next = tmp;
212             p = next + 1;
213         } else {
214             p = NULL;
215         }
216     }
217 }
218
219 /**
220  * url syntax: rtp://host:port[?option=val...]
221  * option: 'ttl=n'            : set the ttl value (for multicast only)
222  *         'rtcpport=n'       : set the remote rtcp port to n
223  *         'localrtpport=n'   : set the local rtp port to n
224  *         'localrtcpport=n'  : set the local rtcp port to n
225  *         'pkt_size=n'       : set max packet size
226  *         'connect=0/1'      : do a connect() on the UDP socket
227  * deprecated option:
228  *         'localport=n'      : set the local port to n
229  *         'sources=ip[,ip]'  : list allowed source IP addresses
230  *
231  * if rtcpport isn't set the rtcp port will be the rtp port + 1
232  * if local rtp port isn't set any available port will be used for the local
233  * rtp and rtcp ports
234  * if the local rtcp port is not set it will be the local rtp port + 1
235  */
236
237 static int rtp_open(URLContext *h, const char *uri, int flags)
238 {
239     RTPContext *s = h->priv_data;
240     int rtp_port, rtcp_port,
241         ttl, connect,
242         local_rtp_port, local_rtcp_port, max_packet_size;
243     char hostname[256], include_sources[1024] = "", exclude_sources[1024] = "";
244     char buf[1024];
245     char path[1024];
246     const char *p;
247
248     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &rtp_port,
249                  path, sizeof(path), uri);
250     /* extract parameters */
251     ttl = -1;
252     rtcp_port = rtp_port+1;
253     local_rtp_port = -1;
254     local_rtcp_port = -1;
255     max_packet_size = -1;
256     connect = 0;
257
258     p = strchr(uri, '?');
259     if (p) {
260         if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
261             ttl = strtol(buf, NULL, 10);
262         }
263         if (av_find_info_tag(buf, sizeof(buf), "rtcpport", p)) {
264             rtcp_port = strtol(buf, NULL, 10);
265         }
266         if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
267             local_rtp_port = strtol(buf, NULL, 10);
268         }
269         if (av_find_info_tag(buf, sizeof(buf), "localrtpport", p)) {
270             local_rtp_port = strtol(buf, NULL, 10);
271         }
272         if (av_find_info_tag(buf, sizeof(buf), "localrtcpport", p)) {
273             local_rtcp_port = strtol(buf, NULL, 10);
274         }
275         if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
276             max_packet_size = strtol(buf, NULL, 10);
277         }
278         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
279             connect = strtol(buf, NULL, 10);
280         }
281         if (av_find_info_tag(buf, sizeof(buf), "sources", p)) {
282             av_strlcpy(include_sources, buf, sizeof(include_sources));
283             rtp_parse_addr_list(h, buf, &s->ssm_include_addrs, &s->nb_ssm_include_addrs);
284         }
285         if (av_find_info_tag(buf, sizeof(buf), "block", p)) {
286             av_strlcpy(exclude_sources, buf, sizeof(exclude_sources));
287             rtp_parse_addr_list(h, buf, &s->ssm_exclude_addrs, &s->nb_ssm_exclude_addrs);
288         }
289     }
290
291     build_udp_url(buf, sizeof(buf),
292                   hostname, rtp_port, local_rtp_port, ttl, max_packet_size,
293                   connect, include_sources, exclude_sources);
294     if (ffurl_open(&s->rtp_hd, buf, flags, &h->interrupt_callback, NULL) < 0)
295         goto fail;
296     if (local_rtp_port>=0 && local_rtcp_port<0)
297         local_rtcp_port = ff_udp_get_local_port(s->rtp_hd) + 1;
298
299     build_udp_url(buf, sizeof(buf),
300                   hostname, rtcp_port, local_rtcp_port, ttl, max_packet_size,
301                   connect, include_sources, exclude_sources);
302     if (ffurl_open(&s->rtcp_hd, buf, flags, &h->interrupt_callback, NULL) < 0)
303         goto fail;
304
305     /* just to ease handle access. XXX: need to suppress direct handle
306        access */
307     s->rtp_fd = ffurl_get_file_handle(s->rtp_hd);
308     s->rtcp_fd = ffurl_get_file_handle(s->rtcp_hd);
309
310     h->max_packet_size = s->rtp_hd->max_packet_size;
311     h->is_streamed = 1;
312     return 0;
313
314  fail:
315     if (s->rtp_hd)
316         ffurl_close(s->rtp_hd);
317     if (s->rtcp_hd)
318         ffurl_close(s->rtcp_hd);
319     return AVERROR(EIO);
320 }
321
322 static int rtp_read(URLContext *h, uint8_t *buf, int size)
323 {
324     RTPContext *s = h->priv_data;
325     struct sockaddr_storage from;
326     socklen_t from_len;
327     int len, n;
328     struct pollfd p[2] = {{s->rtp_fd, POLLIN, 0}, {s->rtcp_fd, POLLIN, 0}};
329     int poll_delay = h->flags & AVIO_FLAG_NONBLOCK ? 0 : 100;
330
331     for(;;) {
332         if (ff_check_interrupt(&h->interrupt_callback))
333             return AVERROR_EXIT;
334         /* build fdset to listen to RTP and RTCP packets */
335         n = poll(p, 2, poll_delay);
336         if (n > 0) {
337             /* first try RTCP */
338             if (p[1].revents & POLLIN) {
339                 from_len = sizeof(from);
340                 len = recvfrom (s->rtcp_fd, buf, size, 0,
341                                 (struct sockaddr *)&from, &from_len);
342                 if (len < 0) {
343                     if (ff_neterrno() == AVERROR(EAGAIN) ||
344                         ff_neterrno() == AVERROR(EINTR))
345                         continue;
346                     return AVERROR(EIO);
347                 }
348                 if (rtp_check_source_lists(s, &from))
349                     continue;
350                 break;
351             }
352             /* then RTP */
353             if (p[0].revents & POLLIN) {
354                 from_len = sizeof(from);
355                 len = recvfrom (s->rtp_fd, buf, size, 0,
356                                 (struct sockaddr *)&from, &from_len);
357                 if (len < 0) {
358                     if (ff_neterrno() == AVERROR(EAGAIN) ||
359                         ff_neterrno() == AVERROR(EINTR))
360                         continue;
361                     return AVERROR(EIO);
362                 }
363                 if (rtp_check_source_lists(s, &from))
364                     continue;
365                 break;
366             }
367         } else if (n < 0) {
368             if (ff_neterrno() == AVERROR(EINTR))
369                 continue;
370             return AVERROR(EIO);
371         }
372         if (h->flags & AVIO_FLAG_NONBLOCK)
373             return AVERROR(EAGAIN);
374     }
375     return len;
376 }
377
378 static int rtp_write(URLContext *h, const uint8_t *buf, int size)
379 {
380     RTPContext *s = h->priv_data;
381     int ret;
382     URLContext *hd;
383
384     if (RTP_PT_IS_RTCP(buf[1])) {
385         /* RTCP payload type */
386         hd = s->rtcp_hd;
387     } else {
388         /* RTP payload type */
389         hd = s->rtp_hd;
390     }
391
392     ret = ffurl_write(hd, buf, size);
393     return ret;
394 }
395
396 static int rtp_close(URLContext *h)
397 {
398     RTPContext *s = h->priv_data;
399     int i;
400
401     for (i = 0; i < s->nb_ssm_include_addrs; i++)
402         av_free(s->ssm_include_addrs[i]);
403     av_freep(&s->ssm_include_addrs);
404     for (i = 0; i < s->nb_ssm_exclude_addrs; i++)
405         av_free(s->ssm_exclude_addrs[i]);
406     av_freep(&s->ssm_exclude_addrs);
407
408     ffurl_close(s->rtp_hd);
409     ffurl_close(s->rtcp_hd);
410     return 0;
411 }
412
413 /**
414  * Return the local rtp port used by the RTP connection
415  * @param h media file context
416  * @return the local port number
417  */
418
419 int ff_rtp_get_local_rtp_port(URLContext *h)
420 {
421     RTPContext *s = h->priv_data;
422     return ff_udp_get_local_port(s->rtp_hd);
423 }
424
425 /**
426  * Return the local rtcp port used by the RTP connection
427  * @param h media file context
428  * @return the local port number
429  */
430
431 int ff_rtp_get_local_rtcp_port(URLContext *h)
432 {
433     RTPContext *s = h->priv_data;
434     return ff_udp_get_local_port(s->rtcp_hd);
435 }
436
437 static int rtp_get_file_handle(URLContext *h)
438 {
439     RTPContext *s = h->priv_data;
440     return s->rtp_fd;
441 }
442
443 static int rtp_get_multi_file_handle(URLContext *h, int **handles,
444                                      int *numhandles)
445 {
446     RTPContext *s = h->priv_data;
447     int *hs       = *handles = av_malloc(sizeof(**handles) * 2);
448     if (!hs)
449         return AVERROR(ENOMEM);
450     hs[0] = s->rtp_fd;
451     hs[1] = s->rtcp_fd;
452     *numhandles = 2;
453     return 0;
454 }
455
456 URLProtocol ff_rtp_protocol = {
457     .name                      = "rtp",
458     .url_open                  = rtp_open,
459     .url_read                  = rtp_read,
460     .url_write                 = rtp_write,
461     .url_close                 = rtp_close,
462     .url_get_file_handle       = rtp_get_file_handle,
463     .url_get_multi_file_handle = rtp_get_multi_file_handle,
464     .priv_data_size            = sizeof(RTPContext),
465     .flags                     = URL_PROTOCOL_FLAG_NETWORK,
466 };