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