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