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