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