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