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