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