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