]> git.sesse.net Git - vlc/blob - modules/demux/rtp.c
ee99286a276e272fc76e1d584cb45da996c4c45b
[vlc] / modules / demux / rtp.c
1 /**
2  * @file rtp.c
3  * @brief Real-Time Protocol (RTP) demux module for VLC media player
4  */
5 /*****************************************************************************
6  * Copyright (C) 2001-2005 the VideoLAN team
7  * Copyright © 2007-2008 Rémi Denis-Courmont
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2.0
12  * of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
22  ****************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 # include <config.h>
26 #endif
27 #include <stdarg.h>
28 #include <assert.h>
29
30 #include <vlc_common.h>
31 #include <vlc_demux.h>
32 #include <vlc_aout.h>
33 #include <vlc_network.h>
34 #ifdef HAVE_POLL
35 # include <poll.h>
36 #endif
37 #include <vlc_plugin.h>
38
39 #include <vlc_codecs.h>
40
41 #include "rtp.h"
42 #include <srtp.h>
43
44 #define RTP_CACHING_TEXT N_("RTP de-jitter buffer length (msec)")
45 #define RTP_CACHING_LONGTEXT N_( \
46     "How long to wait for late RTP packets (and delay the performance)." )
47
48 #define SRTP_KEY_TEXT N_("SRTP key (hexadecimal)")
49 #define SRTP_KEY_LONGTEXT N_( \
50     "RTP packets will be authenticated and deciphered "\
51     "with this Secure RTP master shared secret key.")
52
53 #define SRTP_SALT_TEXT N_("SRTP salt (hexadecimal)")
54 #define SRTP_SALT_LONGTEXT N_( \
55     "Secure RTP requires a (non-secret) master salt value.")
56
57 #define RTP_MAX_SRC_TEXT N_("Maximum RTP sources")
58 #define RTP_MAX_SRC_LONGTEXT N_( \
59     "How many distinct active RTP sources are allowed at a time." )
60
61 #define RTP_TIMEOUT_TEXT N_("RTP source timeout (sec)")
62 #define RTP_TIMEOUT_LONGTEXT N_( \
63     "How long to wait for any packet before a source is expired.")
64
65 #define RTP_MAX_DROPOUT_TEXT N_("Maximum RTP sequence number dropout")
66 #define RTP_MAX_DROPOUT_LONGTEXT N_( \
67     "RTP packets will be discarded if they are too much ahead (i.e. in the " \
68     "future) by this many packets from the last received packet." )
69
70 #define RTP_MAX_MISORDER_TEXT N_("Maximum RTP sequence number misordering")
71 #define RTP_MAX_MISORDER_LONGTEXT N_( \
72     "RTP packets will be discarded if they are too far behind (i.e. in the " \
73     "past) by this many packets from the last received packet." )
74
75 static int  Open (vlc_object_t *);
76 static void Close (vlc_object_t *);
77
78 /*
79  * Module descriptor
80  */
81 vlc_module_begin ();
82     set_shortname (_("RTP"));
83     set_description (_("(Experimental) Real-Time Protocol demuxer"));
84     set_category (CAT_INPUT);
85     set_subcategory (SUBCAT_INPUT_DEMUX);
86     set_capability ("access_demux", 10);
87     set_callbacks (Open, Close);
88
89     add_integer ("rtp-caching", 1000, NULL, RTP_CACHING_TEXT,
90                  RTP_CACHING_LONGTEXT, true);
91         change_integer_range (0, 65535);
92     add_string ("srtp-key", "", NULL,
93                 SRTP_KEY_TEXT, SRTP_KEY_LONGTEXT, false);
94     add_string ("srtp-salt", "", NULL,
95                 SRTP_SALT_TEXT, SRTP_SALT_LONGTEXT, false);
96     add_integer ("rtp-max-src", 1, NULL, RTP_MAX_SRC_TEXT,
97                  RTP_MAX_SRC_LONGTEXT, true);
98         change_integer_range (1, 255);
99     add_integer ("rtp-timeout", 5, NULL, RTP_TIMEOUT_TEXT,
100                  RTP_TIMEOUT_LONGTEXT, true);
101     add_integer ("rtp-max-dropout", 3000, NULL, RTP_MAX_DROPOUT_TEXT,
102                  RTP_MAX_DROPOUT_LONGTEXT, true);
103         change_integer_range (0, 32767);
104     add_integer ("rtp-max-misorder", 100, NULL, RTP_MAX_MISORDER_TEXT,
105                  RTP_MAX_MISORDER_LONGTEXT, true);
106         change_integer_range (0, 32767);
107
108     add_shortcut ("dccp");
109     /*add_shortcut ("sctp");*/
110     add_shortcut ("rtptcp"); /* "tcp" is already taken :( */
111     add_shortcut ("rtp");
112     add_shortcut ("udplite");
113 vlc_module_end ();
114
115 /*
116  * TODO: so much stuff
117  * - send RTCP-RR and RTCP-BYE
118  * - dynamic payload types (need SDP parser)
119  * - multiple medias (need SDP parser, and RTCP-SR parser for lip-sync)
120  * - support for access_filter in case of stream_Demux (MPEG-TS)
121  */
122
123 #ifndef IPPROTO_DCCP
124 # define IPPROTO_DCCP 33 /* IANA */
125 #endif
126
127 #ifndef IPPROTO_UDPLITE
128 # define IPPROTO_UDPLITE 136 /* from IANA */
129 #endif
130
131
132 /*
133  * Local prototypes
134  */
135 static int Demux (demux_t *);
136 static int Control (demux_t *, int i_query, va_list args);
137 static int extract_port (char **phost);
138
139 /**
140  * Probes and initializes.
141  */
142 static int Open (vlc_object_t *obj)
143 {
144     demux_t *demux = (demux_t *)obj;
145     int tp; /* transport protocol */
146
147     if (!strcmp (demux->psz_access, "dccp"))
148         tp = IPPROTO_DCCP;
149     else
150     if (!strcmp (demux->psz_access, "rtptcp"))
151         tp = IPPROTO_TCP;
152     else
153     if (!strcmp (demux->psz_access, "rtp"))
154         tp = IPPROTO_UDP;
155     else
156     if (!strcmp (demux->psz_access, "udplite"))
157         tp = IPPROTO_UDPLITE;
158     else
159         return VLC_EGENERIC;
160
161     char *tmp = strdup (demux->psz_path);
162     char *shost = tmp;
163     if (shost == NULL)
164         return VLC_ENOMEM;
165
166     char *dhost = strchr (shost, '@');
167     if (dhost)
168         *dhost++ = '\0';
169
170     /* Parses the port numbers */
171     int sport = 0, dport = 0;
172     sport = extract_port (&shost);
173     if (dhost != NULL)
174         dport = extract_port (&dhost);
175     if (dport == 0)
176         dport = 5004; /* avt-profile-1 port */
177
178     /* Try to connect */
179     int fd = -1, rtcp_fd = -1;
180
181     switch (tp)
182     {
183         case IPPROTO_UDP:
184         case IPPROTO_UDPLITE:
185             fd = net_OpenDgram (obj, dhost, (dport + 1) & ~1,
186                                 shost, (sport + 1) & ~1, AF_UNSPEC, tp);
187             if (fd == -1)
188                 break;
189             rtcp_fd = net_OpenDgram (obj, dhost, dport | 1, shost,
190                                      sport ? (sport | 1) : 0, AF_UNSPEC, tp);
191             break;
192
193          case IPPROTO_DCCP:
194 #ifndef SOCK_DCCP /* provisional API (FIXME) */
195 # ifdef __linux__
196 #  define SOCK_DCCP 6
197 # endif
198 #endif
199 #ifdef SOCK_DCCP
200             var_Create (obj, "dccp-service", VLC_VAR_STRING);
201             var_SetString (obj, "dccp-service", "RTPV"); /* FIXME: RTPA? */
202             fd = net_Connect (obj, shost, (sport + 1) & ~1, SOCK_DCCP, tp);
203 #else
204             msg_Err (obj, "DCCP support not included");
205 #endif
206             break;
207
208         case IPPROTO_TCP:
209             fd = net_Connect (obj, shost, (sport + 1) & ~1, SOCK_STREAM, tp);
210             break;
211     }
212
213     free (tmp);
214     if (fd == -1)
215         return VLC_EGENERIC;
216     net_SetCSCov (fd, -1, 12);
217
218     /* Initializes demux */
219     demux_sys_t *p_sys = malloc (sizeof (*p_sys));
220     if (p_sys == NULL)
221     {
222         net_Close (fd);
223         if (rtcp_fd != -1)
224             net_Close (rtcp_fd);
225         return VLC_EGENERIC;
226     }
227
228     p_sys->srtp         = NULL;
229     p_sys->fd           = fd;
230     p_sys->rtcp_fd      = rtcp_fd;
231     p_sys->caching      = var_CreateGetInteger (obj, "rtp-caching");
232     p_sys->max_src      = var_CreateGetInteger (obj, "rtp-max-src");
233     p_sys->timeout      = var_CreateGetInteger (obj, "rtp-timeout");
234     p_sys->max_dropout  = var_CreateGetInteger (obj, "rtp-max-dropout");
235     p_sys->max_misorder = var_CreateGetInteger (obj, "rtp-max-misorder");
236     p_sys->autodetect   = true;
237     p_sys->framed_rtp   = (tp == IPPROTO_TCP);
238
239     demux->pf_demux   = Demux;
240     demux->pf_control = Control;
241     demux->p_sys      = p_sys;
242
243     p_sys->session = rtp_session_create (demux);
244     if (p_sys->session == NULL)
245         goto error;
246
247     char *key = var_CreateGetNonEmptyString (demux, "srtp-key");
248     if (key)
249     {
250         p_sys->srtp = srtp_create (SRTP_ENCR_AES_CM, SRTP_AUTH_HMAC_SHA1, 10,
251                                    SRTP_PRF_AES_CM, SRTP_RCC_MODE1);
252         if (p_sys->srtp == NULL)
253         {
254             free (key);
255             goto error;
256         }
257
258         char *salt = var_CreateGetNonEmptyString (demux, "srtp-salt");
259         errno = srtp_setkeystring (p_sys->srtp, key, salt ? salt : "");
260         free (salt);
261         free (key);
262         if (errno)
263         {
264             msg_Err (obj, "bad SRTP key/salt combination (%m)");
265             goto error;
266         }
267     }
268
269     return VLC_SUCCESS;
270
271 error:
272     Close (obj);
273     return VLC_EGENERIC;
274 }
275
276
277 /**
278  * Releases resources
279  */
280 static void Close (vlc_object_t *obj)
281 {
282     demux_t *demux = (demux_t *)obj;
283     demux_sys_t *p_sys = demux->p_sys;
284
285     if (p_sys->srtp)
286         srtp_destroy (p_sys->srtp);
287     if (p_sys->session)
288         rtp_session_destroy (demux, p_sys->session);
289     if (p_sys->rtcp_fd != -1)
290         net_Close (p_sys->rtcp_fd);
291     net_Close (p_sys->fd);
292     free (p_sys);
293 }
294
295
296 /**
297  * Extracts port number from "[host]:port" or "host:port" strings,
298  * and remove brackets from the host name.
299  * @param phost pointer to the string upon entry,
300  * pointer to the hostname upon return.
301  * @return port number, 0 if missing.
302  */
303 static int extract_port (char **phost)
304 {
305     char *host = *phost, *port;
306
307     if (host[0] == '[')
308     {
309         host = *++phost; /* skip '[' */
310         port = strchr (host, ']');
311         if (port)
312             *port++ = '\0'; /* skip ']' */
313     }
314     else
315         port = strchr (host, ':');
316
317     if (port == NULL)
318         return 0;
319     *port++ = '\0'; /* skip ':' */
320     return atoi (port);
321 }
322
323
324 /**
325  * Control callback
326  */
327 static int Control (demux_t *demux, int i_query, va_list args)
328 {
329     demux_sys_t *p_sys = demux->p_sys;
330
331     switch (i_query)
332     {
333         case DEMUX_GET_POSITION:
334         {
335             float *v = va_arg (args, float *);
336             *v = 0.;
337             return 0;
338         }
339
340         case DEMUX_GET_LENGTH:
341         case DEMUX_GET_TIME:
342         {
343             int64_t *v = va_arg (args, int64_t *);
344             *v = 0;
345             return 0;
346         }
347
348         case DEMUX_GET_PTS_DELAY:
349         {
350             int64_t *v = va_arg (args, int64_t *);
351             *v = p_sys->caching;
352             return 0;
353         }
354     }
355
356     return VLC_EGENERIC;
357 }
358
359
360 /**
361  * Checks if a file descriptor is hung up.
362  */
363 static bool fd_dead (int fd)
364 {
365     struct pollfd ufd = { .fd = fd, };
366
367     return (poll (&ufd, 1, 0) == 1) && (ufd.revents & POLLHUP);
368 }
369
370
371 /**
372  * Gets a datagram from the network, or NULL in case of fatal error.
373  */
374 static block_t *rtp_dgram_recv (demux_t *demux, int fd)
375 {
376     block_t *block = block_Alloc (0xffff);
377     ssize_t len;
378
379     do
380     {
381         len = net_Read (VLC_OBJECT (demux), fd, NULL,
382                                 block->p_buffer, block->i_buffer, false);
383         if (((len <= 0) && fd_dead (fd))
384          || !vlc_object_alive (demux))
385         {
386             block_Release (block);
387             return NULL;
388         }
389     }
390     while (len == -1);
391
392     return block_Realloc (block, 0, len);
393 }
394
395 /**
396  * Gets a framed RTP packet, or NULL in case of fatal error.
397  */
398 static block_t *rtp_stream_recv (demux_t *demux, int fd)
399 {
400     ssize_t len = 0;
401     uint8_t hdr[2]; /* frame header */
402
403     /* Receives the RTP frame header */
404     do
405     {
406         ssize_t val = net_Read (VLC_OBJECT (demux), fd, NULL,
407                                 hdr + len, 2 - len, false);
408         if (val <= 0)
409             return NULL;
410         len += val;
411     }
412     while (len < 2);
413
414     block_t *block = block_Alloc (GetWBE (hdr));
415
416     /* Receives the RTP packet */
417     for (ssize_t i = 0; i < len;)
418     {
419         ssize_t val;
420
421         val = net_Read (VLC_OBJECT (demux), fd, NULL,
422                         block->p_buffer + i, block->i_buffer - i, false);
423         if (val <= 0)
424         {
425             block_Release (block);
426             return NULL;
427         }
428         i += val;
429     }
430
431     return block;
432 }
433
434
435 /*
436  * Generic packet handlers
437  */
438
439 static void *codec_init (demux_t *demux, es_format_t *fmt)
440 {
441     return es_out_Add (demux->out, fmt);
442 }
443
444 static void codec_destroy (demux_t *demux, void *data)
445 {
446     if (data)
447         es_out_Del (demux->out, (es_out_id_t *)data);
448 }
449
450 /* Send a packet to decoder */
451 static void codec_decode (demux_t *demux, void *data, block_t *block)
452 {
453     if (data)
454     {
455         block->i_dts = 0; /* RTP does not specify this */
456         es_out_Control (demux->out, ES_OUT_SET_PCR,
457                         block->i_pts - demux->p_sys->caching * 1000);
458         es_out_Send (demux->out, (es_out_id_t *)data, block);
459     }
460     else
461         block_Release (block);
462 }
463
464
465 static void *stream_init (demux_t *demux, const char *name)
466 {
467     return stream_DemuxNew (demux, name, demux->out);
468 }
469
470 static void stream_destroy (demux_t *demux, void *data)
471 {
472     if (data)
473         stream_DemuxDelete ((stream_t *)data);
474     (void)demux;
475 }
476
477 /* Send a packet to a chained demuxer */
478 static void stream_decode (demux_t *demux, void *data, block_t *block)
479 {
480     if (data)
481         stream_DemuxSend ((stream_t *)data, block);
482     else
483         block_Release (block);
484     (void)demux;
485 }
486
487 /*
488  * Static payload types handler
489  */
490
491 /* PT=0
492  * PCMU: G.711 µ-law (RFC3551)
493  */
494 static void *pcmu_init (demux_t *demux)
495 {
496     es_format_t fmt;
497
498     es_format_Init (&fmt, AUDIO_ES, VLC_FOURCC ('u', 'l', 'a', 'w'));
499     fmt.audio.i_rate = 8000;
500     fmt.audio.i_channels = 1;
501     return codec_init (demux, &fmt);
502 }
503
504 /* PT=8
505  * PCMA: G.711 A-law (RFC3551)
506  */
507 static void *pcma_init (demux_t *demux)
508 {
509     es_format_t fmt;
510
511     es_format_Init (&fmt, AUDIO_ES, VLC_FOURCC ('a', 'l', 'a', 'w'));
512     fmt.audio.i_rate = 8000;
513     fmt.audio.i_channels = 1;
514     return codec_init (demux, &fmt);
515 }
516
517 /* PT=10,11
518  * L16: 16-bits (network byte order) PCM
519  */
520 static void *l16s_init (demux_t *demux)
521 {
522     es_format_t fmt;
523
524     es_format_Init (&fmt, AUDIO_ES, VLC_FOURCC ('s', '1', '6', 'b'));
525     fmt.audio.i_rate = 44100;
526     fmt.audio.i_channels = 2;
527     return codec_init (demux, &fmt);
528 }
529
530 static void *l16m_init (demux_t *demux)
531 {
532     es_format_t fmt;
533
534     es_format_Init (&fmt, AUDIO_ES, VLC_FOURCC ('s', '1', '6', 'b'));
535     fmt.audio.i_rate = 44100;
536     fmt.audio.i_channels = 1;
537     return codec_init (demux, &fmt);
538 }
539
540 /* PT=14
541  * MPA: MPEG Audio (RFC2250, §3.4)
542  */
543 static void *mpa_init (demux_t *demux)
544 {
545     es_format_t fmt;
546
547     es_format_Init (&fmt, AUDIO_ES, VLC_FOURCC ('m', 'p', 'g', 'a'));
548     fmt.audio.i_channels = 2;
549     return codec_init (demux, &fmt);
550 }
551
552 static void mpa_decode (demux_t *demux, void *data, block_t *block)
553 {
554     if (block->i_buffer < 4)
555     {
556         block_Release (block);
557         return;
558     }
559
560     block->i_buffer -= 4; /* 32-bits RTP/MPA header */
561     block->p_buffer += 4;
562
563     codec_decode (demux, data, block);
564 }
565
566
567 /* PT=32
568  * MPV: MPEG Video (RFC2250, §3.5)
569  */
570 static void *mpv_init (demux_t *demux)
571 {
572     es_format_t fmt;
573
574     es_format_Init (&fmt, VIDEO_ES, VLC_FOURCC ('m', 'p', 'g', 'v'));
575     return codec_init (demux, &fmt);
576 }
577
578 static void mpv_decode (demux_t *demux, void *data, block_t *block)
579 {
580     if (block->i_buffer < 4)
581     {
582         block_Release (block);
583         return;
584     }
585
586     block->i_buffer -= 4; /* 32-bits RTP/MPV header */
587     block->p_buffer += 4;
588 #if 0
589     if (block->p_buffer[-3] & 0x4)
590     {
591         /* MPEG2 Video extension header */
592         /* TODO: shouldn't we skip this too ? */
593     }
594 #endif
595     codec_decode (demux, data, block);
596 }
597
598
599 /* PT=33
600  * MP2: MPEG TS (RFC2250, §2)
601  */
602 static void *ts_init (demux_t *demux)
603 {
604     return stream_init (demux, "ts");
605 }
606
607
608 /*
609  * Dynamic payload type handlers
610  * Hmm, none implemented yet.
611  */
612
613 /**
614  * Processing callback
615  */
616 static int Demux (demux_t *demux)
617 {
618     demux_sys_t *p_sys = demux->p_sys;
619     block_t     *block;
620
621     block = p_sys->framed_rtp
622         ? rtp_stream_recv (demux, p_sys->fd)
623         : rtp_dgram_recv (demux, p_sys->fd);
624     if (!block)
625         return 0;
626
627     if (block->i_buffer < 2)
628         goto drop;
629
630     const uint8_t ptype = block->p_buffer[1] & 0x7F;
631     if (ptype >= 72 && ptype <= 76)
632         goto drop; /* Muxed RTCP, ignore for now */
633
634     if (p_sys->srtp)
635     {
636         size_t len = block->i_buffer;
637         if (srtp_recv (p_sys->srtp, block->p_buffer, &len))
638         {
639             msg_Dbg (demux, "SRTP authentication/decryption failed");
640             goto drop;
641         }
642         block->i_buffer = len;
643     }
644
645     /* Not using SDP, we need to guess the payload format used */
646     /* see http://www.iana.org/assignments/rtp-parameters */
647     if (p_sys->autodetect)
648     {
649         rtp_pt_t pt = {
650             .init = NULL,
651             .destroy = codec_destroy,
652             .decode = codec_decode,
653             .frequency = 0,
654             .number = ptype,
655         };
656         switch (ptype)
657         {
658           case 0:
659             msg_Dbg (demux, "detected G.711 mu-law");
660             pt.init = pcmu_init;
661             pt.frequency = 8000;
662             break;
663
664           case 8:
665             msg_Dbg (demux, "detected G.711 A-law");
666             pt.init = pcma_init;
667             pt.frequency = 8000;
668             break;
669
670           case 10:
671             msg_Dbg (demux, "detected stereo PCM");
672             pt.init = l16s_init;
673             pt.frequency = 44100;
674             break;
675
676           case 11:
677             msg_Dbg (demux, "detected mono PCM");
678             pt.init = l16m_init;
679             pt.frequency = 44100;
680             break;
681
682           case 14:
683             msg_Dbg (demux, "detected MPEG Audio");
684             pt.init = mpa_init;
685             pt.decode = mpa_decode;
686             pt.frequency = 90000;
687             break;
688
689           case 32:
690             msg_Dbg (demux, "detected MPEG Video");
691             pt.init = mpv_init;
692             pt.decode = mpv_decode;
693             pt.frequency = 90000;
694             break;
695
696           case 33:
697             msg_Dbg (demux, "detected MPEG2 TS");
698             pt.init = ts_init;
699             pt.destroy = stream_destroy;
700             pt.decode = stream_decode;
701             pt.frequency = 90000;
702             break;
703
704           default:
705             goto drop;
706         }
707         rtp_add_type (demux, p_sys->session, &pt);
708         p_sys->autodetect = false;
709     }
710     rtp_receive (demux, p_sys->session, block);
711
712     return 1;
713 drop:
714     block_Release (block);
715     return 1;
716 }