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