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