]> git.sesse.net Git - ffmpeg/blob - libavformat/rtpproto.c
avisynth: Simplify shared library name construction
[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 "libavutil/opt.h"
30 #include "avformat.h"
31 #include "avio_internal.h"
32 #include "rtp.h"
33 #include "rtpproto.h"
34 #include "url.h"
35
36 #include <stdarg.h>
37 #include "internal.h"
38 #include "network.h"
39 #include "os_support.h"
40 #include <fcntl.h>
41 #if HAVE_POLL_H
42 #include <sys/poll.h>
43 #endif
44
45 typedef struct RTPContext {
46     const AVClass *class;
47     URLContext *rtp_hd, *rtcp_hd;
48     int rtp_fd, rtcp_fd, nb_ssm_include_addrs, nb_ssm_exclude_addrs;
49     struct sockaddr_storage **ssm_include_addrs, **ssm_exclude_addrs;
50     int write_to_source;
51     struct sockaddr_storage last_rtp_source, last_rtcp_source;
52     socklen_t last_rtp_source_len, last_rtcp_source_len;
53     int ttl;
54     int buffer_size;
55     int rtcp_port, local_rtpport, local_rtcpport;
56     int connect;
57     int pkt_size;
58     char *sources;
59     char *block;
60 } RTPContext;
61
62 #define OFFSET(x) offsetof(RTPContext, x)
63 #define D AV_OPT_FLAG_DECODING_PARAM
64 #define E AV_OPT_FLAG_ENCODING_PARAM
65 static const AVOption options[] = {
66     { "ttl",                "Time to live (in milliseconds, multicast only)",                   OFFSET(ttl),             AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
67     { "buffer_size",        "Send/Receive buffer size (in bytes)",                              OFFSET(buffer_size),     AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
68     { "rtcp_port",          "Custom rtcp port",                                                 OFFSET(rtcp_port),       AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
69     { "local_rtpport",      "Local rtp port",                                                   OFFSET(local_rtpport),   AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
70     { "local_rtcpport",     "Local rtcp port",                                                  OFFSET(local_rtcpport),  AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
71     { "connect",            "Connect socket",                                                   OFFSET(connect),         AV_OPT_TYPE_INT,    { .i64 =  0 },     0, 1,       .flags = D|E },
72     { "write_to_source",    "Send packets to the source address of the latest received packet", OFFSET(write_to_source), AV_OPT_TYPE_INT,    { .i64 =  0 },     0, 1,       .flags = D|E },
73     { "pkt_size",           "Maximum packet size",                                              OFFSET(pkt_size),        AV_OPT_TYPE_INT,    { .i64 = -1 },    -1, INT_MAX, .flags = D|E },
74     { "sources",            "Source list",                                                      OFFSET(sources),         AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
75     { "block",              "Block list",                                                       OFFSET(block),           AV_OPT_TYPE_STRING, { .str = NULL },               .flags = D|E },
76     { NULL }
77 };
78
79 static const AVClass rtp_class = {
80     .class_name = "rtp",
81     .item_name  = av_default_item_name,
82     .option     = options,
83     .version    = LIBAVUTIL_VERSION_INT,
84 };
85
86 /**
87  * If no filename is given to av_open_input_file because you want to
88  * get the local port first, then you must call this function to set
89  * the remote server address.
90  *
91  * @param h media file context
92  * @param uri of the remote server
93  * @return zero if no error.
94  */
95
96 int ff_rtp_set_remote_url(URLContext *h, const char *uri)
97 {
98     RTPContext *s = h->priv_data;
99     char hostname[256];
100     int port, rtcp_port;
101     const char *p;
102
103     char buf[1024];
104     char path[1024];
105
106     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port,
107                  path, sizeof(path), uri);
108     rtcp_port = port + 1;
109
110     p = strchr(uri, '?');
111     if (p) {
112         if (av_find_info_tag(buf, sizeof(buf), "rtcpport", p)) {
113             rtcp_port = strtol(buf, NULL, 10);
114         }
115     }
116
117     ff_url_join(buf, sizeof(buf), "udp", NULL, hostname, port, "%s", path);
118     ff_udp_set_remote_url(s->rtp_hd, buf);
119
120     ff_url_join(buf, sizeof(buf), "udp", NULL, hostname, rtcp_port, "%s", path);
121     ff_udp_set_remote_url(s->rtcp_hd, buf);
122     return 0;
123 }
124
125 static struct addrinfo* rtp_resolve_host(const char *hostname, int port,
126                                          int type, int family, int flags)
127 {
128     struct addrinfo hints = { 0 }, *res = 0;
129     int error;
130     char service[16];
131
132     snprintf(service, sizeof(service), "%d", port);
133     hints.ai_socktype = type;
134     hints.ai_family   = family;
135     hints.ai_flags    = flags;
136     if ((error = getaddrinfo(hostname, service, &hints, &res))) {
137         res = NULL;
138         av_log(NULL, AV_LOG_ERROR, "rtp_resolve_host: %s\n", gai_strerror(error));
139     }
140
141     return res;
142 }
143
144 static int compare_addr(const struct sockaddr_storage *a,
145                         const struct sockaddr_storage *b)
146 {
147     if (a->ss_family != b->ss_family)
148         return 1;
149     if (a->ss_family == AF_INET) {
150         return (((const struct sockaddr_in *)a)->sin_addr.s_addr !=
151                 ((const struct sockaddr_in *)b)->sin_addr.s_addr);
152     }
153
154 #if HAVE_STRUCT_SOCKADDR_IN6
155     if (a->ss_family == AF_INET6) {
156         const uint8_t *s6_addr_a = ((const struct sockaddr_in6 *)a)->sin6_addr.s6_addr;
157         const uint8_t *s6_addr_b = ((const struct sockaddr_in6 *)b)->sin6_addr.s6_addr;
158         return memcmp(s6_addr_a, s6_addr_b, 16);
159     }
160 #endif
161     return 1;
162 }
163
164 static int get_port(const struct sockaddr_storage *ss)
165 {
166     if (ss->ss_family == AF_INET)
167         return ntohs(((const struct sockaddr_in *)ss)->sin_port);
168 #if HAVE_STRUCT_SOCKADDR_IN6
169     if (ss->ss_family == AF_INET6)
170         return ntohs(((const struct sockaddr_in6 *)ss)->sin6_port);
171 #endif
172     return 0;
173 }
174
175 static void set_port(struct sockaddr_storage *ss, int port)
176 {
177     if (ss->ss_family == AF_INET)
178         ((struct sockaddr_in *)ss)->sin_port = htons(port);
179 #if HAVE_STRUCT_SOCKADDR_IN6
180     else if (ss->ss_family == AF_INET6)
181         ((struct sockaddr_in6 *)ss)->sin6_port = htons(port);
182 #endif
183 }
184
185 static int rtp_check_source_lists(RTPContext *s, struct sockaddr_storage *source_addr_ptr)
186 {
187     int i;
188     if (s->nb_ssm_exclude_addrs) {
189         for (i = 0; i < s->nb_ssm_exclude_addrs; i++) {
190             if (!compare_addr(source_addr_ptr, s->ssm_exclude_addrs[i]))
191                 return 1;
192         }
193     }
194     if (s->nb_ssm_include_addrs) {
195         for (i = 0; i < s->nb_ssm_include_addrs; i++) {
196             if (!compare_addr(source_addr_ptr, s->ssm_include_addrs[i]))
197                 return 0;
198         }
199         return 1;
200     }
201     return 0;
202 }
203
204 /**
205  * add option to url of the form:
206  * "http://host:port/path?option1=val1&option2=val2...
207  */
208
209 static av_printf_format(3, 4) void url_add_option(char *buf, int buf_size, const char *fmt, ...)
210 {
211     char buf1[1024];
212     va_list ap;
213
214     va_start(ap, fmt);
215     if (strchr(buf, '?'))
216         av_strlcat(buf, "&", buf_size);
217     else
218         av_strlcat(buf, "?", buf_size);
219     vsnprintf(buf1, sizeof(buf1), fmt, ap);
220     av_strlcat(buf, buf1, buf_size);
221     va_end(ap);
222 }
223
224 static void build_udp_url(RTPContext *s,
225                           char *buf, int buf_size,
226                           const char *hostname,
227                           int port, int local_port,
228                           const char *include_sources,
229                           const char *exclude_sources)
230 {
231     ff_url_join(buf, buf_size, "udp", NULL, hostname, port, NULL);
232     if (local_port >= 0)
233         url_add_option(buf, buf_size, "localport=%d", local_port);
234     if (s->ttl >= 0)
235         url_add_option(buf, buf_size, "ttl=%d", s->ttl);
236     if (s->buffer_size >= 0)
237         url_add_option(buf, buf_size, "buffer_size=%d", s->buffer_size);
238     if (s->pkt_size >= 0)
239         url_add_option(buf, buf_size, "pkt_size=%d", s->pkt_size);
240     if (s->connect)
241         url_add_option(buf, buf_size, "connect=1");
242     if (include_sources && include_sources[0])
243         url_add_option(buf, buf_size, "sources=%s", include_sources);
244     if (exclude_sources && exclude_sources[0])
245         url_add_option(buf, buf_size, "block=%s", exclude_sources);
246 }
247
248 static void rtp_parse_addr_list(URLContext *h, char *buf,
249                                 struct sockaddr_storage ***address_list_ptr,
250                                 int *address_list_size_ptr)
251 {
252     struct addrinfo *ai = NULL;
253     struct sockaddr_storage *source_addr;
254     char tmp = '\0', *p = buf, *next;
255
256     /* Resolve all of the IPs */
257
258     while (p && p[0]) {
259         next = strchr(p, ',');
260
261         if (next) {
262             tmp = *next;
263             *next = '\0';
264         }
265
266         ai = rtp_resolve_host(p, 0, SOCK_DGRAM, AF_UNSPEC, 0);
267         if (ai) {
268             source_addr = av_mallocz(sizeof(struct sockaddr_storage));
269             if (!source_addr) {
270                 freeaddrinfo(ai);
271                 break;
272             }
273
274             memcpy(source_addr, ai->ai_addr, ai->ai_addrlen);
275             freeaddrinfo(ai);
276             dynarray_add(address_list_ptr, address_list_size_ptr, source_addr);
277         } else {
278             av_log(h, AV_LOG_WARNING, "Unable to resolve %s\n", p);
279         }
280
281         if (next) {
282             *next = tmp;
283             p = next + 1;
284         } else {
285             p = NULL;
286         }
287     }
288 }
289
290 /**
291  * url syntax: rtp://host:port[?option=val...]
292  * option: 'ttl=n'            : set the ttl value (for multicast only)
293  *         'rtcpport=n'       : set the remote rtcp port to n
294  *         'localrtpport=n'   : set the local rtp port to n
295  *         'localrtcpport=n'  : set the local rtcp port to n
296  *         'pkt_size=n'       : set max packet size
297  *         'connect=0/1'      : do a connect() on the UDP socket
298  *         'sources=ip[,ip]'  : list allowed source IP addresses
299  *         'block=ip[,ip]'    : list disallowed source IP addresses
300  *         'write_to_source=0/1' : send packets to the source address of the latest received packet
301  * deprecated option:
302  *         'localport=n'      : set the local port to n
303  *
304  * if rtcpport isn't set the rtcp port will be the rtp port + 1
305  * if local rtp port isn't set any available port will be used for the local
306  * rtp and rtcp ports
307  * if the local rtcp port is not set it will be the local rtp port + 1
308  */
309
310 static int rtp_open(URLContext *h, const char *uri, int flags)
311 {
312     RTPContext *s = h->priv_data;
313     int rtp_port;
314     char hostname[256], include_sources[1024] = "", exclude_sources[1024] = "";
315     char *sources = include_sources, *block = exclude_sources;
316     char buf[1024];
317     char path[1024];
318     const char *p;
319
320     av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &rtp_port,
321                  path, sizeof(path), uri);
322     /* extract parameters */
323     if (s->rtcp_port < 0)
324         s->rtcp_port = rtp_port + 1;
325
326     p = strchr(uri, '?');
327     if (p) {
328         if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
329             s->ttl = strtol(buf, NULL, 10);
330         }
331         if (av_find_info_tag(buf, sizeof(buf), "rtcpport", p)) {
332             s->rtcp_port = strtol(buf, NULL, 10);
333         }
334         if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
335             s->local_rtpport = strtol(buf, NULL, 10);
336         }
337         if (av_find_info_tag(buf, sizeof(buf), "localrtpport", p)) {
338             s->local_rtpport = strtol(buf, NULL, 10);
339         }
340         if (av_find_info_tag(buf, sizeof(buf), "localrtcpport", p)) {
341             s->local_rtcpport = strtol(buf, NULL, 10);
342         }
343         if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
344             s->pkt_size = strtol(buf, NULL, 10);
345         }
346         if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
347             s->connect = strtol(buf, NULL, 10);
348         }
349         if (av_find_info_tag(buf, sizeof(buf), "write_to_source", p)) {
350             s->write_to_source = strtol(buf, NULL, 10);
351         }
352         if (av_find_info_tag(buf, sizeof(buf), "sources", p)) {
353             av_strlcpy(include_sources, buf, sizeof(include_sources));
354
355             rtp_parse_addr_list(h, buf, &s->ssm_include_addrs, &s->nb_ssm_include_addrs);
356         } else {
357             rtp_parse_addr_list(h, s->sources, &s->ssm_include_addrs, &s->nb_ssm_include_addrs);
358             sources = s->sources;
359         }
360         if (av_find_info_tag(buf, sizeof(buf), "block", p)) {
361             av_strlcpy(exclude_sources, buf, sizeof(exclude_sources));
362             rtp_parse_addr_list(h, buf, &s->ssm_exclude_addrs, &s->nb_ssm_exclude_addrs);
363         } else {
364             rtp_parse_addr_list(h, s->block, &s->ssm_exclude_addrs, &s->nb_ssm_exclude_addrs);
365             block = s->block;
366         }
367     }
368
369     build_udp_url(s, buf, sizeof(buf),
370                   hostname, rtp_port, s->local_rtpport, sources, block);
371     if (ffurl_open(&s->rtp_hd, buf, flags, &h->interrupt_callback, NULL) < 0)
372         goto fail;
373     if (s->local_rtpport >= 0 && s->local_rtcpport < 0)
374         s->local_rtcpport = ff_udp_get_local_port(s->rtp_hd) + 1;
375
376     build_udp_url(s, buf, sizeof(buf),
377                   hostname, s->rtcp_port, s->local_rtcpport, sources, block);
378     if (ffurl_open(&s->rtcp_hd, buf, flags, &h->interrupt_callback, NULL) < 0)
379         goto fail;
380
381     /* just to ease handle access. XXX: need to suppress direct handle
382        access */
383     s->rtp_fd = ffurl_get_file_handle(s->rtp_hd);
384     s->rtcp_fd = ffurl_get_file_handle(s->rtcp_hd);
385
386     h->max_packet_size = s->rtp_hd->max_packet_size;
387     h->is_streamed = 1;
388     return 0;
389
390  fail:
391     if (s->rtp_hd)
392         ffurl_close(s->rtp_hd);
393     if (s->rtcp_hd)
394         ffurl_close(s->rtcp_hd);
395     return AVERROR(EIO);
396 }
397
398 static int rtp_read(URLContext *h, uint8_t *buf, int size)
399 {
400     RTPContext *s = h->priv_data;
401     int len, n, i;
402     struct pollfd p[2] = {{s->rtp_fd, POLLIN, 0}, {s->rtcp_fd, POLLIN, 0}};
403     int poll_delay = h->flags & AVIO_FLAG_NONBLOCK ? 0 : 100;
404     struct sockaddr_storage *addrs[2] = { &s->last_rtp_source, &s->last_rtcp_source };
405     socklen_t *addr_lens[2] = { &s->last_rtp_source_len, &s->last_rtcp_source_len };
406
407     for(;;) {
408         if (ff_check_interrupt(&h->interrupt_callback))
409             return AVERROR_EXIT;
410         n = poll(p, 2, poll_delay);
411         if (n > 0) {
412             /* first try RTCP, then RTP */
413             for (i = 1; i >= 0; i--) {
414                 if (!(p[i].revents & POLLIN))
415                     continue;
416                 *addr_lens[i] = sizeof(*addrs[i]);
417                 len = recvfrom(p[i].fd, buf, size, 0,
418                                 (struct sockaddr *)addrs[i], addr_lens[i]);
419                 if (len < 0) {
420                     if (ff_neterrno() == AVERROR(EAGAIN) ||
421                         ff_neterrno() == AVERROR(EINTR))
422                         continue;
423                     return AVERROR(EIO);
424                 }
425                 if (rtp_check_source_lists(s, addrs[i]))
426                     continue;
427                 return len;
428             }
429         } else if (n < 0) {
430             if (ff_neterrno() == AVERROR(EINTR))
431                 continue;
432             return AVERROR(EIO);
433         }
434         if (h->flags & AVIO_FLAG_NONBLOCK)
435             return AVERROR(EAGAIN);
436     }
437     return len;
438 }
439
440 static int rtp_write(URLContext *h, const uint8_t *buf, int size)
441 {
442     RTPContext *s = h->priv_data;
443     int ret;
444     URLContext *hd;
445
446     if (size < 2)
447         return AVERROR(EINVAL);
448
449     if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
450         av_log(h, AV_LOG_WARNING, "Data doesn't look like RTP packets, "
451                                   "make sure the RTP muxer is used\n");
452
453     if (s->write_to_source) {
454         int fd;
455         struct sockaddr_storage *source, temp_source;
456         socklen_t *source_len, temp_len;
457         if (!s->last_rtp_source.ss_family && !s->last_rtcp_source.ss_family) {
458             av_log(h, AV_LOG_ERROR,
459                    "Unable to send packet to source, no packets received yet\n");
460             // Intentionally not returning an error here
461             return size;
462         }
463
464         if (RTP_PT_IS_RTCP(buf[1])) {
465             fd = s->rtcp_fd;
466             source     = &s->last_rtcp_source;
467             source_len = &s->last_rtcp_source_len;
468         } else {
469             fd = s->rtp_fd;
470             source     = &s->last_rtp_source;
471             source_len = &s->last_rtp_source_len;
472         }
473         if (!source->ss_family) {
474             source      = &temp_source;
475             source_len  = &temp_len;
476             if (RTP_PT_IS_RTCP(buf[1])) {
477                 temp_source = s->last_rtp_source;
478                 temp_len    = s->last_rtp_source_len;
479                 set_port(source, get_port(source) + 1);
480                 av_log(h, AV_LOG_INFO,
481                        "Not received any RTCP packets yet, inferring peer port "
482                        "from the RTP port\n");
483             } else {
484                 temp_source = s->last_rtcp_source;
485                 temp_len    = s->last_rtcp_source_len;
486                 set_port(source, get_port(source) - 1);
487                 av_log(h, AV_LOG_INFO,
488                        "Not received any RTP packets yet, inferring peer port "
489                        "from the RTCP port\n");
490             }
491         }
492
493         if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
494             ret = ff_network_wait_fd(fd, 1);
495             if (ret < 0)
496                 return ret;
497         }
498         ret = sendto(fd, buf, size, 0, (struct sockaddr *) source,
499                      *source_len);
500
501         return ret < 0 ? ff_neterrno() : ret;
502     }
503
504     if (RTP_PT_IS_RTCP(buf[1])) {
505         /* RTCP payload type */
506         hd = s->rtcp_hd;
507     } else {
508         /* RTP payload type */
509         hd = s->rtp_hd;
510     }
511
512     ret = ffurl_write(hd, buf, size);
513     return ret;
514 }
515
516 static int rtp_close(URLContext *h)
517 {
518     RTPContext *s = h->priv_data;
519     int i;
520
521     for (i = 0; i < s->nb_ssm_include_addrs; i++)
522         av_free(s->ssm_include_addrs[i]);
523     av_freep(&s->ssm_include_addrs);
524     for (i = 0; i < s->nb_ssm_exclude_addrs; i++)
525         av_free(s->ssm_exclude_addrs[i]);
526     av_freep(&s->ssm_exclude_addrs);
527
528     ffurl_close(s->rtp_hd);
529     ffurl_close(s->rtcp_hd);
530     return 0;
531 }
532
533 /**
534  * Return the local rtp port used by the RTP connection
535  * @param h media file context
536  * @return the local port number
537  */
538
539 int ff_rtp_get_local_rtp_port(URLContext *h)
540 {
541     RTPContext *s = h->priv_data;
542     return ff_udp_get_local_port(s->rtp_hd);
543 }
544
545 /**
546  * Return the local rtcp port used by the RTP connection
547  * @param h media file context
548  * @return the local port number
549  */
550
551 int ff_rtp_get_local_rtcp_port(URLContext *h)
552 {
553     RTPContext *s = h->priv_data;
554     return ff_udp_get_local_port(s->rtcp_hd);
555 }
556
557 static int rtp_get_file_handle(URLContext *h)
558 {
559     RTPContext *s = h->priv_data;
560     return s->rtp_fd;
561 }
562
563 static int rtp_get_multi_file_handle(URLContext *h, int **handles,
564                                      int *numhandles)
565 {
566     RTPContext *s = h->priv_data;
567     int *hs       = *handles = av_malloc(sizeof(**handles) * 2);
568     if (!hs)
569         return AVERROR(ENOMEM);
570     hs[0] = s->rtp_fd;
571     hs[1] = s->rtcp_fd;
572     *numhandles = 2;
573     return 0;
574 }
575
576 URLProtocol ff_rtp_protocol = {
577     .name                      = "rtp",
578     .url_open                  = rtp_open,
579     .url_read                  = rtp_read,
580     .url_write                 = rtp_write,
581     .url_close                 = rtp_close,
582     .url_get_file_handle       = rtp_get_file_handle,
583     .url_get_multi_file_handle = rtp_get_multi_file_handle,
584     .priv_data_size            = sizeof(RTPContext),
585     .flags                     = URL_PROTOCOL_FLAG_NETWORK,
586     .priv_data_class           = &rtp_class,
587 };