]> git.sesse.net Git - vlc/blob - modules/stream_out/rtp.c
Oups: s/getsockname/getpeername/
[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 Rémi Denis-Courmont
6  * $Id$
7  *
8  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #include <vlc/vlc.h>
30 #include <vlc_sout.h>
31 #include <vlc_block.h>
32
33 #include <vlc_httpd.h>
34 #include <vlc_url.h>
35 #include <vlc_network.h>
36 #include <vlc_charset.h>
37 #include <vlc_strings.h>
38
39 #include "rtp.h"
40
41 #ifdef HAVE_UNISTD_H
42 #   include <sys/types.h>
43 #   include <unistd.h>
44 #   include <fcntl.h>
45 #   include <sys/stat.h>
46 #endif
47
48 #include <errno.h>
49
50 /*****************************************************************************
51  * Module descriptor
52  *****************************************************************************/
53
54 #define DST_TEXT N_("Destination")
55 #define DST_LONGTEXT N_( \
56     "This is the output URL that will be used." )
57 #define SDP_TEXT N_("SDP")
58 #define SDP_LONGTEXT N_( \
59     "This allows you to specify how the SDP (Session Descriptor) for this RTP "\
60     "session will be made available. You must use an url: http://location to " \
61     "access the SDP via HTTP, rtsp://location for RTSP access, and sap:// " \
62     "for the SDP to be announced via SAP." )
63 #define MUX_TEXT N_("Muxer")
64 #define MUX_LONGTEXT N_( \
65     "This allows you to specify the muxer used for the streaming output. " \
66     "Default is to use no muxer (standard RTP stream)." )
67
68 #define NAME_TEXT N_("Session name")
69 #define NAME_LONGTEXT N_( \
70     "This is the name of the session that will be announced in the SDP " \
71     "(Session Descriptor)." )
72 #define DESC_TEXT N_("Session description")
73 #define DESC_LONGTEXT N_( \
74     "This allows you to give a broader description of the stream, that will " \
75     "be announced in the SDP (Session Descriptor)." )
76 #define URL_TEXT N_("Session URL")
77 #define URL_LONGTEXT N_( \
78     "This allows you to give an URL with more details about the stream " \
79     "(often the website of the streaming organization), that will " \
80     "be announced in the SDP (Session Descriptor)." )
81 #define EMAIL_TEXT N_("Session email")
82 #define EMAIL_LONGTEXT N_( \
83    "This allows you to give a contact mail address for the stream, that will " \
84    "be announced in the SDP (Session Descriptor)." )
85 #define PORT_TEXT N_("Port")
86 #define PORT_LONGTEXT N_( \
87     "This allows you to specify the base port for the RTP streaming." )
88 #define PORT_AUDIO_TEXT N_("Audio port")
89 #define PORT_AUDIO_LONGTEXT N_( \
90     "This allows you to specify the default audio port for the RTP streaming." )
91 #define PORT_VIDEO_TEXT N_("Video port")
92 #define PORT_VIDEO_LONGTEXT N_( \
93     "This allows you to specify the default video port for the RTP streaming." )
94
95 #define TTL_TEXT N_("Hop limit (TTL)")
96 #define TTL_LONGTEXT N_( \
97     "This is the hop limit (also known as \"Time-To-Live\" or TTL) of " \
98     "the multicast packets sent by the stream output (0 = use operating " \
99     "system built-in default).")
100
101 #define DCCP_TEXT N_("DCCP transport")
102 #define DCCP_LONGTEXT N_( \
103     "This enables DCCP instead of UDP as a transport for RTP." )
104 #define TCP_TEXT N_("TCP transport")
105 #define TCP_LONGTEXT N_( \
106     "This enables TCP instead of UDP as a transport for RTP." )
107 #define UDP_LITE_TEXT N_("UDP-Lite transport")
108 #define UDP_LITE_LONGTEXT N_( \
109     "This enables UDP-Lite instead of UDP as a transport for RTP." )
110
111 #define RFC3016_TEXT N_("MP4A LATM")
112 #define RFC3016_LONGTEXT N_( \
113     "This allows you to stream MPEG4 LATM audio streams (see RFC3016)." )
114
115 static int  Open ( vlc_object_t * );
116 static void Close( vlc_object_t * );
117
118 #define SOUT_CFG_PREFIX "sout-rtp-"
119 #define MAX_EMPTY_BLOCKS 200
120
121 vlc_module_begin();
122     set_shortname( _("RTP"));
123     set_description( _("RTP stream output") );
124     set_capability( "sout stream", 0 );
125     add_shortcut( "rtp" );
126     set_category( CAT_SOUT );
127     set_subcategory( SUBCAT_SOUT_STREAM );
128
129     add_string( SOUT_CFG_PREFIX "dst", "", NULL, DST_TEXT,
130                 DST_LONGTEXT, VLC_TRUE );
131     add_string( SOUT_CFG_PREFIX "sdp", "", NULL, SDP_TEXT,
132                 SDP_LONGTEXT, VLC_TRUE );
133     add_string( SOUT_CFG_PREFIX "mux", "", NULL, MUX_TEXT,
134                 MUX_LONGTEXT, VLC_TRUE );
135
136     add_string( SOUT_CFG_PREFIX "name", "", NULL, NAME_TEXT,
137                 NAME_LONGTEXT, VLC_TRUE );
138     add_string( SOUT_CFG_PREFIX "description", "", NULL, DESC_TEXT,
139                 DESC_LONGTEXT, VLC_TRUE );
140     add_string( SOUT_CFG_PREFIX "url", "", NULL, URL_TEXT,
141                 URL_LONGTEXT, VLC_TRUE );
142     add_string( SOUT_CFG_PREFIX "email", "", NULL, EMAIL_TEXT,
143                 EMAIL_LONGTEXT, VLC_TRUE );
144
145     add_integer( SOUT_CFG_PREFIX "port", 1234, NULL, PORT_TEXT,
146                  PORT_LONGTEXT, VLC_TRUE );
147     add_integer( SOUT_CFG_PREFIX "port-audio", 1230, NULL, PORT_AUDIO_TEXT,
148                  PORT_AUDIO_LONGTEXT, VLC_TRUE );
149     add_integer( SOUT_CFG_PREFIX "port-video", 1232, NULL, PORT_VIDEO_TEXT,
150                  PORT_VIDEO_LONGTEXT, VLC_TRUE );
151
152     add_integer( SOUT_CFG_PREFIX "ttl", 0, NULL, TTL_TEXT,
153                  TTL_LONGTEXT, VLC_TRUE );
154
155     add_bool( SOUT_CFG_PREFIX "dccp", 0, NULL,
156               DCCP_TEXT, DCCP_LONGTEXT, VLC_FALSE );
157     add_bool( SOUT_CFG_PREFIX "tcp", 0, NULL,
158               TCP_TEXT, TCP_LONGTEXT, VLC_FALSE );
159     add_bool( SOUT_CFG_PREFIX "udplite", 0, NULL,
160               UDP_LITE_TEXT, UDP_LITE_LONGTEXT, VLC_FALSE );
161
162     add_bool( SOUT_CFG_PREFIX "mp4a-latm", 0, NULL, RFC3016_TEXT,
163                  RFC3016_LONGTEXT, VLC_FALSE );
164
165     set_callbacks( Open, Close );
166 vlc_module_end();
167
168 /*****************************************************************************
169  * Exported prototypes
170  *****************************************************************************/
171 static const char *ppsz_sout_options[] = {
172     "dst", "name", "port", "port-audio", "port-video", "*sdp", "ttl", "mux",
173     "description", "url", "email",
174     "dccp", "tcp", "udplite",
175     "mp4a-latm", NULL
176 };
177
178 static sout_stream_id_t *Add ( sout_stream_t *, es_format_t * );
179 static int               Del ( sout_stream_t *, sout_stream_id_t * );
180 static int               Send( sout_stream_t *, sout_stream_id_t *,
181                                block_t* );
182 static sout_stream_id_t *MuxAdd ( sout_stream_t *, es_format_t * );
183 static int               MuxDel ( sout_stream_t *, sout_stream_id_t * );
184 static int               MuxSend( sout_stream_t *, sout_stream_id_t *,
185                                   block_t* );
186
187 static sout_access_out_t *GrabberCreate( sout_stream_t *p_sout );
188 static void ThreadSend( vlc_object_t *p_this );
189
190 static void SDPHandleUrl( sout_stream_t *, char * );
191
192 static int SapSetup( sout_stream_t *p_stream );
193 static int FileSetup( sout_stream_t *p_stream );
194 static int HttpSetup( sout_stream_t *p_stream, vlc_url_t * );
195
196 struct sout_stream_sys_t
197 {
198     /* SDP */
199     int64_t i_sdp_id;
200     int     i_sdp_version;
201     char    *psz_sdp;
202     vlc_mutex_t  lock_sdp;
203
204     char        *psz_session_name;
205     char        *psz_session_description;
206     char        *psz_session_url;
207     char        *psz_session_email;
208
209     /* SDP to disk */
210     vlc_bool_t b_export_sdp_file;
211     char *psz_sdp_file;
212
213     /* SDP via SAP */
214     vlc_bool_t b_export_sap;
215     session_descriptor_t *p_session;
216
217     /* SDP via HTTP */
218     httpd_host_t *p_httpd_host;
219     httpd_file_t *p_httpd_file;
220
221     /* RTSP */
222     rtsp_stream_t *rtsp;
223
224     /* */
225     char     *psz_destination;
226     uint8_t   proto;
227     uint8_t   i_ttl;
228     uint16_t  i_port;
229     uint16_t  i_port_audio;
230     uint16_t  i_port_video;
231     vlc_bool_t b_latm;
232
233     /* when need to use a private one or when using muxer */
234     int i_payload_type;
235
236     /* in case we do TS/PS over rtp */
237     sout_mux_t        *p_mux;
238     sout_access_out_t *p_grab;
239     block_t           *packet;
240
241     /* */
242     vlc_mutex_t      lock_es;
243     int              i_es;
244     sout_stream_id_t **es;
245 };
246
247 typedef int (*pf_rtp_packetizer_t)( sout_stream_t *, sout_stream_id_t *,
248                                     block_t * );
249
250 typedef struct rtp_sink_t
251 {
252     int rtp_fd;
253     rtcp_sender_t *rtcp;
254 } rtp_sink_t;
255
256 struct sout_stream_id_t
257 {
258     VLC_COMMON_MEMBERS
259
260     sout_stream_t *p_stream;
261     /* rtp field */
262     uint32_t    i_timestamp_start;
263     uint16_t    i_sequence;
264     uint8_t     i_payload_type;
265     uint8_t     ssrc[4];
266
267     /* for sdp */
268     char        *psz_rtpmap;
269     char        *psz_fmtp;
270     int          i_clock_rate;
271     int          i_port;
272     int          i_cat;
273     int          i_bitrate;
274
275     /* Packetizer specific fields */
276     pf_rtp_packetizer_t pf_packetize;
277     int          i_mtu;
278
279     /* Packets sinks */
280     vlc_mutex_t       lock_sink;
281     int               sinkc;
282     rtp_sink_t       *sinkv;
283     rtsp_stream_id_t *rtsp_id;
284
285     block_fifo_t     *p_fifo;
286     int64_t           i_caching;
287 };
288
289
290 /*****************************************************************************
291  * Open:
292  *****************************************************************************/
293 static int Open( vlc_object_t *p_this )
294 {
295     sout_stream_t       *p_stream = (sout_stream_t*)p_this;
296     sout_instance_t     *p_sout = p_stream->p_sout;
297     sout_stream_sys_t   *p_sys = NULL;
298     config_chain_t      *p_cfg = NULL;
299     char                *psz;
300     vlc_bool_t          b_rtsp = VLC_FALSE;
301
302     config_ChainParse( p_stream, SOUT_CFG_PREFIX,
303                        ppsz_sout_options, p_stream->p_cfg );
304
305     p_sys = malloc( sizeof( sout_stream_sys_t ) );
306     if( p_sys == NULL )
307         return VLC_ENOMEM;
308
309     p_sys->psz_destination = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "dst" );
310     p_sys->psz_session_name = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "name" );
311     p_sys->psz_session_description = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "description" );
312     p_sys->psz_session_url = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "url" );
313     p_sys->psz_session_email = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "email" );
314
315     p_sys->i_port       = var_GetInteger( p_stream, SOUT_CFG_PREFIX "port" );
316     p_sys->i_port_audio = var_GetInteger( p_stream, SOUT_CFG_PREFIX "port-audio" );
317     p_sys->i_port_video = var_GetInteger( p_stream, SOUT_CFG_PREFIX "port-video" );
318
319     p_sys->psz_sdp_file = NULL;
320
321     if( p_sys->i_port_audio == p_sys->i_port_video )
322     {
323         msg_Err( p_stream, "audio and video port cannot be the same" );
324         p_sys->i_port_audio = 0;
325         p_sys->i_port_video = 0;
326     }
327
328     if( !p_sys->psz_session_name )
329     {
330         if( p_sys->psz_destination )
331             p_sys->psz_session_name = strdup( p_sys->psz_destination );
332         else
333            p_sys->psz_session_name = strdup( "NONE" );
334     }
335
336     for( p_cfg = p_stream->p_cfg; p_cfg != NULL; p_cfg = p_cfg->p_next )
337     {
338         if( !strcmp( p_cfg->psz_name, "sdp" )
339          && ( p_cfg->psz_value != NULL )
340          && !strncasecmp( p_cfg->psz_value, "rtsp:", 5 ) )
341         {
342             b_rtsp = VLC_TRUE;
343             break;
344         }
345     }
346     if( !b_rtsp )
347     {
348         psz = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "sdp" );
349         if( psz != NULL )
350         {
351             if( !strncasecmp( psz, "rtsp:", 5 ) )
352                 b_rtsp = VLC_TRUE;
353             free( psz );
354         }
355     }
356
357     /* Transport protocol */
358     p_sys->proto = IPPROTO_UDP;
359
360 #if 0
361     if( var_GetBool( p_stream, SOUT_CFG_PREFIX "dccp" ) )
362     {
363         p_sys->sotype = SOCK_DCCP;
364         p_sys->proto = 33 /*IPPROTO_DCCP*/;
365     }
366     else
367     if( var_GetBool( p_stream, SOUT_CFG_PREFIX "tcp" ) )
368     {
369         p_sys->sotype = SOCK_STREAM;
370         p_sys->proto = IPPROTO_TCP;
371     }
372     else
373 #endif
374     if( var_GetBool( p_stream, SOUT_CFG_PREFIX "udplite" ) )
375         p_sys->proto = 136 /*IPPROTO_UDPLITE*/;
376
377     if( ( p_sys->psz_destination == NULL ) && !b_rtsp )
378     {
379         msg_Err( p_stream, "missing destination and not in RTSP mode" );
380         free( p_sys );
381         return VLC_EGENERIC;
382     }
383
384     p_sys->i_ttl = var_GetInteger( p_stream, SOUT_CFG_PREFIX "ttl" );
385     if( p_sys->i_ttl == 0 )
386     {
387         /* Normally, we should let the default hop limit up to the core,
388          * but we have to know it to build our SDP properly, which is why
389          * we ask the core. FIXME: broken when neither sout-rtp-ttl nor
390          * ttl are set. */
391         p_sys->i_ttl = config_GetInt( p_stream, "ttl" );
392     }
393
394     p_sys->b_latm = var_GetBool( p_stream, SOUT_CFG_PREFIX "mp4a-latm" );
395
396     p_sys->i_payload_type = 96;
397     p_sys->i_es = 0;
398     p_sys->es   = NULL;
399     p_sys->rtsp = NULL;
400     p_sys->psz_sdp = NULL;
401
402     p_sys->i_sdp_id = mdate();
403     p_sys->i_sdp_version = 1;
404     p_sys->psz_sdp = NULL;
405
406     p_sys->b_export_sap = VLC_FALSE;
407     p_sys->b_export_sdp_file = VLC_FALSE;
408     p_sys->p_session = NULL;
409
410     p_sys->p_httpd_host = NULL;
411     p_sys->p_httpd_file = NULL;
412
413     p_stream->p_sys     = p_sys;
414
415     vlc_mutex_init( p_stream, &p_sys->lock_sdp );
416     vlc_mutex_init( p_stream, &p_sys->lock_es );
417
418     psz = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "mux" );
419     if( psz != NULL )
420     {
421         sout_stream_id_t *id;
422         const char *psz_rtpmap;
423         int i_payload_type;
424
425         /* Check muxer type */
426         if( !strncasecmp( psz, "ps", 2 )
427          || !strncasecmp( psz, "mpeg1", 5 ) )
428         {
429             psz_rtpmap = "MP2P/90000";
430         }
431         else if( !strncasecmp( psz, "ts", 2 ) )
432         {
433             psz_rtpmap = "MP2T/90000";
434             i_payload_type = 33;
435         }
436         else
437         {
438             msg_Err( p_stream, "unsupported muxer type for RTP (only TS/PS)" );
439             free( psz );
440             vlc_mutex_destroy( &p_sys->lock_sdp );
441             vlc_mutex_destroy( &p_sys->lock_es );
442             free( p_sys );
443             return VLC_EGENERIC;
444         }
445
446         p_sys->p_grab = GrabberCreate( p_stream );
447         p_sys->p_mux = sout_MuxNew( p_sout, psz, p_sys->p_grab );
448         free( psz );
449
450         if( p_sys->p_mux == NULL )
451         {
452             msg_Err( p_stream, "cannot create muxer" );
453             sout_AccessOutDelete( p_sys->p_grab );
454             vlc_mutex_destroy( &p_sys->lock_sdp );
455             vlc_mutex_destroy( &p_sys->lock_es );
456             free( p_sys );
457             return VLC_EGENERIC;
458         }
459
460         id = Add( p_stream, NULL );
461         if( id == NULL )
462         {
463             sout_MuxDelete( p_sys->p_mux );
464             sout_AccessOutDelete( p_sys->p_grab );
465             vlc_mutex_destroy( &p_sys->lock_sdp );
466             vlc_mutex_destroy( &p_sys->lock_es );
467             free( p_sys );
468             return VLC_EGENERIC;
469         }
470
471         id->psz_rtpmap = strdup( psz_rtpmap );
472         id->i_payload_type = i_payload_type;
473
474         p_sys->packet = NULL;
475
476         p_stream->pf_add  = MuxAdd;
477         p_stream->pf_del  = MuxDel;
478         p_stream->pf_send = MuxSend;
479     }
480     else
481     {
482         p_sys->p_mux    = NULL;
483         p_sys->p_grab   = NULL;
484
485         p_stream->pf_add    = Add;
486         p_stream->pf_del    = Del;
487         p_stream->pf_send   = Send;
488     }
489
490     psz = var_GetNonEmptyString( p_stream, SOUT_CFG_PREFIX "sdp" );
491     if( psz != NULL )
492     {
493         config_chain_t *p_cfg;
494
495         SDPHandleUrl( p_stream, psz );
496
497         for( p_cfg = p_stream->p_cfg; p_cfg != NULL; p_cfg = p_cfg->p_next )
498         {
499             if( !strcmp( p_cfg->psz_name, "sdp" ) )
500             {
501                 if( p_cfg->psz_value == NULL || *p_cfg->psz_value == '\0' )
502                     continue;
503
504                 /* needed both :sout-rtp-sdp= and rtp{sdp=} can be used */
505                 if( !strcmp( p_cfg->psz_value, psz ) )
506                     continue;
507
508                 SDPHandleUrl( p_stream, p_cfg->psz_value );
509             }
510         }
511         free( psz );
512     }
513
514     /* update p_sout->i_out_pace_nocontrol */
515     p_stream->p_sout->i_out_pace_nocontrol++;
516
517     return VLC_SUCCESS;
518 }
519
520 /*****************************************************************************
521  * Close:
522  *****************************************************************************/
523 static void Close( vlc_object_t * p_this )
524 {
525     sout_stream_t     *p_stream = (sout_stream_t*)p_this;
526     sout_stream_sys_t *p_sys = p_stream->p_sys;
527
528     /* update p_sout->i_out_pace_nocontrol */
529     p_stream->p_sout->i_out_pace_nocontrol--;
530
531     if( p_sys->p_mux )
532     {
533         assert( p_sys->i_es == 1 );
534         Del( p_stream, p_sys->es[0] );
535
536         sout_MuxDelete( p_sys->p_mux );
537         sout_AccessOutDelete( p_sys->p_grab );
538         if( p_sys->packet )
539         {
540             block_Release( p_sys->packet );
541         }
542         if( p_sys->b_export_sap )
543         {
544             p_sys->p_mux = NULL;
545             SapSetup( p_stream );
546         }
547     }
548
549     if( p_sys->rtsp != NULL )
550         RtspUnsetup( p_sys->rtsp );
551
552     vlc_mutex_destroy( &p_sys->lock_sdp );
553     vlc_mutex_destroy( &p_sys->lock_es );
554
555     if( p_sys->p_httpd_file )
556         httpd_FileDelete( p_sys->p_httpd_file );
557
558     if( p_sys->p_httpd_host )
559         httpd_HostDelete( p_sys->p_httpd_host );
560
561     free( p_sys->psz_session_name );
562     free( p_sys->psz_session_description );
563     free( p_sys->psz_session_url );
564     free( p_sys->psz_session_email );
565     free( p_sys->psz_sdp );
566
567     if( p_sys->b_export_sdp_file )
568     {
569 #ifdef HAVE_UNISTD_H
570         unlink( p_sys->psz_sdp_file );
571 #endif
572         free( p_sys->psz_sdp_file );
573     }
574     free( p_sys->psz_destination );
575     free( p_sys );
576 }
577
578 /*****************************************************************************
579  * SDPHandleUrl:
580  *****************************************************************************/
581 static void SDPHandleUrl( sout_stream_t *p_stream, char *psz_url )
582 {
583     sout_stream_sys_t *p_sys = p_stream->p_sys;
584     vlc_url_t url;
585
586     vlc_UrlParse( &url, psz_url, 0 );
587     if( url.psz_protocol && !strcasecmp( url.psz_protocol, "http" ) )
588     {
589         if( p_sys->p_httpd_file )
590         {
591             msg_Err( p_stream, "you can use sdp=http:// only once" );
592             goto out;
593         }
594
595         if( HttpSetup( p_stream, &url ) )
596         {
597             msg_Err( p_stream, "cannot export SDP as HTTP" );
598         }
599     }
600     else if( url.psz_protocol && !strcasecmp( url.psz_protocol, "rtsp" ) )
601     {
602         if( p_sys->rtsp != NULL )
603         {
604             msg_Err( p_stream, "you can use sdp=rtsp:// only once" );
605             goto out;
606         }
607
608         /* FIXME test if destination is multicast or no destination at all */
609         p_sys->rtsp = RtspSetup( p_stream, &url );
610         if( p_sys->rtsp == NULL )
611         {
612             msg_Err( p_stream, "cannot export SDP as RTSP" );
613         }
614
615         if( p_sys->p_mux != NULL )
616         {
617             sout_stream_id_t *id = p_sys->es[0];
618             id->rtsp_id = RtspAddId( p_sys->rtsp, id, 0,
619                                      p_sys->psz_destination, p_sys->i_ttl,
620                                      id->i_port, id->i_port + 1 );
621         }
622     }
623     else if( ( url.psz_protocol && !strcasecmp( url.psz_protocol, "sap" ) ) ||
624              ( url.psz_host && !strcasecmp( url.psz_host, "sap" ) ) )
625     {
626         p_sys->b_export_sap = VLC_TRUE;
627         SapSetup( p_stream );
628     }
629     else if( url.psz_protocol && !strcasecmp( url.psz_protocol, "file" ) )
630     {
631         if( p_sys->b_export_sdp_file )
632         {
633             msg_Err( p_stream, "you can use sdp=file:// only once" );
634             goto out;
635         }
636         p_sys->b_export_sdp_file = VLC_TRUE;
637         psz_url = &psz_url[5];
638         if( psz_url[0] == '/' && psz_url[1] == '/' )
639             psz_url += 2;
640         p_sys->psz_sdp_file = strdup( psz_url );
641     }
642     else
643     {
644         msg_Warn( p_stream, "unknown protocol for SDP (%s)",
645                   url.psz_protocol );
646     }
647
648 out:
649     vlc_UrlClean( &url );
650 }
651
652 /*****************************************************************************
653  * SDPGenerate
654  *****************************************************************************/
655         /* FIXME  http://www.faqs.org/rfcs/rfc2327.html
656            All text fields should be UTF-8 encoded. Use global a:charset to announce this.
657            o= - should be local username (no spaces allowed)
658            o= time should be hashed with some other value to garantue uniqueness
659            o= we need IP6 support?
660            o= don't use the localhost address. use fully qualified domain name or IP4 address
661            p= international phone number (pass via vars?)
662            c= IP6 support
663            a= recvonly (missing)
664            a= type:broadcast (missing)
665            a= charset: (normally charset should be UTF-8, this can be used to override s= and i=)
666            a= x-plgroup: (missing)
667            RTP packets need to get the correct src IP address  */
668 /*static*/
669 char *SDPGenerate( const sout_stream_t *p_stream, const char *rtsp_url )
670 {
671     const sout_stream_sys_t *p_sys = p_stream->p_sys;
672     char *psz_sdp;
673     struct sockaddr_storage dst;
674     socklen_t dstlen;
675     int i;
676     /*
677      * When we have a fixed destination (typically when we do multicast),
678      * we need to put the actual port numbers in the SDP.
679      * When there is no fixed destination, we only support RTSP unicast
680      * on-demand setup, so we should rather let the clients decide which ports
681      * to use.
682      * When there is both a fixed destination and RTSP unicast, we need to
683      * put port numbers used by the fixed destination, otherwise the SDP would
684      * become totally incorrect for multicast use. It should be noted that
685      * port numbers from SDP with RTSP are only "recommendation" from the
686      * server to the clients (per RFC2326), so only broken clients will fail
687      * to handle this properly. There is no solution but to use two differents
688      * output chain with two different RTSP URLs if you need to handle this
689      * scenario.
690      */
691     int inclport;
692
693     if( p_sys->psz_destination != NULL )
694     {
695         inclport = 1;
696
697         /* Oh boy, this is really ugly! (+ race condition on lock_es) */
698         dstlen = sizeof( dst );
699         getpeername( p_sys->es[0]->sinkv[0].rtp_fd, (struct sockaddr *)&dst,
700                      &dstlen );
701     }
702     else
703     {
704         inclport = 0;
705
706         /* Dummy destination address for RTSP */
707         memset (&dst, 0, sizeof( struct sockaddr_in ) );
708         dst.ss_family = AF_INET;
709 #ifdef HAVE_SA_LEN
710         dst.ss_len =
711 #endif
712         dstlen = sizeof( struct sockaddr_in );
713     }
714
715     psz_sdp = sdp_Start( p_sys->psz_session_name,
716                          p_sys->psz_session_description,
717                          p_sys->psz_session_url, p_sys->psz_session_email,
718                          NULL, NULL, 0, (struct sockaddr *)&dst, dstlen );
719     if( psz_sdp == NULL )
720         return NULL;
721
722     /* TODO: a=source-filter */
723
724     /* FIXME: locking?! */
725     for( i = 0; i < p_sys->i_es; i++ )
726     {
727         sout_stream_id_t *id = p_sys->es[i];
728         const char *mime_major; /* major MIME type */
729
730         if( id->i_cat == AUDIO_ES )
731             mime_major = "audio";
732         else
733         if( id->i_cat == VIDEO_ES )
734             mime_major = "video";
735         else
736             continue;
737
738         sdp_AddMedia( &psz_sdp, mime_major, "RTP/AVP", inclport * id->i_port,
739                      id->i_payload_type, VLC_FALSE, id->i_bitrate,
740                      id->psz_rtpmap, id->psz_fmtp);
741
742 #if 0
743         if ( id->i_bitrate )
744         {
745             p += sprintf(p,"b=AS:%d\r\n",id->i_bitrate);
746         }
747 #endif
748
749         if( rtsp_url != NULL )
750             sdp_AddAttribute ( &psz_sdp, "control", "/trackID=%d", i );
751     }
752
753     return psz_sdp;
754 }
755
756 /*****************************************************************************
757  * RTP mux
758  *****************************************************************************/
759 static int rtp_packetize_l16  ( sout_stream_t *, sout_stream_id_t *, block_t * );
760 static int rtp_packetize_l8   ( sout_stream_t *, sout_stream_id_t *, block_t * );
761 static int rtp_packetize_mpa  ( sout_stream_t *, sout_stream_id_t *, block_t * );
762 static int rtp_packetize_mpv  ( sout_stream_t *, sout_stream_id_t *, block_t * );
763 static int rtp_packetize_ac3  ( sout_stream_t *, sout_stream_id_t *, block_t * );
764 static int rtp_packetize_split( sout_stream_t *, sout_stream_id_t *, block_t * );
765 static int rtp_packetize_mp4a ( sout_stream_t *, sout_stream_id_t *, block_t * );
766 static int rtp_packetize_mp4a_latm ( sout_stream_t *, sout_stream_id_t *, block_t * );
767 static int rtp_packetize_h263 ( sout_stream_t *, sout_stream_id_t *, block_t * );
768 static int rtp_packetize_h264 ( sout_stream_t *, sout_stream_id_t *, block_t * );
769 static int rtp_packetize_amr  ( sout_stream_t *, sout_stream_id_t *, block_t * );
770
771 static void sprintf_hexa( char *s, uint8_t *p_data, int i_data )
772 {
773     static const char hex[16] = "0123456789abcdef";
774     int i;
775
776     for( i = 0; i < i_data; i++ )
777     {
778         s[2*i+0] = hex[(p_data[i]>>4)&0xf];
779         s[2*i+1] = hex[(p_data[i]   )&0xf];
780     }
781     s[2*i_data] = '\0';
782 }
783
784
785 /** Add an ES as a new RTP stream */
786 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
787 {
788     /* NOTE: As a special case, if we use a non-RTP
789      * mux (TS/PS), then p_fmt is NULL. */
790     sout_stream_sys_t *p_sys = p_stream->p_sys;
791     sout_stream_id_t  *id;
792     int               i_port, cscov = -1;
793     char              *psz_sdp;
794
795     id = vlc_object_create( p_stream, sizeof( sout_stream_id_t ) );
796     if( id == NULL )
797         return NULL;
798
799     /* Choose the port */
800     i_port = 0;
801     if( p_fmt == NULL )
802         ;
803     else
804     if( p_fmt->i_cat == AUDIO_ES && p_sys->i_port_audio > 0 )
805     {
806         i_port = p_sys->i_port_audio;
807         p_sys->i_port_audio = 0;
808     }
809     else
810     if( p_fmt->i_cat == VIDEO_ES && p_sys->i_port_video > 0 )
811     {
812         i_port = p_sys->i_port_video;
813         p_sys->i_port_video = 0;
814     }
815
816     while( i_port == 0 )
817     {
818         if( p_sys->i_port != p_sys->i_port_audio
819          && p_sys->i_port != p_sys->i_port_video )
820         {
821             i_port = p_sys->i_port;
822             p_sys->i_port += 2;
823             break;
824         }
825         p_sys->i_port += 2;
826     }
827
828     id->p_stream   = p_stream;
829
830     id->i_timestamp_start = rand()&0xffffffff;
831     id->i_sequence = rand()&0xffff;
832     id->i_payload_type = p_sys->i_payload_type;
833     id->ssrc[0] = rand()&0xff;
834     id->ssrc[1] = rand()&0xff;
835     id->ssrc[2] = rand()&0xff;
836     id->ssrc[3] = rand()&0xff;
837
838     id->psz_rtpmap = NULL;
839     id->psz_fmtp   = NULL;
840     id->i_clock_rate = 90000; /* most common case */
841     id->i_port     = i_port;
842     if( p_fmt != NULL )
843     {
844         id->i_cat  = p_fmt->i_cat;
845         id->i_bitrate = p_fmt->i_bitrate/1000; /* Stream bitrate in kbps */
846     }
847     else
848     {
849         id->i_cat  = VIDEO_ES;
850         id->i_bitrate = 0;
851     }
852
853     id->pf_packetize = NULL;
854     id->i_mtu = config_GetInt( p_stream, "mtu" );
855     if( id->i_mtu <= 12 + 16 )
856         id->i_mtu = 576 - 20 - 8; /* pessimistic */
857
858     msg_Dbg( p_stream, "maximum RTP packet size: %d bytes", id->i_mtu );
859
860     vlc_mutex_init( p_stream, &id->lock_sink );
861     id->sinkc = 0;
862     id->sinkv = NULL;
863     id->rtsp_id = NULL;
864
865     id->i_caching =
866         (int64_t)1000 * var_GetInteger( p_stream, SOUT_CFG_PREFIX "caching");
867     id->p_fifo = block_FifoNew( p_stream );
868
869     if( vlc_thread_create( id, "RTP send thread", ThreadSend,
870                            VLC_THREAD_PRIORITY_HIGHEST, VLC_FALSE ) )
871     {
872         vlc_mutex_destroy( &id->lock_sink );
873         vlc_object_destroy( id );
874         return NULL;
875     }
876
877     if( p_sys->psz_destination != NULL )
878     {
879         int ttl = (p_sys->i_ttl > 0) ? p_sys->i_ttl : -1;
880         int fd = net_ConnectDgram( p_stream, p_sys->psz_destination,
881                                    i_port, ttl, p_sys->proto );
882
883         if( fd == -1 )
884         {
885             msg_Err( p_stream, "cannot create RTP socket" );
886             vlc_thread_join( id );
887             vlc_mutex_destroy( &id->lock_sink );
888             vlc_object_destroy( id );
889             return NULL;
890         }
891         rtp_add_sink( id, fd );
892     }
893
894     if( p_fmt == NULL )
895         ;
896     else
897     switch( p_fmt->i_codec )
898     {
899         case VLC_FOURCC( 's', '1', '6', 'b' ):
900             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 44100 )
901             {
902                 id->i_payload_type = 11;
903             }
904             else if( p_fmt->audio.i_channels == 2 &&
905                      p_fmt->audio.i_rate == 44100 )
906             {
907                 id->i_payload_type = 10;
908             }
909             if( asprintf( &id->psz_rtpmap, "L16/%d/%d", p_fmt->audio.i_rate,
910                           p_fmt->audio.i_channels ) == -1 )
911                 id->psz_rtpmap = NULL;
912             id->i_clock_rate = p_fmt->audio.i_rate;
913             id->pf_packetize = rtp_packetize_l16;
914             break;
915         case VLC_FOURCC( 'u', '8', ' ', ' ' ):
916             if( asprintf( &id->psz_rtpmap, "L8/%d/%d", p_fmt->audio.i_rate,
917                           p_fmt->audio.i_channels ) == -1 )
918                 id->psz_rtpmap = NULL;
919             id->i_clock_rate = p_fmt->audio.i_rate;
920             id->pf_packetize = rtp_packetize_l8;
921             break;
922         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
923             id->i_payload_type = 14;
924             id->psz_rtpmap = strdup( "MPA/90000" );
925             id->pf_packetize = rtp_packetize_mpa;
926             break;
927         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
928             id->i_payload_type = 32;
929             id->psz_rtpmap = strdup( "MPV/90000" );
930             id->pf_packetize = rtp_packetize_mpv;
931             break;
932         case VLC_FOURCC( 'a', '5', '2', ' ' ):
933             id->psz_rtpmap = strdup( "ac3/90000" );
934             id->pf_packetize = rtp_packetize_ac3;
935             break;
936         case VLC_FOURCC( 'H', '2', '6', '3' ):
937             id->psz_rtpmap = strdup( "H263-1998/90000" );
938             id->pf_packetize = rtp_packetize_h263;
939             break;
940         case VLC_FOURCC( 'h', '2', '6', '4' ):
941             id->psz_rtpmap = strdup( "H264/90000" );
942             id->pf_packetize = rtp_packetize_h264;
943             id->psz_fmtp = NULL;
944
945             if( p_fmt->i_extra > 0 )
946             {
947                 uint8_t *p_buffer = p_fmt->p_extra;
948                 int     i_buffer = p_fmt->i_extra;
949                 char    *p_64_sps = NULL;
950                 char    *p_64_pps = NULL;
951                 char    hexa[6+1];
952
953                 while( i_buffer > 4 &&
954                        p_buffer[0] == 0 && p_buffer[1] == 0 &&
955                        p_buffer[2] == 0 && p_buffer[3] == 1 )
956                 {
957                     const int i_nal_type = p_buffer[4]&0x1f;
958                     int i_offset;
959                     int i_size      = 0;
960
961                     msg_Dbg( p_stream, "we found a startcode for NAL with TYPE:%d", i_nal_type );
962
963                     i_size = i_buffer;
964                     for( i_offset = 4; i_offset+3 < i_buffer ; i_offset++)
965                     {
966                         if( !memcmp (p_buffer + i_offset, "\x00\x00\x00\x01", 4 ) )
967                         {
968                             /* we found another startcode */
969                             i_size = i_offset;
970                             break;
971                         }
972                     }
973                     if( i_nal_type == 7 )
974                     {
975                         p_64_sps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
976                         sprintf_hexa( hexa, &p_buffer[5], 3 );
977                     }
978                     else if( i_nal_type == 8 )
979                     {
980                         p_64_pps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
981                     }
982                     i_buffer -= i_size;
983                     p_buffer += i_size;
984                 }
985                 /* */
986                 if( p_64_sps && p_64_pps &&
987                     ( asprintf( &id->psz_fmtp,
988                                 "packetization-mode=1;profile-level-id=%s;"
989                                 "sprop-parameter-sets=%s,%s;", hexa, p_64_sps,
990                                 p_64_pps ) == -1 ) )
991                     id->psz_fmtp = NULL;
992                 free( p_64_sps );
993                 free( p_64_pps );
994             }
995             if( !id->psz_fmtp )
996                 id->psz_fmtp = strdup( "packetization-mode=1" );
997             break;
998
999         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
1000         {
1001             char hexa[2*p_fmt->i_extra +1];
1002
1003             id->psz_rtpmap = strdup( "MP4V-ES/90000" );
1004             id->pf_packetize = rtp_packetize_split;
1005             if( p_fmt->i_extra > 0 )
1006             {
1007                 sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
1008                 if( asprintf( &id->psz_fmtp,
1009                               "profile-level-id=3; config=%s;", hexa ) == -1 )
1010                     id->psz_fmtp = NULL;
1011             }
1012             break;
1013         }
1014         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
1015         {
1016             id->i_clock_rate = p_fmt->audio.i_rate;
1017
1018             if(!p_sys->b_latm)
1019             {
1020                 char hexa[2*p_fmt->i_extra +1];
1021
1022                 if( asprintf( &id->psz_rtpmap, "mpeg4-generic/%d",
1023                               p_fmt->audio.i_rate ) == -1 )
1024                     id->psz_rtpmap = NULL;
1025                 id->pf_packetize = rtp_packetize_mp4a;
1026                 sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
1027                 if( asprintf( &id->psz_fmtp,
1028                               "streamtype=5; profile-level-id=15; "
1029                               "mode=AAC-hbr; config=%s; SizeLength=13; "
1030                               "IndexLength=3; IndexDeltaLength=3; Profile=1;",
1031                               hexa ) == -1 )
1032                     id->psz_fmtp = NULL;
1033             }
1034             else
1035             {
1036                 char hexa[13];
1037                 int i;
1038                 unsigned char config[6];
1039                 unsigned int aacsrates[15] = {
1040                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1041                     16000, 12000, 11025, 8000, 7350, 0, 0 };
1042
1043                 for( i = 0; i < 15; i++ )
1044                     if( p_fmt->audio.i_rate == aacsrates[i] )
1045                         break;
1046
1047                 config[0]=0x40;
1048                 config[1]=0;
1049                 config[2]=0x20|i;
1050                 config[3]=p_fmt->audio.i_channels<<4;
1051                 config[4]=0x3f;
1052                 config[5]=0xc0;
1053
1054                 if( asprintf( &id->psz_rtpmap, "MP4A-LATM/%d/%d",
1055                               p_fmt->audio.i_rate,
1056                               p_fmt->audio.i_channels ) == -1)
1057                     id->psz_rtpmap = NULL;
1058                 id->pf_packetize = rtp_packetize_mp4a_latm;
1059                 sprintf_hexa( hexa, config, 6 );
1060                 if( asprintf( &id->psz_fmtp, "profile-level-id=15; "
1061                               "object=2; cpresent=0; config=%s", hexa ) == -1 )
1062                     id->psz_fmtp = NULL;
1063             }
1064             break;
1065         }
1066         case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1067             id->psz_rtpmap = strdup( p_fmt->audio.i_channels == 2 ?
1068                                      "AMR/8000/2" : "AMR/8000" );
1069             id->psz_fmtp = strdup( "octet-align=1" );
1070             id->i_clock_rate = p_fmt->audio.i_rate;
1071             id->pf_packetize = rtp_packetize_amr;
1072             break;
1073         case VLC_FOURCC( 's', 'a', 'w', 'b' ):
1074             id->psz_rtpmap = strdup( p_fmt->audio.i_channels == 2 ?
1075                                      "AMR-WB/16000/2" : "AMR-WB/16000" );
1076             id->psz_fmtp = strdup( "octet-align=1" );
1077             id->i_clock_rate = p_fmt->audio.i_rate;
1078             id->pf_packetize = rtp_packetize_amr;
1079             break;
1080
1081         default:
1082             msg_Err( p_stream, "cannot add this stream (unsupported "
1083                      "codec:%4.4s)", (char*)&p_fmt->i_codec );
1084             if( id->sinkc > 0 )
1085                 rtp_del_sink( id, id->sinkv[0].rtp_fd );
1086             vlc_thread_join( id );
1087             vlc_mutex_destroy( &id->lock_sink );
1088             vlc_object_destroy( id );
1089             return NULL;
1090     }
1091
1092     if( cscov != -1 )
1093         cscov += 8 /* UDP */ + 12 /* RTP */;
1094     if( id->sinkc > 0 )
1095         net_SetCSCov( id->sinkv[0].rtp_fd, cscov, -1 );
1096
1097     if( id->i_payload_type == p_sys->i_payload_type )
1098         p_sys->i_payload_type++;
1099
1100     if( p_sys->rtsp != NULL )
1101         id->rtsp_id = RtspAddId( p_sys->rtsp, id, p_sys->i_es,
1102                                  p_sys->psz_destination,
1103                                  p_sys->i_ttl, id->i_port, id->i_port + 1 );
1104
1105     /* Update p_sys context */
1106     vlc_mutex_lock( &p_sys->lock_es );
1107     TAB_APPEND( p_sys->i_es, p_sys->es, id );
1108     vlc_mutex_unlock( &p_sys->lock_es );
1109
1110     psz_sdp = SDPGenerate( p_stream, NULL );
1111
1112     vlc_mutex_lock( &p_sys->lock_sdp );
1113     free( p_sys->psz_sdp );
1114     p_sys->psz_sdp = psz_sdp;
1115     vlc_mutex_unlock( &p_sys->lock_sdp );
1116
1117     p_sys->i_sdp_version++;
1118
1119     msg_Dbg( p_stream, "sdp=\n%s", p_sys->psz_sdp );
1120
1121     /* Update SDP (sap/file) */
1122     if( p_sys->b_export_sap ) SapSetup( p_stream );
1123     if( p_sys->b_export_sdp_file ) FileSetup( p_stream );
1124
1125     vlc_object_attach( id, p_stream );
1126     return id;
1127 }
1128
1129 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
1130 {
1131     sout_stream_sys_t *p_sys = p_stream->p_sys;
1132
1133     vlc_object_kill( id );
1134
1135     vlc_mutex_lock( &p_sys->lock_es );
1136     TAB_REMOVE( p_sys->i_es, p_sys->es, id );
1137     vlc_mutex_unlock( &p_sys->lock_es );
1138
1139     /* Release port */
1140     if( id->i_port > 0 )
1141     {
1142         if( id->i_cat == AUDIO_ES && p_sys->i_port_audio == 0 )
1143             p_sys->i_port_audio = id->i_port;
1144         else if( id->i_cat == VIDEO_ES && p_sys->i_port_video == 0 )
1145             p_sys->i_port_video = id->i_port;
1146     }
1147
1148     free( id->psz_rtpmap );
1149     free( id->psz_fmtp );
1150
1151     if( id->rtsp_id )
1152         RtspDelId( p_sys->rtsp, id->rtsp_id );
1153     if( id->sinkc > 0 )
1154         rtp_del_sink( id, id->sinkv[0].rtp_fd ); /* sink for explicit dst= */
1155
1156     vlc_thread_join( id );
1157     vlc_mutex_destroy( &id->lock_sink );
1158     block_FifoRelease( id->p_fifo );
1159
1160     /* Update SDP (sap/file) */
1161     if( p_sys->b_export_sap && !p_sys->p_mux ) SapSetup( p_stream );
1162     if( p_sys->b_export_sdp_file ) FileSetup( p_stream );
1163
1164     vlc_object_detach( id );
1165     vlc_object_destroy( id );
1166     return VLC_SUCCESS;
1167 }
1168
1169 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
1170                  block_t *p_buffer )
1171 {
1172     block_t *p_next;
1173
1174     assert( p_stream->p_sys->p_mux == NULL );
1175
1176     while( p_buffer != NULL )
1177     {
1178         p_next = p_buffer->p_next;
1179         if( id->pf_packetize( p_stream, id, p_buffer ) )
1180             break;
1181
1182         block_Release( p_buffer );
1183         p_buffer = p_next;
1184     }
1185     return VLC_SUCCESS;
1186 }
1187
1188 /****************************************************************************
1189  * SAP:
1190  ****************************************************************************/
1191 static int SapSetup( sout_stream_t *p_stream )
1192 {
1193     sout_stream_sys_t *p_sys = p_stream->p_sys;
1194     sout_instance_t   *p_sout = p_stream->p_sout;
1195     announce_method_t *p_method = sout_SAPMethod();
1196
1197     /* Remove the previous session */
1198     if( p_sys->p_session != NULL)
1199     {
1200         sout_AnnounceUnRegister( p_sout, p_sys->p_session);
1201         sout_AnnounceSessionDestroy( p_sys->p_session );
1202         p_sys->p_session = NULL;
1203     }
1204
1205     if( ( p_sys->i_es > 0 || p_sys->p_mux ) && p_sys->psz_sdp && *p_sys->psz_sdp )
1206     {
1207         p_sys->p_session = sout_AnnounceRegisterSDP( p_sout, SOUT_CFG_PREFIX,
1208                                                      p_sys->psz_sdp,
1209                                                      p_sys->psz_destination,
1210                                                      p_method );
1211     }
1212
1213     sout_MethodRelease( p_method );
1214     return VLC_SUCCESS;
1215 }
1216
1217 /****************************************************************************
1218 * File:
1219 ****************************************************************************/
1220 static int FileSetup( sout_stream_t *p_stream )
1221 {
1222     sout_stream_sys_t *p_sys = p_stream->p_sys;
1223     FILE            *f;
1224
1225     if( ( f = utf8_fopen( p_sys->psz_sdp_file, "wt" ) ) == NULL )
1226     {
1227         msg_Err( p_stream, "cannot open file '%s' (%s)",
1228                  p_sys->psz_sdp_file, strerror(errno) );
1229         return VLC_EGENERIC;
1230     }
1231
1232     fputs( p_sys->psz_sdp, f );
1233     fclose( f );
1234
1235     return VLC_SUCCESS;
1236 }
1237
1238 /****************************************************************************
1239  * HTTP:
1240  ****************************************************************************/
1241 static int  HttpCallback( httpd_file_sys_t *p_args,
1242                           httpd_file_t *, uint8_t *p_request,
1243                           uint8_t **pp_data, int *pi_data );
1244
1245 static int HttpSetup( sout_stream_t *p_stream, vlc_url_t *url)
1246 {
1247     sout_stream_sys_t *p_sys = p_stream->p_sys;
1248
1249     p_sys->p_httpd_host = httpd_HostNew( VLC_OBJECT(p_stream), url->psz_host,
1250                                          url->i_port > 0 ? url->i_port : 80 );
1251     if( p_sys->p_httpd_host )
1252     {
1253         p_sys->p_httpd_file = httpd_FileNew( p_sys->p_httpd_host,
1254                                              url->psz_path ? url->psz_path : "/",
1255                                              "application/sdp",
1256                                              NULL, NULL, NULL,
1257                                              HttpCallback, (void*)p_sys );
1258     }
1259     if( p_sys->p_httpd_file == NULL )
1260     {
1261         return VLC_EGENERIC;
1262     }
1263     return VLC_SUCCESS;
1264 }
1265
1266 static int  HttpCallback( httpd_file_sys_t *p_args,
1267                           httpd_file_t *f, uint8_t *p_request,
1268                           uint8_t **pp_data, int *pi_data )
1269 {
1270     sout_stream_sys_t *p_sys = (sout_stream_sys_t*)p_args;
1271
1272     vlc_mutex_lock( &p_sys->lock_sdp );
1273     if( p_sys->psz_sdp && *p_sys->psz_sdp )
1274     {
1275         *pi_data = strlen( p_sys->psz_sdp );
1276         *pp_data = malloc( *pi_data );
1277         memcpy( *pp_data, p_sys->psz_sdp, *pi_data );
1278     }
1279     else
1280     {
1281         *pp_data = NULL;
1282         *pi_data = 0;
1283     }
1284     vlc_mutex_unlock( &p_sys->lock_sdp );
1285
1286     return VLC_SUCCESS;
1287 }
1288
1289 /****************************************************************************
1290  * RTP send
1291  ****************************************************************************/
1292 static void ThreadSend( vlc_object_t *p_this )
1293 {
1294     sout_stream_id_t *id = (sout_stream_id_t *)p_this;
1295     unsigned i_caching = id->i_caching;
1296 #ifdef HAVE_TEE
1297     int fd[5] = { -1, -1, -1, -1, -1 };
1298
1299     if( pipe( fd ) )
1300         fd[0] = fd[1] = -1;
1301     else
1302     if( pipe( fd ) )
1303         fd[2] = fd[3] = -1;
1304     else
1305         fd[4] = open( "/dev/null", O_WRONLY );
1306 #endif
1307
1308     while( !id->b_die )
1309     {
1310         block_t *out = block_FifoGet( id->p_fifo );
1311         mtime_t  i_date = out->i_dts + i_caching;
1312         ssize_t  len = out->i_buffer;
1313
1314 #ifdef HAVE_TEE
1315         if( fd[4] != -1 )
1316             len = write( fd[1], out->p_buffer, len);
1317         if( len == -1 )
1318             continue; /* Uho - should not happen */
1319 #endif
1320         mwait( i_date );
1321
1322         vlc_mutex_lock( &id->lock_sink );
1323         for( int i = 0; i < id->sinkc; i++ )
1324         {
1325             SendRTCP( id->sinkv[i].rtcp, out );
1326
1327 #ifdef HAVE_TEE
1328             tee( fd[0], fd[3], len, 0 );
1329             if( splice( fd[2], NULL, id->sinkv[i].rtp_fd, NULL, len,
1330                         SPLICE_F_NONBLOCK ) >= 0 )
1331                 continue;
1332
1333             /* splice failed */
1334             splice( fd[2], NULL, fd[4], NULL, len, 0 );
1335 #endif
1336             send( id->sinkv[i].rtp_fd, out->p_buffer, len, 0 );
1337         }
1338         vlc_mutex_unlock( &id->lock_sink );
1339
1340         block_Release( out );
1341 #ifdef HAVE_TEE
1342         splice( fd[0], NULL, fd[4], NULL, len, 0 );
1343 #endif
1344     }
1345
1346 #ifdef HAVE_TEE
1347     for( unsigned i = 0; i < 5; i++ )
1348         close( fd[i] );
1349 #endif
1350 }
1351
1352 static inline void rtp_packetize_send( sout_stream_id_t *id, block_t *out )
1353 {
1354     block_FifoPut( id->p_fifo, out );
1355 }
1356
1357 int rtp_add_sink( sout_stream_id_t *id, int fd )
1358 {
1359     rtp_sink_t sink = { fd, NULL };
1360     sink.rtcp = OpenRTCP( VLC_OBJECT( id->p_stream ), fd, IPPROTO_UDP );
1361     if( sink.rtcp == NULL )
1362         msg_Err( id, "RTCP failed!" );
1363
1364     vlc_mutex_lock( &id->lock_sink );
1365     INSERT_ELEM( id->sinkv, id->sinkc, id->sinkc, sink );
1366     vlc_mutex_unlock( &id->lock_sink );
1367     return VLC_SUCCESS;
1368 }
1369
1370 void rtp_del_sink( sout_stream_id_t *id, int fd )
1371 {
1372     rtp_sink_t sink = { fd, NULL };
1373
1374     /* NOTE: must be safe to use if fd is not included */
1375     vlc_mutex_lock( &id->lock_sink );
1376     for( int i = 0; i < id->sinkc; i++ )
1377     {
1378         if (id->sinkv[i].rtp_fd == fd)
1379         {
1380             sink = id->sinkv[i];
1381             REMOVE_ELEM( id->sinkv, id->sinkc, i );
1382             break;
1383         }
1384     }
1385     vlc_mutex_unlock( &id->lock_sink );
1386
1387     CloseRTCP( sink.rtcp );
1388     net_Close( sink.rtp_fd );
1389 }
1390
1391 /****************************************************************************
1392  * rtp_packetize_*:
1393  ****************************************************************************/
1394 static void rtp_packetize_common( sout_stream_id_t *id, block_t *out,
1395                                   int b_marker, int64_t i_pts )
1396 {
1397     uint32_t i_timestamp = i_pts * (int64_t)id->i_clock_rate / I64C(1000000);
1398
1399     out->p_buffer[0] = 0x80;
1400     out->p_buffer[1] = (b_marker?0x80:0x00)|id->i_payload_type;
1401     out->p_buffer[2] = ( id->i_sequence >> 8)&0xff;
1402     out->p_buffer[3] = ( id->i_sequence     )&0xff;
1403     out->p_buffer[4] = ( i_timestamp >> 24 )&0xff;
1404     out->p_buffer[5] = ( i_timestamp >> 16 )&0xff;
1405     out->p_buffer[6] = ( i_timestamp >>  8 )&0xff;
1406     out->p_buffer[7] = ( i_timestamp       )&0xff;
1407
1408     memcpy( out->p_buffer + 8, id->ssrc, 4 );
1409
1410     out->i_buffer = 12;
1411     id->i_sequence++;
1412 }
1413
1414 static int rtp_packetize_mpa( sout_stream_t *p_stream, sout_stream_id_t *id,
1415                               block_t *in )
1416 {
1417     int     i_max   = id->i_mtu - 12 - 4; /* payload max in one packet */
1418     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1419
1420     uint8_t *p_data = in->p_buffer;
1421     int     i_data  = in->i_buffer;
1422     int     i;
1423
1424     for( i = 0; i < i_count; i++ )
1425     {
1426         int           i_payload = __MIN( i_max, i_data );
1427         block_t *out = block_New( p_stream, 16 + i_payload );
1428
1429         /* rtp common header */
1430         rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts );
1431         /* mbz set to 0 */
1432         out->p_buffer[12] = 0;
1433         out->p_buffer[13] = 0;
1434         /* fragment offset in the current frame */
1435         out->p_buffer[14] = ( (i*i_max) >> 8 )&0xff;
1436         out->p_buffer[15] = ( (i*i_max)      )&0xff;
1437         memcpy( &out->p_buffer[16], p_data, i_payload );
1438
1439         out->i_buffer   = 16 + i_payload;
1440         out->i_dts    = in->i_dts + i * in->i_length / i_count;
1441         out->i_length = in->i_length / i_count;
1442
1443         rtp_packetize_send( id, out );
1444
1445         p_data += i_payload;
1446         i_data -= i_payload;
1447     }
1448
1449     return VLC_SUCCESS;
1450 }
1451
1452 /* rfc2250 */
1453 static int rtp_packetize_mpv( sout_stream_t *p_stream, sout_stream_id_t *id,
1454                               block_t *in )
1455 {
1456     int     i_max   = id->i_mtu - 12 - 4; /* payload max in one packet */
1457     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1458
1459     uint8_t *p_data = in->p_buffer;
1460     int     i_data  = in->i_buffer;
1461     int     i;
1462     int     b_sequence_start = 0;
1463     int     i_temporal_ref = 0;
1464     int     i_picture_coding_type = 0;
1465     int     i_fbv = 0, i_bfc = 0, i_ffv = 0, i_ffc = 0;
1466     int     b_start_slice = 0;
1467
1468     /* preparse this packet to get some info */
1469     if( in->i_buffer > 4 )
1470     {
1471         uint8_t *p = p_data;
1472         int      i_rest = in->i_buffer;
1473
1474         for( ;; )
1475         {
1476             while( i_rest > 4 &&
1477                    ( p[0] != 0x00 || p[1] != 0x00 || p[2] != 0x01 ) )
1478             {
1479                 p++;
1480                 i_rest--;
1481             }
1482             if( i_rest <= 4 )
1483             {
1484                 break;
1485             }
1486             p += 3;
1487             i_rest -= 4;
1488
1489             if( *p == 0xb3 )
1490             {
1491                 /* sequence start code */
1492                 b_sequence_start = 1;
1493             }
1494             else if( *p == 0x00 && i_rest >= 4 )
1495             {
1496                 /* picture */
1497                 i_temporal_ref = ( p[1] << 2) |((p[2]>>6)&0x03);
1498                 i_picture_coding_type = (p[2] >> 3)&0x07;
1499
1500                 if( i_rest >= 4 && ( i_picture_coding_type == 2 ||
1501                                     i_picture_coding_type == 3 ) )
1502                 {
1503                     i_ffv = (p[3] >> 2)&0x01;
1504                     i_ffc = ((p[3]&0x03) << 1)|((p[4]>>7)&0x01);
1505                     if( i_rest > 4 && i_picture_coding_type == 3 )
1506                     {
1507                         i_fbv = (p[4]>>6)&0x01;
1508                         i_bfc = (p[4]>>3)&0x07;
1509                     }
1510                 }
1511             }
1512             else if( *p <= 0xaf )
1513             {
1514                 b_start_slice = 1;
1515             }
1516         }
1517     }
1518
1519     for( i = 0; i < i_count; i++ )
1520     {
1521         int           i_payload = __MIN( i_max, i_data );
1522         block_t *out = block_New( p_stream,
1523                                              16 + i_payload );
1524         uint32_t      h = ( i_temporal_ref << 16 )|
1525                           ( b_sequence_start << 13 )|
1526                           ( b_start_slice << 12 )|
1527                           ( i == i_count - 1 ? 1 << 11 : 0 )|
1528                           ( i_picture_coding_type << 8 )|
1529                           ( i_fbv << 7 )|( i_bfc << 4 )|( i_ffv << 3 )|i_ffc;
1530
1531         /* rtp common header */
1532         rtp_packetize_common( id, out, (i == i_count - 1)?1:0,
1533                               in->i_pts > 0 ? in->i_pts : in->i_dts );
1534
1535         /* MBZ:5 T:1 TR:10 AN:1 N:1 S:1 B:1 E:1 P:3 FBV:1 BFC:3 FFV:1 FFC:3 */
1536         out->p_buffer[12] = ( h >> 24 )&0xff;
1537         out->p_buffer[13] = ( h >> 16 )&0xff;
1538         out->p_buffer[14] = ( h >>  8 )&0xff;
1539         out->p_buffer[15] = ( h       )&0xff;
1540
1541         memcpy( &out->p_buffer[16], p_data, i_payload );
1542
1543         out->i_buffer   = 16 + i_payload;
1544         out->i_dts    = in->i_dts + i * in->i_length / i_count;
1545         out->i_length = in->i_length / i_count;
1546
1547         rtp_packetize_send( id, out );
1548
1549         p_data += i_payload;
1550         i_data -= i_payload;
1551     }
1552
1553     return VLC_SUCCESS;
1554 }
1555
1556 static int rtp_packetize_ac3( sout_stream_t *p_stream, sout_stream_id_t *id,
1557                               block_t *in )
1558 {
1559     int     i_max   = id->i_mtu - 12 - 2; /* payload max in one packet */
1560     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1561
1562     uint8_t *p_data = in->p_buffer;
1563     int     i_data  = in->i_buffer;
1564     int     i;
1565
1566     for( i = 0; i < i_count; i++ )
1567     {
1568         int           i_payload = __MIN( i_max, i_data );
1569         block_t *out = block_New( p_stream, 14 + i_payload );
1570
1571         /* rtp common header */
1572         rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts );
1573         /* unit count */
1574         out->p_buffer[12] = 1;
1575         /* unit header */
1576         out->p_buffer[13] = 0x00;
1577         /* data */
1578         memcpy( &out->p_buffer[14], p_data, i_payload );
1579
1580         out->i_buffer   = 14 + i_payload;
1581         out->i_dts    = in->i_dts + i * in->i_length / i_count;
1582         out->i_length = in->i_length / i_count;
1583
1584         rtp_packetize_send( id, out );
1585
1586         p_data += i_payload;
1587         i_data -= i_payload;
1588     }
1589
1590     return VLC_SUCCESS;
1591 }
1592
1593 static int rtp_packetize_split( sout_stream_t *p_stream, sout_stream_id_t *id,
1594                                 block_t *in )
1595 {
1596     int     i_max   = id->i_mtu - 12; /* payload max in one packet */
1597     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1598
1599     uint8_t *p_data = in->p_buffer;
1600     int     i_data  = in->i_buffer;
1601     int     i;
1602
1603     for( i = 0; i < i_count; i++ )
1604     {
1605         int           i_payload = __MIN( i_max, i_data );
1606         block_t *out = block_New( p_stream, 12 + i_payload );
1607
1608         /* rtp common header */
1609         rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
1610                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
1611         memcpy( &out->p_buffer[12], p_data, i_payload );
1612
1613         out->i_buffer   = 12 + i_payload;
1614         out->i_dts    = in->i_dts + i * in->i_length / i_count;
1615         out->i_length = in->i_length / i_count;
1616
1617         rtp_packetize_send( id, out );
1618
1619         p_data += i_payload;
1620         i_data -= i_payload;
1621     }
1622
1623     return VLC_SUCCESS;
1624 }
1625
1626 /* rfc3016 */
1627 static int rtp_packetize_mp4a_latm( sout_stream_t *p_stream, sout_stream_id_t *id,
1628                                 block_t *in )
1629 {
1630     int     i_max   = id->i_mtu - 14;              /* payload max in one packet */
1631     int     latmhdrsize = in->i_buffer / 0xff + 1;
1632     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1633
1634     uint8_t *p_data = in->p_buffer, *p_header = NULL;
1635     int     i_data  = in->i_buffer;
1636     int     i;
1637
1638     for( i = 0; i < i_count; i++ )
1639     {
1640         int     i_payload = __MIN( i_max, i_data );
1641         block_t *out;
1642
1643         if( i != 0 )
1644             latmhdrsize = 0;
1645         out = block_New( p_stream, 12 + latmhdrsize + i_payload );
1646
1647         /* rtp common header */
1648         rtp_packetize_common( id, out, ((i == i_count - 1) ? 1 : 0),
1649                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
1650
1651         if( i == 0 )
1652         {
1653             int tmp = in->i_buffer;
1654
1655             p_header=out->p_buffer+12;
1656             while( tmp > 0xfe )
1657             {
1658                 *p_header = 0xff;
1659                 p_header++;
1660                 tmp -= 0xff;
1661             }
1662             *p_header = tmp;
1663         }
1664
1665         memcpy( &out->p_buffer[12+latmhdrsize], p_data, i_payload );
1666
1667         out->i_buffer   = 12 + latmhdrsize + i_payload;
1668         out->i_dts    = in->i_dts + i * in->i_length / i_count;
1669         out->i_length = in->i_length / i_count;
1670
1671         rtp_packetize_send( id, out );
1672
1673         p_data += i_payload;
1674         i_data -= i_payload;
1675     }
1676
1677     return VLC_SUCCESS;
1678 }
1679
1680 static int rtp_packetize_l16( sout_stream_t *p_stream, sout_stream_id_t *id,
1681                               block_t *in )
1682 {
1683     int     i_max   = id->i_mtu - 12; /* payload max in one packet */
1684     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1685
1686     uint8_t *p_data = in->p_buffer;
1687     int     i_data  = in->i_buffer;
1688     int     i_packet = 0;
1689
1690     while( i_data > 0 )
1691     {
1692         int           i_payload = (__MIN( i_max, i_data )/4)*4;
1693         block_t *out = block_New( p_stream, 12 + i_payload );
1694
1695         /* rtp common header */
1696         rtp_packetize_common( id, out, 0,
1697                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
1698         memcpy( &out->p_buffer[12], p_data, i_payload );
1699
1700         out->i_buffer   = 12 + i_payload;
1701         out->i_dts    = in->i_dts + i_packet * in->i_length / i_count;
1702         out->i_length = in->i_length / i_count;
1703
1704         rtp_packetize_send( id, out );
1705
1706         p_data += i_payload;
1707         i_data -= i_payload;
1708         i_packet++;
1709     }
1710
1711     return VLC_SUCCESS;
1712 }
1713
1714 static int rtp_packetize_l8( sout_stream_t *p_stream, sout_stream_id_t *id,
1715                              block_t *in )
1716 {
1717     int     i_max   = id->i_mtu - 12; /* payload max in one packet */
1718     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1719
1720     uint8_t *p_data = in->p_buffer;
1721     int     i_data  = in->i_buffer;
1722     int     i_packet = 0;
1723
1724     while( i_data > 0 )
1725     {
1726         int           i_payload = (__MIN( i_max, i_data )/2)*2;
1727         block_t *out = block_New( p_stream, 12 + i_payload );
1728
1729         /* rtp common header */
1730         rtp_packetize_common( id, out, 0,
1731                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
1732         memcpy( &out->p_buffer[12], p_data, i_payload );
1733
1734         out->i_buffer   = 12 + i_payload;
1735         out->i_dts    = in->i_dts + i_packet * in->i_length / i_count;
1736         out->i_length = in->i_length / i_count;
1737
1738         rtp_packetize_send( id, out );
1739
1740         p_data += i_payload;
1741         i_data -= i_payload;
1742         i_packet++;
1743     }
1744
1745     return VLC_SUCCESS;
1746 }
1747
1748 static int rtp_packetize_mp4a( sout_stream_t *p_stream, sout_stream_id_t *id,
1749                                block_t *in )
1750 {
1751     int     i_max   = id->i_mtu - 16; /* payload max in one packet */
1752     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1753
1754     uint8_t *p_data = in->p_buffer;
1755     int     i_data  = in->i_buffer;
1756     int     i;
1757
1758     for( i = 0; i < i_count; i++ )
1759     {
1760         int           i_payload = __MIN( i_max, i_data );
1761         block_t *out = block_New( p_stream, 16 + i_payload );
1762
1763         /* rtp common header */
1764         rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
1765                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
1766         /* AU headers */
1767         /* AU headers length (bits) */
1768         out->p_buffer[12] = 0;
1769         out->p_buffer[13] = 2*8;
1770         /* for each AU length 13 bits + idx 3bits, */
1771         out->p_buffer[14] = ( in->i_buffer >> 5 )&0xff;
1772         out->p_buffer[15] = ( (in->i_buffer&0xff)<<3 )|0;
1773
1774         memcpy( &out->p_buffer[16], p_data, i_payload );
1775
1776         out->i_buffer   = 16 + i_payload;
1777         out->i_dts    = in->i_dts + i * in->i_length / i_count;
1778         out->i_length = in->i_length / i_count;
1779
1780         rtp_packetize_send( id, out );
1781
1782         p_data += i_payload;
1783         i_data -= i_payload;
1784     }
1785
1786     return VLC_SUCCESS;
1787 }
1788
1789
1790 /* rfc2429 */
1791 #define RTP_H263_HEADER_SIZE (2)  // plen = 0
1792 #define RTP_H263_PAYLOAD_START (14)  // plen = 0
1793 static int rtp_packetize_h263( sout_stream_t *p_stream, sout_stream_id_t *id,
1794                                block_t *in )
1795 {
1796     uint8_t *p_data = in->p_buffer;
1797     int     i_data  = in->i_buffer;
1798     int     i;
1799     int     i_max   = id->i_mtu - 12 - RTP_H263_HEADER_SIZE; /* payload max in one packet */
1800     int     i_count;
1801     int     b_p_bit;
1802     int     b_v_bit = 0; // no pesky error resilience
1803     int     i_plen = 0; // normally plen=0 for PSC packet
1804     int     i_pebit = 0; // because plen=0
1805     uint16_t h;
1806
1807     if( i_data < 2 )
1808     {
1809         return VLC_EGENERIC;
1810     }
1811     if( p_data[0] || p_data[1] )
1812     {
1813         return VLC_EGENERIC;
1814     }
1815     /* remove 2 leading 0 bytes */
1816     p_data += 2;
1817     i_data -= 2;
1818     i_count = ( i_data + i_max - 1 ) / i_max;
1819
1820     for( i = 0; i < i_count; i++ )
1821     {
1822         int      i_payload = __MIN( i_max, i_data );
1823         block_t *out = block_New( p_stream,
1824                                   RTP_H263_PAYLOAD_START + i_payload );
1825         b_p_bit = (i == 0) ? 1 : 0;
1826         h = ( b_p_bit << 10 )|
1827             ( b_v_bit << 9  )|
1828             ( i_plen  << 3  )|
1829               i_pebit;
1830
1831         /* rtp common header */
1832         //b_m_bit = 1; // always contains end of frame
1833         rtp_packetize_common( id, out, (i == i_count - 1)?1:0,
1834                               in->i_pts > 0 ? in->i_pts : in->i_dts );
1835
1836         /* h263 header */
1837         out->p_buffer[12] = ( h >>  8 )&0xff;
1838         out->p_buffer[13] = ( h       )&0xff;
1839         memcpy( &out->p_buffer[RTP_H263_PAYLOAD_START], p_data, i_payload );
1840
1841         out->i_buffer = RTP_H263_PAYLOAD_START + i_payload;
1842         out->i_dts    = in->i_dts + i * in->i_length / i_count;
1843         out->i_length = in->i_length / i_count;
1844
1845         rtp_packetize_send( id, out );
1846
1847         p_data += i_payload;
1848         i_data -= i_payload;
1849     }
1850
1851     return VLC_SUCCESS;
1852 }
1853
1854 /* rfc3984 */
1855 static int
1856 rtp_packetize_h264_nal( sout_stream_t *p_stream, sout_stream_id_t *id,
1857                         const uint8_t *p_data, int i_data, int64_t i_pts,
1858                         int64_t i_dts, vlc_bool_t b_last, int64_t i_length )
1859 {
1860     const int i_max = id->i_mtu - 12; /* payload max in one packet */
1861     int i_nal_hdr;
1862     int i_nal_type;
1863
1864     if( i_data < 5 )
1865         return VLC_SUCCESS;
1866
1867     i_nal_hdr = p_data[3];
1868     i_nal_type = i_nal_hdr&0x1f;
1869
1870     /* Skip start code */
1871     p_data += 3;
1872     i_data -= 3;
1873
1874     /* */
1875     if( i_data <= i_max )
1876     {
1877         /* Single NAL unit packet */
1878         block_t *out = block_New( p_stream, 12 + i_data );
1879         out->i_dts    = i_dts;
1880         out->i_length = i_length;
1881
1882         /* */
1883         rtp_packetize_common( id, out, b_last, i_pts );
1884         out->i_buffer = 12 + i_data;
1885
1886         memcpy( &out->p_buffer[12], p_data, i_data );
1887
1888         rtp_packetize_send( id, out );
1889     }
1890     else
1891     {
1892         /* FU-A Fragmentation Unit without interleaving */
1893         const int i_count = ( i_data-1 + i_max-2 - 1 ) / (i_max-2);
1894         int i;
1895
1896         p_data++;
1897         i_data--;
1898
1899         for( i = 0; i < i_count; i++ )
1900         {
1901             const int i_payload = __MIN( i_data, i_max-2 );
1902             block_t *out = block_New( p_stream, 12 + 2 + i_payload );
1903             out->i_dts    = i_dts + i * i_length / i_count;
1904             out->i_length = i_length / i_count;
1905
1906             /* */
1907             rtp_packetize_common( id, out, (b_last && i_payload == i_data), i_pts );
1908             out->i_buffer = 14 + i_payload;
1909
1910             /* FU indicator */
1911             out->p_buffer[12] = 0x00 | (i_nal_hdr & 0x60) | 28;
1912             /* FU header */
1913             out->p_buffer[13] = ( i == 0 ? 0x80 : 0x00 ) | ( (i == i_count-1) ? 0x40 : 0x00 )  | i_nal_type;
1914             memcpy( &out->p_buffer[14], p_data, i_payload );
1915
1916             rtp_packetize_send( id, out );
1917
1918             i_data -= i_payload;
1919             p_data += i_payload;
1920         }
1921     }
1922     return VLC_SUCCESS;
1923 }
1924
1925 static int rtp_packetize_h264( sout_stream_t *p_stream, sout_stream_id_t *id,
1926                                block_t *in )
1927 {
1928     const uint8_t *p_buffer = in->p_buffer;
1929     int i_buffer = in->i_buffer;
1930
1931     while( i_buffer > 4 && ( p_buffer[0] != 0 || p_buffer[1] != 0 || p_buffer[2] != 1 ) )
1932     {
1933         i_buffer--;
1934         p_buffer++;
1935     }
1936
1937     /* Split nal units */
1938     while( i_buffer > 4 )
1939     {
1940         int i_offset;
1941         int i_size = i_buffer;
1942         int i_skip = i_buffer;
1943
1944         /* search nal end */
1945         for( i_offset = 4; i_offset+2 < i_buffer ; i_offset++)
1946         {
1947             if( p_buffer[i_offset] == 0 && p_buffer[i_offset+1] == 0 && p_buffer[i_offset+2] == 1 )
1948             {
1949                 /* we found another startcode */
1950                 i_size = i_offset - ( p_buffer[i_offset-1] == 0 ? 1 : 0);
1951                 i_skip = i_offset;
1952                 break;
1953             }
1954         }
1955         /* TODO add STAP-A to remove a lot of overhead with small slice/sei/... */
1956         rtp_packetize_h264_nal( p_stream, id, p_buffer, i_size,
1957                                 (in->i_pts > 0 ? in->i_pts : in->i_dts), in->i_dts,
1958                                 (i_size >= i_buffer), in->i_length * i_size / in->i_buffer );
1959
1960         i_buffer -= i_skip;
1961         p_buffer += i_skip;
1962     }
1963     return VLC_SUCCESS;
1964 }
1965
1966 static int rtp_packetize_amr( sout_stream_t *p_stream, sout_stream_id_t *id,
1967                               block_t *in )
1968 {
1969     int     i_max   = id->i_mtu - 14; /* payload max in one packet */
1970     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1971
1972     uint8_t *p_data = in->p_buffer;
1973     int     i_data  = in->i_buffer;
1974     int     i;
1975
1976     /* Only supports octet-aligned mode */
1977     for( i = 0; i < i_count; i++ )
1978     {
1979         int           i_payload = __MIN( i_max, i_data );
1980         block_t *out = block_New( p_stream, 14 + i_payload );
1981
1982         /* rtp common header */
1983         rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
1984                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
1985         /* Payload header */
1986         out->p_buffer[12] = 0xF0; /* CMR */
1987         out->p_buffer[13] = p_data[0]&0x7C; /* ToC */ /* FIXME: frame type */
1988
1989         /* FIXME: are we fed multiple frames ? */
1990         memcpy( &out->p_buffer[14], p_data+1, i_payload-1 );
1991
1992         out->i_buffer   = 14 + i_payload-1;
1993         out->i_dts    = in->i_dts + i * in->i_length / i_count;
1994         out->i_length = in->i_length / i_count;
1995
1996         rtp_packetize_send( id, out );
1997
1998         p_data += i_payload;
1999         i_data -= i_payload;
2000     }
2001
2002     return VLC_SUCCESS;
2003 }
2004
2005 /*****************************************************************************
2006  * Non-RTP mux
2007  *****************************************************************************/
2008
2009 /** Add an ES to a non-RTP muxed stream */
2010 static sout_stream_id_t *MuxAdd( sout_stream_t *p_stream, es_format_t *p_fmt )
2011 {
2012     sout_input_t      *p_input;
2013     sout_mux_t *p_mux = p_stream->p_sys->p_mux;
2014     assert( p_mux != NULL );
2015
2016     p_input = sout_MuxAddStream( p_mux, p_fmt );
2017     if( p_input == NULL )
2018     {
2019         msg_Err( p_stream, "cannot add this stream to the muxer" );
2020         return NULL;
2021     }
2022
2023     return (sout_stream_id_t *)p_input;
2024 }
2025
2026
2027 static int MuxSend( sout_stream_t *p_stream, sout_stream_id_t *id,
2028                     block_t *p_buffer )
2029 {
2030     sout_mux_t *p_mux = p_stream->p_sys->p_mux;
2031     assert( p_mux != NULL );
2032
2033     sout_MuxSendBuffer( p_mux, (sout_input_t *)id, p_buffer );
2034     return VLC_SUCCESS;
2035 }
2036
2037
2038 /** Remove an ES from a non-RTP muxed stream */
2039 static int MuxDel( sout_stream_t *p_stream, sout_stream_id_t *id )
2040 {
2041     sout_mux_t *p_mux = p_stream->p_sys->p_mux;
2042     assert( p_mux != NULL );
2043
2044     sout_MuxDeleteStream( p_mux, (sout_input_t *)id );
2045     return VLC_SUCCESS;
2046 }
2047
2048
2049 static int AccessOutGrabberWriteBuffer( sout_stream_t *p_stream,
2050                                         const block_t *p_buffer )
2051 {
2052     sout_stream_sys_t *p_sys = p_stream->p_sys;
2053     sout_stream_id_t *id = p_sys->es[0];
2054
2055     int64_t  i_dts = p_buffer->i_dts;
2056
2057     uint8_t         *p_data = p_buffer->p_buffer;
2058     unsigned int    i_data  = p_buffer->i_buffer;
2059     unsigned int    i_max   = id->i_mtu - 12;
2060
2061     unsigned i_packet = ( p_buffer->i_buffer + i_max - 1 ) / i_max;
2062
2063     while( i_data > 0 )
2064     {
2065         unsigned int i_size;
2066
2067         /* output complete packet */
2068         if( p_sys->packet &&
2069             p_sys->packet->i_buffer + i_data > i_max )
2070         {
2071             rtp_packetize_send( id, p_sys->packet );
2072             p_sys->packet = NULL;
2073         }
2074
2075         if( p_sys->packet == NULL )
2076         {
2077             /* allocate a new packet */
2078             p_sys->packet = block_New( p_stream, id->i_mtu );
2079             rtp_packetize_common( id, p_sys->packet, 1, i_dts );
2080             p_sys->packet->i_dts = i_dts;
2081             p_sys->packet->i_length = p_buffer->i_length / i_packet;
2082             i_dts += p_sys->packet->i_length;
2083         }
2084
2085         i_size = __MIN( i_data,
2086                         (unsigned)(id->i_mtu - p_sys->packet->i_buffer) );
2087
2088         memcpy( &p_sys->packet->p_buffer[p_sys->packet->i_buffer],
2089                 p_data, i_size );
2090
2091         p_sys->packet->i_buffer += i_size;
2092         p_data += i_size;
2093         i_data -= i_size;
2094     }
2095
2096     return VLC_SUCCESS;
2097 }
2098
2099
2100 static int AccessOutGrabberWrite( sout_access_out_t *p_access,
2101                                   block_t *p_buffer )
2102 {
2103     sout_stream_t *p_stream = (sout_stream_t*)p_access->p_sys;
2104
2105     while( p_buffer )
2106     {
2107         block_t *p_next;
2108
2109         AccessOutGrabberWriteBuffer( p_stream, p_buffer );
2110
2111         p_next = p_buffer->p_next;
2112         block_Release( p_buffer );
2113         p_buffer = p_next;
2114     }
2115
2116     return VLC_SUCCESS;
2117 }
2118
2119
2120 static sout_access_out_t *GrabberCreate( sout_stream_t *p_stream )
2121 {
2122     sout_access_out_t *p_grab;
2123
2124     p_grab = vlc_object_create( p_stream->p_sout, sizeof( *p_grab ) );
2125     if( p_grab == NULL )
2126         return NULL;
2127
2128     p_grab->p_module    = NULL;
2129     p_grab->p_sout      = p_stream->p_sout;
2130     p_grab->psz_access  = strdup( "grab" );
2131     p_grab->p_cfg       = NULL;
2132     p_grab->psz_path    = strdup( "" );
2133     p_grab->p_sys       = (sout_access_out_sys_t *)p_stream;
2134     p_grab->pf_seek     = NULL;
2135     p_grab->pf_write    = AccessOutGrabberWrite;
2136     return p_grab;
2137 }