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