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