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