]> git.sesse.net Git - vlc/blob - modules/stream_out/rtp.c
RTP sout: fix buffer size for SRTP
[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 (0 = 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", 0, 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 *, 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 == 0 )
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, 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     }
1018     else
1019     switch( p_fmt->i_codec )
1020     {
1021         case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1022             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 8000 )
1023                 id->i_payload_type = 0;
1024             id->psz_enc = "PCMU";
1025             id->pf_packetize = rtp_packetize_split;
1026             rtp_set_ptime (id, 20, 1);
1027             break;
1028         case VLC_FOURCC( 'a', 'l', 'a', 'w' ):
1029             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 8000 )
1030                 id->i_payload_type = 8;
1031             id->psz_enc = "PCMA";
1032             id->pf_packetize = rtp_packetize_split;
1033             rtp_set_ptime (id, 20, 1);
1034             break;
1035         case VLC_FOURCC( 's', '1', '6', 'b' ):
1036             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 44100 )
1037             {
1038                 id->i_payload_type = 11;
1039             }
1040             else if( p_fmt->audio.i_channels == 2 &&
1041                      p_fmt->audio.i_rate == 44100 )
1042             {
1043                 id->i_payload_type = 10;
1044             }
1045             id->psz_enc = "L16";
1046             id->pf_packetize = rtp_packetize_split;
1047             rtp_set_ptime (id, 20, 2);
1048             break;
1049         case VLC_FOURCC( 'u', '8', ' ', ' ' ):
1050             id->psz_enc = "L8";
1051             id->pf_packetize = rtp_packetize_split;
1052             rtp_set_ptime (id, 20, 1);
1053             break;
1054         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
1055         case VLC_FOURCC( 'm', 'p', '3', ' ' ):
1056             id->i_payload_type = 14;
1057             id->psz_enc = "MPA";
1058             id->pf_packetize = rtp_packetize_mpa;
1059             break;
1060         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
1061             id->i_payload_type = 32;
1062             id->psz_enc = "MPV";
1063             id->pf_packetize = rtp_packetize_mpv;
1064             break;
1065         case VLC_FOURCC( 'a', '5', '2', ' ' ):
1066             id->psz_enc = "ac3";
1067             id->pf_packetize = rtp_packetize_ac3;
1068             break;
1069         case VLC_FOURCC( 'H', '2', '6', '3' ):
1070             id->psz_enc = "H263-1998";
1071             id->pf_packetize = rtp_packetize_h263;
1072             break;
1073         case VLC_FOURCC( 'h', '2', '6', '4' ):
1074             id->psz_enc = "H264";
1075             id->pf_packetize = rtp_packetize_h264;
1076             id->psz_fmtp = NULL;
1077
1078             if( p_fmt->i_extra > 0 )
1079             {
1080                 uint8_t *p_buffer = p_fmt->p_extra;
1081                 int     i_buffer = p_fmt->i_extra;
1082                 char    *p_64_sps = NULL;
1083                 char    *p_64_pps = NULL;
1084                 char    hexa[6+1];
1085
1086                 while( i_buffer > 4 &&
1087                        p_buffer[0] == 0 && p_buffer[1] == 0 &&
1088                        p_buffer[2] == 0 && p_buffer[3] == 1 )
1089                 {
1090                     const int i_nal_type = p_buffer[4]&0x1f;
1091                     int i_offset;
1092                     int i_size      = 0;
1093
1094                     msg_Dbg( p_stream, "we found a startcode for NAL with TYPE:%d", i_nal_type );
1095
1096                     i_size = i_buffer;
1097                     for( i_offset = 4; i_offset+3 < i_buffer ; i_offset++)
1098                     {
1099                         if( !memcmp (p_buffer + i_offset, "\x00\x00\x00\x01", 4 ) )
1100                         {
1101                             /* we found another startcode */
1102                             i_size = i_offset;
1103                             break;
1104                         }
1105                     }
1106                     if( i_nal_type == 7 )
1107                     {
1108                         p_64_sps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
1109                         sprintf_hexa( hexa, &p_buffer[5], 3 );
1110                     }
1111                     else if( i_nal_type == 8 )
1112                     {
1113                         p_64_pps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
1114                     }
1115                     i_buffer -= i_size;
1116                     p_buffer += i_size;
1117                 }
1118                 /* */
1119                 if( p_64_sps && p_64_pps &&
1120                     ( asprintf( &id->psz_fmtp,
1121                                 "packetization-mode=1;profile-level-id=%s;"
1122                                 "sprop-parameter-sets=%s,%s;", hexa, p_64_sps,
1123                                 p_64_pps ) == -1 ) )
1124                     id->psz_fmtp = NULL;
1125                 free( p_64_sps );
1126                 free( p_64_pps );
1127             }
1128             if( !id->psz_fmtp )
1129                 id->psz_fmtp = strdup( "packetization-mode=1" );
1130             break;
1131
1132         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
1133         {
1134             char hexa[2*p_fmt->i_extra +1];
1135
1136             id->psz_enc = "MP4V-ES";
1137             id->pf_packetize = rtp_packetize_split;
1138             if( p_fmt->i_extra > 0 )
1139             {
1140                 sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
1141                 if( asprintf( &id->psz_fmtp,
1142                               "profile-level-id=3; config=%s;", hexa ) == -1 )
1143                     id->psz_fmtp = NULL;
1144             }
1145             break;
1146         }
1147         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
1148         {
1149             if(!p_sys->b_latm)
1150             {
1151                 char hexa[2*p_fmt->i_extra +1];
1152
1153                 id->psz_enc = "mpeg4-generic";
1154                 id->pf_packetize = rtp_packetize_mp4a;
1155                 sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
1156                 if( asprintf( &id->psz_fmtp,
1157                               "streamtype=5; profile-level-id=15; "
1158                               "mode=AAC-hbr; config=%s; SizeLength=13; "
1159                               "IndexLength=3; IndexDeltaLength=3; Profile=1;",
1160                               hexa ) == -1 )
1161                     id->psz_fmtp = NULL;
1162             }
1163             else
1164             {
1165                 char hexa[13];
1166                 int i;
1167                 unsigned char config[6];
1168                 unsigned int aacsrates[15] = {
1169                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1170                     16000, 12000, 11025, 8000, 7350, 0, 0 };
1171
1172                 for( i = 0; i < 15; i++ )
1173                     if( p_fmt->audio.i_rate == aacsrates[i] )
1174                         break;
1175
1176                 config[0]=0x40;
1177                 config[1]=0;
1178                 config[2]=0x20|i;
1179                 config[3]=p_fmt->audio.i_channels<<4;
1180                 config[4]=0x3f;
1181                 config[5]=0xc0;
1182
1183                 id->psz_enc = "MP4A-LATM";
1184                 id->pf_packetize = rtp_packetize_mp4a_latm;
1185                 sprintf_hexa( hexa, config, 6 );
1186                 if( asprintf( &id->psz_fmtp, "profile-level-id=15; "
1187                               "object=2; cpresent=0; config=%s", hexa ) == -1 )
1188                     id->psz_fmtp = NULL;
1189             }
1190             break;
1191         }
1192         case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1193             id->psz_enc = "AMR";
1194             id->psz_fmtp = strdup( "octet-align=1" );
1195             id->pf_packetize = rtp_packetize_amr;
1196             break;
1197         case VLC_FOURCC( 's', 'a', 'w', 'b' ):
1198             id->psz_enc = "AMR-WB";
1199             id->psz_fmtp = strdup( "octet-align=1" );
1200             id->pf_packetize = rtp_packetize_amr;
1201             break;
1202         case VLC_FOURCC( 's', 'p', 'x', ' ' ):
1203             id->i_payload_type = p_sys->i_payload_type++;
1204             id->psz_enc = "SPEEX";
1205             id->pf_packetize = rtp_packetize_spx;
1206             break;
1207         case VLC_FOURCC( 't', '1', '4', '0' ):
1208             id->psz_enc = "t140" ;
1209             id->i_clock_rate = 1000;
1210             id->pf_packetize = rtp_packetize_t140;
1211             break;
1212
1213         default:
1214             msg_Err( p_stream, "cannot add this stream (unsupported "
1215                      "codec:%4.4s)", (char*)&p_fmt->i_codec );
1216             goto error;
1217     }
1218
1219     if( cscov != -1 )
1220         cscov += 8 /* UDP */ + 12 /* RTP */;
1221     if( id->sinkc > 0 )
1222         net_SetCSCov( id->sinkv[0].rtp_fd, cscov, -1 );
1223
1224     if( id->i_payload_type == p_sys->i_payload_type )
1225         p_sys->i_payload_type++;
1226
1227     if( p_sys->rtsp != NULL )
1228         id->rtsp_id = RtspAddId( p_sys->rtsp, id, p_sys->i_es,
1229                                  GetDWBE( id->ssrc ),
1230                                  p_sys->psz_destination,
1231                                  p_sys->i_ttl, id->i_port, id->i_port + 1 );
1232
1233     id->p_fifo = block_FifoNew();
1234     if( vlc_thread_create( id, "RTP send thread", ThreadSend,
1235                            VLC_THREAD_PRIORITY_HIGHEST, false ) )
1236         goto error;
1237
1238     /* Update p_sys context */
1239     vlc_mutex_lock( &p_sys->lock_es );
1240     TAB_APPEND( p_sys->i_es, p_sys->es, id );
1241     vlc_mutex_unlock( &p_sys->lock_es );
1242
1243     psz_sdp = SDPGenerate( p_stream, NULL );
1244
1245     vlc_mutex_lock( &p_sys->lock_sdp );
1246     free( p_sys->psz_sdp );
1247     p_sys->psz_sdp = psz_sdp;
1248     vlc_mutex_unlock( &p_sys->lock_sdp );
1249
1250     msg_Dbg( p_stream, "sdp=\n%s", p_sys->psz_sdp );
1251
1252     /* Update SDP (sap/file) */
1253     if( p_sys->b_export_sap ) SapSetup( p_stream );
1254     if( p_sys->b_export_sdp_file ) FileSetup( p_stream );
1255
1256     return id;
1257
1258 error:
1259     Del( p_stream, id );
1260     return NULL;
1261 }
1262
1263 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
1264 {
1265     sout_stream_sys_t *p_sys = p_stream->p_sys;
1266
1267     if( id->p_fifo != NULL )
1268     {
1269         vlc_object_kill( id );
1270         block_FifoWake( id->p_fifo );
1271         vlc_thread_join( id );
1272         block_FifoRelease( id->p_fifo );
1273     }
1274
1275     vlc_mutex_lock( &p_sys->lock_es );
1276     TAB_REMOVE( p_sys->i_es, p_sys->es, id );
1277     vlc_mutex_unlock( &p_sys->lock_es );
1278
1279     /* Release port */
1280     if( id->i_port == var_GetInteger( p_stream, "port-audio" ) )
1281         p_sys->i_port_audio = id->i_port;
1282     if( id->i_port == var_GetInteger( p_stream, "port-video" ) )
1283         p_sys->i_port_video = id->i_port;
1284
1285     free( id->psz_fmtp );
1286
1287     if( id->rtsp_id )
1288         RtspDelId( p_sys->rtsp, id->rtsp_id );
1289     if( id->sinkc > 0 )
1290         rtp_del_sink( id, id->sinkv[0].rtp_fd ); /* sink for explicit dst= */
1291     if( id->listen_fd != NULL )
1292         net_ListenClose( id->listen_fd );
1293     if( id->srtp != NULL )
1294         srtp_destroy( id->srtp );
1295
1296     vlc_mutex_destroy( &id->lock_sink );
1297
1298     /* Update SDP (sap/file) */
1299     if( p_sys->b_export_sap && !p_sys->p_mux ) SapSetup( p_stream );
1300     if( p_sys->b_export_sdp_file ) FileSetup( p_stream );
1301
1302     vlc_object_detach( id );
1303     vlc_object_release( id );
1304     return VLC_SUCCESS;
1305 }
1306
1307 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
1308                  block_t *p_buffer )
1309 {
1310     block_t *p_next;
1311
1312     assert( p_stream->p_sys->p_mux == NULL );
1313
1314     while( p_buffer != NULL )
1315     {
1316         p_next = p_buffer->p_next;
1317         if( id->pf_packetize( id, p_buffer ) )
1318             break;
1319
1320         block_Release( p_buffer );
1321         p_buffer = p_next;
1322     }
1323     return VLC_SUCCESS;
1324 }
1325
1326 /****************************************************************************
1327  * SAP:
1328  ****************************************************************************/
1329 static int SapSetup( sout_stream_t *p_stream )
1330 {
1331     sout_stream_sys_t *p_sys = p_stream->p_sys;
1332     sout_instance_t   *p_sout = p_stream->p_sout;
1333
1334     /* Remove the previous session */
1335     if( p_sys->p_session != NULL)
1336     {
1337         sout_AnnounceUnRegister( p_sout, p_sys->p_session);
1338         p_sys->p_session = NULL;
1339     }
1340
1341     if( ( p_sys->i_es > 0 || p_sys->p_mux ) && p_sys->psz_sdp && *p_sys->psz_sdp )
1342     {
1343         announce_method_t *p_method = sout_SAPMethod();
1344         p_sys->p_session = sout_AnnounceRegisterSDP( p_sout,
1345                                                      p_sys->psz_sdp,
1346                                                      p_sys->psz_destination,
1347                                                      p_method );
1348         sout_MethodRelease( p_method );
1349     }
1350
1351     return VLC_SUCCESS;
1352 }
1353
1354 /****************************************************************************
1355 * File:
1356 ****************************************************************************/
1357 static int FileSetup( sout_stream_t *p_stream )
1358 {
1359     sout_stream_sys_t *p_sys = p_stream->p_sys;
1360     FILE            *f;
1361
1362     if( ( f = utf8_fopen( p_sys->psz_sdp_file, "wt" ) ) == NULL )
1363     {
1364         msg_Err( p_stream, "cannot open file '%s' (%m)",
1365                  p_sys->psz_sdp_file );
1366         return VLC_EGENERIC;
1367     }
1368
1369     fputs( p_sys->psz_sdp, f );
1370     fclose( f );
1371
1372     return VLC_SUCCESS;
1373 }
1374
1375 /****************************************************************************
1376  * HTTP:
1377  ****************************************************************************/
1378 static int  HttpCallback( httpd_file_sys_t *p_args,
1379                           httpd_file_t *, uint8_t *p_request,
1380                           uint8_t **pp_data, int *pi_data );
1381
1382 static int HttpSetup( sout_stream_t *p_stream, const vlc_url_t *url)
1383 {
1384     sout_stream_sys_t *p_sys = p_stream->p_sys;
1385
1386     p_sys->p_httpd_host = httpd_HostNew( VLC_OBJECT(p_stream), url->psz_host,
1387                                          url->i_port > 0 ? url->i_port : 80 );
1388     if( p_sys->p_httpd_host )
1389     {
1390         p_sys->p_httpd_file = httpd_FileNew( p_sys->p_httpd_host,
1391                                              url->psz_path ? url->psz_path : "/",
1392                                              "application/sdp",
1393                                              NULL, NULL, NULL,
1394                                              HttpCallback, (void*)p_sys );
1395     }
1396     if( p_sys->p_httpd_file == NULL )
1397     {
1398         return VLC_EGENERIC;
1399     }
1400     return VLC_SUCCESS;
1401 }
1402
1403 static int  HttpCallback( httpd_file_sys_t *p_args,
1404                           httpd_file_t *f, uint8_t *p_request,
1405                           uint8_t **pp_data, int *pi_data )
1406 {
1407     VLC_UNUSED(f); VLC_UNUSED(p_request);
1408     sout_stream_sys_t *p_sys = (sout_stream_sys_t*)p_args;
1409
1410     vlc_mutex_lock( &p_sys->lock_sdp );
1411     if( p_sys->psz_sdp && *p_sys->psz_sdp )
1412     {
1413         *pi_data = strlen( p_sys->psz_sdp );
1414         *pp_data = malloc( *pi_data );
1415         memcpy( *pp_data, p_sys->psz_sdp, *pi_data );
1416     }
1417     else
1418     {
1419         *pp_data = NULL;
1420         *pi_data = 0;
1421     }
1422     vlc_mutex_unlock( &p_sys->lock_sdp );
1423
1424     return VLC_SUCCESS;
1425 }
1426
1427 /****************************************************************************
1428  * RTP send
1429  ****************************************************************************/
1430 static void ThreadSend( vlc_object_t *p_this )
1431 {
1432     sout_stream_id_t *id = (sout_stream_id_t *)p_this;
1433     unsigned i_caching = id->i_caching;
1434
1435     while( !id->b_die )
1436     {
1437         block_t *out = block_FifoGet( id->p_fifo );
1438         if( out == NULL )
1439             continue; /* Forced wakeup */
1440
1441         if( id->srtp )
1442         {   /* FIXME: this is awfully inefficient */
1443             size_t len = out->i_buffer;
1444             out = block_Realloc( out, 0, len + 10 );
1445             out->i_buffer = len;
1446
1447             int val = srtp_send( id->srtp, out->p_buffer, &len, len + 10 );
1448             if( val )
1449             {
1450                 errno = val;
1451                 msg_Dbg( id, "SRTP sending error: %m" );
1452                 block_Release( out );
1453                 continue;
1454             }
1455             out->i_buffer = len;
1456         }
1457
1458         mtime_t  i_date = out->i_dts + i_caching;
1459         ssize_t  len = out->i_buffer;
1460
1461         mwait( i_date );
1462
1463         vlc_mutex_lock( &id->lock_sink );
1464         unsigned deadc = 0; /* How many dead sockets? */
1465         int deadv[id->sinkc]; /* Dead sockets list */
1466
1467         for( int i = 0; i < id->sinkc; i++ )
1468         {
1469             if( !id->srtp ) /* FIXME: SRTCP support */
1470                 SendRTCP( id->sinkv[i].rtcp, out );
1471
1472             if( send( id->sinkv[i].rtp_fd, out->p_buffer, len, 0 ) >= 0 )
1473                 continue;
1474             /* Retry sending to root out soft-errors */
1475             if( send( id->sinkv[i].rtp_fd, out->p_buffer, len, 0 ) >= 0 )
1476                 continue;
1477
1478             deadv[deadc++] = id->sinkv[i].rtp_fd;
1479         }
1480         vlc_mutex_unlock( &id->lock_sink );
1481         block_Release( out );
1482
1483         for( unsigned i = 0; i < deadc; i++ )
1484         {
1485             msg_Dbg( id, "removing socket %d", deadv[i] );
1486             rtp_del_sink( id, deadv[i] );
1487         }
1488
1489         /* Hopefully we won't overflow the SO_MAXCONN accept queue */
1490         while( id->listen_fd != NULL )
1491         {
1492             int fd = net_Accept( id, id->listen_fd, 0 );
1493             if( fd == -1 )
1494                 break;
1495             msg_Dbg( id, "adding socket %d", fd );
1496             rtp_add_sink( id, fd, true );
1497         }
1498     }
1499 }
1500
1501 int rtp_add_sink( sout_stream_id_t *id, int fd, bool rtcp_mux )
1502 {
1503     rtp_sink_t sink = { fd, NULL };
1504     sink.rtcp = OpenRTCP( VLC_OBJECT( id->p_stream ), fd, IPPROTO_UDP,
1505                           rtcp_mux );
1506     if( sink.rtcp == NULL )
1507         msg_Err( id, "RTCP failed!" );
1508
1509     vlc_mutex_lock( &id->lock_sink );
1510     INSERT_ELEM( id->sinkv, id->sinkc, id->sinkc, sink );
1511     vlc_mutex_unlock( &id->lock_sink );
1512     return VLC_SUCCESS;
1513 }
1514
1515 void rtp_del_sink( sout_stream_id_t *id, int fd )
1516 {
1517     rtp_sink_t sink = { fd, NULL };
1518
1519     /* NOTE: must be safe to use if fd is not included */
1520     vlc_mutex_lock( &id->lock_sink );
1521     for( int i = 0; i < id->sinkc; i++ )
1522     {
1523         if (id->sinkv[i].rtp_fd == fd)
1524         {
1525             sink = id->sinkv[i];
1526             REMOVE_ELEM( id->sinkv, id->sinkc, i );
1527             break;
1528         }
1529     }
1530     vlc_mutex_unlock( &id->lock_sink );
1531
1532     CloseRTCP( sink.rtcp );
1533     net_Close( sink.rtp_fd );
1534 }
1535
1536 uint16_t rtp_get_seq( const sout_stream_id_t *id )
1537 {
1538     /* This will return values for the next packet.
1539      * Accounting for caching would not be totally trivial. */
1540     return id->i_sequence;
1541 }
1542
1543 /* FIXME: this is pretty bad - if we remove and then insert an ES
1544  * the number will get unsynched from inside RTSP */
1545 unsigned rtp_get_num( const sout_stream_id_t *id )
1546 {
1547     sout_stream_sys_t *p_sys = id->p_stream->p_sys;
1548     int i;
1549
1550     vlc_mutex_lock( &p_sys->lock_es );
1551     for( i = 0; i < p_sys->i_es; i++ )
1552     {
1553         if( id == p_sys->es[i] )
1554             break;
1555     }
1556     vlc_mutex_unlock( &p_sys->lock_es );
1557
1558     return i;
1559 }
1560
1561
1562 void rtp_packetize_common( sout_stream_id_t *id, block_t *out,
1563                            int b_marker, int64_t i_pts )
1564 {
1565     uint32_t i_timestamp = i_pts * (int64_t)id->i_clock_rate / INT64_C(1000000);
1566
1567     out->p_buffer[0] = 0x80;
1568     out->p_buffer[1] = (b_marker?0x80:0x00)|id->i_payload_type;
1569     out->p_buffer[2] = ( id->i_sequence >> 8)&0xff;
1570     out->p_buffer[3] = ( id->i_sequence     )&0xff;
1571     out->p_buffer[4] = ( i_timestamp >> 24 )&0xff;
1572     out->p_buffer[5] = ( i_timestamp >> 16 )&0xff;
1573     out->p_buffer[6] = ( i_timestamp >>  8 )&0xff;
1574     out->p_buffer[7] = ( i_timestamp       )&0xff;
1575
1576     memcpy( out->p_buffer + 8, id->ssrc, 4 );
1577
1578     out->i_buffer = 12;
1579     id->i_sequence++;
1580 }
1581
1582 void rtp_packetize_send( sout_stream_id_t *id, block_t *out )
1583 {
1584     block_FifoPut( id->p_fifo, out );
1585 }
1586
1587 /**
1588  * @return configured max RTP payload size (including payload type-specific
1589  * headers, excluding RTP and transport headers)
1590  */
1591 size_t rtp_mtu (const sout_stream_id_t *id)
1592 {
1593     return id->i_mtu - 12;
1594 }
1595
1596 /*****************************************************************************
1597  * Non-RTP mux
1598  *****************************************************************************/
1599
1600 /** Add an ES to a non-RTP muxed stream */
1601 static sout_stream_id_t *MuxAdd( sout_stream_t *p_stream, es_format_t *p_fmt )
1602 {
1603     sout_input_t      *p_input;
1604     sout_mux_t *p_mux = p_stream->p_sys->p_mux;
1605     assert( p_mux != NULL );
1606
1607     p_input = sout_MuxAddStream( p_mux, p_fmt );
1608     if( p_input == NULL )
1609     {
1610         msg_Err( p_stream, "cannot add this stream to the muxer" );
1611         return NULL;
1612     }
1613
1614     return (sout_stream_id_t *)p_input;
1615 }
1616
1617
1618 static int MuxSend( sout_stream_t *p_stream, sout_stream_id_t *id,
1619                     block_t *p_buffer )
1620 {
1621     sout_mux_t *p_mux = p_stream->p_sys->p_mux;
1622     assert( p_mux != NULL );
1623
1624     sout_MuxSendBuffer( p_mux, (sout_input_t *)id, p_buffer );
1625     return VLC_SUCCESS;
1626 }
1627
1628
1629 /** Remove an ES from a non-RTP muxed stream */
1630 static int MuxDel( sout_stream_t *p_stream, sout_stream_id_t *id )
1631 {
1632     sout_mux_t *p_mux = p_stream->p_sys->p_mux;
1633     assert( p_mux != NULL );
1634
1635     sout_MuxDeleteStream( p_mux, (sout_input_t *)id );
1636     return VLC_SUCCESS;
1637 }
1638
1639
1640 static int AccessOutGrabberWriteBuffer( sout_stream_t *p_stream,
1641                                         const block_t *p_buffer )
1642 {
1643     sout_stream_sys_t *p_sys = p_stream->p_sys;
1644     sout_stream_id_t *id = p_sys->es[0];
1645
1646     int64_t  i_dts = p_buffer->i_dts;
1647
1648     uint8_t         *p_data = p_buffer->p_buffer;
1649     unsigned int    i_data  = p_buffer->i_buffer;
1650     unsigned int    i_max   = id->i_mtu - 12;
1651
1652     unsigned i_packet = ( p_buffer->i_buffer + i_max - 1 ) / i_max;
1653
1654     while( i_data > 0 )
1655     {
1656         unsigned int i_size;
1657
1658         /* output complete packet */
1659         if( p_sys->packet &&
1660             p_sys->packet->i_buffer + i_data > i_max )
1661         {
1662             rtp_packetize_send( id, p_sys->packet );
1663             p_sys->packet = NULL;
1664         }
1665
1666         if( p_sys->packet == NULL )
1667         {
1668             /* allocate a new packet */
1669             p_sys->packet = block_New( p_stream, id->i_mtu );
1670             rtp_packetize_common( id, p_sys->packet, 1, i_dts );
1671             p_sys->packet->i_dts = i_dts;
1672             p_sys->packet->i_length = p_buffer->i_length / i_packet;
1673             i_dts += p_sys->packet->i_length;
1674         }
1675
1676         i_size = __MIN( i_data,
1677                         (unsigned)(id->i_mtu - p_sys->packet->i_buffer) );
1678
1679         memcpy( &p_sys->packet->p_buffer[p_sys->packet->i_buffer],
1680                 p_data, i_size );
1681
1682         p_sys->packet->i_buffer += i_size;
1683         p_data += i_size;
1684         i_data -= i_size;
1685     }
1686
1687     return VLC_SUCCESS;
1688 }
1689
1690
1691 static int AccessOutGrabberWrite( sout_access_out_t *p_access,
1692                                   block_t *p_buffer )
1693 {
1694     sout_stream_t *p_stream = (sout_stream_t*)p_access->p_sys;
1695
1696     while( p_buffer )
1697     {
1698         block_t *p_next;
1699
1700         AccessOutGrabberWriteBuffer( p_stream, p_buffer );
1701
1702         p_next = p_buffer->p_next;
1703         block_Release( p_buffer );
1704         p_buffer = p_next;
1705     }
1706
1707     return VLC_SUCCESS;
1708 }
1709
1710
1711 static sout_access_out_t *GrabberCreate( sout_stream_t *p_stream )
1712 {
1713     sout_access_out_t *p_grab;
1714
1715     p_grab = vlc_object_create( p_stream->p_sout, sizeof( *p_grab ) );
1716     if( p_grab == NULL )
1717         return NULL;
1718
1719     p_grab->p_module    = NULL;
1720     p_grab->p_sout      = p_stream->p_sout;
1721     p_grab->psz_access  = strdup( "grab" );
1722     p_grab->p_cfg       = NULL;
1723     p_grab->psz_path    = strdup( "" );
1724     p_grab->p_sys       = (sout_access_out_sys_t *)p_stream;
1725     p_grab->pf_seek     = NULL;
1726     p_grab->pf_write    = AccessOutGrabberWrite;
1727     vlc_object_attach( p_grab, p_stream );
1728     return p_grab;
1729 }