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