]> git.sesse.net Git - vlc/blob - modules/stream_out/rtp.c
fix rtp default ttl value
[vlc] / modules / stream_out / rtp.c
1 /*****************************************************************************
2  * rtp.c: rtp stream output module
3  *****************************************************************************
4  * Copyright (C) 2003-2004 the VideoLAN team
5  * Copyright © 2007-2008 Rémi Denis-Courmont
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program 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 License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <vlc_sout.h>
35 #include <vlc_block.h>
36
37 #include <vlc_httpd.h>
38 #include <vlc_url.h>
39 #include <vlc_network.h>
40 #include <vlc_charset.h>
41 #include <vlc_strings.h>
42 #include <srtp.h>
43
44 #include "rtp.h"
45
46 #ifdef HAVE_UNISTD_H
47 #   include <sys/types.h>
48 #   include <unistd.h>
49 #   include <fcntl.h>
50 #   include <sys/stat.h>
51 #endif
52 #ifdef HAVE_LINUX_DCCP_H
53 #   include <linux/dccp.h>
54 #endif
55 #ifndef IPPROTO_DCCP
56 # define IPPROTO_DCCP 33
57 #endif
58 #ifndef IPPROTO_UDPLITE
59 # define IPPROTO_UDPLITE 136
60 #endif
61
62 #include <errno.h>
63
64 #include <assert.h>
65
66 /*****************************************************************************
67  * Module descriptor
68  *****************************************************************************/
69
70 #define DEST_TEXT N_("Destination")
71 #define DEST_LONGTEXT N_( \
72     "This is the output URL that will be used." )
73 #define SDP_TEXT N_("SDP")
74 #define SDP_LONGTEXT N_( \
75     "This allows you to specify how the SDP (Session Descriptor) for this RTP "\
76     "session will be made available. You must use an url: http://location to " \
77     "access the SDP via HTTP, rtsp://location for RTSP access, and sap:// " \
78     "for the SDP to be announced via SAP." )
79 #define SAP_TEXT N_("SAP announcing")
80 #define SAP_LONGTEXT N_("Announce this session with SAP.")
81 #define MUX_TEXT N_("Muxer")
82 #define MUX_LONGTEXT N_( \
83     "This allows you to specify the muxer used for the streaming output. " \
84     "Default is to use no muxer (standard RTP stream)." )
85
86 #define NAME_TEXT N_("Session name")
87 #define NAME_LONGTEXT N_( \
88     "This is the name of the session that will be announced in the SDP " \
89     "(Session Descriptor)." )
90 #define DESC_TEXT N_("Session description")
91 #define DESC_LONGTEXT N_( \
92     "This allows you to give a short description with details about the stream, " \
93     "that will be announced in the SDP (Session Descriptor)." )
94 #define URL_TEXT N_("Session URL")
95 #define URL_LONGTEXT N_( \
96     "This allows you to give an URL with more details about the stream " \
97     "(often the website of the streaming organization), that will " \
98     "be announced in the SDP (Session Descriptor)." )
99 #define EMAIL_TEXT N_("Session email")
100 #define EMAIL_LONGTEXT N_( \
101     "This allows you to give a contact mail address for the stream, that will " \
102     "be announced in the SDP (Session Descriptor)." )
103 #define PHONE_TEXT N_("Session phone number")
104 #define PHONE_LONGTEXT N_( \
105     "This allows you to give a contact telephone number for the stream, that will " \
106     "be announced in the SDP (Session Descriptor)." )
107
108 #define PORT_TEXT N_("Port")
109 #define PORT_LONGTEXT N_( \
110     "This allows you to specify the base port for the RTP streaming." )
111 #define PORT_AUDIO_TEXT N_("Audio port")
112 #define PORT_AUDIO_LONGTEXT N_( \
113     "This allows you to specify the default audio port for the RTP streaming." )
114 #define PORT_VIDEO_TEXT N_("Video port")
115 #define PORT_VIDEO_LONGTEXT N_( \
116     "This allows you to specify the default video port for the RTP streaming." )
117
118 #define TTL_TEXT N_("Hop limit (TTL)")
119 #define TTL_LONGTEXT N_( \
120     "This is the hop limit (also known as \"Time-To-Live\" or TTL) of " \
121     "the multicast packets sent by the stream output (-1 = use operating " \
122     "system built-in default).")
123
124 #define RTCP_MUX_TEXT N_("RTP/RTCP multiplexing")
125 #define RTCP_MUX_LONGTEXT N_( \
126     "This sends and receives RTCP packet multiplexed over the same port " \
127     "as RTP packets." )
128
129 #define PROTO_TEXT N_("Transport protocol")
130 #define PROTO_LONGTEXT N_( \
131     "This selects which transport protocol to use for RTP." )
132
133 #define SRTP_KEY_TEXT N_("SRTP key (hexadecimal)")
134 #define SRTP_KEY_LONGTEXT N_( \
135     "RTP packets will be integrity-protected and ciphered "\
136     "with this Secure RTP master shared secret key.")
137
138 #define SRTP_SALT_TEXT N_("SRTP salt (hexadecimal)")
139 #define SRTP_SALT_LONGTEXT N_( \
140     "Secure RTP requires a (non-secret) master salt value.")
141
142 static const char *const ppsz_protos[] = {
143     "dccp", "sctp", "tcp", "udp", "udplite",
144 };
145
146 static const char *const ppsz_protocols[] = {
147     "DCCP", "SCTP", "TCP", "UDP", "UDP-Lite",
148 };
149
150 #define RFC3016_TEXT N_("MP4A LATM")
151 #define RFC3016_LONGTEXT N_( \
152     "This allows you to stream MPEG4 LATM audio streams (see RFC3016)." )
153
154 static int  Open ( vlc_object_t * );
155 static void Close( vlc_object_t * );
156
157 #define SOUT_CFG_PREFIX "sout-rtp-"
158 #define MAX_EMPTY_BLOCKS 200
159
160 vlc_module_begin();
161     set_shortname( N_("RTP"));
162     set_description( N_("RTP stream output") );
163     set_capability( "sout stream", 0 );
164     add_shortcut( "rtp" );
165     set_category( CAT_SOUT );
166     set_subcategory( SUBCAT_SOUT_STREAM );
167
168     add_string( SOUT_CFG_PREFIX "dst", "", NULL, DEST_TEXT,
169                 DEST_LONGTEXT, true );
170         change_unsafe();
171     add_string( SOUT_CFG_PREFIX "sdp", "", NULL, SDP_TEXT,
172                 SDP_LONGTEXT, true );
173     add_string( SOUT_CFG_PREFIX "mux", "", NULL, MUX_TEXT,
174                 MUX_LONGTEXT, true );
175     add_bool( SOUT_CFG_PREFIX "sap", false, NULL, SAP_TEXT, SAP_LONGTEXT,
176               true );
177
178     add_string( SOUT_CFG_PREFIX "name", "", NULL, NAME_TEXT,
179                 NAME_LONGTEXT, true );
180     add_string( SOUT_CFG_PREFIX "description", "", NULL, DESC_TEXT,
181                 DESC_LONGTEXT, true );
182     add_string( SOUT_CFG_PREFIX "url", "", NULL, URL_TEXT,
183                 URL_LONGTEXT, true );
184     add_string( SOUT_CFG_PREFIX "email", "", NULL, EMAIL_TEXT,
185                 EMAIL_LONGTEXT, true );
186     add_string( SOUT_CFG_PREFIX "phone", "", NULL, PHONE_TEXT,
187                 PHONE_LONGTEXT, true );
188
189     add_string( SOUT_CFG_PREFIX "proto", "udp", NULL, PROTO_TEXT,
190                 PROTO_LONGTEXT, false );
191         change_string_list( ppsz_protos, ppsz_protocols, NULL );
192     add_integer( SOUT_CFG_PREFIX "port", 50004, NULL, PORT_TEXT,
193                  PORT_LONGTEXT, true );
194     add_integer( SOUT_CFG_PREFIX "port-audio", 50000, NULL, PORT_AUDIO_TEXT,
195                  PORT_AUDIO_LONGTEXT, true );
196     add_integer( SOUT_CFG_PREFIX "port-video", 50002, NULL, PORT_VIDEO_TEXT,
197                  PORT_VIDEO_LONGTEXT, true );
198
199     add_integer( SOUT_CFG_PREFIX "ttl", -1, NULL, TTL_TEXT,
200                  TTL_LONGTEXT, true );
201     add_bool( SOUT_CFG_PREFIX "rtcp-mux", false, NULL,
202               RTCP_MUX_TEXT, RTCP_MUX_LONGTEXT, false );
203
204     add_string( SOUT_CFG_PREFIX "key", "", NULL,
205                 SRTP_KEY_TEXT, SRTP_KEY_LONGTEXT, false );
206     add_string( SOUT_CFG_PREFIX "salt", "", NULL,
207                 SRTP_SALT_TEXT, SRTP_SALT_LONGTEXT, false );
208
209     add_bool( SOUT_CFG_PREFIX "mp4a-latm", 0, NULL, RFC3016_TEXT,
210                  RFC3016_LONGTEXT, false );
211
212     set_callbacks( Open, Close );
213 vlc_module_end();
214
215 /*****************************************************************************
216  * Exported prototypes
217  *****************************************************************************/
218 static const char *const ppsz_sout_options[] = {
219     "dst", "name", "port", "port-audio", "port-video", "*sdp", "ttl", "mux",
220     "sap", "description", "url", "email", "phone",
221     "proto", "rtcp-mux", "key", "salt",
222     "mp4a-latm", NULL
223 };
224
225 static sout_stream_id_t *Add ( sout_stream_t *, es_format_t * );
226 static int               Del ( sout_stream_t *, sout_stream_id_t * );
227 static int               Send( sout_stream_t *, sout_stream_id_t *,
228                                block_t* );
229 static sout_stream_id_t *MuxAdd ( sout_stream_t *, es_format_t * );
230 static int               MuxDel ( sout_stream_t *, sout_stream_id_t * );
231 static int               MuxSend( sout_stream_t *, sout_stream_id_t *,
232                                   block_t* );
233
234 static sout_access_out_t *GrabberCreate( sout_stream_t *p_sout );
235 static void* ThreadSend( vlc_object_t *p_this );
236
237 static void SDPHandleUrl( sout_stream_t *, const char * );
238
239 static int SapSetup( sout_stream_t *p_stream );
240 static int FileSetup( sout_stream_t *p_stream );
241 static int HttpSetup( sout_stream_t *p_stream, const vlc_url_t * );
242
243 struct sout_stream_sys_t
244 {
245     /* SDP */
246     char    *psz_sdp;
247     vlc_mutex_t  lock_sdp;
248
249     /* SDP to disk */
250     bool b_export_sdp_file;
251     char *psz_sdp_file;
252
253     /* SDP via SAP */
254     bool b_export_sap;
255     session_descriptor_t *p_session;
256
257     /* SDP via HTTP */
258     httpd_host_t *p_httpd_host;
259     httpd_file_t *p_httpd_file;
260
261     /* RTSP */
262     rtsp_stream_t *rtsp;
263
264     /* */
265     char     *psz_destination;
266     uint8_t   proto;
267     uint8_t   i_ttl;
268     uint16_t  i_port;
269     uint16_t  i_port_audio;
270     uint16_t  i_port_video;
271     bool b_latm;
272     bool rtcp_mux;
273
274     /* when need to use a private one or when using muxer */
275     int i_payload_type;
276
277     /* in case we do TS/PS over rtp */
278     sout_mux_t        *p_mux;
279     sout_access_out_t *p_grab;
280     block_t           *packet;
281
282     /* */
283     vlc_mutex_t      lock_es;
284     int              i_es;
285     sout_stream_id_t **es;
286 };
287
288 typedef int (*pf_rtp_packetizer_t)( sout_stream_id_t *, block_t * );
289
290 typedef struct rtp_sink_t
291 {
292     int rtp_fd;
293     rtcp_sender_t *rtcp;
294 } rtp_sink_t;
295
296 struct sout_stream_id_t
297 {
298     VLC_COMMON_MEMBERS
299
300     sout_stream_t *p_stream;
301     /* rtp field */
302     uint16_t    i_sequence;
303     uint8_t     i_payload_type;
304     uint8_t     ssrc[4];
305
306     /* for sdp */
307     const char  *psz_enc;
308     char        *psz_fmtp;
309     int          i_clock_rate;
310     int          i_port;
311     int          i_cat;
312     int          i_channels;
313     int          i_bitrate;
314
315     /* Packetizer specific fields */
316     int                 i_mtu;
317     srtp_session_t     *srtp;
318     pf_rtp_packetizer_t pf_packetize;
319
320     /* Packets sinks */
321     vlc_mutex_t       lock_sink;
322     int               sinkc;
323     rtp_sink_t       *sinkv;
324     rtsp_stream_id_t *rtsp_id;
325     int              *listen_fd;
326
327     block_fifo_t     *p_fifo;
328     int64_t           i_caching;
329 };
330
331 /*****************************************************************************
332  * Open:
333  *****************************************************************************/
334 static int Open( vlc_object_t *p_this )
335 {
336     sout_stream_t       *p_stream = (sout_stream_t*)p_this;
337     sout_instance_t     *p_sout = p_stream->p_sout;
338     sout_stream_sys_t   *p_sys = NULL;
339     config_chain_t      *p_cfg = NULL;
340     char                *psz;
341     bool          b_rtsp = false;
342
343     config_ChainParse( p_stream, SOUT_CFG_PREFIX,
344                        ppsz_sout_options, p_stream->p_cfg );
345
346     p_sys = malloc( sizeof( sout_stream_sys_t ) );
347     if( p_sys == NULL )
348         return VLC_ENOMEM;
349
350     p_sys->psz_destination = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "dst" );
351
352     p_sys->i_port       = var_GetInteger( p_stream, SOUT_CFG_PREFIX "port" );
353     p_sys->i_port_audio = var_GetInteger( p_stream, SOUT_CFG_PREFIX "port-audio" );
354     p_sys->i_port_video = var_GetInteger( p_stream, SOUT_CFG_PREFIX "port-video" );
355     p_sys->rtcp_mux   = var_GetBool( p_stream, SOUT_CFG_PREFIX "rtcp-mux" );
356
357     p_sys->psz_sdp_file = NULL;
358
359     if( p_sys->i_port_audio == p_sys->i_port_video )
360     {
361         msg_Err( p_stream, "audio and video port cannot be the same" );
362         p_sys->i_port_audio = 0;
363         p_sys->i_port_video = 0;
364     }
365
366     for( p_cfg = p_stream->p_cfg; p_cfg != NULL; p_cfg = p_cfg->p_next )
367     {
368         if( !strcmp( p_cfg->psz_name, "sdp" )
369          && ( p_cfg->psz_value != NULL )
370          && !strncasecmp( p_cfg->psz_value, "rtsp:", 5 ) )
371         {
372             b_rtsp = true;
373             break;
374         }
375     }
376     if( !b_rtsp )
377     {
378         psz = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "sdp" );
379         if( psz != NULL )
380         {
381             if( !strncasecmp( psz, "rtsp:", 5 ) )
382                 b_rtsp = true;
383             free( psz );
384         }
385     }
386
387     /* Transport protocol */
388     p_sys->proto = IPPROTO_UDP;
389     psz = var_GetNonEmptyString (p_stream, SOUT_CFG_PREFIX"proto");
390
391     if ((psz == NULL) || !strcasecmp (psz, "udp"))
392         (void)0; /* default */
393     else
394     if (!strcasecmp (psz, "dccp"))
395     {
396         p_sys->proto = IPPROTO_DCCP;
397         p_sys->rtcp_mux = true; /* Force RTP/RTCP mux */
398     }
399 #if 0
400     else
401     if (!strcasecmp (psz, "sctp"))
402     {
403         p_sys->proto = IPPROTO_TCP;
404         p_sys->rtcp_mux = true; /* Force RTP/RTCP mux */
405     }
406 #endif
407 #if 0
408     else
409     if (!strcasecmp (psz, "tcp"))
410     {
411         p_sys->proto = IPPROTO_TCP;
412         p_sys->rtcp_mux = true; /* Force RTP/RTCP mux */
413     }
414 #endif
415     else
416     if (!strcasecmp (psz, "udplite") || !strcasecmp (psz, "udp-lite"))
417         p_sys->proto = IPPROTO_UDPLITE;
418     else
419         msg_Warn (p_this, "unknown or unsupported transport protocol \"%s\"",
420                   psz);
421     free (psz);
422     var_Create (p_this, "dccp-service", VLC_VAR_STRING);
423
424     if( ( p_sys->psz_destination == NULL ) && !b_rtsp )
425     {
426         msg_Err( p_stream, "missing destination and not in RTSP mode" );
427         free( p_sys );
428         return VLC_EGENERIC;
429     }
430
431     p_sys->i_ttl = var_GetInteger( p_stream, SOUT_CFG_PREFIX "ttl" );
432     if( p_sys->i_ttl == -1 )
433     {
434         /* Normally, we should let the default hop limit up to the core,
435          * but we have to know it to build our SDP properly, which is why
436          * we ask the core. FIXME: broken when neither sout-rtp-ttl nor
437          * ttl are set. */
438         p_sys->i_ttl = config_GetInt( p_stream, "ttl" );
439     }
440
441     p_sys->b_latm = var_GetBool( p_stream, SOUT_CFG_PREFIX "mp4a-latm" );
442
443     p_sys->i_payload_type = 96;
444     p_sys->i_es = 0;
445     p_sys->es   = NULL;
446     p_sys->rtsp = NULL;
447     p_sys->psz_sdp = NULL;
448
449     p_sys->b_export_sap = false;
450     p_sys->b_export_sdp_file = false;
451     p_sys->p_session = NULL;
452
453     p_sys->p_httpd_host = NULL;
454     p_sys->p_httpd_file = NULL;
455
456     p_stream->p_sys     = p_sys;
457
458     vlc_mutex_init( &p_sys->lock_sdp );
459     vlc_mutex_init( &p_sys->lock_es );
460
461     psz = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "mux" );
462     if( psz != NULL )
463     {
464         sout_stream_id_t *id;
465
466         /* Check muxer type */
467         if( strncasecmp( psz, "ps", 2 )
468          && strncasecmp( psz, "mpeg1", 5 )
469          && strncasecmp( psz, "ts", 2 ) )
470         {
471             msg_Err( p_stream, "unsupported muxer type for RTP (only TS/PS)" );
472             free( psz );
473             vlc_mutex_destroy( &p_sys->lock_sdp );
474             vlc_mutex_destroy( &p_sys->lock_es );
475             free( p_sys );
476             return VLC_EGENERIC;
477         }
478
479         p_sys->p_grab = GrabberCreate( p_stream );
480         p_sys->p_mux = sout_MuxNew( p_sout, psz, p_sys->p_grab );
481         free( psz );
482
483         if( p_sys->p_mux == NULL )
484         {
485             msg_Err( p_stream, "cannot create muxer" );
486             sout_AccessOutDelete( p_sys->p_grab );
487             vlc_mutex_destroy( &p_sys->lock_sdp );
488             vlc_mutex_destroy( &p_sys->lock_es );
489             free( p_sys );
490             return VLC_EGENERIC;
491         }
492
493         id = Add( p_stream, NULL );
494         if( id == NULL )
495         {
496             sout_MuxDelete( p_sys->p_mux );
497             sout_AccessOutDelete( p_sys->p_grab );
498             vlc_mutex_destroy( &p_sys->lock_sdp );
499             vlc_mutex_destroy( &p_sys->lock_es );
500             free( p_sys );
501             return VLC_EGENERIC;
502         }
503
504         p_sys->packet = NULL;
505
506         p_stream->pf_add  = MuxAdd;
507         p_stream->pf_del  = MuxDel;
508         p_stream->pf_send = MuxSend;
509     }
510     else
511     {
512         p_sys->p_mux    = NULL;
513         p_sys->p_grab   = NULL;
514
515         p_stream->pf_add    = Add;
516         p_stream->pf_del    = Del;
517         p_stream->pf_send   = Send;
518     }
519
520     if( var_GetBool( p_stream, SOUT_CFG_PREFIX"sap" ) )
521         SDPHandleUrl( p_stream, "sap" );
522
523     psz = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "sdp" );
524     if( psz != NULL )
525     {
526         config_chain_t *p_cfg;
527
528         SDPHandleUrl( p_stream, psz );
529
530         for( p_cfg = p_stream->p_cfg; p_cfg != NULL; p_cfg = p_cfg->p_next )
531         {
532             if( !strcmp( p_cfg->psz_name, "sdp" ) )
533             {
534                 if( p_cfg->psz_value == NULL || *p_cfg->psz_value == '\0' )
535                     continue;
536
537                 /* needed both :sout-rtp-sdp= and rtp{sdp=} can be used */
538                 if( !strcmp( p_cfg->psz_value, psz ) )
539                     continue;
540
541                 SDPHandleUrl( p_stream, p_cfg->psz_value );
542             }
543         }
544         free( psz );
545     }
546
547     /* update p_sout->i_out_pace_nocontrol */
548     p_stream->p_sout->i_out_pace_nocontrol++;
549
550     return VLC_SUCCESS;
551 }
552
553 /*****************************************************************************
554  * Close:
555  *****************************************************************************/
556 static void Close( vlc_object_t * p_this )
557 {
558     sout_stream_t     *p_stream = (sout_stream_t*)p_this;
559     sout_stream_sys_t *p_sys = p_stream->p_sys;
560
561     /* update p_sout->i_out_pace_nocontrol */
562     p_stream->p_sout->i_out_pace_nocontrol--;
563
564     if( p_sys->p_mux )
565     {
566         assert( p_sys->i_es == 1 );
567         Del( p_stream, p_sys->es[0] );
568
569         sout_MuxDelete( p_sys->p_mux );
570         sout_AccessOutDelete( p_sys->p_grab );
571         if( p_sys->packet )
572         {
573             block_Release( p_sys->packet );
574         }
575         if( p_sys->b_export_sap )
576         {
577             p_sys->p_mux = NULL;
578             SapSetup( p_stream );
579         }
580     }
581
582     if( p_sys->rtsp != NULL )
583         RtspUnsetup( p_sys->rtsp );
584
585     vlc_mutex_destroy( &p_sys->lock_sdp );
586     vlc_mutex_destroy( &p_sys->lock_es );
587
588     if( p_sys->p_httpd_file )
589         httpd_FileDelete( p_sys->p_httpd_file );
590
591     if( p_sys->p_httpd_host )
592         httpd_HostDelete( p_sys->p_httpd_host );
593
594     free( p_sys->psz_sdp );
595
596     if( p_sys->b_export_sdp_file )
597     {
598 #ifdef HAVE_UNISTD_H
599         unlink( p_sys->psz_sdp_file );
600 #endif
601         free( p_sys->psz_sdp_file );
602     }
603     free( p_sys->psz_destination );
604     free( p_sys );
605 }
606
607 /*****************************************************************************
608  * SDPHandleUrl:
609  *****************************************************************************/
610 static void SDPHandleUrl( sout_stream_t *p_stream, const char *psz_url )
611 {
612     sout_stream_sys_t *p_sys = p_stream->p_sys;
613     vlc_url_t url;
614
615     vlc_UrlParse( &url, psz_url, 0 );
616     if( url.psz_protocol && !strcasecmp( url.psz_protocol, "http" ) )
617     {
618         if( p_sys->p_httpd_file )
619         {
620             msg_Err( p_stream, "you can use sdp=http:// only once" );
621             goto out;
622         }
623
624         if( HttpSetup( p_stream, &url ) )
625         {
626             msg_Err( p_stream, "cannot export SDP as HTTP" );
627         }
628     }
629     else if( url.psz_protocol && !strcasecmp( url.psz_protocol, "rtsp" ) )
630     {
631         if( p_sys->rtsp != NULL )
632         {
633             msg_Err( p_stream, "you can use sdp=rtsp:// only once" );
634             goto out;
635         }
636
637         /* FIXME test if destination is multicast or no destination at all */
638         p_sys->rtsp = RtspSetup( p_stream, &url );
639         if( p_sys->rtsp == NULL )
640         {
641             msg_Err( p_stream, "cannot export SDP as RTSP" );
642         }
643
644         if( p_sys->p_mux != NULL )
645         {
646             sout_stream_id_t *id = p_sys->es[0];
647             id->rtsp_id = RtspAddId( p_sys->rtsp, id, 0, GetDWBE( id->ssrc ),
648                                      p_sys->psz_destination, p_sys->i_ttl,
649                                      id->i_port, id->i_port + 1 );
650         }
651     }
652     else if( ( url.psz_protocol && !strcasecmp( url.psz_protocol, "sap" ) ) ||
653              ( url.psz_host && !strcasecmp( url.psz_host, "sap" ) ) )
654     {
655         p_sys->b_export_sap = true;
656         SapSetup( p_stream );
657     }
658     else if( url.psz_protocol && !strcasecmp( url.psz_protocol, "file" ) )
659     {
660         if( p_sys->b_export_sdp_file )
661         {
662             msg_Err( p_stream, "you can use sdp=file:// only once" );
663             goto out;
664         }
665         p_sys->b_export_sdp_file = true;
666         psz_url = &psz_url[5];
667         if( psz_url[0] == '/' && psz_url[1] == '/' )
668             psz_url += 2;
669         p_sys->psz_sdp_file = strdup( psz_url );
670     }
671     else
672     {
673         msg_Warn( p_stream, "unknown protocol for SDP (%s)",
674                   url.psz_protocol );
675     }
676
677 out:
678     vlc_UrlClean( &url );
679 }
680
681 /*****************************************************************************
682  * SDPGenerate
683  *****************************************************************************/
684 /*static*/
685 char *SDPGenerate( const sout_stream_t *p_stream, const char *rtsp_url )
686 {
687     const sout_stream_sys_t *p_sys = p_stream->p_sys;
688     char *psz_sdp;
689     struct sockaddr_storage dst;
690     socklen_t dstlen;
691     int i;
692     /*
693      * When we have a fixed destination (typically when we do multicast),
694      * we need to put the actual port numbers in the SDP.
695      * When there is no fixed destination, we only support RTSP unicast
696      * on-demand setup, so we should rather let the clients decide which ports
697      * to use.
698      * When there is both a fixed destination and RTSP unicast, we need to
699      * put port numbers used by the fixed destination, otherwise the SDP would
700      * become totally incorrect for multicast use. It should be noted that
701      * port numbers from SDP with RTSP are only "recommendation" from the
702      * server to the clients (per RFC2326), so only broken clients will fail
703      * to handle this properly. There is no solution but to use two differents
704      * output chain with two different RTSP URLs if you need to handle this
705      * scenario.
706      */
707     int inclport;
708
709     if( p_sys->psz_destination != NULL )
710     {
711         inclport = 1;
712
713         /* Oh boy, this is really ugly! (+ race condition on lock_es) */
714         dstlen = sizeof( dst );
715         if( p_sys->es[0]->listen_fd != NULL )
716             getsockname( p_sys->es[0]->listen_fd[0],
717                          (struct sockaddr *)&dst, &dstlen );
718         else
719             getpeername( p_sys->es[0]->sinkv[0].rtp_fd,
720                          (struct sockaddr *)&dst, &dstlen );
721     }
722     else
723     {
724         inclport = 0;
725
726         /* Dummy destination address for RTSP */
727         memset (&dst, 0, sizeof( struct sockaddr_in ) );
728         dst.ss_family = AF_INET;
729 #ifdef HAVE_SA_LEN
730         dst.ss_len =
731 #endif
732         dstlen = sizeof( struct sockaddr_in );
733     }
734
735     psz_sdp = vlc_sdp_Start( VLC_OBJECT( p_stream ), SOUT_CFG_PREFIX,
736                              NULL, 0, (struct sockaddr *)&dst, dstlen );
737     if( psz_sdp == NULL )
738         return NULL;
739
740     /* TODO: a=source-filter */
741     if( p_sys->rtcp_mux )
742         sdp_AddAttribute( &psz_sdp, "rtcp-mux", NULL );
743
744     if( rtsp_url != NULL )
745         sdp_AddAttribute ( &psz_sdp, "control", "%s", rtsp_url );
746
747     /* FIXME: locking?! */
748     for( i = 0; i < p_sys->i_es; i++ )
749     {
750         sout_stream_id_t *id = p_sys->es[i];
751         const char *mime_major; /* major MIME type */
752         const char *proto = "RTP/AVP"; /* protocol */
753
754         switch( id->i_cat )
755         {
756             case VIDEO_ES:
757                 mime_major = "video";
758                 break;
759             case AUDIO_ES:
760                 mime_major = "audio";
761                 break;
762             case SPU_ES:
763                 mime_major = "text";
764                 break;
765             default:
766                 continue;
767         }
768
769         if( rtsp_url == NULL )
770         {
771             switch( p_sys->proto )
772             {
773                 case IPPROTO_UDP:
774                     break;
775                 case IPPROTO_TCP:
776                     proto = "TCP/RTP/AVP";
777                     break;
778                 case IPPROTO_DCCP:
779                     proto = "DCCP/RTP/AVP";
780                     break;
781                 case IPPROTO_UDPLITE:
782                     continue;
783             }
784         }
785
786         sdp_AddMedia( &psz_sdp, mime_major, proto, inclport * id->i_port,
787                       id->i_payload_type, false, id->i_bitrate,
788                       id->psz_enc, id->i_clock_rate, id->i_channels,
789                       id->psz_fmtp);
790
791         if( rtsp_url != NULL )
792         {
793             assert( strlen( rtsp_url ) > 0 );
794             bool addslash = ( rtsp_url[strlen( rtsp_url ) - 1] != '/' );
795             sdp_AddAttribute ( &psz_sdp, "control",
796                                addslash ? "%s/trackID=%u" : "%strackID=%u",
797                                rtsp_url, i );
798         }
799         else
800         {
801             if( id->listen_fd != NULL )
802                 sdp_AddAttribute( &psz_sdp, "setup", "passive" );
803             if( p_sys->proto == IPPROTO_DCCP )
804                 sdp_AddAttribute( &psz_sdp, "dccp-service-code",
805                                   "SC:RTP%c", toupper( mime_major[0] ) );
806         }
807     }
808
809     return psz_sdp;
810 }
811
812 /*****************************************************************************
813  * RTP mux
814  *****************************************************************************/
815
816 static void sprintf_hexa( char *s, uint8_t *p_data, int i_data )
817 {
818     static const char hex[16] = "0123456789abcdef";
819     int i;
820
821     for( i = 0; i < i_data; i++ )
822     {
823         s[2*i+0] = hex[(p_data[i]>>4)&0xf];
824         s[2*i+1] = hex[(p_data[i]   )&0xf];
825     }
826     s[2*i_data] = '\0';
827 }
828
829 /**
830  * Shrink the MTU down to a fixed packetization time (for audio).
831  */
832 static void
833 rtp_set_ptime (sout_stream_id_t *id, unsigned ptime_ms, size_t bytes)
834 {
835     /* Samples per second */
836     size_t spl = (id->i_clock_rate - 1) * ptime_ms / 1000 + 1;
837     bytes *= id->i_channels;
838     spl *= bytes;
839
840     if (spl < rtp_mtu (id)) /* MTU is big enough for ptime */
841         id->i_mtu = 12 + spl;
842     else /* MTU is too small for ptime, align to a sample boundary */
843         id->i_mtu = 12 + (((id->i_mtu - 12) / bytes) * bytes);
844 }
845
846 /** Add an ES as a new RTP stream */
847 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
848 {
849     /* NOTE: As a special case, if we use a non-RTP
850      * mux (TS/PS), then p_fmt is NULL. */
851     sout_stream_sys_t *p_sys = p_stream->p_sys;
852     sout_stream_id_t  *id;
853     int               i_port, cscov = -1;
854     char              *psz_sdp;
855
856     id = vlc_object_create( p_stream, sizeof( sout_stream_id_t ) );
857     if( id == NULL )
858         return NULL;
859     vlc_object_attach( id, p_stream );
860
861     /* Choose the port */
862     i_port = 0;
863     if( p_fmt == NULL )
864         ;
865     else
866     if( p_fmt->i_cat == AUDIO_ES && p_sys->i_port_audio > 0 )
867     {
868         i_port = p_sys->i_port_audio;
869         p_sys->i_port_audio = 0;
870     }
871     else
872     if( p_fmt->i_cat == VIDEO_ES && p_sys->i_port_video > 0 )
873     {
874         i_port = p_sys->i_port_video;
875         p_sys->i_port_video = 0;
876     }
877
878     while( i_port == 0 )
879     {
880         if( p_sys->i_port != p_sys->i_port_audio
881          && p_sys->i_port != p_sys->i_port_video )
882         {
883             i_port = p_sys->i_port;
884             p_sys->i_port += 2;
885             break;
886         }
887         p_sys->i_port += 2;
888     }
889
890     id->p_stream   = p_stream;
891
892     id->i_sequence = rand()&0xffff;
893     id->i_payload_type = p_sys->i_payload_type;
894     id->ssrc[0] = rand()&0xff;
895     id->ssrc[1] = rand()&0xff;
896     id->ssrc[2] = rand()&0xff;
897     id->ssrc[3] = rand()&0xff;
898
899     id->psz_enc    = NULL;
900     id->psz_fmtp   = NULL;
901     id->i_clock_rate = 90000; /* most common case for video */
902     id->i_channels = 0;
903     id->i_port     = i_port;
904     if( p_fmt != NULL )
905     {
906         id->i_cat  = p_fmt->i_cat;
907         if( p_fmt->i_cat == AUDIO_ES )
908         {
909             id->i_clock_rate = p_fmt->audio.i_rate;
910             id->i_channels = p_fmt->audio.i_channels;
911         }
912         id->i_bitrate = p_fmt->i_bitrate/1000; /* Stream bitrate in kbps */
913     }
914     else
915     {
916         id->i_cat  = VIDEO_ES;
917         id->i_bitrate = 0;
918     }
919
920     id->i_mtu = config_GetInt( p_stream, "mtu" );
921     if( id->i_mtu <= 12 + 16 )
922         id->i_mtu = 576 - 20 - 8; /* pessimistic */
923     msg_Dbg( p_stream, "maximum RTP packet size: %d bytes", id->i_mtu );
924
925     id->srtp = NULL;
926     id->pf_packetize = NULL;
927
928     char *key = var_CreateGetNonEmptyString (p_stream, SOUT_CFG_PREFIX"key");
929     if (key)
930     {
931         id->srtp = srtp_create (SRTP_ENCR_AES_CM, SRTP_AUTH_HMAC_SHA1, 10,
932                                    SRTP_PRF_AES_CM, SRTP_RCC_MODE1);
933         if (id->srtp == NULL)
934         {
935             free (key);
936             goto error;
937         }
938
939         char *salt = var_CreateGetNonEmptyString (p_stream, SOUT_CFG_PREFIX"salt");
940         errno = srtp_setkeystring (id->srtp, key, salt ? salt : "");
941         free (salt);
942         free (key);
943         if (errno)
944         {
945             msg_Err (p_stream, "bad SRTP key/salt combination (%m)");
946             goto error;
947         }
948         id->i_sequence = 0; /* FIXME: awful hack for libvlc_srtp */
949     }
950
951     vlc_mutex_init( &id->lock_sink );
952     id->sinkc = 0;
953     id->sinkv = NULL;
954     id->rtsp_id = NULL;
955     id->p_fifo = NULL;
956     id->listen_fd = NULL;
957
958     id->i_caching =
959         (int64_t)1000 * var_GetInteger( p_stream, SOUT_CFG_PREFIX "caching");
960
961     if( p_sys->psz_destination != NULL )
962         switch( p_sys->proto )
963         {
964             case IPPROTO_DCCP:
965             {
966                 const char *code;
967                 switch (id->i_cat)
968                 {
969                     case VIDEO_ES: code = "RTPV";     break;
970                     case AUDIO_ES: code = "RTPARTPV"; break;
971                     case SPU_ES:   code = "RTPTRPTV"; break;
972                     default:       code = "RTPORTPV"; break;
973                 }
974                 var_SetString (p_stream, "dccp-service", code);
975             }   /* fall through */
976             case IPPROTO_TCP:
977                 id->listen_fd = net_Listen( VLC_OBJECT(p_stream),
978                                             p_sys->psz_destination, i_port,
979                                             p_sys->proto );
980                 if( id->listen_fd == NULL )
981                 {
982                     msg_Err( p_stream, "passive COMEDIA RTP socket failed" );
983                     goto error;
984                 }
985                 break;
986
987             default:
988             {
989                 int ttl = (p_sys->i_ttl > 0) ? p_sys->i_ttl : -1;
990                 int fd = net_ConnectDgram( p_stream, p_sys->psz_destination,
991                                            i_port, ttl, p_sys->proto );
992                 if( fd == -1 )
993                 {
994                     msg_Err( p_stream, "cannot create RTP socket" );
995                     goto error;
996                 }
997                 rtp_add_sink( id, fd, p_sys->rtcp_mux );
998             }
999         }
1000
1001     if( p_fmt == NULL )
1002     {
1003         char *psz = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "mux" );
1004
1005         if( psz == NULL ) /* Uho! */
1006             ;
1007         else
1008         if( strncmp( psz, "ts", 2 ) == 0 )
1009         {
1010             id->i_payload_type = 33;
1011             id->psz_enc = "MP2T";
1012         }
1013         else
1014         {
1015             id->psz_enc = "MP2P";
1016         }
1017         free( psz );
1018     }
1019     else
1020     switch( p_fmt->i_codec )
1021     {
1022         case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1023             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 8000 )
1024                 id->i_payload_type = 0;
1025             id->psz_enc = "PCMU";
1026             id->pf_packetize = rtp_packetize_split;
1027             rtp_set_ptime (id, 20, 1);
1028             break;
1029         case VLC_FOURCC( 'a', 'l', 'a', 'w' ):
1030             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 8000 )
1031                 id->i_payload_type = 8;
1032             id->psz_enc = "PCMA";
1033             id->pf_packetize = rtp_packetize_split;
1034             rtp_set_ptime (id, 20, 1);
1035             break;
1036         case VLC_FOURCC( 's', '1', '6', 'b' ):
1037             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 44100 )
1038             {
1039                 id->i_payload_type = 11;
1040             }
1041             else if( p_fmt->audio.i_channels == 2 &&
1042                      p_fmt->audio.i_rate == 44100 )
1043             {
1044                 id->i_payload_type = 10;
1045             }
1046             id->psz_enc = "L16";
1047             id->pf_packetize = rtp_packetize_split;
1048             rtp_set_ptime (id, 20, 2);
1049             break;
1050         case VLC_FOURCC( 'u', '8', ' ', ' ' ):
1051             id->psz_enc = "L8";
1052             id->pf_packetize = rtp_packetize_split;
1053             rtp_set_ptime (id, 20, 1);
1054             break;
1055         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
1056         case VLC_FOURCC( 'm', 'p', '3', ' ' ):
1057             id->i_payload_type = 14;
1058             id->psz_enc = "MPA";
1059             id->i_clock_rate = 90000; /* not 44100 */
1060             id->pf_packetize = rtp_packetize_mpa;
1061             break;
1062         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
1063             id->i_payload_type = 32;
1064             id->psz_enc = "MPV";
1065             id->pf_packetize = rtp_packetize_mpv;
1066             break;
1067         case VLC_FOURCC( 'G', '7', '2', '6' ):
1068         case VLC_FOURCC( 'g', '7', '2', '6' ):
1069             switch( p_fmt->i_bitrate / 1000 )
1070             {
1071             case 16:
1072                 id->psz_enc = "G726-16";
1073                 id->pf_packetize = rtp_packetize_g726_16;
1074                 break;
1075             case 24:
1076                 id->psz_enc = "G726-24";
1077                 id->pf_packetize = rtp_packetize_g726_24;
1078                 break;
1079             case 32:
1080                 id->psz_enc = "G726-32";
1081                 id->pf_packetize = rtp_packetize_g726_32;
1082                 break;
1083             case 40:
1084                 id->psz_enc = "G726-40";
1085                 id->pf_packetize = rtp_packetize_g726_40;
1086                 break;
1087             }
1088             break;
1089         case VLC_FOURCC( 'a', '5', '2', ' ' ):
1090             id->psz_enc = "ac3";
1091             id->pf_packetize = rtp_packetize_ac3;
1092             break;
1093         case VLC_FOURCC( 'H', '2', '6', '3' ):
1094             id->psz_enc = "H263-1998";
1095             id->pf_packetize = rtp_packetize_h263;
1096             break;
1097         case VLC_FOURCC( 'h', '2', '6', '4' ):
1098             id->psz_enc = "H264";
1099             id->pf_packetize = rtp_packetize_h264;
1100             id->psz_fmtp = NULL;
1101
1102             if( p_fmt->i_extra > 0 )
1103             {
1104                 uint8_t *p_buffer = p_fmt->p_extra;
1105                 int     i_buffer = p_fmt->i_extra;
1106                 char    *p_64_sps = NULL;
1107                 char    *p_64_pps = NULL;
1108                 char    hexa[6+1];
1109
1110                 while( i_buffer > 4 &&
1111                        p_buffer[0] == 0 && p_buffer[1] == 0 &&
1112                        p_buffer[2] == 0 && p_buffer[3] == 1 )
1113                 {
1114                     const int i_nal_type = p_buffer[4]&0x1f;
1115                     int i_offset;
1116                     int i_size      = 0;
1117
1118                     msg_Dbg( p_stream, "we found a startcode for NAL with TYPE:%d", i_nal_type );
1119
1120                     i_size = i_buffer;
1121                     for( i_offset = 4; i_offset+3 < i_buffer ; i_offset++)
1122                     {
1123                         if( !memcmp (p_buffer + i_offset, "\x00\x00\x00\x01", 4 ) )
1124                         {
1125                             /* we found another startcode */
1126                             i_size = i_offset;
1127                             break;
1128                         }
1129                     }
1130                     if( i_nal_type == 7 )
1131                     {
1132                         p_64_sps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
1133                         sprintf_hexa( hexa, &p_buffer[5], 3 );
1134                     }
1135                     else if( i_nal_type == 8 )
1136                     {
1137                         p_64_pps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
1138                     }
1139                     i_buffer -= i_size;
1140                     p_buffer += i_size;
1141                 }
1142                 /* */
1143                 if( p_64_sps && p_64_pps &&
1144                     ( asprintf( &id->psz_fmtp,
1145                                 "packetization-mode=1;profile-level-id=%s;"
1146                                 "sprop-parameter-sets=%s,%s;", hexa, p_64_sps,
1147                                 p_64_pps ) == -1 ) )
1148                     id->psz_fmtp = NULL;
1149                 free( p_64_sps );
1150                 free( p_64_pps );
1151             }
1152             if( !id->psz_fmtp )
1153                 id->psz_fmtp = strdup( "packetization-mode=1" );
1154             break;
1155
1156         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
1157         {
1158             char hexa[2*p_fmt->i_extra +1];
1159
1160             id->psz_enc = "MP4V-ES";
1161             id->pf_packetize = rtp_packetize_split;
1162             if( p_fmt->i_extra > 0 )
1163             {
1164                 sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
1165                 if( asprintf( &id->psz_fmtp,
1166                               "profile-level-id=3; config=%s;", hexa ) == -1 )
1167                     id->psz_fmtp = NULL;
1168             }
1169             break;
1170         }
1171         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
1172         {
1173             if(!p_sys->b_latm)
1174             {
1175                 char hexa[2*p_fmt->i_extra +1];
1176
1177                 id->psz_enc = "mpeg4-generic";
1178                 id->pf_packetize = rtp_packetize_mp4a;
1179                 sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
1180                 if( asprintf( &id->psz_fmtp,
1181                               "streamtype=5; profile-level-id=15; "
1182                               "mode=AAC-hbr; config=%s; SizeLength=13; "
1183                               "IndexLength=3; IndexDeltaLength=3; Profile=1;",
1184                               hexa ) == -1 )
1185                     id->psz_fmtp = NULL;
1186             }
1187             else
1188             {
1189                 char hexa[13];
1190                 int i;
1191                 unsigned char config[6];
1192                 unsigned int aacsrates[15] = {
1193                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1194                     16000, 12000, 11025, 8000, 7350, 0, 0 };
1195
1196                 for( i = 0; i < 15; i++ )
1197                     if( p_fmt->audio.i_rate == aacsrates[i] )
1198                         break;
1199
1200                 config[0]=0x40;
1201                 config[1]=0;
1202                 config[2]=0x20|i;
1203                 config[3]=p_fmt->audio.i_channels<<4;
1204                 config[4]=0x3f;
1205                 config[5]=0xc0;
1206
1207                 id->psz_enc = "MP4A-LATM";
1208                 id->pf_packetize = rtp_packetize_mp4a_latm;
1209                 sprintf_hexa( hexa, config, 6 );
1210                 if( asprintf( &id->psz_fmtp, "profile-level-id=15; "
1211                               "object=2; cpresent=0; config=%s", hexa ) == -1 )
1212                     id->psz_fmtp = NULL;
1213             }
1214             break;
1215         }
1216         case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1217             id->psz_enc = "AMR";
1218             id->psz_fmtp = strdup( "octet-align=1" );
1219             id->pf_packetize = rtp_packetize_amr;
1220             break;
1221         case VLC_FOURCC( 's', 'a', 'w', 'b' ):
1222             id->psz_enc = "AMR-WB";
1223             id->psz_fmtp = strdup( "octet-align=1" );
1224             id->pf_packetize = rtp_packetize_amr;
1225             break;
1226         case VLC_FOURCC( 's', 'p', 'x', ' ' ):
1227             id->i_payload_type = p_sys->i_payload_type++;
1228             id->psz_enc = "SPEEX";
1229             id->pf_packetize = rtp_packetize_spx;
1230             break;
1231         case VLC_FOURCC( 't', '1', '4', '0' ):
1232             id->psz_enc = "t140" ;
1233             id->i_clock_rate = 1000;
1234             id->pf_packetize = rtp_packetize_t140;
1235             break;
1236
1237         default:
1238             msg_Err( p_stream, "cannot add this stream (unsupported "
1239                      "codec:%4.4s)", (char*)&p_fmt->i_codec );
1240             goto error;
1241     }
1242
1243     if( cscov != -1 )
1244         cscov += 8 /* UDP */ + 12 /* RTP */;
1245     if( id->sinkc > 0 )
1246         net_SetCSCov( id->sinkv[0].rtp_fd, cscov, -1 );
1247
1248     if( id->i_payload_type == p_sys->i_payload_type )
1249         p_sys->i_payload_type++;
1250
1251     if( p_sys->rtsp != NULL )
1252         id->rtsp_id = RtspAddId( p_sys->rtsp, id, p_sys->i_es,
1253                                  GetDWBE( id->ssrc ),
1254                                  p_sys->psz_destination,
1255                                  p_sys->i_ttl, id->i_port, id->i_port + 1 );
1256
1257     id->p_fifo = block_FifoNew();
1258     if( vlc_thread_create( id, "RTP send thread", ThreadSend,
1259                            VLC_THREAD_PRIORITY_HIGHEST, false ) )
1260         goto error;
1261
1262     /* Update p_sys context */
1263     vlc_mutex_lock( &p_sys->lock_es );
1264     TAB_APPEND( p_sys->i_es, p_sys->es, id );
1265     vlc_mutex_unlock( &p_sys->lock_es );
1266
1267     psz_sdp = SDPGenerate( p_stream, NULL );
1268
1269     vlc_mutex_lock( &p_sys->lock_sdp );
1270     free( p_sys->psz_sdp );
1271     p_sys->psz_sdp = psz_sdp;
1272     vlc_mutex_unlock( &p_sys->lock_sdp );
1273
1274     msg_Dbg( p_stream, "sdp=\n%s", p_sys->psz_sdp );
1275
1276     /* Update SDP (sap/file) */
1277     if( p_sys->b_export_sap ) SapSetup( p_stream );
1278     if( p_sys->b_export_sdp_file ) FileSetup( p_stream );
1279
1280     return id;
1281
1282 error:
1283     Del( p_stream, id );
1284     return NULL;
1285 }
1286
1287 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
1288 {
1289     sout_stream_sys_t *p_sys = p_stream->p_sys;
1290
1291     if( id->p_fifo != NULL )
1292     {
1293         vlc_object_kill( id );
1294         vlc_thread_join( id );
1295         block_FifoRelease( id->p_fifo );
1296     }
1297
1298     vlc_mutex_lock( &p_sys->lock_es );
1299     TAB_REMOVE( p_sys->i_es, p_sys->es, id );
1300     vlc_mutex_unlock( &p_sys->lock_es );
1301
1302     /* Release port */
1303     if( id->i_port == var_GetInteger( p_stream, "port-audio" ) )
1304         p_sys->i_port_audio = id->i_port;
1305     if( id->i_port == var_GetInteger( p_stream, "port-video" ) )
1306         p_sys->i_port_video = id->i_port;
1307
1308     free( id->psz_fmtp );
1309
1310     if( id->rtsp_id )
1311         RtspDelId( p_sys->rtsp, id->rtsp_id );
1312     if( id->sinkc > 0 )
1313         rtp_del_sink( id, id->sinkv[0].rtp_fd ); /* sink for explicit dst= */
1314     if( id->listen_fd != NULL )
1315         net_ListenClose( id->listen_fd );
1316     if( id->srtp != NULL )
1317         srtp_destroy( id->srtp );
1318
1319     vlc_mutex_destroy( &id->lock_sink );
1320
1321     /* Update SDP (sap/file) */
1322     if( p_sys->b_export_sap && !p_sys->p_mux ) SapSetup( p_stream );
1323     if( p_sys->b_export_sdp_file ) FileSetup( p_stream );
1324
1325     vlc_object_detach( id );
1326     vlc_object_release( id );
1327     return VLC_SUCCESS;
1328 }
1329
1330 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
1331                  block_t *p_buffer )
1332 {
1333     block_t *p_next;
1334
1335     assert( p_stream->p_sys->p_mux == NULL );
1336     (void)p_stream;
1337
1338     while( p_buffer != NULL )
1339     {
1340         p_next = p_buffer->p_next;
1341         if( id->pf_packetize( id, p_buffer ) )
1342             break;
1343
1344         block_Release( p_buffer );
1345         p_buffer = p_next;
1346     }
1347     return VLC_SUCCESS;
1348 }
1349
1350 /****************************************************************************
1351  * SAP:
1352  ****************************************************************************/
1353 static int SapSetup( sout_stream_t *p_stream )
1354 {
1355     sout_stream_sys_t *p_sys = p_stream->p_sys;
1356     sout_instance_t   *p_sout = p_stream->p_sout;
1357
1358     /* Remove the previous session */
1359     if( p_sys->p_session != NULL)
1360     {
1361         sout_AnnounceUnRegister( p_sout, p_sys->p_session);
1362         p_sys->p_session = NULL;
1363     }
1364
1365     if( ( p_sys->i_es > 0 || p_sys->p_mux ) && p_sys->psz_sdp && *p_sys->psz_sdp )
1366     {
1367         announce_method_t *p_method = sout_SAPMethod();
1368         p_sys->p_session = sout_AnnounceRegisterSDP( p_sout,
1369                                                      p_sys->psz_sdp,
1370                                                      p_sys->psz_destination,
1371                                                      p_method );
1372         sout_MethodRelease( p_method );
1373     }
1374
1375     return VLC_SUCCESS;
1376 }
1377
1378 /****************************************************************************
1379 * File:
1380 ****************************************************************************/
1381 static int FileSetup( sout_stream_t *p_stream )
1382 {
1383     sout_stream_sys_t *p_sys = p_stream->p_sys;
1384     FILE            *f;
1385
1386     if( ( f = utf8_fopen( p_sys->psz_sdp_file, "wt" ) ) == NULL )
1387     {
1388         msg_Err( p_stream, "cannot open file '%s' (%m)",
1389                  p_sys->psz_sdp_file );
1390         return VLC_EGENERIC;
1391     }
1392
1393     fputs( p_sys->psz_sdp, f );
1394     fclose( f );
1395
1396     return VLC_SUCCESS;
1397 }
1398
1399 /****************************************************************************
1400  * HTTP:
1401  ****************************************************************************/
1402 static int  HttpCallback( httpd_file_sys_t *p_args,
1403                           httpd_file_t *, uint8_t *p_request,
1404                           uint8_t **pp_data, int *pi_data );
1405
1406 static int HttpSetup( sout_stream_t *p_stream, const vlc_url_t *url)
1407 {
1408     sout_stream_sys_t *p_sys = p_stream->p_sys;
1409
1410     p_sys->p_httpd_host = httpd_HostNew( VLC_OBJECT(p_stream), url->psz_host,
1411                                          url->i_port > 0 ? url->i_port : 80 );
1412     if( p_sys->p_httpd_host )
1413     {
1414         p_sys->p_httpd_file = httpd_FileNew( p_sys->p_httpd_host,
1415                                              url->psz_path ? url->psz_path : "/",
1416                                              "application/sdp",
1417                                              NULL, NULL, NULL,
1418                                              HttpCallback, (void*)p_sys );
1419     }
1420     if( p_sys->p_httpd_file == NULL )
1421     {
1422         return VLC_EGENERIC;
1423     }
1424     return VLC_SUCCESS;
1425 }
1426
1427 static int  HttpCallback( httpd_file_sys_t *p_args,
1428                           httpd_file_t *f, uint8_t *p_request,
1429                           uint8_t **pp_data, int *pi_data )
1430 {
1431     VLC_UNUSED(f); VLC_UNUSED(p_request);
1432     sout_stream_sys_t *p_sys = (sout_stream_sys_t*)p_args;
1433
1434     vlc_mutex_lock( &p_sys->lock_sdp );
1435     if( p_sys->psz_sdp && *p_sys->psz_sdp )
1436     {
1437         *pi_data = strlen( p_sys->psz_sdp );
1438         *pp_data = malloc( *pi_data );
1439         memcpy( *pp_data, p_sys->psz_sdp, *pi_data );
1440     }
1441     else
1442     {
1443         *pp_data = NULL;
1444         *pi_data = 0;
1445     }
1446     vlc_mutex_unlock( &p_sys->lock_sdp );
1447
1448     return VLC_SUCCESS;
1449 }
1450
1451 /****************************************************************************
1452  * RTP send
1453  ****************************************************************************/
1454 static void* ThreadSend( vlc_object_t *p_this )
1455 {
1456     sout_stream_id_t *id = (sout_stream_id_t *)p_this;
1457     unsigned i_caching = id->i_caching;
1458
1459     for (;;)
1460     {
1461         block_t *out = block_FifoGet( id->p_fifo );
1462         block_cleanup_push (out);
1463
1464         if( id->srtp )
1465         {   /* FIXME: this is awfully inefficient */
1466             size_t len = out->i_buffer;
1467             out = block_Realloc( out, 0, len + 10 );
1468             out->i_buffer = len;
1469
1470             int canc = vlc_savecancel ();
1471             int val = srtp_send( id->srtp, out->p_buffer, &len, len + 10 );
1472             vlc_restorecancel (canc);
1473             if( val )
1474             {
1475                 errno = val;
1476                 msg_Dbg( id, "SRTP sending error: %m" );
1477                 block_Release( out );
1478                 out = NULL;
1479             }
1480             else
1481                 out->i_buffer = len;
1482         }
1483
1484         if (out)
1485             mwait (out->i_dts + i_caching);
1486         vlc_cleanup_pop ();
1487         if (out == NULL)
1488             continue;
1489
1490         ssize_t len = out->i_buffer;
1491         int canc = vlc_savecancel ();
1492
1493         vlc_mutex_lock( &id->lock_sink );
1494         unsigned deadc = 0; /* How many dead sockets? */
1495         int deadv[id->sinkc]; /* Dead sockets list */
1496
1497         for( int i = 0; i < id->sinkc; i++ )
1498         {
1499             if( !id->srtp ) /* FIXME: SRTCP support */
1500                 SendRTCP( id->sinkv[i].rtcp, out );
1501
1502             if( send( id->sinkv[i].rtp_fd, out->p_buffer, len, 0 ) >= 0 )
1503                 continue;
1504             /* Retry sending to root out soft-errors */
1505             if( send( id->sinkv[i].rtp_fd, out->p_buffer, len, 0 ) >= 0 )
1506                 continue;
1507
1508             deadv[deadc++] = id->sinkv[i].rtp_fd;
1509         }
1510         vlc_mutex_unlock( &id->lock_sink );
1511         block_Release( out );
1512
1513         for( unsigned i = 0; i < deadc; i++ )
1514         {
1515             msg_Dbg( id, "removing socket %d", deadv[i] );
1516             rtp_del_sink( id, deadv[i] );
1517         }
1518
1519         /* Hopefully we won't overflow the SO_MAXCONN accept queue */
1520         while( id->listen_fd != NULL )
1521         {
1522             int fd = net_Accept( id, id->listen_fd, 0 );
1523             if( fd == -1 )
1524                 break;
1525             msg_Dbg( id, "adding socket %d", fd );
1526             rtp_add_sink( id, fd, true );
1527         }
1528         vlc_restorecancel (canc);
1529     }
1530     return NULL;
1531 }
1532
1533 int rtp_add_sink( sout_stream_id_t *id, int fd, bool rtcp_mux )
1534 {
1535     rtp_sink_t sink = { fd, NULL };
1536     sink.rtcp = OpenRTCP( VLC_OBJECT( id->p_stream ), fd, IPPROTO_UDP,
1537                           rtcp_mux );
1538     if( sink.rtcp == NULL )
1539         msg_Err( id, "RTCP failed!" );
1540
1541     vlc_mutex_lock( &id->lock_sink );
1542     INSERT_ELEM( id->sinkv, id->sinkc, id->sinkc, sink );
1543     vlc_mutex_unlock( &id->lock_sink );
1544     return VLC_SUCCESS;
1545 }
1546
1547 void rtp_del_sink( sout_stream_id_t *id, int fd )
1548 {
1549     rtp_sink_t sink = { fd, NULL };
1550
1551     /* NOTE: must be safe to use if fd is not included */
1552     vlc_mutex_lock( &id->lock_sink );
1553     for( int i = 0; i < id->sinkc; i++ )
1554     {
1555         if (id->sinkv[i].rtp_fd == fd)
1556         {
1557             sink = id->sinkv[i];
1558             REMOVE_ELEM( id->sinkv, id->sinkc, i );
1559             break;
1560         }
1561     }
1562     vlc_mutex_unlock( &id->lock_sink );
1563
1564     CloseRTCP( sink.rtcp );
1565     net_Close( sink.rtp_fd );
1566 }
1567
1568 uint16_t rtp_get_seq( const sout_stream_id_t *id )
1569 {
1570     /* This will return values for the next packet.
1571      * Accounting for caching would not be totally trivial. */
1572     return id->i_sequence;
1573 }
1574
1575 /* FIXME: this is pretty bad - if we remove and then insert an ES
1576  * the number will get unsynched from inside RTSP */
1577 unsigned rtp_get_num( const sout_stream_id_t *id )
1578 {
1579     sout_stream_sys_t *p_sys = id->p_stream->p_sys;
1580     int i;
1581
1582     vlc_mutex_lock( &p_sys->lock_es );
1583     for( i = 0; i < p_sys->i_es; i++ )
1584     {
1585         if( id == p_sys->es[i] )
1586             break;
1587     }
1588     vlc_mutex_unlock( &p_sys->lock_es );
1589
1590     return i;
1591 }
1592
1593
1594 void rtp_packetize_common( sout_stream_id_t *id, block_t *out,
1595                            int b_marker, int64_t i_pts )
1596 {
1597     uint32_t i_timestamp = i_pts * (int64_t)id->i_clock_rate / INT64_C(1000000);
1598
1599     out->p_buffer[0] = 0x80;
1600     out->p_buffer[1] = (b_marker?0x80:0x00)|id->i_payload_type;
1601     out->p_buffer[2] = ( id->i_sequence >> 8)&0xff;
1602     out->p_buffer[3] = ( id->i_sequence     )&0xff;
1603     out->p_buffer[4] = ( i_timestamp >> 24 )&0xff;
1604     out->p_buffer[5] = ( i_timestamp >> 16 )&0xff;
1605     out->p_buffer[6] = ( i_timestamp >>  8 )&0xff;
1606     out->p_buffer[7] = ( i_timestamp       )&0xff;
1607
1608     memcpy( out->p_buffer + 8, id->ssrc, 4 );
1609
1610     out->i_buffer = 12;
1611     id->i_sequence++;
1612 }
1613
1614 void rtp_packetize_send( sout_stream_id_t *id, block_t *out )
1615 {
1616     block_FifoPut( id->p_fifo, out );
1617 }
1618
1619 /**
1620  * @return configured max RTP payload size (including payload type-specific
1621  * headers, excluding RTP and transport headers)
1622  */
1623 size_t rtp_mtu (const sout_stream_id_t *id)
1624 {
1625     return id->i_mtu - 12;
1626 }
1627
1628 /*****************************************************************************
1629  * Non-RTP mux
1630  *****************************************************************************/
1631
1632 /** Add an ES to a non-RTP muxed stream */
1633 static sout_stream_id_t *MuxAdd( sout_stream_t *p_stream, es_format_t *p_fmt )
1634 {
1635     sout_input_t      *p_input;
1636     sout_mux_t *p_mux = p_stream->p_sys->p_mux;
1637     assert( p_mux != NULL );
1638
1639     p_input = sout_MuxAddStream( p_mux, p_fmt );
1640     if( p_input == NULL )
1641     {
1642         msg_Err( p_stream, "cannot add this stream to the muxer" );
1643         return NULL;
1644     }
1645
1646     return (sout_stream_id_t *)p_input;
1647 }
1648
1649
1650 static int MuxSend( sout_stream_t *p_stream, sout_stream_id_t *id,
1651                     block_t *p_buffer )
1652 {
1653     sout_mux_t *p_mux = p_stream->p_sys->p_mux;
1654     assert( p_mux != NULL );
1655
1656     sout_MuxSendBuffer( p_mux, (sout_input_t *)id, p_buffer );
1657     return VLC_SUCCESS;
1658 }
1659
1660
1661 /** Remove an ES from a non-RTP muxed stream */
1662 static int MuxDel( sout_stream_t *p_stream, sout_stream_id_t *id )
1663 {
1664     sout_mux_t *p_mux = p_stream->p_sys->p_mux;
1665     assert( p_mux != NULL );
1666
1667     sout_MuxDeleteStream( p_mux, (sout_input_t *)id );
1668     return VLC_SUCCESS;
1669 }
1670
1671
1672 static ssize_t AccessOutGrabberWriteBuffer( sout_stream_t *p_stream,
1673                                             const block_t *p_buffer )
1674 {
1675     sout_stream_sys_t *p_sys = p_stream->p_sys;
1676     sout_stream_id_t *id = p_sys->es[0];
1677
1678     int64_t  i_dts = p_buffer->i_dts;
1679
1680     uint8_t         *p_data = p_buffer->p_buffer;
1681     size_t          i_data  = p_buffer->i_buffer;
1682     size_t          i_max   = id->i_mtu - 12;
1683
1684     size_t i_packet = ( p_buffer->i_buffer + i_max - 1 ) / i_max;
1685
1686     while( i_data > 0 )
1687     {
1688         size_t i_size;
1689
1690         /* output complete packet */
1691         if( p_sys->packet &&
1692             p_sys->packet->i_buffer + i_data > i_max )
1693         {
1694             rtp_packetize_send( id, p_sys->packet );
1695             p_sys->packet = NULL;
1696         }
1697
1698         if( p_sys->packet == NULL )
1699         {
1700             /* allocate a new packet */
1701             p_sys->packet = block_New( p_stream, id->i_mtu );
1702             rtp_packetize_common( id, p_sys->packet, 1, i_dts );
1703             p_sys->packet->i_dts = i_dts;
1704             p_sys->packet->i_length = p_buffer->i_length / i_packet;
1705             i_dts += p_sys->packet->i_length;
1706         }
1707
1708         i_size = __MIN( i_data,
1709                         (unsigned)(id->i_mtu - p_sys->packet->i_buffer) );
1710
1711         memcpy( &p_sys->packet->p_buffer[p_sys->packet->i_buffer],
1712                 p_data, i_size );
1713
1714         p_sys->packet->i_buffer += i_size;
1715         p_data += i_size;
1716         i_data -= i_size;
1717     }
1718
1719     return VLC_SUCCESS;
1720 }
1721
1722
1723 static ssize_t AccessOutGrabberWrite( sout_access_out_t *p_access,
1724                                       block_t *p_buffer )
1725 {
1726     sout_stream_t *p_stream = (sout_stream_t*)p_access->p_sys;
1727
1728     while( p_buffer )
1729     {
1730         block_t *p_next;
1731
1732         AccessOutGrabberWriteBuffer( p_stream, p_buffer );
1733
1734         p_next = p_buffer->p_next;
1735         block_Release( p_buffer );
1736         p_buffer = p_next;
1737     }
1738
1739     return VLC_SUCCESS;
1740 }
1741
1742
1743 static sout_access_out_t *GrabberCreate( sout_stream_t *p_stream )
1744 {
1745     sout_access_out_t *p_grab;
1746
1747     p_grab = vlc_object_create( p_stream->p_sout, sizeof( *p_grab ) );
1748     if( p_grab == NULL )
1749         return NULL;
1750
1751     p_grab->p_module    = NULL;
1752     p_grab->psz_access  = strdup( "grab" );
1753     p_grab->p_cfg       = NULL;
1754     p_grab->psz_path    = strdup( "" );
1755     p_grab->p_sys       = (sout_access_out_sys_t *)p_stream;
1756     p_grab->pf_seek     = NULL;
1757     p_grab->pf_write    = AccessOutGrabberWrite;
1758     vlc_object_attach( p_grab, p_stream );
1759     return p_grab;
1760 }