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