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