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