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