]> git.sesse.net Git - vlc/blob - modules/stream_out/rtp.c
Do not force a default TTL value (the value 1 will be used in SDP only).
[vlc] / modules / stream_out / rtp.c
1 /*****************************************************************************
2  * rtp.c: rtp stream output module
3  *****************************************************************************
4  * Copyright (C) 2003-2004 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include "config.h"
28 #include <stdio.h>
29 #include <stdlib.h>
30 #ifdef HAVE_UNISTD_H
31 #   include <unistd.h>
32 #endif
33
34 #include <errno.h>
35
36 #include <vlc/vlc.h>
37 #include <vlc_sout.h>
38 #include <vlc_block.h>
39
40 #include <vlc_httpd.h>
41 #include <vlc_url.h>
42 #include <vlc_network.h>
43 #include <vlc_charset.h>
44
45 /*****************************************************************************
46  * Module descriptor
47  *****************************************************************************/
48
49 #define MTU_REDUCE 50
50
51 #define DST_TEXT N_("Destination")
52 #define DST_LONGTEXT N_( \
53     "This is the output URL that will be used." )
54 #define SDP_TEXT N_("SDP")
55 #define SDP_LONGTEXT N_( \
56     "This allows you to specify how the SDP (Session Descriptor) for this RTP "\
57     "session will be made available. You must use an url: http://location to " \
58     "access the SDP via HTTP, rtsp://location for RTSP access, and sap:// " \
59     "for the SDP to be announced via SAP." )
60 #define MUX_TEXT N_("Muxer")
61 #define MUX_LONGTEXT N_( \
62     "This allows you to specify the muxer used for the streaming output. " \
63     "Default is to use no muxer (standard RTP stream)." )
64
65 #define NAME_TEXT N_("Session name")
66 #define NAME_LONGTEXT N_( \
67     "This is the name of the session that will be announced in the SDP " \
68     "(Session Descriptor)." )
69 #define DESC_TEXT N_("Session description")
70 #define DESC_LONGTEXT N_( \
71     "This allows you to give a broader description of the stream, that will " \
72     "be announced in the SDP (Session Descriptor)." )
73 #define URL_TEXT N_("Session URL")
74 #define URL_LONGTEXT N_( \
75     "This allows you to give an URL with more details about the stream " \
76     "(often the website of the streaming organization), that will " \
77     "be announced in the SDP (Session Descriptor)." )
78 #define EMAIL_TEXT N_("Session email")
79 #define EMAIL_LONGTEXT N_( \
80    "This allows you to give a contact mail address for the stream, that will " \
81    "be announced in the SDP (Session Descriptor)." )
82 #define PORT_TEXT N_("Port")
83 #define PORT_LONGTEXT N_( \
84     "This allows you to specify the base port for the RTP streaming." )
85 #define PORT_AUDIO_TEXT N_("Audio port")
86 #define PORT_AUDIO_LONGTEXT N_( \
87     "This allows you to specify the default audio port for the RTP streaming." )
88 #define PORT_VIDEO_TEXT N_("Video port")
89 #define PORT_VIDEO_LONGTEXT N_( \
90     "This allows you to specify the default video port for the RTP streaming." )
91
92 #define TTL_TEXT N_("Hop limit (TTL)")
93 #define TTL_LONGTEXT N_( \
94     "This is the hop limit (also known as \"Time-To-Live\" or TTL) of " \
95     "the multicast packets sent by the stream output (0 = use operating " \
96     "system built-in default).")
97
98 #define RFC3016_TEXT N_("MP4A LATM")
99 #define RFC3016_LONGTEXT N_( \
100     "This allows you to stream MPEG4 LATM audio streams (see RFC3016)." )
101
102 static int  Open ( vlc_object_t * );
103 static void Close( vlc_object_t * );
104
105 #define SOUT_CFG_PREFIX "sout-rtp-"
106
107 vlc_module_begin();
108     set_shortname( _("RTP"));
109     set_description( _("RTP stream output") );
110     set_capability( "sout stream", 0 );
111     add_shortcut( "rtp" );
112     set_category( CAT_SOUT );
113     set_subcategory( SUBCAT_SOUT_STREAM );
114
115     add_string( SOUT_CFG_PREFIX "dst", "", NULL, DST_TEXT,
116                 DST_LONGTEXT, VLC_TRUE );
117     add_string( SOUT_CFG_PREFIX "sdp", "", NULL, SDP_TEXT,
118                 SDP_LONGTEXT, VLC_TRUE );
119     add_string( SOUT_CFG_PREFIX "mux", "", NULL, MUX_TEXT,
120                 MUX_LONGTEXT, VLC_TRUE );
121
122     add_string( SOUT_CFG_PREFIX "name", "NONE", NULL, NAME_TEXT,
123                 NAME_LONGTEXT, VLC_TRUE );
124     add_string( SOUT_CFG_PREFIX "description", "", NULL, DESC_TEXT,
125                 DESC_LONGTEXT, VLC_TRUE );
126     add_string( SOUT_CFG_PREFIX "url", "", NULL, URL_TEXT,
127                 URL_LONGTEXT, VLC_TRUE );
128     add_string( SOUT_CFG_PREFIX "email", "", NULL, EMAIL_TEXT,
129                 EMAIL_LONGTEXT, VLC_TRUE );
130
131     add_integer( SOUT_CFG_PREFIX "port", 1234, NULL, PORT_TEXT,
132                  PORT_LONGTEXT, VLC_TRUE );
133     add_integer( SOUT_CFG_PREFIX "port-audio", 1230, NULL, PORT_AUDIO_TEXT,
134                  PORT_AUDIO_LONGTEXT, VLC_TRUE );
135     add_integer( SOUT_CFG_PREFIX "port-video", 1232, NULL, PORT_VIDEO_TEXT,
136                  PORT_VIDEO_LONGTEXT, VLC_TRUE );
137
138     add_integer( SOUT_CFG_PREFIX "ttl", 0, NULL, TTL_TEXT,
139                  TTL_LONGTEXT, VLC_TRUE );
140
141     add_bool( SOUT_CFG_PREFIX "mp4a-latm", 0, NULL, RFC3016_TEXT,
142                  RFC3016_LONGTEXT, VLC_FALSE );
143
144     set_callbacks( Open, Close );
145 vlc_module_end();
146
147 /*****************************************************************************
148  * Exported prototypes
149  *****************************************************************************/
150 static const char *ppsz_sout_options[] = {
151     "dst", "name", "port", "port-audio", "port-video", "*sdp", "ttl", "mux",
152     "description", "url","email", "mp4a-latm", NULL
153 };
154
155 static sout_stream_id_t *Add ( sout_stream_t *, es_format_t * );
156 static int               Del ( sout_stream_t *, sout_stream_id_t * );
157 static int               Send( sout_stream_t *, sout_stream_id_t *,
158                                block_t* );
159
160 /* For unicast/interleaved streaming */
161 typedef struct
162 {
163     char    *psz_session;
164     int64_t i_last; /* for timeout */
165
166     /* is it in "play" state */
167     vlc_bool_t b_playing;
168
169     /* output (id-access) */
170     int               i_id;
171     sout_stream_id_t  **id;
172     int               i_access;
173     sout_access_out_t **access;
174 } rtsp_client_t;
175
176 struct sout_stream_sys_t
177 {
178     /* sdp */
179     int64_t i_sdp_id;
180     int     i_sdp_version;
181     char    *psz_sdp;
182     vlc_mutex_t  lock_sdp;
183
184     char        *psz_session_name;
185     char        *psz_session_description;
186     char        *psz_session_url;
187     char        *psz_session_email;
188
189     /* */
190     vlc_bool_t b_export_sdp_file;
191     char *psz_sdp_file;
192     /* sap */
193     vlc_bool_t b_export_sap;
194     session_descriptor_t *p_session;
195
196     httpd_host_t *p_httpd_host;
197     httpd_file_t *p_httpd_file;
198
199     httpd_host_t *p_rtsp_host;
200     httpd_url_t  *p_rtsp_url;
201     char         *psz_rtsp_control;
202     char         *psz_rtsp_path;
203
204     /* */
205     char *psz_destination;
206     int  i_port;
207     int  i_port_audio;
208     int  i_port_video;
209     int  i_ttl;
210     vlc_bool_t b_latm;
211
212     /* when need to use a private one or when using muxer */
213     int i_payload_type;
214
215     /* in case we do TS/PS over rtp */
216     sout_mux_t        *p_mux;
217     sout_access_out_t *p_access;
218     int               i_mtu;
219     sout_access_out_t *p_grab;
220     uint16_t          i_sequence;
221     uint32_t          i_timestamp_start;
222     uint8_t           ssrc[4];
223     block_t           *packet;
224
225     /* */
226     vlc_mutex_t      lock_es;
227     int              i_es;
228     sout_stream_id_t **es;
229
230     /* */
231     int              i_rtsp;
232     rtsp_client_t    **rtsp;
233 };
234
235 typedef int (*pf_rtp_packetizer_t)( sout_stream_t *, sout_stream_id_t *,
236                                     block_t * );
237
238 struct sout_stream_id_t
239 {
240     sout_stream_t *p_stream;
241     /* rtp field */
242     uint8_t     i_payload_type;
243     uint16_t    i_sequence;
244     uint32_t    i_timestamp_start;
245     uint8_t     ssrc[4];
246
247     /* for sdp */
248     int         i_clock_rate;
249     char        *psz_rtpmap;
250     char        *psz_fmtp;
251     char        *psz_destination;
252     int         i_port;
253     int         i_cat;
254     int         i_bitrate;
255
256     /* Packetizer specific fields */
257     pf_rtp_packetizer_t pf_packetize;
258     int           i_mtu;
259
260     /* for sending the packets */
261     sout_access_out_t *p_access;
262
263     vlc_mutex_t       lock_rtsp;
264     int               i_rtsp_access;
265     sout_access_out_t **rtsp_access;
266
267     /* */
268     sout_input_t      *p_input;
269
270     /* RTSP url control */
271     httpd_url_t  *p_rtsp_url;
272 };
273
274 static int AccessOutGrabberWrite( sout_access_out_t *, block_t * );
275
276 static void SDPHandleUrl( sout_stream_t *, char * );
277
278 static int SapSetup( sout_stream_t *p_stream );
279 static int FileSetup( sout_stream_t *p_stream );
280 static int HttpSetup( sout_stream_t *p_stream, vlc_url_t * );
281 static int RtspSetup( sout_stream_t *p_stream, vlc_url_t * );
282
283 static int  RtspCallback( httpd_callback_sys_t *, httpd_client_t *,
284                           httpd_message_t *, httpd_message_t * );
285 static int  RtspCallbackId( httpd_callback_sys_t *, httpd_client_t *,
286                             httpd_message_t *, httpd_message_t * );
287
288
289 static rtsp_client_t *RtspClientNew( sout_stream_t *, const char *psz_session );
290 static rtsp_client_t *RtspClientGet( sout_stream_t *, const char *psz_session );
291 static void           RtspClientDel( sout_stream_t *, rtsp_client_t * );
292
293 /*****************************************************************************
294  * Open:
295  *****************************************************************************/
296 static int Open( vlc_object_t *p_this )
297 {
298     sout_stream_t       *p_stream = (sout_stream_t*)p_this;
299     sout_instance_t     *p_sout = p_stream->p_sout;
300     sout_stream_sys_t   *p_sys = NULL;
301     config_chain_t      *p_cfg = NULL;
302     vlc_value_t         val;
303     vlc_bool_t          b_rtsp = VLC_FALSE;
304
305     config_ChainParse( p_stream, SOUT_CFG_PREFIX,
306                        ppsz_sout_options, p_stream->p_cfg );
307
308     p_sys = malloc( sizeof( sout_stream_sys_t ) );
309
310     p_sys->psz_destination = var_GetString( p_stream, SOUT_CFG_PREFIX "dst" );
311     if( *p_sys->psz_destination == '\0' )
312     {
313         free( p_sys->psz_destination );
314         p_sys->psz_destination = NULL;
315     }
316
317     p_sys->psz_session_name = var_GetString( p_stream, SOUT_CFG_PREFIX "name" );
318     p_sys->psz_session_description = var_GetString( p_stream, SOUT_CFG_PREFIX "description" );
319     p_sys->psz_session_url = var_GetString( p_stream, SOUT_CFG_PREFIX "url" );
320     p_sys->psz_session_email = var_GetString( p_stream, SOUT_CFG_PREFIX "email" );
321
322     p_sys->i_port       = var_GetInteger( p_stream, SOUT_CFG_PREFIX "port" );
323     p_sys->i_port_audio = var_GetInteger( p_stream, SOUT_CFG_PREFIX "port-audio" );
324     p_sys->i_port_video = var_GetInteger( p_stream, SOUT_CFG_PREFIX "port-video" );
325
326     p_sys->psz_sdp_file = NULL;
327
328     if( p_sys->i_port_audio == p_sys->i_port_video )
329     {
330         msg_Err( p_stream, "audio and video port cannot be the same" );
331         p_sys->i_port_audio = 0;
332         p_sys->i_port_video = 0;
333     }
334
335     if( !p_sys->psz_session_name )
336     {
337         if( p_sys->psz_destination )
338             p_sys->psz_session_name = strdup( p_sys->psz_destination );
339         else
340            p_sys->psz_session_name = strdup( "NONE" );
341     }
342
343     for( p_cfg = p_stream->p_cfg; p_cfg != NULL; p_cfg = p_cfg->p_next )
344     {
345         if( !strcmp( p_cfg->psz_name, "sdp" ) )
346         {
347             if( p_cfg->psz_value && !strncasecmp( p_cfg->psz_value, "rtsp", 4 ) )
348             {
349                 b_rtsp = VLC_TRUE;
350                 break;
351             }
352         }
353     }
354     if( !b_rtsp )
355     {
356         vlc_value_t val2;
357         var_Get( p_stream, SOUT_CFG_PREFIX "sdp", &val2 );
358         if( !strncasecmp( val2.psz_string, "rtsp", 4 ) )
359             b_rtsp = VLC_TRUE;
360         free( val2.psz_string );
361     }
362
363     if( !p_sys->psz_destination || *p_sys->psz_destination == '\0' )
364     {
365         if( !b_rtsp )
366         {
367             msg_Err( p_stream, "missing destination and not in rtsp mode" );
368             free( p_sys );
369             return VLC_EGENERIC;
370         }
371         p_sys->psz_destination = NULL;
372     }
373     else if( p_sys->i_port <= 0 )
374     {
375         msg_Err( p_stream, "invalid port" );
376         free( p_sys );
377         return VLC_EGENERIC;
378     }
379
380     var_Get( p_stream, SOUT_CFG_PREFIX "ttl", &val );
381     if( val.i_int == 0 )
382     {
383         /* Normally, we should let the default hop limit up to the core,
384          * but we have to know it to build our SDP properly, which is why
385          * we ask the core. FIXME: broken when neither sout-rtp-ttl nor
386          * ttl are set. */
387         val.i_int = config_GetInt( p_stream, "ttl" );
388     }
389     if( val.i_int > 255 ) val.i_int = 255;
390     /* must not exceed 999 once formatted */
391
392     if( val.i_int < 0 )
393         msg_Warn( p_stream, "illegal TTL %d, the SDP advertised value will be faked", val.i_int );
394     p_sys->i_ttl = val.i_int;
395
396     var_Get( p_stream, SOUT_CFG_PREFIX "mp4a-latm", &val );
397     p_sys->b_latm = val.b_bool;
398
399     p_sys->i_payload_type = 96;
400     p_sys->i_es = 0;
401     p_sys->es   = NULL;
402     p_sys->i_rtsp = 0;
403     p_sys->rtsp   = NULL;
404     p_sys->psz_sdp = NULL;
405
406     p_sys->i_sdp_id = mdate();
407     p_sys->i_sdp_version = 1;
408     p_sys->psz_sdp = NULL;
409
410     p_sys->b_export_sap = VLC_FALSE;
411     p_sys->b_export_sdp_file = VLC_FALSE;
412     p_sys->p_session = NULL;
413
414     p_sys->p_httpd_host = NULL;
415     p_sys->p_httpd_file = NULL;
416     p_sys->p_rtsp_host  = NULL;
417     p_sys->p_rtsp_url   = NULL;
418     p_sys->psz_rtsp_control = NULL;
419     p_sys->psz_rtsp_path = NULL;
420
421     vlc_mutex_init( p_stream, &p_sys->lock_sdp );
422     vlc_mutex_init( p_stream, &p_sys->lock_es );
423
424     p_stream->pf_add    = Add;
425     p_stream->pf_del    = Del;
426     p_stream->pf_send   = Send;
427
428     p_stream->p_sys     = p_sys;
429
430     var_Get( p_stream, SOUT_CFG_PREFIX "mux", &val );
431     if( *val.psz_string )
432     {
433         sout_access_out_t *p_grab;
434         const char *psz_rtpmap;
435         char url[NI_MAXHOST + 8], access[17], psz_ttl[5], ipv;
436
437         if( b_rtsp )
438         {
439             msg_Err( p_stream, "muxing is not supported in RTSP mode" );
440             free( p_sys );
441             return VLC_EGENERIC;
442         }
443         else if( !p_sys->psz_destination || *p_sys->psz_destination == '\0' )
444         {
445             msg_Err( p_stream, "rtp needs a destination when muxing" );
446             free( p_sys );
447             return VLC_EGENERIC;
448         }
449
450         /* Check muxer type */
451         if( !strncasecmp( val.psz_string, "ps", 2 ) || !strncasecmp( val.psz_string, "mpeg1", 5 ) )
452         {
453             psz_rtpmap = "MP2P/90000";
454         }
455         else if( !strncasecmp( val.psz_string, "ts", 2 ) )
456         {
457             psz_rtpmap = "MP2T/90000";
458             p_sys->i_payload_type = 33;
459         }
460         else
461         {
462             msg_Err( p_stream, "unsupported muxer type with rtp (only ts/ps)" );
463             free( p_sys );
464             return VLC_EGENERIC;
465         }
466
467         /* create the access out */
468         if( p_sys->i_ttl > 0 )
469         {
470             sprintf( access, "udp{raw,ttl=%d}", p_sys->i_ttl );
471         }
472         else
473         {
474             sprintf( access, "udp{raw}" );
475         }
476
477         /* IPv6 needs brackets if not already present */
478         snprintf( url, sizeof( url ),
479                   ( ( p_sys->psz_destination[0] != '[' ) 
480                  && ( strchr( p_sys->psz_destination, ':' ) != NULL ) )
481                   ? "[%s]:%d" : "%s:%d", p_sys->psz_destination,
482                   p_sys->i_port );
483         url[sizeof( url ) - 1] = '\0';
484         /* FIXME: we should check that url is a numerical address, otherwise
485          * the SDP will be quite broken (regardless of the IP protocol version)
486          * Also it might be IPv6 with no ':' if it is a DNS name.
487          */
488         ipv = ( strchr( p_sys->psz_destination, ':' ) != NULL ) ? '6' : '4';
489
490         if( !( p_sys->p_access = sout_AccessOutNew( p_sout, access, url ) ) )
491         {
492             msg_Err( p_stream, "cannot create the access out for %s://%s",
493                      access, url );
494             free( p_sys );
495             return VLC_EGENERIC;
496         }
497         p_sys->i_mtu = config_GetInt( p_stream, "mtu" );  /* XXX beurk */
498         if( p_sys->i_mtu <= 16 + MTU_REDUCE )
499         {
500             /* better than nothing */
501             p_sys->i_mtu = 1500;
502         }
503         p_sys->i_mtu -= MTU_REDUCE;
504
505         /* the access out grabber TODO export it as sout_AccessOutGrabberNew */
506         p_grab = p_sys->p_grab =
507             vlc_object_create( p_sout, sizeof( sout_access_out_t ) );
508         p_grab->p_module    = NULL;
509         p_grab->p_sout      = p_sout;
510         p_grab->psz_access  = strdup( "grab" );
511         p_grab->p_cfg       = NULL;
512         p_grab->psz_path    = strdup( "" );
513         p_grab->p_sys       = (sout_access_out_sys_t*)p_stream;
514         p_grab->pf_seek     = NULL;
515         p_grab->pf_write    = AccessOutGrabberWrite;
516
517         /* the muxer */
518         if( !( p_sys->p_mux = sout_MuxNew( p_sout, val.psz_string, p_sys->p_grab ) ) )
519         {
520             msg_Err( p_stream, "cannot create the muxer (%s)", val.psz_string );
521             sout_AccessOutDelete( p_sys->p_grab );
522             sout_AccessOutDelete( p_sys->p_access );
523             free( p_sys );
524             return VLC_EGENERIC;
525         }
526
527         /* create the SDP for a muxed stream (only once) */
528         /* FIXME  http://www.faqs.org/rfcs/rfc4566.html
529            o= - should be local username (no spaces allowed)
530            o= time should be hashed with some other value to garantee uniqueness
531            o= don't use the localhost address. use fully qualified domain name or IP4 address
532            a= source-filter: we need our source address
533            a= x-plgroup: (missing)
534            RTP packets need to get the correct src IP address  */
535         if( ipv == 4 && net_AddressIsMulticast( VLC_OBJECT(p_stream), p_sys->psz_destination ) )
536         {
537             snprintf( psz_ttl, sizeof( psz_ttl ), "/%d", p_sys->i_ttl );
538             psz_ttl[sizeof( psz_ttl ) - 1] = '\0';
539         }
540         else
541         {
542             psz_ttl[0] = '\0'; 
543         }
544
545         asprintf( &p_sys->psz_sdp,
546                   "v=0\r\n"
547                   /* FIXME: source address not known :( */
548                   "o=- "I64Fd" %d IN IP%c %s\r\n"
549                   "s=%s\r\n"
550                   "i=%s\r\n"
551                   "u=%s\r\n"
552                   "e=%s\r\n"
553                   "c=IN IP%c %s%s\r\n"
554                   "t=0 0\r\n" /* permanent stream */ /* when scheduled from vlm, we should set this info correctly */
555                   "a=tool:"PACKAGE_STRING"\r\n"
556                   "a=recvonly\r\n"
557                   "a=type:broadcast\r\n"
558                   "m=video %d RTP/AVP %d\r\n"
559                   "a=rtpmap:%d %s\r\n",
560                   p_sys->i_sdp_id, p_sys->i_sdp_version,
561                   ipv, ipv == '6' ? "::1" : "127.0.0.1" /* FIXME */,
562                   p_sys->psz_session_name,
563                   p_sys->psz_session_description,
564                   p_sys->psz_session_url,
565                   p_sys->psz_session_email,
566                   ipv, p_sys->psz_destination, psz_ttl,
567                   p_sys->i_port, p_sys->i_payload_type,
568                   p_sys->i_payload_type, psz_rtpmap );
569         msg_Dbg( p_stream, "sdp=%s", p_sys->psz_sdp );
570
571         /* create the rtp context */
572         p_sys->ssrc[0] = rand()&0xff;
573         p_sys->ssrc[1] = rand()&0xff;
574         p_sys->ssrc[2] = rand()&0xff;
575         p_sys->ssrc[3] = rand()&0xff;
576         p_sys->i_sequence = rand()&0xffff;
577         p_sys->i_timestamp_start = rand()&0xffffffff;
578         p_sys->packet = NULL;
579     }
580     else
581     {
582         p_sys->p_mux    = NULL;
583         p_sys->p_access = NULL;
584         p_sys->p_grab   = NULL;
585     }
586     free( val.psz_string );
587
588
589     var_Get( p_stream, SOUT_CFG_PREFIX "sdp", &val );
590     if( *val.psz_string )
591     {
592         config_chain_t *p_cfg;
593
594         SDPHandleUrl( p_stream, val.psz_string );
595
596         for( p_cfg = p_stream->p_cfg; p_cfg != NULL; p_cfg = p_cfg->p_next )
597         {
598             if( !strcmp( p_cfg->psz_name, "sdp" ) )
599             {
600                 if( p_cfg->psz_value == NULL || *p_cfg->psz_value == '\0' )
601                     continue;
602
603                 if( !strcmp( p_cfg->psz_value, val.psz_string ) )   /* needed both :sout-rtp-sdp= and rtp{sdp=} can be used */
604                     continue;
605
606                 SDPHandleUrl( p_stream, p_cfg->psz_value );
607             }
608         }
609     }
610     free( val.psz_string );
611
612     /* update p_sout->i_out_pace_nocontrol */
613     p_stream->p_sout->i_out_pace_nocontrol++;
614
615     return VLC_SUCCESS;
616 }
617
618 /*****************************************************************************
619  * Close:
620  *****************************************************************************/
621 static void Close( vlc_object_t * p_this )
622 {
623     sout_stream_t     *p_stream = (sout_stream_t*)p_this;
624     sout_stream_sys_t *p_sys = p_stream->p_sys;
625
626     /* update p_sout->i_out_pace_nocontrol */
627     p_stream->p_sout->i_out_pace_nocontrol--;
628
629     if( p_sys->p_mux )
630     {
631         sout_MuxDelete( p_sys->p_mux );
632         sout_AccessOutDelete( p_sys->p_access );
633         sout_AccessOutDelete( p_sys->p_grab );
634         if( p_sys->packet )
635         {
636             block_Release( p_sys->packet );
637         }
638         if( p_sys->b_export_sap )
639         {   
640             p_sys->p_mux = NULL;
641             SapSetup( p_stream );
642         }
643     }
644
645     while( p_sys->i_rtsp > 0 )
646     {
647         RtspClientDel( p_stream, p_sys->rtsp[0] );
648     }
649
650     vlc_mutex_destroy( &p_sys->lock_sdp );
651
652     if( p_sys->p_httpd_file )
653     {
654         httpd_FileDelete( p_sys->p_httpd_file );
655     }
656     if( p_sys->p_httpd_host )
657     {
658         httpd_HostDelete( p_sys->p_httpd_host );
659     }
660     if( p_sys->p_rtsp_url )
661     {
662         httpd_UrlDelete( p_sys->p_rtsp_url );
663     }
664     if( p_sys->p_rtsp_host )
665     {
666         httpd_HostDelete( p_sys->p_rtsp_host );
667     }
668     if( p_sys->psz_session_name )
669     {
670         free( p_sys->psz_session_name );
671         p_sys->psz_session_name = NULL;
672     }
673     if( p_sys->psz_session_description )
674     {
675         free( p_sys->psz_session_description );
676         p_sys->psz_session_description = NULL;
677     }
678     if( p_sys->psz_session_url )
679     {
680         free( p_sys->psz_session_url );
681         p_sys->psz_session_url = NULL;
682     }
683     if( p_sys->psz_session_email )
684     {
685         free( p_sys->psz_session_email );
686         p_sys->psz_session_email = NULL;
687     }
688     if( p_sys->psz_sdp )
689     {
690         free( p_sys->psz_sdp );
691         p_sys->psz_sdp = NULL;
692     }
693     if( p_sys->b_export_sdp_file )
694     {
695 #ifdef HAVE_UNISTD_H
696         unlink( p_sys->psz_sdp_file );
697 #endif
698         free( p_sys->psz_sdp_file );
699     }
700     free( p_sys );
701 }
702
703 /*****************************************************************************
704  * SDPHandleUrl:
705  *****************************************************************************/
706 static void SDPHandleUrl( sout_stream_t *p_stream, char *psz_url )
707 {
708     sout_stream_sys_t *p_sys = p_stream->p_sys;
709     vlc_url_t url;
710
711     vlc_UrlParse( &url, psz_url, 0 );
712     if( url.psz_protocol && !strcasecmp( url.psz_protocol, "http" ) )
713     {
714         if( p_sys->p_httpd_file )
715         {
716             msg_Err( p_stream, "you can use sdp=http:// only once" );
717             return;
718         }
719
720         if( HttpSetup( p_stream, &url ) )
721         {
722             msg_Err( p_stream, "cannot export sdp as http" );
723         }
724     }
725     else if( url.psz_protocol && !strcasecmp( url.psz_protocol, "rtsp" ) )
726     {
727         if( p_sys->p_rtsp_url )
728         {
729             msg_Err( p_stream, "you can use sdp=rtsp:// only once" );
730             return;
731         }
732
733         /* FIXME test if destination is multicast or no destination at all FIXME */
734         if( RtspSetup( p_stream, &url ) )
735         {
736             msg_Err( p_stream, "cannot export sdp as rtsp" );
737         }
738     }
739     else if( ( url.psz_protocol && !strcasecmp( url.psz_protocol, "sap" ) ) || 
740              ( url.psz_host && !strcasecmp( url.psz_host, "sap" ) ) )
741     {
742         p_sys->b_export_sap = VLC_TRUE;
743         SapSetup( p_stream );
744     }
745     else if( url.psz_protocol && !strcasecmp( url.psz_protocol, "file" ) )
746     {
747         if( p_sys->b_export_sdp_file )
748         {
749             msg_Err( p_stream, "you can use sdp=file:// only once" );
750             return;
751         }
752         p_sys->b_export_sdp_file = VLC_TRUE;
753         psz_url = &psz_url[5];
754         if( psz_url[0] == '/' && psz_url[1] == '/' )
755             psz_url += 2;
756         p_sys->psz_sdp_file = strdup( psz_url );
757     }
758     else
759     {
760         msg_Warn( p_stream, "unknown protocol for SDP (%s)",
761                   url.psz_protocol );
762     }
763     vlc_UrlClean( &url );
764 }
765
766 /*****************************************************************************
767  * SDPGenerate
768  *****************************************************************************/
769         /* FIXME  http://www.faqs.org/rfcs/rfc2327.html
770            All text fields should be UTF-8 encoded. Use global a:charset to announce this.
771            o= - should be local username (no spaces allowed)
772            o= time should be hashed with some other value to garantue uniqueness
773            o= we need IP6 support?
774            o= don't use the localhost address. use fully qualified domain name or IP4 address
775            p= international phone number (pass via vars?)
776            c= IP6 support
777            a= recvonly (missing)
778            a= type:broadcast (missing)
779            a= charset: (normally charset should be UTF-8, this can be used to override s= and i=)
780            a= x-plgroup: (missing)
781            RTP packets need to get the correct src IP address  */
782 static char *SDPGenerate( const sout_stream_t *p_stream,
783                           const char *psz_destination, vlc_bool_t b_rtsp )
784 {
785     sout_stream_sys_t *p_sys = p_stream->p_sys;
786     int i_size;
787     char *psz_sdp, *p, ipv;
788     int i;
789
790     /* FIXME: breaks IP version check on unknown destination */
791     if( psz_destination == NULL )
792         psz_destination = "0.0.0.0";
793
794     i_size = sizeof( "v=0\r\n" ) +
795              sizeof( "o=- * * IN IP4 127.0.0.1\r\n" ) + 10 + 10 +
796              sizeof( "s=*\r\n" ) + strlen( p_sys->psz_session_name ) +
797              sizeof( "i=*\r\n" ) + strlen( p_sys->psz_session_description ) +
798              sizeof( "u=*\r\n" ) + strlen( p_sys->psz_session_url ) +
799              sizeof( "e=*\r\n" ) + strlen( p_sys->psz_session_email ) +
800              sizeof( "t=0 0\r\n" ) + /* permanent stream */ /* when scheduled from vlm, we should set this info correctly */
801              sizeof( "a=tool:"PACKAGE_STRING"\r\n" ) +
802              sizeof( "c=IN IP4 */*\r\n" ) + 20 + 10 +
803              strlen( psz_destination ) ;
804     for( i = 0; i < p_sys->i_es; i++ )
805     {
806         sout_stream_id_t *id = p_sys->es[i];
807
808         i_size += strlen( "m=**d*o * RTP/AVP *\r\n" ) + 10 + 10;
809         if( id->psz_rtpmap )
810         {
811             i_size += strlen( "a=rtpmap:* *\r\n" ) + strlen( id->psz_rtpmap )+10;
812         }
813         if( id->psz_fmtp )
814         {
815             i_size += strlen( "a=fmtp:* *\r\n" ) + strlen( id->psz_fmtp ) + 10;
816         }
817         if ( id->i_bitrate)
818         {
819             i_size += strlen( "b=AS: *\r\n") + 10;
820         }
821         if( b_rtsp )
822         {
823             i_size += strlen( "a=control:*/trackID=*\r\n" ) + strlen( p_sys->psz_rtsp_control ) + 10;
824         }
825     }
826     if( p_sys->p_mux )
827     {
828         i_size += strlen( "m=video %d RTP/AVP %d\r\n" ) +10 +10;
829     }
830
831     ipv = ( strchr( psz_destination, ':' ) != NULL ) ? '6' : '4';
832
833     p = psz_sdp = malloc( i_size );
834     p += sprintf( p, "v=0\r\n" );
835     p += sprintf( p, "o=- "I64Fd" %d IN IP%c %s\r\n",
836                   p_sys->i_sdp_id, p_sys->i_sdp_version,
837                   ipv, ipv == '6' ? "::" : "127.0.0.1" );
838     if( *p_sys->psz_session_name )
839         p += sprintf( p, "s=%s\r\n", p_sys->psz_session_name );
840     if( *p_sys->psz_session_description )
841         p += sprintf( p, "i=%s\r\n", p_sys->psz_session_description );
842     if( *p_sys->psz_session_url )
843         p += sprintf( p, "u=%s\r\n", p_sys->psz_session_url );
844     if( *p_sys->psz_session_email )
845         p += sprintf( p, "e=%s\r\n", p_sys->psz_session_email );
846
847     p += sprintf( p, "t=0 0\r\n" ); /* permanent stream */ /* when scheduled from vlm, we should set this info correctly */
848     p += sprintf( p, "a=tool:"PACKAGE_STRING"\r\n" );
849
850     p += sprintf( p, "c=IN IP%c %s", ipv, psz_destination );
851
852     if( net_AddressIsMulticast( (vlc_object_t *)p_stream, psz_destination ) )
853     {
854         /* Add the ttl if it is a multicast address */
855         /* FIXME: 1 is not a correct default value in the case of IPv6 */
856         p += sprintf( p, "/%d\r\n", p_sys->i_ttl ? p_sys->i_ttl : 1 );
857     }
858     else
859     {
860         p += sprintf( p, "\r\n" );
861     }
862
863     for( i = 0; i < p_sys->i_es; i++ )
864     {
865         sout_stream_id_t *id = p_sys->es[i];
866
867         if( id->i_cat == AUDIO_ES )
868         {
869             p += sprintf( p, "m=audio %d RTP/AVP %d\r\n",
870                           id->i_port, id->i_payload_type );
871         }
872         else if( id->i_cat == VIDEO_ES )
873         {
874             p += sprintf( p, "m=video %d RTP/AVP %d\r\n",
875                           id->i_port, id->i_payload_type );
876         }
877         else
878         {
879             continue;
880         }
881         if( id->psz_rtpmap )
882         {
883             p += sprintf( p, "a=rtpmap:%d %s\r\n", id->i_payload_type,
884                           id->psz_rtpmap );
885         }
886         if( id->psz_fmtp )
887         {
888             p += sprintf( p, "a=fmtp:%d %s\r\n", id->i_payload_type,
889                           id->psz_fmtp );
890         }
891         if ( id->i_bitrate)
892         {
893             p += sprintf(p,"b=AS:%d\r\n",id->i_bitrate);
894         }
895         if( b_rtsp )
896         {
897             p += sprintf( p, "a=control:/trackID=%d\r\n", i );
898         }
899     }
900     if( p_sys->p_mux )
901     {
902        p += sprintf( p, "m=video %d RTP/AVP %d\r\n",
903                  p_sys->i_port, p_sys->i_payload_type );
904     }
905
906     return psz_sdp;
907 }
908
909 /*****************************************************************************
910  *
911  *****************************************************************************/
912 static int rtp_packetize_l16  ( sout_stream_t *, sout_stream_id_t *, block_t * );
913 static int rtp_packetize_l8   ( sout_stream_t *, sout_stream_id_t *, block_t * );
914 static int rtp_packetize_mpa  ( sout_stream_t *, sout_stream_id_t *, block_t * );
915 static int rtp_packetize_mpv  ( sout_stream_t *, sout_stream_id_t *, block_t * );
916 static int rtp_packetize_ac3  ( sout_stream_t *, sout_stream_id_t *, block_t * );
917 static int rtp_packetize_split( sout_stream_t *, sout_stream_id_t *, block_t * );
918 static int rtp_packetize_mp4a ( sout_stream_t *, sout_stream_id_t *, block_t * );
919 static int rtp_packetize_mp4a_latm ( sout_stream_t *, sout_stream_id_t *, block_t * );
920 static int rtp_packetize_h263 ( sout_stream_t *, sout_stream_id_t *, block_t * );
921 static int rtp_packetize_h264 ( sout_stream_t *, sout_stream_id_t *, block_t * );
922 static int rtp_packetize_amr  ( sout_stream_t *, sout_stream_id_t *, block_t * );
923
924 static void sprintf_hexa( char *s, uint8_t *p_data, int i_data )
925 {
926     static const char hex[16] = "0123456789abcdef";
927     int i;
928
929     for( i = 0; i < i_data; i++ )
930     {
931         s[2*i+0] = hex[(p_data[i]>>4)&0xf];
932         s[2*i+1] = hex[(p_data[i]   )&0xf];
933     }
934     s[2*i_data] = '\0';
935 }
936
937 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
938 {
939     sout_instance_t   *p_sout = p_stream->p_sout;
940     sout_stream_sys_t *p_sys = p_stream->p_sys;
941     sout_stream_id_t  *id;
942     sout_access_out_t *p_access = NULL;
943     int               i_port;
944     char              *psz_sdp;
945
946     if( p_sys->p_mux != NULL )
947     {
948         sout_input_t      *p_input  = NULL;
949         if( ( p_input = sout_MuxAddStream( p_sys->p_mux, p_fmt ) ) == NULL )
950         {
951             msg_Err( p_stream, "cannot add this stream to the muxer" );
952             return NULL;
953         }
954
955         id = malloc( sizeof( sout_stream_id_t ) );
956         memset( id, 0, sizeof( sout_stream_id_t ) );
957         id->p_access    = NULL;
958         id->p_input     = p_input;
959         id->pf_packetize= NULL;
960         id->p_rtsp_url  = NULL;
961         id->i_port      = 0;
962         return id;
963     }
964
965
966     /* Choose the port */
967     i_port = 0;
968     if( p_fmt->i_cat == AUDIO_ES && p_sys->i_port_audio > 0 )
969     {
970         i_port = p_sys->i_port_audio;
971         p_sys->i_port_audio = 0;
972     }
973     else if( p_fmt->i_cat == VIDEO_ES && p_sys->i_port_video > 0 )
974     {
975         i_port = p_sys->i_port_video;
976         p_sys->i_port_video = 0;
977     }
978     while( i_port == 0 )
979     {
980         if( p_sys->i_port != p_sys->i_port_audio && p_sys->i_port != p_sys->i_port_video )
981         {
982             i_port = p_sys->i_port;
983             p_sys->i_port += 2;
984             break;
985         }
986         p_sys->i_port += 2;
987     }
988
989     if( p_sys->psz_destination )
990     {
991         char access[17];
992         char url[NI_MAXHOST + 8];
993
994         /* first try to create the access out */
995         if( p_sys->i_ttl )
996         {
997             snprintf( access, sizeof( access ), "udp{raw,ttl=%d}",
998                       p_sys->i_ttl );
999             access[sizeof( access ) - 1] = '\0';
1000         }
1001         else
1002             strcpy( access, "udp{raw}" );
1003
1004         snprintf( url, sizeof( url ), (( p_sys->psz_destination[0] != '[' ) &&
1005                  strchr( p_sys->psz_destination, ':' )) ? "[%s]:%d" : "%s:%d",
1006                  p_sys->psz_destination, i_port );
1007         url[sizeof( url ) - 1] = '\0';
1008
1009         if( ( p_access = sout_AccessOutNew( p_sout, access, url ) ) == NULL )
1010         {
1011             msg_Err( p_stream, "cannot create the access out for %s://%s",
1012                      access, url );
1013             return NULL;
1014         }
1015         msg_Dbg( p_stream, "access out %s:%s", access, url );
1016     }
1017
1018     /* not create the rtp specific stuff */
1019     id = malloc( sizeof( sout_stream_id_t ) );
1020     memset( id, 0, sizeof( sout_stream_id_t ) );
1021     id->p_stream   = p_stream;
1022     id->p_access   = p_access;
1023     id->p_input    = NULL;
1024     id->psz_rtpmap = NULL;
1025     id->psz_fmtp   = NULL;
1026     id->psz_destination = p_sys->psz_destination ? strdup( p_sys->psz_destination ) : NULL;
1027     id->i_port = i_port;
1028     id->p_rtsp_url = NULL;
1029     vlc_mutex_init( p_stream, &id->lock_rtsp );
1030     id->i_rtsp_access = 0;
1031     id->rtsp_access = NULL;
1032
1033     switch( p_fmt->i_codec )
1034     {
1035         case VLC_FOURCC( 's', '1', '6', 'b' ):
1036             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 44100 )
1037             {
1038                 id->i_payload_type = 11;
1039             }
1040             else if( p_fmt->audio.i_channels == 2 &&
1041                      p_fmt->audio.i_rate == 44100 )
1042             {
1043                 id->i_payload_type = 10;
1044             }
1045             else
1046             {
1047                 id->i_payload_type = p_sys->i_payload_type++;
1048             }
1049             id->psz_rtpmap = malloc( strlen( "L16/*/*" ) + 20+1 );
1050             sprintf( id->psz_rtpmap, "L16/%d/%d", p_fmt->audio.i_rate,
1051                      p_fmt->audio.i_channels );
1052             id->i_clock_rate = p_fmt->audio.i_rate;
1053             id->pf_packetize = rtp_packetize_l16;
1054             break;
1055         case VLC_FOURCC( 'u', '8', ' ', ' ' ):
1056             id->i_payload_type = p_sys->i_payload_type++;
1057             id->psz_rtpmap = malloc( strlen( "L8/*/*" ) + 20+1 );
1058             sprintf( id->psz_rtpmap, "L8/%d/%d", p_fmt->audio.i_rate,
1059                      p_fmt->audio.i_channels );
1060             id->i_clock_rate = p_fmt->audio.i_rate;
1061             id->pf_packetize = rtp_packetize_l8;
1062             break;
1063         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
1064             id->i_payload_type = 14;
1065             id->i_clock_rate = 90000;
1066             id->psz_rtpmap = strdup( "MPA/90000" );
1067             id->pf_packetize = rtp_packetize_mpa;
1068             break;
1069         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
1070             id->i_payload_type = 32;
1071             id->i_clock_rate = 90000;
1072             id->psz_rtpmap = strdup( "MPV/90000" );
1073             id->pf_packetize = rtp_packetize_mpv;
1074             break;
1075         case VLC_FOURCC( 'a', '5', '2', ' ' ):
1076             id->i_payload_type = p_sys->i_payload_type++;
1077             id->i_clock_rate = 90000;
1078             id->psz_rtpmap = strdup( "ac3/90000" );
1079             id->pf_packetize = rtp_packetize_ac3;
1080             break;
1081         case VLC_FOURCC( 'H', '2', '6', '3' ):
1082             id->i_payload_type = p_sys->i_payload_type++;
1083             id->i_clock_rate = 90000;
1084             id->psz_rtpmap = strdup( "H263-1998/90000" );
1085             id->pf_packetize = rtp_packetize_h263;
1086             break;
1087         case VLC_FOURCC( 'h', '2', '6', '4' ):
1088             id->i_payload_type = p_sys->i_payload_type++;
1089             id->i_clock_rate = 90000;
1090             id->psz_rtpmap = strdup( "H264/90000" );
1091             id->pf_packetize = rtp_packetize_h264;
1092             id->psz_fmtp = NULL;
1093
1094             if( p_fmt->i_extra > 0 )
1095             {
1096                 uint8_t *p_buffer = p_fmt->p_extra;
1097                 int     i_buffer = p_fmt->i_extra;
1098                 char    *p_64_sps = NULL;
1099                 char    *p_64_pps = NULL;
1100                 char    hexa[6+1];
1101
1102                 while( i_buffer > 4 && 
1103                        p_buffer[0] == 0 && p_buffer[1] == 0 &&
1104                        p_buffer[2] == 0 && p_buffer[3] == 1 )
1105                 {
1106                     const int i_nal_type = p_buffer[4]&0x1f;
1107                     int i_offset;
1108                     int i_size      = 0;
1109
1110                     msg_Dbg( p_stream, "we found a startcode for NAL with TYPE:%d", i_nal_type );
1111
1112                     i_size = i_buffer;
1113                     for( i_offset = 4; i_offset+3 < i_buffer ; i_offset++)
1114                     {
1115                         if( p_buffer[i_offset] == 0 && p_buffer[i_offset+1] == 0 && p_buffer[i_offset+2] == 0 && p_buffer[i_offset+3] == 1 )
1116                         {
1117                             /* we found another startcode */
1118                             i_size = i_offset;
1119                             break;
1120                         } 
1121                     }
1122                     if( i_nal_type == 7 )
1123                     {
1124                         p_64_sps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
1125                         sprintf_hexa( hexa, &p_buffer[5], 3 );
1126                     }
1127                     else if( i_nal_type == 8 )
1128                     {
1129                         p_64_pps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
1130                     }
1131                     i_buffer -= i_size;
1132                     p_buffer += i_size;
1133                 }
1134                 /* */
1135                 if( p_64_sps && p_64_pps )
1136                     asprintf( &id->psz_fmtp, "packetization-mode=1;profile-level-id=%s;sprop-parameter-sets=%s,%s;", hexa, p_64_sps, p_64_pps );
1137                 if( p_64_sps )
1138                     free( p_64_sps );
1139                 if( p_64_pps )
1140                     free( p_64_pps );
1141             }
1142             if( !id->psz_fmtp )
1143                 id->psz_fmtp = strdup( "packetization-mode=1" );
1144             break;
1145
1146         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
1147         {
1148             char hexa[2*p_fmt->i_extra +1];
1149
1150             id->i_payload_type = p_sys->i_payload_type++;
1151             id->i_clock_rate = 90000;
1152             id->psz_rtpmap = strdup( "MP4V-ES/90000" );
1153             id->pf_packetize = rtp_packetize_split;
1154             if( p_fmt->i_extra > 0 )
1155             {
1156                 id->psz_fmtp = malloc( 100 + 2 * p_fmt->i_extra );
1157                 sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
1158                 sprintf( id->psz_fmtp,
1159                          "profile-level-id=3; config=%s;", hexa );
1160             }
1161             break;
1162         }
1163         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
1164         {
1165             id->i_payload_type = p_sys->i_payload_type++;
1166             id->i_clock_rate = p_fmt->audio.i_rate;
1167
1168             if(!p_sys->b_latm)
1169             {
1170                 char hexa[2*p_fmt->i_extra +1];
1171
1172                 id->psz_rtpmap = malloc( strlen( "mpeg4-generic/" ) + 12 );
1173                 sprintf( id->psz_rtpmap, "mpeg4-generic/%d", p_fmt->audio.i_rate );
1174                 id->pf_packetize = rtp_packetize_mp4a;
1175                 id->psz_fmtp = malloc( 200 + 2 * p_fmt->i_extra );
1176                 sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
1177                 sprintf( id->psz_fmtp,
1178                         "streamtype=5; profile-level-id=15; mode=AAC-hbr; "
1179                         "config=%s; SizeLength=13;IndexLength=3; "
1180                         "IndexDeltaLength=3; Profile=1;", hexa );
1181             }
1182             else
1183             {
1184                 char hexa[13];
1185                 int i;
1186                 unsigned char config[6];
1187                 unsigned int aacsrates[15] = {
1188                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1189                     16000, 12000, 11025, 8000, 7350, 0, 0 };
1190
1191                 for( i = 0; i < 15; i++ )
1192                     if( p_fmt->audio.i_rate == aacsrates[i] )
1193                         break;
1194
1195                 config[0]=0x40;
1196                 config[1]=0;
1197                 config[2]=0x20|i;
1198                 config[3]=p_fmt->audio.i_channels<<4;
1199                 config[4]=0x3f;
1200                 config[5]=0xc0;
1201
1202                 asprintf( &id->psz_rtpmap, "MP4A-LATM/%d/%d",
1203                           p_fmt->audio.i_rate, p_fmt->audio.i_channels );
1204                 id->pf_packetize = rtp_packetize_mp4a_latm;
1205                 sprintf_hexa( hexa, config, 6 );
1206                 asprintf( &id->psz_fmtp, "profile-level-id=15; "
1207                           "object=2; cpresent=0; config=%s", hexa );
1208             }
1209             break;
1210         }
1211         case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1212             id->i_payload_type = p_sys->i_payload_type++;
1213             id->psz_rtpmap = strdup( p_fmt->audio.i_channels == 2 ?
1214                                      "AMR/8000/2" : "AMR/8000" );
1215             id->psz_fmtp = strdup( "octet-align=1" );
1216             id->i_clock_rate = p_fmt->audio.i_rate;
1217             id->pf_packetize = rtp_packetize_amr;
1218             break; 
1219         case VLC_FOURCC( 's', 'a', 'w', 'b' ):
1220             id->i_payload_type = p_sys->i_payload_type++;
1221             id->psz_rtpmap = strdup( p_fmt->audio.i_channels == 2 ?
1222                                      "AMR-WB/16000/2" : "AMR-WB/16000" );
1223             id->psz_fmtp = strdup( "octet-align=1" );
1224             id->i_clock_rate = p_fmt->audio.i_rate;
1225             id->pf_packetize = rtp_packetize_amr;
1226             break; 
1227
1228         default:
1229             msg_Err( p_stream, "cannot add this stream (unsupported "
1230                      "codec:%4.4s)", (char*)&p_fmt->i_codec );
1231             if( p_access )
1232             {
1233                 sout_AccessOutDelete( p_access );
1234             }
1235             free( id );
1236             return NULL;
1237     }
1238     id->i_cat = p_fmt->i_cat;
1239
1240     id->ssrc[0] = rand()&0xff;
1241     id->ssrc[1] = rand()&0xff;
1242     id->ssrc[2] = rand()&0xff;
1243     id->ssrc[3] = rand()&0xff;
1244     id->i_sequence = rand()&0xffff;
1245     id->i_timestamp_start = rand()&0xffffffff;
1246     id->i_bitrate = p_fmt->i_bitrate/1000; /* Stream bitrate in kbps */
1247
1248     id->i_mtu    = config_GetInt( p_stream, "mtu" );  /* XXX beuk */
1249     if( id->i_mtu <= 16 + MTU_REDUCE )
1250     {
1251         /* better than nothing */
1252         id->i_mtu = 1500;
1253     }
1254     id->i_mtu -= MTU_REDUCE;
1255     msg_Dbg( p_stream, "maximum RTP packet size: %d bytes", id->i_mtu );
1256
1257     if( p_sys->p_rtsp_url )
1258     {
1259         char psz_urlc[strlen( p_sys->psz_rtsp_control ) + 1 + 10];
1260
1261         sprintf( psz_urlc, "%s/trackID=%d", p_sys->psz_rtsp_path, p_sys->i_es );
1262         msg_Dbg( p_stream, "rtsp: adding %s\n", psz_urlc );
1263         id->p_rtsp_url = httpd_UrlNewUnique( p_sys->p_rtsp_host, psz_urlc, NULL, NULL, NULL );
1264
1265         if( id->p_rtsp_url )
1266         {
1267             httpd_UrlCatch( id->p_rtsp_url, HTTPD_MSG_SETUP,    RtspCallbackId, (void*)id );
1268             //httpd_UrlCatch( id->p_rtsp_url, HTTPD_MSG_PLAY,     RtspCallback, (void*)p_stream );
1269             //httpd_UrlCatch( id->p_rtsp_url, HTTPD_MSG_PAUSE,    RtspCallback, (void*)p_stream );
1270         }
1271     }
1272
1273
1274     /* Update p_sys context */
1275     vlc_mutex_lock( &p_sys->lock_es );
1276     TAB_APPEND( p_sys->i_es, p_sys->es, id );
1277     vlc_mutex_unlock( &p_sys->lock_es );
1278
1279     psz_sdp = SDPGenerate( p_stream, p_sys->psz_destination, VLC_FALSE );
1280
1281     vlc_mutex_lock( &p_sys->lock_sdp );
1282     free( p_sys->psz_sdp );
1283     p_sys->psz_sdp = psz_sdp;
1284     vlc_mutex_unlock( &p_sys->lock_sdp );
1285
1286     p_sys->i_sdp_version++;
1287
1288     msg_Dbg( p_stream, "sdp=%s", p_sys->psz_sdp );
1289
1290     /* Update SDP (sap/file) */
1291     if( p_sys->b_export_sap ) SapSetup( p_stream );
1292     if( p_sys->b_export_sdp_file ) FileSetup( p_stream );
1293
1294     return id;
1295 }
1296
1297 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
1298 {
1299     sout_stream_sys_t *p_sys = p_stream->p_sys;
1300
1301     vlc_mutex_lock( &p_sys->lock_es );
1302     TAB_REMOVE( p_sys->i_es, p_sys->es, id );
1303     vlc_mutex_unlock( &p_sys->lock_es );
1304
1305     /* Release port */
1306     if( id->i_port > 0 )
1307     {
1308         if( id->i_cat == AUDIO_ES && p_sys->i_port_audio == 0 )
1309             p_sys->i_port_audio = id->i_port;
1310         else if( id->i_cat == VIDEO_ES && p_sys->i_port_video == 0 )
1311             p_sys->i_port_video = id->i_port;
1312     }
1313
1314     if( id->p_access )
1315     {
1316         if( id->psz_rtpmap )
1317         {
1318             free( id->psz_rtpmap );
1319         }
1320         if( id->psz_fmtp )
1321         {
1322             free( id->psz_fmtp );
1323         }
1324         if( id->psz_destination )
1325             free( id->psz_destination );
1326         sout_AccessOutDelete( id->p_access );
1327     }
1328     else if( id->p_input )
1329     {
1330         sout_MuxDeleteStream( p_sys->p_mux, id->p_input );
1331     }
1332     if( id->p_rtsp_url )
1333     {
1334         httpd_UrlDelete( id->p_rtsp_url );
1335     }
1336     vlc_mutex_destroy( &id->lock_rtsp );
1337     if( id->rtsp_access ) free( id->rtsp_access );
1338
1339     /* Update SDP (sap/file) */
1340     if( p_sys->b_export_sap && !p_sys->p_mux ) SapSetup( p_stream );
1341     if( p_sys->b_export_sdp_file ) FileSetup( p_stream );
1342
1343     free( id );
1344     return VLC_SUCCESS;
1345 }
1346
1347 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
1348                  block_t *p_buffer )
1349 {
1350     block_t *p_next;
1351
1352     if( p_stream->p_sys->p_mux )
1353     {
1354         sout_MuxSendBuffer( p_stream->p_sys->p_mux, id->p_input, p_buffer );
1355     }
1356     else
1357     {
1358         while( p_buffer )
1359         {
1360             p_next = p_buffer->p_next;
1361             if( id->pf_packetize( p_stream, id, p_buffer ) )
1362             {
1363                 break;
1364             }
1365             block_Release( p_buffer );
1366             p_buffer = p_next;
1367         }
1368     }
1369     return VLC_SUCCESS;
1370 }
1371
1372
1373 static int AccessOutGrabberWriteBuffer( sout_stream_t *p_stream,
1374                                         block_t *p_buffer )
1375 {
1376     sout_stream_sys_t *p_sys = p_stream->p_sys;
1377
1378     int64_t  i_dts = p_buffer->i_dts;
1379     uint32_t i_timestamp = i_dts * 9 / 100;
1380
1381     uint8_t         *p_data = p_buffer->p_buffer;
1382     unsigned int    i_data  = p_buffer->i_buffer;
1383     unsigned int    i_max   = p_sys->i_mtu - 12;
1384
1385     unsigned i_packet = ( p_buffer->i_buffer + i_max - 1 ) / i_max;
1386
1387     while( i_data > 0 )
1388     {
1389         unsigned int i_size;
1390
1391         /* output complete packet */
1392         if( p_sys->packet &&
1393             p_sys->packet->i_buffer + i_data > i_max )
1394         {
1395             sout_AccessOutWrite( p_sys->p_access, p_sys->packet );
1396             p_sys->packet = NULL;
1397         }
1398
1399         if( p_sys->packet == NULL )
1400         {
1401             /* allocate a new packet */
1402             p_sys->packet = block_New( p_stream, p_sys->i_mtu );
1403             p_sys->packet->p_buffer[ 0] = 0x80;
1404             p_sys->packet->p_buffer[ 1] = 0x80|p_sys->i_payload_type;
1405             p_sys->packet->p_buffer[ 2] = ( p_sys->i_sequence >> 8)&0xff;
1406             p_sys->packet->p_buffer[ 3] = ( p_sys->i_sequence     )&0xff;
1407             p_sys->packet->p_buffer[ 4] = ( i_timestamp >> 24 )&0xff;
1408             p_sys->packet->p_buffer[ 5] = ( i_timestamp >> 16 )&0xff;
1409             p_sys->packet->p_buffer[ 6] = ( i_timestamp >>  8 )&0xff;
1410             p_sys->packet->p_buffer[ 7] = ( i_timestamp       )&0xff;
1411             p_sys->packet->p_buffer[ 8] = p_sys->ssrc[0];
1412             p_sys->packet->p_buffer[ 9] = p_sys->ssrc[1];
1413             p_sys->packet->p_buffer[10] = p_sys->ssrc[2];
1414             p_sys->packet->p_buffer[11] = p_sys->ssrc[3];
1415             p_sys->packet->i_buffer = 12;
1416
1417             p_sys->packet->i_dts = i_dts;
1418             p_sys->packet->i_length = p_buffer->i_length / i_packet;
1419             i_dts += p_sys->packet->i_length;
1420
1421             p_sys->i_sequence++;
1422         }
1423
1424         i_size = __MIN( i_data,
1425                         (unsigned)(p_sys->i_mtu - p_sys->packet->i_buffer) );
1426
1427         memcpy( &p_sys->packet->p_buffer[p_sys->packet->i_buffer],
1428                 p_data, i_size );
1429
1430         p_sys->packet->i_buffer += i_size;
1431         p_data += i_size;
1432         i_data -= i_size;
1433     }
1434
1435     return VLC_SUCCESS;
1436 }
1437
1438 static int AccessOutGrabberWrite( sout_access_out_t *p_access,
1439                                   block_t *p_buffer )
1440 {
1441     sout_stream_t *p_stream = (sout_stream_t*)p_access->p_sys;
1442
1443     //fprintf( stderr, "received buffer size=%d\n", p_buffer->i_buffer );
1444     //
1445     while( p_buffer )
1446     {
1447         block_t *p_next;
1448
1449         AccessOutGrabberWriteBuffer( p_stream, p_buffer );
1450
1451         p_next = p_buffer->p_next;
1452         block_Release( p_buffer );
1453         p_buffer = p_next;
1454     }
1455
1456     return VLC_SUCCESS;
1457 }
1458
1459 /****************************************************************************
1460  * SAP:
1461  ****************************************************************************/
1462 static int SapSetup( sout_stream_t *p_stream )
1463 {
1464     sout_stream_sys_t *p_sys = p_stream->p_sys;
1465     sout_instance_t   *p_sout = p_stream->p_sout;
1466     announce_method_t *p_method = sout_SAPMethod();
1467
1468     /* Remove the previous session */
1469     if( p_sys->p_session != NULL)
1470     {
1471         sout_AnnounceUnRegister( p_sout, p_sys->p_session);
1472         sout_AnnounceSessionDestroy( p_sys->p_session );
1473         p_sys->p_session = NULL;
1474     }
1475
1476     if( ( p_sys->i_es > 0 || p_sys->p_mux ) && p_sys->psz_sdp && *p_sys->psz_sdp )
1477     {
1478         p_sys->p_session = sout_AnnounceRegisterSDP( p_sout, SOUT_CFG_PREFIX,
1479                                                      p_sys->psz_sdp,
1480                                                      p_sys->psz_destination,
1481                                                      p_method );
1482     }
1483
1484     sout_MethodRelease( p_method );
1485     return VLC_SUCCESS;
1486 }
1487
1488 /****************************************************************************
1489 * File:
1490 ****************************************************************************/
1491 static int FileSetup( sout_stream_t *p_stream )
1492 {
1493     sout_stream_sys_t *p_sys = p_stream->p_sys;
1494     FILE            *f;
1495
1496     if( ( f = utf8_fopen( p_sys->psz_sdp_file, "wt" ) ) == NULL )
1497     {
1498         msg_Err( p_stream, "cannot open file '%s' (%s)",
1499                  p_sys->psz_sdp_file, strerror(errno) );
1500         return VLC_EGENERIC;
1501     }
1502
1503     fprintf( f, "%s", p_sys->psz_sdp );
1504     fclose( f );
1505
1506     return VLC_SUCCESS;
1507 }
1508
1509 /****************************************************************************
1510  * HTTP:
1511  ****************************************************************************/
1512 static int  HttpCallback( httpd_file_sys_t *p_args,
1513                           httpd_file_t *, uint8_t *p_request,
1514                           uint8_t **pp_data, int *pi_data );
1515
1516 static int HttpSetup( sout_stream_t *p_stream, vlc_url_t *url)
1517 {
1518     sout_stream_sys_t *p_sys = p_stream->p_sys;
1519
1520     p_sys->p_httpd_host = httpd_HostNew( VLC_OBJECT(p_stream), url->psz_host, url->i_port > 0 ? url->i_port : 80 );
1521     if( p_sys->p_httpd_host )
1522     {
1523         p_sys->p_httpd_file = httpd_FileNew( p_sys->p_httpd_host,
1524                                              url->psz_path ? url->psz_path : "/",
1525                                              "application/sdp",
1526                                              NULL, NULL, NULL,
1527                                              HttpCallback, (void*)p_sys );
1528     }
1529     if( p_sys->p_httpd_file == NULL )
1530     {
1531         return VLC_EGENERIC;
1532     }
1533     return VLC_SUCCESS;
1534 }
1535
1536 static int  HttpCallback( httpd_file_sys_t *p_args,
1537                           httpd_file_t *f, uint8_t *p_request,
1538                           uint8_t **pp_data, int *pi_data )
1539 {
1540     sout_stream_sys_t *p_sys = (sout_stream_sys_t*)p_args;
1541
1542     vlc_mutex_lock( &p_sys->lock_sdp );
1543     if( p_sys->psz_sdp && *p_sys->psz_sdp )
1544     {
1545         *pi_data = strlen( p_sys->psz_sdp );
1546         *pp_data = malloc( *pi_data );
1547         memcpy( *pp_data, p_sys->psz_sdp, *pi_data );
1548     }
1549     else
1550     {
1551         *pp_data = NULL;
1552         *pi_data = 0;
1553     }
1554     vlc_mutex_unlock( &p_sys->lock_sdp );
1555
1556     return VLC_SUCCESS;
1557 }
1558
1559 /****************************************************************************
1560  * RTSP:
1561  ****************************************************************************/
1562 static rtsp_client_t *RtspClientNew( sout_stream_t *p_stream, const char *psz_session )
1563 {
1564     rtsp_client_t *rtsp = malloc( sizeof( rtsp_client_t ));
1565
1566     rtsp->psz_session = strdup( psz_session );
1567     rtsp->i_last = 0;
1568     rtsp->b_playing = VLC_FALSE;
1569     rtsp->i_id = 0;
1570     rtsp->id = NULL;
1571     rtsp->i_access = 0;
1572     rtsp->access = NULL;
1573
1574     TAB_APPEND( p_stream->p_sys->i_rtsp, p_stream->p_sys->rtsp, rtsp );
1575
1576     return rtsp;
1577 }
1578 static rtsp_client_t *RtspClientGet( sout_stream_t *p_stream, const char *psz_session )
1579 {
1580     int i;
1581
1582     if( !psz_session ) return NULL;
1583
1584     for( i = 0; i < p_stream->p_sys->i_rtsp; i++ )
1585     {
1586         if( !strcmp( p_stream->p_sys->rtsp[i]->psz_session, psz_session ) )
1587         {
1588             return p_stream->p_sys->rtsp[i];
1589         }
1590     }
1591     return NULL;
1592 }
1593
1594 static void RtspClientDel( sout_stream_t *p_stream, rtsp_client_t *rtsp )
1595 {
1596     int i;
1597     TAB_REMOVE( p_stream->p_sys->i_rtsp, p_stream->p_sys->rtsp, rtsp );
1598
1599     for( i = 0; i < rtsp->i_access; i++ )
1600     {
1601         sout_AccessOutDelete( rtsp->access[i] );
1602     }
1603     if( rtsp->id )     free( rtsp->id );
1604     if( rtsp->access ) free( rtsp->access );
1605
1606     free( rtsp->psz_session );
1607     free( rtsp );
1608 }
1609
1610 static int RtspSetup( sout_stream_t *p_stream, vlc_url_t *url )
1611 {
1612     sout_stream_sys_t *p_sys = p_stream->p_sys;
1613
1614     msg_Dbg( p_stream, "rtsp setup: %s : %d / %s\n", url->psz_host, url->i_port, url->psz_path );
1615
1616     p_sys->p_rtsp_host = httpd_HostNew( VLC_OBJECT(p_stream), url->psz_host, url->i_port > 0 ? url->i_port : 554 );
1617     if( p_sys->p_rtsp_host == NULL )
1618     {
1619         return VLC_EGENERIC;
1620     }
1621
1622     p_sys->psz_rtsp_path = strdup( url->psz_path ? url->psz_path : "/" );
1623     p_sys->psz_rtsp_control = malloc (strlen( url->psz_host ) + 20 + strlen( p_sys->psz_rtsp_path ) + 1 );
1624     sprintf( p_sys->psz_rtsp_control, "rtsp://%s:%d%s",
1625              url->psz_host,  url->i_port > 0 ? url->i_port : 554, p_sys->psz_rtsp_path );
1626
1627     p_sys->p_rtsp_url = httpd_UrlNewUnique( p_sys->p_rtsp_host, p_sys->psz_rtsp_path, NULL, NULL, NULL );
1628     if( p_sys->p_rtsp_url == 0 )
1629     {
1630         return VLC_EGENERIC;
1631     }
1632     httpd_UrlCatch( p_sys->p_rtsp_url, HTTPD_MSG_DESCRIBE, RtspCallback, (void*)p_stream );
1633     httpd_UrlCatch( p_sys->p_rtsp_url, HTTPD_MSG_PLAY,     RtspCallback, (void*)p_stream );
1634     httpd_UrlCatch( p_sys->p_rtsp_url, HTTPD_MSG_PAUSE,    RtspCallback, (void*)p_stream );
1635     httpd_UrlCatch( p_sys->p_rtsp_url, HTTPD_MSG_TEARDOWN, RtspCallback, (void*)p_stream );
1636
1637     return VLC_SUCCESS;
1638 }
1639
1640 static int  RtspCallback( httpd_callback_sys_t *p_args,
1641                           httpd_client_t *cl,
1642                           httpd_message_t *answer, httpd_message_t *query )
1643 {
1644     sout_stream_t *p_stream = (sout_stream_t*)p_args;
1645     sout_stream_sys_t *p_sys = p_stream->p_sys;
1646     char *psz_destination = p_sys->psz_destination;
1647     const char *psz_session = NULL;
1648     const char *psz_cseq = NULL;
1649     int i_cseq = 0;
1650
1651     if( answer == NULL || query == NULL )
1652     {
1653         return VLC_SUCCESS;
1654     }
1655     //fprintf( stderr, "RtspCallback query: type=%d\n", query->i_type );
1656
1657     answer->i_proto = HTTPD_PROTO_RTSP;
1658     answer->i_version= query->i_version;
1659     answer->i_type   = HTTPD_MSG_ANSWER;
1660
1661     switch( query->i_type )
1662     {
1663         case HTTPD_MSG_DESCRIBE:
1664         {
1665             char *psz_sdp = SDPGenerate( p_stream, psz_destination ? psz_destination : "0.0.0.0", VLC_TRUE );
1666
1667             answer->i_status = 200;
1668             answer->psz_status = strdup( "OK" );
1669             httpd_MsgAdd( answer, "Content-type",  "%s", "application/sdp" );
1670             httpd_MsgAdd( answer, "Content-Base",  "%s", p_sys->psz_rtsp_control );
1671             answer->p_body = (uint8_t *)psz_sdp;
1672             answer->i_body = strlen( psz_sdp );
1673             break;
1674         }
1675
1676         case HTTPD_MSG_PLAY:
1677         {
1678             rtsp_client_t *rtsp;
1679             /* for now only multicast so easy */
1680             answer->i_status = 200;
1681             answer->psz_status = strdup( "OK" );
1682             answer->i_body = 0;
1683             answer->p_body = NULL;
1684
1685             psz_session = httpd_MsgGet( query, "Session" );
1686             rtsp = RtspClientGet( p_stream, psz_session );
1687             if( rtsp && !rtsp->b_playing )
1688             {
1689                 int i_id;
1690                 /* FIXME */
1691                 rtsp->b_playing = VLC_TRUE;
1692
1693                 vlc_mutex_lock( &p_sys->lock_es );
1694                 for( i_id = 0; i_id < rtsp->i_id; i_id++ )
1695                 {
1696                     sout_stream_id_t *id = rtsp->id[i_id];
1697                     int i;
1698
1699                     for( i = 0; i < p_sys->i_es; i++ )
1700                     {
1701                         if( id == p_sys->es[i] )
1702                             break;
1703                     }
1704                     if( i >= p_sys->i_es ) continue;
1705
1706                     vlc_mutex_lock( &id->lock_rtsp );
1707                     TAB_APPEND( id->i_rtsp_access, id->rtsp_access, rtsp->access[i_id] );
1708                     vlc_mutex_unlock( &id->lock_rtsp );
1709                 }
1710                 vlc_mutex_unlock( &p_sys->lock_es );
1711             }
1712             break;
1713         }
1714         case HTTPD_MSG_PAUSE:
1715             /* FIXME */
1716             return VLC_EGENERIC;
1717         case HTTPD_MSG_TEARDOWN:
1718         {
1719             rtsp_client_t *rtsp;
1720
1721             /* for now only multicast so easy again */
1722             answer->i_status = 200;
1723             answer->psz_status = strdup( "OK" );
1724             answer->i_body = 0;
1725             answer->p_body = NULL;
1726
1727             psz_session = httpd_MsgGet( query, "Session" );
1728             rtsp = RtspClientGet( p_stream, psz_session );
1729             if( rtsp )
1730             {
1731                 int i_id;
1732
1733                 vlc_mutex_lock( &p_sys->lock_es );
1734                 for( i_id = 0; i_id < rtsp->i_id; i_id++ )
1735                 {
1736                     sout_stream_id_t *id = rtsp->id[i_id];
1737                     int i;
1738
1739                     for( i = 0; i < p_sys->i_es; i++ )
1740                     {
1741                         if( id == p_sys->es[i] )
1742                             break;
1743                     }
1744                     if( i >= p_sys->i_es ) continue;
1745
1746                     vlc_mutex_lock( &id->lock_rtsp );
1747                     TAB_REMOVE( id->i_rtsp_access, id->rtsp_access, rtsp->access[i_id] );
1748                     vlc_mutex_unlock( &id->lock_rtsp );
1749                 }
1750                 vlc_mutex_unlock( &p_sys->lock_es );
1751
1752                 RtspClientDel( p_stream, rtsp );
1753             }
1754             break;
1755         }
1756
1757         default:
1758             return VLC_EGENERIC;
1759     }
1760     httpd_MsgAdd( answer, "Server", PACKAGE_STRING );
1761     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
1762     psz_cseq = httpd_MsgGet( query, "Cseq" );
1763     if( psz_cseq )
1764         i_cseq = atoi( psz_cseq );
1765     else
1766         i_cseq = 0;
1767     httpd_MsgAdd( answer, "Cseq", "%d", i_cseq );
1768     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
1769
1770     if( psz_session )
1771         httpd_MsgAdd( answer, "Session", "%s;timeout=5", psz_session );
1772     return VLC_SUCCESS;
1773 }
1774
1775 static int RtspCallbackId( httpd_callback_sys_t *p_args,
1776                           httpd_client_t *cl,
1777                           httpd_message_t *answer, httpd_message_t *query )
1778 {
1779     sout_stream_id_t *id = (sout_stream_id_t*)p_args;
1780     sout_stream_t    *p_stream = id->p_stream;
1781     sout_stream_sys_t *p_sys = p_stream->p_sys;
1782     char psz_session_init[100];
1783     const char *psz_session = NULL;
1784     const char *psz_cseq = NULL;
1785     int  i_cseq = 0;
1786
1787
1788     if( answer == NULL || query == NULL )
1789         return VLC_SUCCESS;
1790     //fprintf( stderr, "RtspCallback query: type=%d\n", query->i_type );
1791
1792     /* */
1793     snprintf( psz_session_init, sizeof(psz_session_init), "%d", rand() );
1794
1795     /* */
1796     answer->i_proto = HTTPD_PROTO_RTSP;
1797     answer->i_version= query->i_version;
1798     answer->i_type   = HTTPD_MSG_ANSWER;
1799
1800     switch( query->i_type )
1801     {
1802         case HTTPD_MSG_SETUP:
1803         {
1804             const char *psz_transport = httpd_MsgGet( query, "Transport" );
1805
1806             //fprintf( stderr, "HTTPD_MSG_SETUP: transport=%s\n", psz_transport );
1807
1808             if( strstr( psz_transport, "multicast" ) && id->psz_destination )
1809             {
1810                 //fprintf( stderr, "HTTPD_MSG_SETUP: multicast\n" );
1811                 answer->i_status = 200;
1812                 answer->psz_status = strdup( "OK" );
1813                 answer->i_body = 0;
1814                 answer->p_body = NULL;
1815
1816                 psz_session = httpd_MsgGet( query, "Session" );
1817                 if( !psz_session )
1818                     psz_session = psz_session_init;
1819
1820                 httpd_MsgAdd( answer, "Transport",
1821                               "RTP/AVP/UDP;destination=%s;port=%d-%d;ttl=%d",
1822                               id->psz_destination, id->i_port,id->i_port+1,
1823                               p_sys->i_ttl > 0 ? p_sys->i_ttl : 1);
1824             }
1825             else if( strstr( psz_transport, "unicast" ) && strstr( psz_transport, "client_port=" ) )
1826             {
1827                 int  i_port = atoi( strstr( psz_transport, "client_port=" ) + strlen("client_port=") );
1828                 char ip[NI_MAXNUMERICHOST], psz_access[17], psz_url[NI_MAXNUMERICHOST + 8];
1829
1830                 sout_access_out_t *p_access;
1831
1832                 rtsp_client_t *rtsp = NULL;
1833
1834                 if( httpd_ClientIP( cl, ip ) == NULL )
1835                 {
1836                     answer->i_status = 500;
1837                     answer->psz_status = strdup( "Internal server error" );
1838                     answer->i_body = 0;
1839                     answer->p_body = NULL;
1840                     break;
1841                 }
1842
1843                 //fprintf( stderr, "HTTPD_MSG_SETUP: unicast ip=%s port=%d\n", ip, i_port );
1844
1845                 psz_session = httpd_MsgGet( query, "Session" );
1846                 if( !psz_session )
1847                 {
1848                     psz_session = psz_session_init;
1849                     rtsp = RtspClientNew( p_stream, psz_session_init );
1850                 }
1851                 else
1852                 {
1853                     rtsp = RtspClientGet( p_stream, psz_session );
1854                     if( rtsp == NULL )
1855                     {
1856                         answer->i_status = 454;
1857                         answer->psz_status = strdup( "Unknown session id" );
1858                         answer->i_body = 0;
1859                         answer->p_body = NULL;
1860                         break;
1861                     }
1862                 }
1863
1864                 /* first try to create the access out */
1865                 if( p_sys->i_ttl )
1866                     snprintf( psz_access, sizeof( psz_access ),
1867                               "udp{raw,ttl=%d}", p_sys->i_ttl );
1868                 else
1869                     strlcpy( psz_access, "udp{raw}", sizeof( psz_access ) );
1870
1871                 snprintf( psz_url, sizeof( psz_url ),
1872                          ( strchr( ip, ':' ) != NULL ) ? "[%s]:%d" : "%s:%d",
1873                          ip, i_port );
1874
1875                 if( ( p_access = sout_AccessOutNew( p_stream->p_sout, psz_access, psz_url ) ) == NULL )
1876                 {
1877                     msg_Err( p_stream, "cannot create the access out for %s://%s",
1878                              psz_access, psz_url );
1879                     answer->i_status = 500;
1880                     answer->psz_status = strdup( "Internal server error" );
1881                     answer->i_body = 0;
1882                     answer->p_body = NULL;
1883                     break;
1884                 }
1885
1886                 TAB_APPEND( rtsp->i_id, rtsp->id, id );
1887                 TAB_APPEND( rtsp->i_access, rtsp->access, p_access );
1888
1889                 answer->i_status = 200;
1890                 answer->psz_status = strdup( "OK" );
1891                 answer->i_body = 0;
1892                 answer->p_body = NULL;
1893
1894                 httpd_MsgAdd( answer, "Transport",
1895                               "RTP/AVP/UDP;client_port=%d-%d", i_port, i_port + 1 );
1896             }
1897             else /* TODO  strstr( psz_transport, "interleaved" ) ) */
1898             {
1899                 answer->i_status = 461;
1900                 answer->psz_status = strdup( "Unsupported Transport" );
1901                 answer->i_body = 0;
1902                 answer->p_body = NULL;
1903             }
1904             break;
1905         }
1906
1907         default:
1908             return VLC_EGENERIC;
1909     }
1910     httpd_MsgAdd( answer, "Server", "VLC Server" );
1911     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
1912     psz_cseq = httpd_MsgGet( query, "Cseq" );
1913     if( psz_cseq )
1914         i_cseq = atoi( psz_cseq );
1915     else
1916         i_cseq = 0;
1917     httpd_MsgAdd( answer, "Cseq", "%d", i_cseq );
1918     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
1919
1920     if( psz_session )
1921         httpd_MsgAdd( answer, "Session", "%s"/*;timeout=5*/, psz_session );
1922     return VLC_SUCCESS;
1923 }
1924
1925 /****************************************************************************
1926  * rtp_packetize_*:
1927  ****************************************************************************/
1928 static void rtp_packetize_common( sout_stream_id_t *id, block_t *out,
1929                                   int b_marker, int64_t i_pts )
1930 {
1931     uint32_t i_timestamp = i_pts * (int64_t)id->i_clock_rate / I64C(1000000);
1932
1933     out->p_buffer[0] = 0x80;
1934     out->p_buffer[1] = (b_marker?0x80:0x00)|id->i_payload_type;
1935     out->p_buffer[2] = ( id->i_sequence >> 8)&0xff;
1936     out->p_buffer[3] = ( id->i_sequence     )&0xff;
1937     out->p_buffer[4] = ( i_timestamp >> 24 )&0xff;
1938     out->p_buffer[5] = ( i_timestamp >> 16 )&0xff;
1939     out->p_buffer[6] = ( i_timestamp >>  8 )&0xff;
1940     out->p_buffer[7] = ( i_timestamp       )&0xff;
1941
1942     out->p_buffer[ 8] = id->ssrc[0];
1943     out->p_buffer[ 9] = id->ssrc[1];
1944     out->p_buffer[10] = id->ssrc[2];
1945     out->p_buffer[11] = id->ssrc[3];
1946
1947     out->i_buffer = 12;
1948     id->i_sequence++;
1949 }
1950
1951 static void rtp_packetize_send( sout_stream_id_t *id, block_t *out )
1952 {
1953     int i;
1954     vlc_mutex_lock( &id->lock_rtsp );
1955     for( i = 0; i < id->i_rtsp_access; i++ )
1956     {
1957         sout_AccessOutWrite( id->rtsp_access[i], block_Duplicate( out ) );
1958     }
1959     vlc_mutex_unlock( &id->lock_rtsp );
1960
1961     if( id->p_access )
1962     {
1963         sout_AccessOutWrite( id->p_access, out );
1964     }
1965     else
1966     {
1967         block_Release( out );
1968     }
1969 }
1970
1971 static int rtp_packetize_mpa( sout_stream_t *p_stream, sout_stream_id_t *id,
1972                               block_t *in )
1973 {
1974     int     i_max   = id->i_mtu - 12 - 4; /* payload max in one packet */
1975     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1976
1977     uint8_t *p_data = in->p_buffer;
1978     int     i_data  = in->i_buffer;
1979     int     i;
1980
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, 16 + i_payload );
1985
1986         /* rtp common header */
1987         rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts );
1988         /* mbz set to 0 */
1989         out->p_buffer[12] = 0;
1990         out->p_buffer[13] = 0;
1991         /* fragment offset in the current frame */
1992         out->p_buffer[14] = ( (i*i_max) >> 8 )&0xff;
1993         out->p_buffer[15] = ( (i*i_max)      )&0xff;
1994         memcpy( &out->p_buffer[16], p_data, i_payload );
1995
1996         out->i_buffer   = 16 + i_payload;
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 /* rfc2250 */
2010 static int rtp_packetize_mpv( sout_stream_t *p_stream, sout_stream_id_t *id,
2011                               block_t *in )
2012 {
2013     int     i_max   = id->i_mtu - 12 - 4; /* payload max in one packet */
2014     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2015
2016     uint8_t *p_data = in->p_buffer;
2017     int     i_data  = in->i_buffer;
2018     int     i;
2019     int     b_sequence_start = 0;
2020     int     i_temporal_ref = 0;
2021     int     i_picture_coding_type = 0;
2022     int     i_fbv = 0, i_bfc = 0, i_ffv = 0, i_ffc = 0;
2023     int     b_start_slice = 0;
2024
2025     /* preparse this packet to get some info */
2026     if( in->i_buffer > 4 )
2027     {
2028         uint8_t *p = p_data;
2029         int      i_rest = in->i_buffer;
2030
2031         for( ;; )
2032         {
2033             while( i_rest > 4 &&
2034                    ( p[0] != 0x00 || p[1] != 0x00 || p[2] != 0x01 ) )
2035             {
2036                 p++;
2037                 i_rest--;
2038             }
2039             if( i_rest <= 4 )
2040             {
2041                 break;
2042             }
2043             p += 3;
2044             i_rest -= 4;
2045
2046             if( *p == 0xb3 )
2047             {
2048                 /* sequence start code */
2049                 b_sequence_start = 1;
2050             }
2051             else if( *p == 0x00 && i_rest >= 4 )
2052             {
2053                 /* picture */
2054                 i_temporal_ref = ( p[1] << 2) |((p[2]>>6)&0x03);
2055                 i_picture_coding_type = (p[2] >> 3)&0x07;
2056
2057                 if( i_rest >= 4 && ( i_picture_coding_type == 2 ||
2058                                     i_picture_coding_type == 3 ) )
2059                 {
2060                     i_ffv = (p[3] >> 2)&0x01;
2061                     i_ffc = ((p[3]&0x03) << 1)|((p[4]>>7)&0x01);
2062                     if( i_rest > 4 && i_picture_coding_type == 3 )
2063                     {
2064                         i_fbv = (p[4]>>6)&0x01;
2065                         i_bfc = (p[4]>>3)&0x07;
2066                     }
2067                 }
2068             }
2069             else if( *p <= 0xaf )
2070             {
2071                 b_start_slice = 1;
2072             }
2073         }
2074     }
2075
2076     for( i = 0; i < i_count; i++ )
2077     {
2078         int           i_payload = __MIN( i_max, i_data );
2079         block_t *out = block_New( p_stream,
2080                                              16 + i_payload );
2081         uint32_t      h = ( i_temporal_ref << 16 )|
2082                           ( b_sequence_start << 13 )|
2083                           ( b_start_slice << 12 )|
2084                           ( i == i_count - 1 ? 1 << 11 : 0 )|
2085                           ( i_picture_coding_type << 8 )|
2086                           ( i_fbv << 7 )|( i_bfc << 4 )|( i_ffv << 3 )|i_ffc;
2087
2088         /* rtp common header */
2089         rtp_packetize_common( id, out, (i == i_count - 1)?1:0,
2090                               in->i_pts > 0 ? in->i_pts : in->i_dts );
2091
2092         /* 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 */
2093         out->p_buffer[12] = ( h >> 24 )&0xff;
2094         out->p_buffer[13] = ( h >> 16 )&0xff;
2095         out->p_buffer[14] = ( h >>  8 )&0xff;
2096         out->p_buffer[15] = ( h       )&0xff;
2097
2098         memcpy( &out->p_buffer[16], p_data, i_payload );
2099
2100         out->i_buffer   = 16 + i_payload;
2101         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2102         out->i_length = in->i_length / i_count;
2103
2104         rtp_packetize_send( id, out );
2105
2106         p_data += i_payload;
2107         i_data -= i_payload;
2108     }
2109
2110     return VLC_SUCCESS;
2111 }
2112
2113 static int rtp_packetize_ac3( sout_stream_t *p_stream, sout_stream_id_t *id,
2114                               block_t *in )
2115 {
2116     int     i_max   = id->i_mtu - 12 - 2; /* payload max in one packet */
2117     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2118
2119     uint8_t *p_data = in->p_buffer;
2120     int     i_data  = in->i_buffer;
2121     int     i;
2122
2123     for( i = 0; i < i_count; i++ )
2124     {
2125         int           i_payload = __MIN( i_max, i_data );
2126         block_t *out = block_New( p_stream, 14 + i_payload );
2127
2128         /* rtp common header */
2129         rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts );
2130         /* unit count */
2131         out->p_buffer[12] = 1;
2132         /* unit header */
2133         out->p_buffer[13] = 0x00;
2134         /* data */
2135         memcpy( &out->p_buffer[14], p_data, i_payload );
2136
2137         out->i_buffer   = 14 + i_payload;
2138         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2139         out->i_length = in->i_length / i_count;
2140
2141         rtp_packetize_send( id, out );
2142
2143         p_data += i_payload;
2144         i_data -= i_payload;
2145     }
2146
2147     return VLC_SUCCESS;
2148 }
2149
2150 static int rtp_packetize_split( sout_stream_t *p_stream, sout_stream_id_t *id,
2151                                 block_t *in )
2152 {
2153     int     i_max   = id->i_mtu - 12; /* payload max in one packet */
2154     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2155
2156     uint8_t *p_data = in->p_buffer;
2157     int     i_data  = in->i_buffer;
2158     int     i;
2159
2160     for( i = 0; i < i_count; i++ )
2161     {
2162         int           i_payload = __MIN( i_max, i_data );
2163         block_t *out = block_New( p_stream, 12 + i_payload );
2164
2165         /* rtp common header */
2166         rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
2167                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2168         memcpy( &out->p_buffer[12], p_data, i_payload );
2169
2170         out->i_buffer   = 12 + i_payload;
2171         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2172         out->i_length = in->i_length / i_count;
2173
2174         rtp_packetize_send( id, out );
2175
2176         p_data += i_payload;
2177         i_data -= i_payload;
2178     }
2179
2180     return VLC_SUCCESS;
2181 }
2182
2183 /* rfc3016 */
2184 static int rtp_packetize_mp4a_latm( sout_stream_t *p_stream, sout_stream_id_t *id,
2185                                 block_t *in )
2186 {
2187     int     i_max   = id->i_mtu - 14;              /* payload max in one packet */
2188     int     latmhdrsize = in->i_buffer / 0xff + 1;
2189     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2190
2191     uint8_t *p_data = in->p_buffer, *p_header = NULL;
2192     int     i_data  = in->i_buffer;
2193     int     i;
2194
2195     for( i = 0; i < i_count; i++ )
2196     {
2197         int     i_payload = __MIN( i_max, i_data );
2198         block_t *out;
2199
2200         if( i != 0 )
2201             latmhdrsize = 0;
2202         out = block_New( p_stream, 12 + latmhdrsize + i_payload );
2203
2204         /* rtp common header */
2205         rtp_packetize_common( id, out, ((i == i_count - 1) ? 1 : 0),
2206                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2207
2208         if( i == 0 )
2209         {
2210             int tmp = in->i_buffer;
2211
2212             p_header=out->p_buffer+12;
2213             while( tmp > 0xfe )
2214             {
2215                 *p_header = 0xff;
2216                 p_header++;
2217                 tmp -= 0xff;
2218             }
2219             *p_header = tmp;
2220         }
2221
2222         memcpy( &out->p_buffer[12+latmhdrsize], p_data, i_payload );
2223
2224         out->i_buffer   = 12 + latmhdrsize + i_payload;
2225         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2226         out->i_length = in->i_length / i_count;
2227
2228         rtp_packetize_send( id, out );
2229
2230         p_data += i_payload;
2231         i_data -= i_payload;
2232     }
2233
2234     return VLC_SUCCESS;
2235 }
2236
2237 static int rtp_packetize_l16( sout_stream_t *p_stream, sout_stream_id_t *id,
2238                               block_t *in )
2239 {
2240     int     i_max   = id->i_mtu - 12; /* payload max in one packet */
2241     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2242
2243     uint8_t *p_data = in->p_buffer;
2244     int     i_data  = in->i_buffer;
2245     int     i_packet = 0;
2246
2247     while( i_data > 0 )
2248     {
2249         int           i_payload = (__MIN( i_max, i_data )/4)*4;
2250         block_t *out = block_New( p_stream, 12 + i_payload );
2251
2252         /* rtp common header */
2253         rtp_packetize_common( id, out, 0,
2254                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2255         memcpy( &out->p_buffer[12], p_data, i_payload );
2256
2257         out->i_buffer   = 12 + i_payload;
2258         out->i_dts    = in->i_dts + i_packet * in->i_length / i_count;
2259         out->i_length = in->i_length / i_count;
2260
2261         rtp_packetize_send( id, out );
2262
2263         p_data += i_payload;
2264         i_data -= i_payload;
2265         i_packet++;
2266     }
2267
2268     return VLC_SUCCESS;
2269 }
2270
2271 static int rtp_packetize_l8( sout_stream_t *p_stream, sout_stream_id_t *id,
2272                              block_t *in )
2273 {
2274     int     i_max   = id->i_mtu - 12; /* payload max in one packet */
2275     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2276
2277     uint8_t *p_data = in->p_buffer;
2278     int     i_data  = in->i_buffer;
2279     int     i_packet = 0;
2280
2281     while( i_data > 0 )
2282     {
2283         int           i_payload = (__MIN( i_max, i_data )/2)*2;
2284         block_t *out = block_New( p_stream, 12 + i_payload );
2285
2286         /* rtp common header */
2287         rtp_packetize_common( id, out, 0,
2288                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2289         memcpy( &out->p_buffer[12], p_data, i_payload );
2290
2291         out->i_buffer   = 12 + i_payload;
2292         out->i_dts    = in->i_dts + i_packet * in->i_length / i_count;
2293         out->i_length = in->i_length / i_count;
2294
2295         rtp_packetize_send( id, out );
2296
2297         p_data += i_payload;
2298         i_data -= i_payload;
2299         i_packet++;
2300     }
2301
2302     return VLC_SUCCESS;
2303 }
2304 static int rtp_packetize_mp4a( sout_stream_t *p_stream, sout_stream_id_t *id,
2305                                block_t *in )
2306 {
2307     int     i_max   = id->i_mtu - 16; /* payload max in one packet */
2308     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2309
2310     uint8_t *p_data = in->p_buffer;
2311     int     i_data  = in->i_buffer;
2312     int     i;
2313
2314     for( i = 0; i < i_count; i++ )
2315     {
2316         int           i_payload = __MIN( i_max, i_data );
2317         block_t *out = block_New( p_stream, 16 + i_payload );
2318
2319         /* rtp common header */
2320         rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
2321                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2322         /* AU headers */
2323         /* AU headers length (bits) */
2324         out->p_buffer[12] = 0;
2325         out->p_buffer[13] = 2*8;
2326         /* for each AU length 13 bits + idx 3bits, */
2327         out->p_buffer[14] = ( in->i_buffer >> 5 )&0xff;
2328         out->p_buffer[15] = ( (in->i_buffer&0xff)<<3 )|0;
2329
2330         memcpy( &out->p_buffer[16], p_data, i_payload );
2331
2332         out->i_buffer   = 16 + i_payload;
2333         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2334         out->i_length = in->i_length / i_count;
2335
2336         rtp_packetize_send( id, out );
2337
2338         p_data += i_payload;
2339         i_data -= i_payload;
2340     }
2341
2342     return VLC_SUCCESS;
2343 }
2344
2345
2346 /* rfc2429 */
2347 #define RTP_H263_HEADER_SIZE (2)  // plen = 0
2348 #define RTP_H263_PAYLOAD_START (14)  // plen = 0
2349 static int rtp_packetize_h263( sout_stream_t *p_stream, sout_stream_id_t *id,
2350                                block_t *in )
2351 {
2352     uint8_t *p_data = in->p_buffer;
2353     int     i_data  = in->i_buffer;
2354     int     i;
2355     int     i_max   = id->i_mtu - 12 - RTP_H263_HEADER_SIZE; /* payload max in one packet */
2356     int     i_count;
2357     int     b_p_bit;
2358     int     b_v_bit = 0; // no pesky error resilience
2359     int     i_plen = 0; // normally plen=0 for PSC packet
2360     int     i_pebit = 0; // because plen=0
2361     uint16_t h;
2362
2363     if( i_data < 2 )
2364     {
2365         return VLC_EGENERIC;
2366     }
2367     if( p_data[0] || p_data[1] )
2368     {
2369         return VLC_EGENERIC;
2370     }
2371     /* remove 2 leading 0 bytes */
2372     p_data += 2;
2373     i_data -= 2;
2374     i_count = ( i_data + i_max - 1 ) / i_max;
2375
2376     for( i = 0; i < i_count; i++ )
2377     {
2378         int      i_payload = __MIN( i_max, i_data );
2379         block_t *out = block_New( p_stream,
2380                                   RTP_H263_PAYLOAD_START + i_payload );
2381         b_p_bit = (i == 0) ? 1 : 0;
2382         h = ( b_p_bit << 10 )|
2383             ( b_v_bit << 9  )|
2384             ( i_plen  << 3  )|
2385               i_pebit;
2386
2387         /* rtp common header */
2388         //b_m_bit = 1; // always contains end of frame
2389         rtp_packetize_common( id, out, (i == i_count - 1)?1:0,
2390                               in->i_pts > 0 ? in->i_pts : in->i_dts );
2391
2392         /* h263 header */
2393         out->p_buffer[12] = ( h >>  8 )&0xff;
2394         out->p_buffer[13] = ( h       )&0xff;
2395         memcpy( &out->p_buffer[RTP_H263_PAYLOAD_START], p_data, i_payload );
2396
2397         out->i_buffer = RTP_H263_PAYLOAD_START + i_payload;
2398         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2399         out->i_length = in->i_length / i_count;
2400
2401         rtp_packetize_send( id, out );
2402
2403         p_data += i_payload;
2404         i_data -= i_payload;
2405     }
2406
2407     return VLC_SUCCESS;
2408 }
2409
2410 /* rfc3984 */
2411 static int rtp_packetize_h264_nal( sout_stream_t *p_stream, sout_stream_id_t *id,
2412                                    const uint8_t *p_data, int i_data, int64_t i_pts, int64_t i_dts, vlc_bool_t b_last, int64_t i_length )
2413 {
2414     const int i_max = id->i_mtu - 12; /* payload max in one packet */
2415     int i_nal_hdr;
2416     int i_nal_type;
2417
2418     if( i_data < 5 )
2419         return VLC_SUCCESS;
2420
2421     i_nal_hdr = p_data[3];
2422     i_nal_type = i_nal_hdr&0x1f;
2423     if( i_nal_type == 7 || i_nal_type == 8 )
2424     {
2425         /* XXX Why do you want to remove them ? It will break streaming with 
2426          * SPS/PPS change (broadcast) ? */
2427         return VLC_SUCCESS;
2428     }
2429
2430     /* Skip start code */
2431     p_data += 3;
2432     i_data -= 3;
2433
2434     /* */
2435     if( i_data <= i_max )
2436     {
2437         /* Single NAL unit packet */
2438         block_t *out = block_New( p_stream, 12 + i_data );
2439         out->i_dts    = i_dts;
2440         out->i_length = i_length;
2441
2442         /* */
2443         rtp_packetize_common( id, out, b_last, i_pts );
2444         out->i_buffer = 12 + i_data;
2445
2446         memcpy( &out->p_buffer[12], p_data, i_data );
2447
2448         rtp_packetize_send( id, out );
2449     }
2450     else
2451     {
2452         /* FU-A Fragmentation Unit without interleaving */
2453         const int i_count = ( i_data-1 + i_max-2 - 1 ) / (i_max-2);
2454         int i;
2455
2456         p_data++;
2457         i_data--;
2458
2459         for( i = 0; i < i_count; i++ )
2460         {
2461             const int i_payload = __MIN( i_data, i_max-2 );
2462             block_t *out = block_New( p_stream, 12 + 2 + i_payload );
2463             out->i_dts    = i_dts + i * i_length / i_count;
2464             out->i_length = i_length / i_count;
2465
2466             /* */
2467             rtp_packetize_common( id, out, (b_last && i_payload == i_data), i_pts );
2468             out->i_buffer = 14 + i_payload;
2469
2470             /* FU indicator */
2471             out->p_buffer[12] = 0x00 | (i_nal_hdr & 0x60) | 28;
2472             /* FU header */
2473             out->p_buffer[13] = ( i == 0 ? 0x80 : 0x00 ) | ( (i == i_count-1) ? 0x40 : 0x00 )  | i_nal_type;
2474             memcpy( &out->p_buffer[14], p_data, i_payload );
2475
2476             rtp_packetize_send( id, out );
2477
2478             i_data -= i_payload;
2479             p_data += i_payload;
2480         }
2481     }
2482     return VLC_SUCCESS;
2483 }
2484
2485 static int rtp_packetize_h264( sout_stream_t *p_stream, sout_stream_id_t *id,
2486                                block_t *in )
2487 {
2488     const uint8_t *p_buffer = in->p_buffer;
2489     int i_buffer = in->i_buffer;
2490
2491     while( i_buffer > 4 && ( p_buffer[0] != 0 || p_buffer[1] != 0 || p_buffer[2] != 1 ) )
2492     {
2493         i_buffer--;
2494         p_buffer++;
2495     }
2496
2497     /* Split nal units */
2498     while( i_buffer > 4 )
2499     {
2500         int i_offset;
2501         int i_size = i_buffer;
2502         int i_skip = i_buffer;
2503
2504         /* search nal end */
2505         for( i_offset = 4; i_offset+2 < i_buffer ; i_offset++)
2506         {
2507             if( p_buffer[i_offset] == 0 && p_buffer[i_offset+1] == 0 && p_buffer[i_offset+2] == 1 )
2508             {
2509                 /* we found another startcode */
2510                 i_size = i_offset - ( p_buffer[i_offset-1] == 0 ? 1 : 0);
2511                 i_skip = i_offset;
2512                 break;
2513             } 
2514         }
2515         /* TODO add STAP-A to remove a lot of overhead with small slice/sei/... */
2516         rtp_packetize_h264_nal( p_stream, id, p_buffer, i_size,
2517                                 (in->i_pts > 0 ? in->i_pts : in->i_dts), in->i_dts,
2518                                 (i_size >= i_buffer), in->i_length * i_size / in->i_buffer );
2519
2520         i_buffer -= i_skip;
2521         p_buffer += i_skip;
2522     }
2523     return VLC_SUCCESS;
2524 }
2525
2526 static int rtp_packetize_amr( sout_stream_t *p_stream, sout_stream_id_t *id,
2527                               block_t *in )
2528 {
2529     int     i_max   = id->i_mtu - 14; /* payload max in one packet */
2530     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2531
2532     uint8_t *p_data = in->p_buffer;
2533     int     i_data  = in->i_buffer;
2534     int     i;
2535
2536     /* Only supports octet-aligned mode */
2537     for( i = 0; i < i_count; i++ )
2538     {
2539         int           i_payload = __MIN( i_max, i_data );
2540         block_t *out = block_New( p_stream, 14 + i_payload );
2541
2542         /* rtp common header */
2543         rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
2544                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2545         /* Payload header */
2546         out->p_buffer[12] = 0xF0; /* CMR */
2547         out->p_buffer[13] = p_data[0]&0x7C; /* ToC */ /* FIXME: frame type */
2548
2549         /* FIXME: are we fed multiple frames ? */
2550         memcpy( &out->p_buffer[14], p_data+1, i_payload-1 );
2551
2552         out->i_buffer   = 14 + i_payload-1;
2553         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2554         out->i_length = in->i_length / i_count;
2555
2556         rtp_packetize_send( id, out );
2557
2558         p_data += i_payload;
2559         i_data -= i_payload;
2560     }
2561
2562     return VLC_SUCCESS;
2563 }