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