]> git.sesse.net Git - vlc/blob - modules/access/rtp/rtp.c
d0a8fa22c495ca8916e20082abf7f04309b9e68c
[vlc] / modules / access / rtp / 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-2009 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
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 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 #include <errno.h>
30
31 #include <vlc_common.h>
32 #include <vlc_demux.h>
33 #include <vlc_network.h>
34 #include <vlc_plugin.h>
35 #include <vlc_dialog.h>
36
37 #include "rtp.h"
38 #ifdef HAVE_SRTP
39 # include <srtp.h>
40 # include <gcrypt.h>
41 # include <vlc_gcrypt.h>
42 #endif
43
44 #define RTCP_PORT_TEXT N_("RTCP (local) port")
45 #define RTCP_PORT_LONGTEXT N_( \
46     "RTCP packets will be received on this transport protocol port. " \
47     "If zero, multiplexed RTP/RTCP is used.")
48
49 #define SRTP_KEY_TEXT N_("SRTP key (hexadecimal)")
50 #define SRTP_KEY_LONGTEXT N_( \
51     "RTP packets will be authenticated and deciphered "\
52     "with this Secure RTP master shared secret key.")
53
54 #define SRTP_SALT_TEXT N_("SRTP salt (hexadecimal)")
55 #define SRTP_SALT_LONGTEXT N_( \
56     "Secure RTP requires a (non-secret) master salt value.")
57
58 #define RTP_MAX_SRC_TEXT N_("Maximum RTP sources")
59 #define RTP_MAX_SRC_LONGTEXT N_( \
60     "How many distinct active RTP sources are allowed at a time." )
61
62 #define RTP_TIMEOUT_TEXT N_("RTP source timeout (sec)")
63 #define RTP_TIMEOUT_LONGTEXT N_( \
64     "How long to wait for any packet before a source is expired.")
65
66 #define RTP_MAX_DROPOUT_TEXT N_("Maximum RTP sequence number dropout")
67 #define RTP_MAX_DROPOUT_LONGTEXT N_( \
68     "RTP packets will be discarded if they are too much ahead (i.e. in the " \
69     "future) by this many packets from the last received packet." )
70
71 #define RTP_MAX_MISORDER_TEXT N_("Maximum RTP sequence number misordering")
72 #define RTP_MAX_MISORDER_LONGTEXT N_( \
73     "RTP packets will be discarded if they are too far behind (i.e. in the " \
74     "past) by this many packets from the last received packet." )
75
76 #define RTP_DYNAMIC_PT_TEXT N_("RTP payload format assumed for dynamic " \
77                                "payloads")
78 #define RTP_DYNAMIC_PT_LONGTEXT N_( \
79     "This payload format will be assumed for dynamic payload types " \
80     "(between 96 and 127) if it can't be determined otherwise with " \
81     "out-of-band mappings (SDP)" )
82
83 static const char *const dynamic_pt_list[] = { "theora" };
84 static const char *const dynamic_pt_list_text[] = { "Theora Encoded Video" };
85
86 static int  Open (vlc_object_t *);
87 static void Close (vlc_object_t *);
88
89 /*
90  * Module descriptor
91  */
92 vlc_module_begin ()
93     set_shortname (N_("RTP"))
94     set_description (N_("Real-Time Protocol (RTP) input"))
95     set_category (CAT_INPUT)
96     set_subcategory (SUBCAT_INPUT_DEMUX)
97     set_capability ("access_demux", 0)
98     set_callbacks (Open, Close)
99
100     add_integer ("rtcp-port", 0, RTCP_PORT_TEXT,
101                  RTCP_PORT_LONGTEXT, false)
102         change_integer_range (0, 65535)
103         change_safe ()
104 #ifdef HAVE_SRTP
105     add_string ("srtp-key", "",
106                 SRTP_KEY_TEXT, SRTP_KEY_LONGTEXT, false)
107         change_safe ()
108     add_string ("srtp-salt", "",
109                 SRTP_SALT_TEXT, SRTP_SALT_LONGTEXT, false)
110         change_safe ()
111 #endif
112     add_integer ("rtp-max-src", 1, RTP_MAX_SRC_TEXT,
113                  RTP_MAX_SRC_LONGTEXT, true)
114         change_integer_range (1, 255)
115     add_integer ("rtp-timeout", 5, RTP_TIMEOUT_TEXT,
116                  RTP_TIMEOUT_LONGTEXT, true)
117     add_integer ("rtp-max-dropout", 3000, RTP_MAX_DROPOUT_TEXT,
118                  RTP_MAX_DROPOUT_LONGTEXT, true)
119         change_integer_range (0, 32767)
120     add_integer ("rtp-max-misorder", 100, RTP_MAX_MISORDER_TEXT,
121                  RTP_MAX_MISORDER_LONGTEXT, true)
122         change_integer_range (0, 32767)
123     add_string ("rtp-dynamic-pt", NULL, RTP_DYNAMIC_PT_TEXT,
124                 RTP_DYNAMIC_PT_LONGTEXT, true)
125         change_string_list (dynamic_pt_list, dynamic_pt_list_text, NULL)
126
127     /*add_shortcut ("sctp")*/
128     add_shortcut ("dccp", "rtptcp", /* "tcp" is already taken :( */
129                   "rtp", "udplite")
130 vlc_module_end ()
131
132 /*
133  * TODO: so much stuff
134  * - send RTCP-RR and RTCP-BYE
135  * - dynamic payload types (need SDP parser)
136  * - multiple medias (need SDP parser, and RTCP-SR parser for lip-sync)
137  * - support for stream_filter in case of stream_Demux (MPEG-TS)
138  */
139
140 #ifndef IPPROTO_DCCP
141 # define IPPROTO_DCCP 33 /* IANA */
142 #endif
143
144 #ifndef IPPROTO_UDPLITE
145 # define IPPROTO_UDPLITE 136 /* from IANA */
146 #endif
147
148
149 /*
150  * Local prototypes
151  */
152 static int Control (demux_t *, int i_query, va_list args);
153 static int extract_port (char **phost);
154
155 /**
156  * Probes and initializes.
157  */
158 static int Open (vlc_object_t *obj)
159 {
160     demux_t *demux = (demux_t *)obj;
161     int tp; /* transport protocol */
162
163     if (!strcmp (demux->psz_access, "dccp"))
164         tp = IPPROTO_DCCP;
165     else
166     if (!strcmp (demux->psz_access, "rtptcp"))
167         tp = IPPROTO_TCP;
168     else
169     if (!strcmp (demux->psz_access, "rtp"))
170         tp = IPPROTO_UDP;
171     else
172     if (!strcmp (demux->psz_access, "udplite"))
173         tp = IPPROTO_UDPLITE;
174     else
175         return VLC_EGENERIC;
176
177     char *tmp = strdup (demux->psz_location);
178     if (tmp == NULL)
179         return VLC_ENOMEM;
180
181     char *shost;
182     char *dhost = strchr (tmp, '@');
183     if (dhost != NULL)
184     {
185         *(dhost++) = '\0';
186         shost = tmp;
187     }
188     else
189     {
190         dhost = tmp;
191         shost = NULL;
192     }
193
194     /* Parses the port numbers */
195     int sport = 0, dport = 0;
196     if (shost != NULL)
197         sport = extract_port (&shost);
198     if (dhost != NULL)
199         dport = extract_port (&dhost);
200     if (dport == 0)
201         dport = 5004; /* avt-profile-1 port */
202
203     int rtcp_dport = var_CreateGetInteger (obj, "rtcp-port");
204
205     /* Try to connect */
206     int fd = -1, rtcp_fd = -1;
207
208     switch (tp)
209     {
210         case IPPROTO_UDP:
211         case IPPROTO_UDPLITE:
212             fd = net_OpenDgram (obj, dhost, dport, shost, sport, tp);
213             if (fd == -1)
214                 break;
215             if (rtcp_dport > 0) /* XXX: source port is unknown */
216                 rtcp_fd = net_OpenDgram (obj, dhost, rtcp_dport, shost, 0, tp);
217             break;
218
219          case IPPROTO_DCCP:
220 #ifndef SOCK_DCCP /* provisional API (FIXME) */
221 # ifdef __linux__
222 #  define SOCK_DCCP 6
223 # endif
224 #endif
225 #ifdef SOCK_DCCP
226             var_Create (obj, "dccp-service", VLC_VAR_STRING);
227             var_SetString (obj, "dccp-service", "RTPV"); /* FIXME: RTPA? */
228             fd = net_Connect (obj, dhost, dport, SOCK_DCCP, tp);
229 #else
230             msg_Err (obj, "DCCP support not included");
231 #endif
232             break;
233
234         case IPPROTO_TCP:
235             fd = net_Connect (obj, dhost, dport, SOCK_STREAM, tp);
236             break;
237     }
238
239     free (tmp);
240     if (fd == -1)
241         return VLC_EGENERIC;
242     net_SetCSCov (fd, -1, 12);
243
244     /* Initializes demux */
245     demux_sys_t *p_sys = malloc (sizeof (*p_sys));
246     if (p_sys == NULL)
247     {
248         net_Close (fd);
249         if (rtcp_fd != -1)
250             net_Close (rtcp_fd);
251         return VLC_EGENERIC;
252     }
253
254 #ifdef HAVE_SRTP
255     p_sys->srtp         = NULL;
256 #endif
257     p_sys->fd           = fd;
258     p_sys->rtcp_fd      = rtcp_fd;
259     p_sys->max_src      = var_CreateGetInteger (obj, "rtp-max-src");
260     p_sys->timeout      = var_CreateGetInteger (obj, "rtp-timeout")
261                         * CLOCK_FREQ;
262     p_sys->max_dropout  = var_CreateGetInteger (obj, "rtp-max-dropout");
263     p_sys->max_misorder = var_CreateGetInteger (obj, "rtp-max-misorder");
264     p_sys->thread_ready = false;
265     p_sys->autodetect   = true;
266
267     demux->pf_demux   = NULL;
268     demux->pf_control = Control;
269     demux->p_sys      = p_sys;
270
271     p_sys->session = rtp_session_create (demux);
272     if (p_sys->session == NULL)
273         goto error;
274
275 #ifdef HAVE_SRTP
276     char *key = var_CreateGetNonEmptyString (demux, "srtp-key");
277     if (key)
278     {
279         vlc_gcrypt_init ();
280         p_sys->srtp = srtp_create (SRTP_ENCR_AES_CM, SRTP_AUTH_HMAC_SHA1, 10,
281                                    SRTP_PRF_AES_CM, SRTP_RCC_MODE1);
282         if (p_sys->srtp == NULL)
283         {
284             free (key);
285             goto error;
286         }
287
288         char *salt = var_CreateGetNonEmptyString (demux, "srtp-salt");
289         errno = srtp_setkeystring (p_sys->srtp, key, salt ? salt : "");
290         free (salt);
291         free (key);
292         if (errno)
293         {
294             msg_Err (obj, "bad SRTP key/salt combination (%m)");
295             goto error;
296         }
297     }
298 #endif
299
300     if (vlc_clone (&p_sys->thread,
301                    (tp != IPPROTO_TCP) ? rtp_dgram_thread : rtp_stream_thread,
302                    demux, VLC_THREAD_PRIORITY_INPUT))
303         goto error;
304     p_sys->thread_ready = true;
305     return VLC_SUCCESS;
306
307 error:
308     Close (obj);
309     return VLC_EGENERIC;
310 }
311
312
313 /**
314  * Releases resources
315  */
316 static void Close (vlc_object_t *obj)
317 {
318     demux_t *demux = (demux_t *)obj;
319     demux_sys_t *p_sys = demux->p_sys;
320
321     if (p_sys->thread_ready)
322     {
323         vlc_cancel (p_sys->thread);
324         vlc_join (p_sys->thread, NULL);
325     }
326
327 #ifdef HAVE_SRTP
328     if (p_sys->srtp)
329         srtp_destroy (p_sys->srtp);
330 #endif
331     if (p_sys->session)
332         rtp_session_destroy (demux, p_sys->session);
333     if (p_sys->rtcp_fd != -1)
334         net_Close (p_sys->rtcp_fd);
335     net_Close (p_sys->fd);
336     free (p_sys);
337 }
338
339
340 /**
341  * Extracts port number from "[host]:port" or "host:port" strings,
342  * and remove brackets from the host name.
343  * @param phost pointer to the string upon entry,
344  * pointer to the hostname upon return.
345  * @return port number, 0 if missing.
346  */
347 static int extract_port (char **phost)
348 {
349     char *host = *phost, *port;
350
351     if (host[0] == '[')
352     {
353         host = ++*phost; /* skip '[' */
354         port = strchr (host, ']');
355         if (port)
356             *port++ = '\0'; /* skip ']' */
357     }
358     else
359         port = strchr (host, ':');
360
361     if (port == NULL)
362         return 0;
363     *port++ = '\0'; /* skip ':' */
364     return atoi (port);
365 }
366
367
368 /**
369  * Control callback
370  */
371 static int Control (demux_t *demux, int i_query, va_list args)
372 {
373     switch (i_query)
374     {
375         case DEMUX_GET_POSITION:
376         {
377             float *v = va_arg (args, float *);
378             *v = 0.;
379             return VLC_SUCCESS;
380         }
381
382         case DEMUX_GET_LENGTH:
383         case DEMUX_GET_TIME:
384         {
385             int64_t *v = va_arg (args, int64_t *);
386             *v = 0;
387             return VLC_SUCCESS;
388         }
389
390         case DEMUX_GET_PTS_DELAY:
391         {
392             int64_t *v = va_arg (args, int64_t *);
393             *v = INT64_C(1000) * var_InheritInteger (demux, "network-caching");
394             return VLC_SUCCESS;
395         }
396
397         case DEMUX_CAN_PAUSE:
398         case DEMUX_CAN_SEEK:
399         case DEMUX_CAN_CONTROL_PACE:
400         {
401             bool *v = (bool*)va_arg( args, bool * );
402             *v = false;
403             return VLC_SUCCESS;
404         }
405     }
406
407     return VLC_EGENERIC;
408 }
409
410
411 /*
412  * Generic packet handlers
413  */
414
415 void *codec_init (demux_t *demux, es_format_t *fmt)
416 {
417     return es_out_Add (demux->out, fmt);
418 }
419
420 void codec_destroy (demux_t *demux, void *data)
421 {
422     if (data)
423         es_out_Del (demux->out, (es_out_id_t *)data);
424 }
425
426 /* Send a packet to decoder */
427 void codec_decode (demux_t *demux, void *data, block_t *block)
428 {
429     if (data)
430     {
431         block->i_dts = VLC_TS_INVALID; /* RTP does not specify this */
432         es_out_Control (demux->out, ES_OUT_SET_PCR, block->i_pts );
433         es_out_Send (demux->out, (es_out_id_t *)data, block);
434     }
435     else
436         block_Release (block);
437 }
438
439 static void *stream_init (demux_t *demux, const char *name)
440 {
441     return stream_DemuxNew (demux, name, demux->out);
442 }
443
444 static void stream_destroy (demux_t *demux, void *data)
445 {
446     if (data)
447         stream_Delete ((stream_t *)data);
448     (void)demux;
449 }
450
451 /* Send a packet to a chained demuxer */
452 static void stream_decode (demux_t *demux, void *data, block_t *block)
453 {
454     if (data)
455         stream_DemuxSend ((stream_t *)data, block);
456     else
457         block_Release (block);
458     (void)demux;
459 }
460
461 static void *demux_init (demux_t *demux)
462 {
463     return stream_init (demux, demux->psz_demux);
464 }
465
466 /*
467  * Static payload types handler
468  */
469
470 /* PT=0
471  * PCMU: G.711 µ-law (RFC3551)
472  */
473 static void *pcmu_init (demux_t *demux)
474 {
475     es_format_t fmt;
476
477     es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_MULAW);
478     fmt.audio.i_rate = 8000;
479     fmt.audio.i_channels = 1;
480     return codec_init (demux, &fmt);
481 }
482
483 /* PT=3
484  * GSM
485  */
486 static void *gsm_init (demux_t *demux)
487 {
488     es_format_t fmt;
489
490     es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_GSM);
491     fmt.audio.i_rate = 8000;
492     fmt.audio.i_channels = 1;
493     return codec_init (demux, &fmt);
494 }
495
496 /* PT=8
497  * PCMA: G.711 A-law (RFC3551)
498  */
499 static void *pcma_init (demux_t *demux)
500 {
501     es_format_t fmt;
502
503     es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_ALAW);
504     fmt.audio.i_rate = 8000;
505     fmt.audio.i_channels = 1;
506     return codec_init (demux, &fmt);
507 }
508
509 /* PT=10,11
510  * L16: 16-bits (network byte order) PCM
511  */
512 static void *l16s_init (demux_t *demux)
513 {
514     es_format_t fmt;
515
516     es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_S16B);
517     fmt.audio.i_rate = 44100;
518     fmt.audio.i_channels = 2;
519     return codec_init (demux, &fmt);
520 }
521
522 static void *l16m_init (demux_t *demux)
523 {
524     es_format_t fmt;
525
526     es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_S16B);
527     fmt.audio.i_rate = 44100;
528     fmt.audio.i_channels = 1;
529     return codec_init (demux, &fmt);
530 }
531
532 /* PT=12
533  * QCELP
534  */
535 static void *qcelp_init (demux_t *demux)
536 {
537     es_format_t fmt;
538
539     es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_QCELP);
540     fmt.audio.i_rate = 8000;
541     fmt.audio.i_channels = 1;
542     return codec_init (demux, &fmt);
543 }
544
545 /* PT=14
546  * MPA: MPEG Audio (RFC2250, §3.4)
547  */
548 static void *mpa_init (demux_t *demux)
549 {
550     es_format_t fmt;
551
552     es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_MPGA);
553     fmt.audio.i_channels = 2;
554     fmt.b_packetized = false;
555     return codec_init (demux, &fmt);
556 }
557
558 static void mpa_decode (demux_t *demux, void *data, block_t *block)
559 {
560     if (block->i_buffer < 4)
561     {
562         block_Release (block);
563         return;
564     }
565
566     block->i_buffer -= 4; /* 32-bits RTP/MPA header */
567     block->p_buffer += 4;
568
569     codec_decode (demux, data, block);
570 }
571
572
573 /* PT=32
574  * MPV: MPEG Video (RFC2250, §3.5)
575  */
576 static void *mpv_init (demux_t *demux)
577 {
578     es_format_t fmt;
579
580     es_format_Init (&fmt, VIDEO_ES, VLC_CODEC_MPGV);
581     fmt.b_packetized = false;
582     return codec_init (demux, &fmt);
583 }
584
585 static void mpv_decode (demux_t *demux, void *data, block_t *block)
586 {
587     if (block->i_buffer < 4)
588     {
589         block_Release (block);
590         return;
591     }
592
593     block->i_buffer -= 4; /* 32-bits RTP/MPV header */
594     block->p_buffer += 4;
595 #if 0
596     if (block->p_buffer[-3] & 0x4)
597     {
598         /* MPEG2 Video extension header */
599         /* TODO: shouldn't we skip this too ? */
600     }
601 #endif
602     codec_decode (demux, data, block);
603 }
604
605
606 /* PT=33
607  * MP2: MPEG TS (RFC2250, §2)
608  */
609 static void *ts_init (demux_t *demux)
610 {
611     return stream_init (demux, *demux->psz_demux ? demux->psz_demux : "ts");
612 }
613
614
615 /* Not using SDP, we need to guess the payload format used */
616 /* see http://www.iana.org/assignments/rtp-parameters */
617 void rtp_autodetect (demux_t *demux, rtp_session_t *session,
618                      const block_t *block)
619 {
620     uint8_t ptype = rtp_ptype (block);
621     rtp_pt_t pt = {
622         .init = NULL,
623         .destroy = codec_destroy,
624         .decode = codec_decode,
625         .frequency = 0,
626         .number = ptype,
627     };
628
629     /* Remember to keep this in sync with modules/services_discovery/sap.c */
630     switch (ptype)
631     {
632       case 0:
633         msg_Dbg (demux, "detected G.711 mu-law");
634         pt.init = pcmu_init;
635         pt.frequency = 8000;
636         break;
637
638       case 3:
639         msg_Dbg (demux, "detected GSM");
640         pt.init = gsm_init;
641         pt.frequency = 8000;
642         break;
643
644       case 8:
645         msg_Dbg (demux, "detected G.711 A-law");
646         pt.init = pcma_init;
647         pt.frequency = 8000;
648         break;
649
650       case 10:
651         msg_Dbg (demux, "detected stereo PCM");
652         pt.init = l16s_init;
653         pt.frequency = 44100;
654         break;
655
656       case 11:
657         msg_Dbg (demux, "detected mono PCM");
658         pt.init = l16m_init;
659         pt.frequency = 44100;
660         break;
661
662       case 12:
663         msg_Dbg (demux, "detected QCELP");
664         pt.init = qcelp_init;
665         pt.frequency = 8000;
666         break;
667
668       case 14:
669         msg_Dbg (demux, "detected MPEG Audio");
670         pt.init = mpa_init;
671         pt.decode = mpa_decode;
672         pt.frequency = 90000;
673         break;
674
675       case 32:
676         msg_Dbg (demux, "detected MPEG Video");
677         pt.init = mpv_init;
678         pt.decode = mpv_decode;
679         pt.frequency = 90000;
680         break;
681
682       case 33:
683         msg_Dbg (demux, "detected MPEG2 TS");
684         pt.init = ts_init;
685         pt.destroy = stream_destroy;
686         pt.decode = stream_decode;
687         pt.frequency = 90000;
688         break;
689
690       default:
691         /*
692          * If the rtp payload type is unknown then check demux if it is specified
693          */
694         if (!strcmp(demux->psz_demux, "h264")
695          || !strcmp(demux->psz_demux, "ts"))
696         {
697             msg_Dbg (demux, "dynamic payload format %s specified by demux",
698                      demux->psz_demux);
699             pt.init = demux_init;
700             pt.destroy = stream_destroy;
701             pt.decode = stream_decode;
702             pt.frequency = 90000;
703             break;
704         }
705         if (ptype >= 96)
706         {
707             char *dynamic = var_InheritString(demux, "rtp-dynamic-pt");
708             if (dynamic == NULL)
709                 ;
710             else if (!strcmp(dynamic, "theora"))
711             {
712                 msg_Dbg (demux, "assuming Theora Encoded Video");
713                 pt.init = theora_init;
714                 pt.destroy = xiph_destroy;
715                 pt.decode = xiph_decode;
716                 pt.frequency = 90000;
717             }
718             else
719                 msg_Err (demux, "unknown dynamic payload format `%s' "
720                                 "specified", dynamic);
721             free (dynamic);
722         }
723
724         msg_Err (demux, "unspecified payload format (type %"PRIu8")", ptype);
725         msg_Info (demux, "A valid SDP is needed to parse this RTP stream.");
726         dialog_Fatal (demux, N_("SDP required"),
727              N_("A description in SDP format is required to receive the RTP "
728                 "stream. Note that rtp:// URIs cannot work with dynamic "
729                 "RTP payload format (%"PRIu8")."), ptype);
730         return;
731     }
732     rtp_add_type (demux, session, &pt);
733 }
734
735 /*
736  * Dynamic payload type handlers
737  * Hmm, none implemented yet apart from Xiph ones.
738  */