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