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