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