]> git.sesse.net Git - vlc/blob - modules/stream_out/rtp.c
Do not insert TTL in c= line for IPv6 - this was invalid
[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         RtspClientDel( p_stream, p_sys->rtsp[0] );
647
648     vlc_mutex_destroy( &p_sys->lock_sdp );
649
650     if( p_sys->p_httpd_file )
651         httpd_FileDelete( p_sys->p_httpd_file );
652
653     if( p_sys->p_httpd_host )
654         httpd_HostDelete( p_sys->p_httpd_host );
655
656     if( p_sys->p_rtsp_url )
657         httpd_UrlDelete( p_sys->p_rtsp_url );
658
659     if( p_sys->p_rtsp_host )
660         httpd_HostDelete( p_sys->p_rtsp_host );
661
662     if( p_sys->psz_session_name )
663         free( p_sys->psz_session_name );
664
665     if( p_sys->psz_session_description )
666         free( p_sys->psz_session_description );
667
668     if( p_sys->psz_session_url )
669         free( p_sys->psz_session_url );
670
671     if( p_sys->psz_session_email )
672         free( p_sys->psz_session_email );
673
674     if( p_sys->psz_sdp )
675         free( p_sys->psz_sdp );
676
677     if( p_sys->b_export_sdp_file )
678     {
679 #ifdef HAVE_UNISTD_H
680         unlink( p_sys->psz_sdp_file );
681 #endif
682         free( p_sys->psz_sdp_file );
683     }
684     if( p_sys->psz_destination )
685         free( p_sys->psz_destination );
686     free( p_sys );
687 }
688
689 /*****************************************************************************
690  * SDPHandleUrl:
691  *****************************************************************************/
692 static void SDPHandleUrl( sout_stream_t *p_stream, char *psz_url )
693 {
694     sout_stream_sys_t *p_sys = p_stream->p_sys;
695     vlc_url_t url;
696
697     vlc_UrlParse( &url, psz_url, 0 );
698     if( url.psz_protocol && !strcasecmp( url.psz_protocol, "http" ) )
699     {
700         if( p_sys->p_httpd_file )
701         {
702             msg_Err( p_stream, "you can use sdp=http:// only once" );
703             return;
704         }
705
706         if( HttpSetup( p_stream, &url ) )
707         {
708             msg_Err( p_stream, "cannot export sdp as http" );
709         }
710     }
711     else if( url.psz_protocol && !strcasecmp( url.psz_protocol, "rtsp" ) )
712     {
713         if( p_sys->p_rtsp_url )
714         {
715             msg_Err( p_stream, "you can use sdp=rtsp:// only once" );
716             return;
717         }
718
719         /* FIXME test if destination is multicast or no destination at all FIXME */
720         if( RtspSetup( p_stream, &url ) )
721         {
722             msg_Err( p_stream, "cannot export sdp as rtsp" );
723         }
724     }
725     else if( ( url.psz_protocol && !strcasecmp( url.psz_protocol, "sap" ) ) || 
726              ( url.psz_host && !strcasecmp( url.psz_host, "sap" ) ) )
727     {
728         p_sys->b_export_sap = VLC_TRUE;
729         SapSetup( p_stream );
730     }
731     else if( url.psz_protocol && !strcasecmp( url.psz_protocol, "file" ) )
732     {
733         if( p_sys->b_export_sdp_file )
734         {
735             msg_Err( p_stream, "you can use sdp=file:// only once" );
736             return;
737         }
738         p_sys->b_export_sdp_file = VLC_TRUE;
739         psz_url = &psz_url[5];
740         if( psz_url[0] == '/' && psz_url[1] == '/' )
741             psz_url += 2;
742         p_sys->psz_sdp_file = strdup( psz_url );
743     }
744     else
745     {
746         msg_Warn( p_stream, "unknown protocol for SDP (%s)",
747                   url.psz_protocol );
748     }
749     vlc_UrlClean( &url );
750 }
751
752 /*****************************************************************************
753  * SDPGenerate
754  *****************************************************************************/
755         /* FIXME  http://www.faqs.org/rfcs/rfc2327.html
756            All text fields should be UTF-8 encoded. Use global a:charset to announce this.
757            o= - should be local username (no spaces allowed)
758            o= time should be hashed with some other value to garantue uniqueness
759            o= we need IP6 support?
760            o= don't use the localhost address. use fully qualified domain name or IP4 address
761            p= international phone number (pass via vars?)
762            c= IP6 support
763            a= recvonly (missing)
764            a= type:broadcast (missing)
765            a= charset: (normally charset should be UTF-8, this can be used to override s= and i=)
766            a= x-plgroup: (missing)
767            RTP packets need to get the correct src IP address  */
768 static char *SDPGenerate( const sout_stream_t *p_stream,
769                           const char *psz_destination, vlc_bool_t b_rtsp )
770 {
771     sout_stream_sys_t *p_sys = p_stream->p_sys;
772     int i_size;
773     char *psz_sdp, *p, ipv;
774     int i;
775
776     /* FIXME: breaks IP version check on unknown destination */
777     if( psz_destination == NULL )
778         psz_destination = "0.0.0.0";
779
780     i_size = sizeof( "v=0\r\n" ) +
781              sizeof( "o=- * * IN IP4 127.0.0.1\r\n" ) + 10 + 10 +
782              sizeof( "s=*\r\n" ) + strlen( p_sys->psz_session_name ) +
783              sizeof( "i=*\r\n" ) + strlen( p_sys->psz_session_description ) +
784              sizeof( "u=*\r\n" ) + strlen( p_sys->psz_session_url ) +
785              sizeof( "e=*\r\n" ) + strlen( p_sys->psz_session_email ) +
786              sizeof( "t=0 0\r\n" ) + /* permanent stream */ /* when scheduled from vlm, we should set this info correctly */
787              sizeof( "a=tool:"PACKAGE_STRING"\r\n" ) +
788              sizeof( "c=IN IP4 */*\r\n" ) + 20 + 10 +
789              strlen( psz_destination ) ;
790     for( i = 0; i < p_sys->i_es; i++ )
791     {
792         sout_stream_id_t *id = p_sys->es[i];
793
794         i_size += strlen( "m=**d*o * RTP/AVP *\r\n" ) + 10 + 10;
795         if( id->psz_rtpmap )
796         {
797             i_size += strlen( "a=rtpmap:* *\r\n" ) + strlen( id->psz_rtpmap )+10;
798         }
799         if( id->psz_fmtp )
800         {
801             i_size += strlen( "a=fmtp:* *\r\n" ) + strlen( id->psz_fmtp ) + 10;
802         }
803         if ( id->i_bitrate)
804         {
805             i_size += strlen( "b=AS: *\r\n") + 10;
806         }
807         if( b_rtsp )
808         {
809             i_size += strlen( "a=control:*/trackID=*\r\n" ) + strlen( p_sys->psz_rtsp_control ) + 10;
810         }
811     }
812     if( p_sys->p_mux )
813     {
814         i_size += strlen( "m=video %d RTP/AVP %d\r\n" ) +10 +10;
815     }
816
817     ipv = ( strchr( psz_destination, ':' ) != NULL ) ? '6' : '4';
818
819     p = psz_sdp = malloc( i_size );
820     p += sprintf( p, "v=0\r\n" );
821     p += sprintf( p, "o=- "I64Fd" %d IN IP%c %s\r\n",
822                   p_sys->i_sdp_id, p_sys->i_sdp_version,
823                   ipv, ipv == '6' ? "::1" : "127.0.0.1" );
824     if( *p_sys->psz_session_name )
825         p += sprintf( p, "s=%s\r\n", p_sys->psz_session_name );
826     if( *p_sys->psz_session_description )
827         p += sprintf( p, "i=%s\r\n", p_sys->psz_session_description );
828     if( *p_sys->psz_session_url )
829         p += sprintf( p, "u=%s\r\n", p_sys->psz_session_url );
830     if( *p_sys->psz_session_email )
831         p += sprintf( p, "e=%s\r\n", p_sys->psz_session_email );
832
833     p += sprintf( p, "t=0 0\r\n" ); /* permanent stream */ /* when scheduled from vlm, we should set this info correctly */
834     p += sprintf( p, "a=tool:"PACKAGE_STRING"\r\n" );
835
836     p += sprintf( p, "c=IN IP%c %s", ipv, psz_destination );
837
838     if( ( ipv == 4 )
839      && net_AddressIsMulticast( (vlc_object_t *)p_stream, psz_destination ) )
840     {
841         /* Add the deprecated TTL field if it is an IPv4 multicast address */
842         p += sprintf( p, "/%d", p_sys->i_ttl ?: 1 );
843     }
844     p += sprintf( p, "\r\n" );
845
846     for( i = 0; i < p_sys->i_es; i++ )
847     {
848         sout_stream_id_t *id = p_sys->es[i];
849
850         if( id->i_cat == AUDIO_ES )
851         {
852             p += sprintf( p, "m=audio %d RTP/AVP %d\r\n",
853                           id->i_port, id->i_payload_type );
854         }
855         else if( id->i_cat == VIDEO_ES )
856         {
857             p += sprintf( p, "m=video %d RTP/AVP %d\r\n",
858                           id->i_port, id->i_payload_type );
859         }
860         else
861         {
862             continue;
863         }
864         if( id->psz_rtpmap )
865         {
866             p += sprintf( p, "a=rtpmap:%d %s\r\n", id->i_payload_type,
867                           id->psz_rtpmap );
868         }
869         if( id->psz_fmtp )
870         {
871             p += sprintf( p, "a=fmtp:%d %s\r\n", id->i_payload_type,
872                           id->psz_fmtp );
873         }
874         if ( id->i_bitrate)
875         {
876             p += sprintf(p,"b=AS:%d\r\n",id->i_bitrate);
877         }
878         if( b_rtsp )
879         {
880             p += sprintf( p, "a=control:/trackID=%d\r\n", i );
881         }
882     }
883     if( p_sys->p_mux )
884     {
885        p += sprintf( p, "m=video %d RTP/AVP %d\r\n",
886                  p_sys->i_port, p_sys->i_payload_type );
887     }
888
889     return psz_sdp;
890 }
891
892 /*****************************************************************************
893  *
894  *****************************************************************************/
895 static int rtp_packetize_l16  ( sout_stream_t *, sout_stream_id_t *, block_t * );
896 static int rtp_packetize_l8   ( sout_stream_t *, sout_stream_id_t *, block_t * );
897 static int rtp_packetize_mpa  ( sout_stream_t *, sout_stream_id_t *, block_t * );
898 static int rtp_packetize_mpv  ( sout_stream_t *, sout_stream_id_t *, block_t * );
899 static int rtp_packetize_ac3  ( sout_stream_t *, sout_stream_id_t *, block_t * );
900 static int rtp_packetize_split( sout_stream_t *, sout_stream_id_t *, block_t * );
901 static int rtp_packetize_mp4a ( sout_stream_t *, sout_stream_id_t *, block_t * );
902 static int rtp_packetize_mp4a_latm ( sout_stream_t *, sout_stream_id_t *, block_t * );
903 static int rtp_packetize_h263 ( sout_stream_t *, sout_stream_id_t *, block_t * );
904 static int rtp_packetize_h264 ( sout_stream_t *, sout_stream_id_t *, block_t * );
905 static int rtp_packetize_amr  ( sout_stream_t *, sout_stream_id_t *, block_t * );
906
907 static void sprintf_hexa( char *s, uint8_t *p_data, int i_data )
908 {
909     static const char hex[16] = "0123456789abcdef";
910     int i;
911
912     for( i = 0; i < i_data; i++ )
913     {
914         s[2*i+0] = hex[(p_data[i]>>4)&0xf];
915         s[2*i+1] = hex[(p_data[i]   )&0xf];
916     }
917     s[2*i_data] = '\0';
918 }
919
920 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
921 {
922     sout_instance_t   *p_sout = p_stream->p_sout;
923     sout_stream_sys_t *p_sys = p_stream->p_sys;
924     sout_stream_id_t  *id;
925     sout_access_out_t *p_access = NULL;
926     int               i_port;
927     char              *psz_sdp;
928
929     if( p_sys->p_mux != NULL )
930     {
931         sout_input_t      *p_input  = NULL;
932         if( ( p_input = sout_MuxAddStream( p_sys->p_mux, p_fmt ) ) == NULL )
933         {
934             msg_Err( p_stream, "cannot add this stream to the muxer" );
935             return NULL;
936         }
937
938         id = malloc( sizeof( sout_stream_id_t ) );
939         memset( id, 0, sizeof( sout_stream_id_t ) );
940         id->p_access    = NULL;
941         id->p_input     = p_input;
942         id->pf_packetize= NULL;
943         id->p_rtsp_url  = NULL;
944         id->i_port      = 0;
945         return id;
946     }
947
948
949     /* Choose the port */
950     i_port = 0;
951     if( p_fmt->i_cat == AUDIO_ES && p_sys->i_port_audio > 0 )
952     {
953         i_port = p_sys->i_port_audio;
954         p_sys->i_port_audio = 0;
955     }
956     else if( p_fmt->i_cat == VIDEO_ES && p_sys->i_port_video > 0 )
957     {
958         i_port = p_sys->i_port_video;
959         p_sys->i_port_video = 0;
960     }
961     while( i_port == 0 )
962     {
963         if( p_sys->i_port != p_sys->i_port_audio && p_sys->i_port != p_sys->i_port_video )
964         {
965             i_port = p_sys->i_port;
966             p_sys->i_port += 2;
967             break;
968         }
969         p_sys->i_port += 2;
970     }
971
972     if( p_sys->psz_destination )
973     {
974         char access[17];
975         char url[NI_MAXHOST + 8];
976
977         /* first try to create the access out */
978         if( p_sys->i_ttl )
979         {
980             snprintf( access, sizeof( access ), "udp{raw,ttl=%d}",
981                       p_sys->i_ttl );
982             access[sizeof( access ) - 1] = '\0';
983         }
984         else
985             strcpy( access, "udp{raw}" );
986
987         snprintf( url, sizeof( url ), (( p_sys->psz_destination[0] != '[' ) &&
988                  strchr( p_sys->psz_destination, ':' )) ? "[%s]:%d" : "%s:%d",
989                  p_sys->psz_destination, i_port );
990         url[sizeof( url ) - 1] = '\0';
991
992         if( ( p_access = sout_AccessOutNew( p_sout, access, url ) ) == NULL )
993         {
994             msg_Err( p_stream, "cannot create the access out for %s://%s",
995                      access, url );
996             return NULL;
997         }
998         msg_Dbg( p_stream, "access out %s:%s", access, url );
999     }
1000
1001     /* not create the rtp specific stuff */
1002     id = malloc( sizeof( sout_stream_id_t ) );
1003     memset( id, 0, sizeof( sout_stream_id_t ) );
1004     id->p_stream   = p_stream;
1005     id->p_access   = p_access;
1006     id->p_input    = NULL;
1007     id->psz_rtpmap = NULL;
1008     id->psz_fmtp   = NULL;
1009     id->psz_destination = p_sys->psz_destination ? strdup( p_sys->psz_destination ) : NULL;
1010     id->i_port = i_port;
1011     id->p_rtsp_url = NULL;
1012     vlc_mutex_init( p_stream, &id->lock_rtsp );
1013     id->i_rtsp_access = 0;
1014     id->rtsp_access = NULL;
1015
1016     switch( p_fmt->i_codec )
1017     {
1018         case VLC_FOURCC( 's', '1', '6', 'b' ):
1019             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 44100 )
1020             {
1021                 id->i_payload_type = 11;
1022             }
1023             else if( p_fmt->audio.i_channels == 2 &&
1024                      p_fmt->audio.i_rate == 44100 )
1025             {
1026                 id->i_payload_type = 10;
1027             }
1028             else
1029             {
1030                 id->i_payload_type = p_sys->i_payload_type++;
1031             }
1032             id->psz_rtpmap = malloc( strlen( "L16/*/*" ) + 20+1 );
1033             sprintf( id->psz_rtpmap, "L16/%d/%d", p_fmt->audio.i_rate,
1034                      p_fmt->audio.i_channels );
1035             id->i_clock_rate = p_fmt->audio.i_rate;
1036             id->pf_packetize = rtp_packetize_l16;
1037             break;
1038         case VLC_FOURCC( 'u', '8', ' ', ' ' ):
1039             id->i_payload_type = p_sys->i_payload_type++;
1040             id->psz_rtpmap = malloc( strlen( "L8/*/*" ) + 20+1 );
1041             sprintf( id->psz_rtpmap, "L8/%d/%d", p_fmt->audio.i_rate,
1042                      p_fmt->audio.i_channels );
1043             id->i_clock_rate = p_fmt->audio.i_rate;
1044             id->pf_packetize = rtp_packetize_l8;
1045             break;
1046         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
1047             id->i_payload_type = 14;
1048             id->i_clock_rate = 90000;
1049             id->psz_rtpmap = strdup( "MPA/90000" );
1050             id->pf_packetize = rtp_packetize_mpa;
1051             break;
1052         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
1053             id->i_payload_type = 32;
1054             id->i_clock_rate = 90000;
1055             id->psz_rtpmap = strdup( "MPV/90000" );
1056             id->pf_packetize = rtp_packetize_mpv;
1057             break;
1058         case VLC_FOURCC( 'a', '5', '2', ' ' ):
1059             id->i_payload_type = p_sys->i_payload_type++;
1060             id->i_clock_rate = 90000;
1061             id->psz_rtpmap = strdup( "ac3/90000" );
1062             id->pf_packetize = rtp_packetize_ac3;
1063             break;
1064         case VLC_FOURCC( 'H', '2', '6', '3' ):
1065             id->i_payload_type = p_sys->i_payload_type++;
1066             id->i_clock_rate = 90000;
1067             id->psz_rtpmap = strdup( "H263-1998/90000" );
1068             id->pf_packetize = rtp_packetize_h263;
1069             break;
1070         case VLC_FOURCC( 'h', '2', '6', '4' ):
1071             id->i_payload_type = p_sys->i_payload_type++;
1072             id->i_clock_rate = 90000;
1073             id->psz_rtpmap = strdup( "H264/90000" );
1074             id->pf_packetize = rtp_packetize_h264;
1075             id->psz_fmtp = NULL;
1076
1077             if( p_fmt->i_extra > 0 )
1078             {
1079                 uint8_t *p_buffer = p_fmt->p_extra;
1080                 int     i_buffer = p_fmt->i_extra;
1081                 char    *p_64_sps = NULL;
1082                 char    *p_64_pps = NULL;
1083                 char    hexa[6+1];
1084
1085                 while( i_buffer > 4 && 
1086                        p_buffer[0] == 0 && p_buffer[1] == 0 &&
1087                        p_buffer[2] == 0 && p_buffer[3] == 1 )
1088                 {
1089                     const int i_nal_type = p_buffer[4]&0x1f;
1090                     int i_offset;
1091                     int i_size      = 0;
1092
1093                     msg_Dbg( p_stream, "we found a startcode for NAL with TYPE:%d", i_nal_type );
1094
1095                     i_size = i_buffer;
1096                     for( i_offset = 4; i_offset+3 < i_buffer ; i_offset++)
1097                     {
1098                         if( p_buffer[i_offset] == 0 && p_buffer[i_offset+1] == 0 && p_buffer[i_offset+2] == 0 && p_buffer[i_offset+3] == 1 )
1099                         {
1100                             /* we found another startcode */
1101                             i_size = i_offset;
1102                             break;
1103                         } 
1104                     }
1105                     if( i_nal_type == 7 )
1106                     {
1107                         p_64_sps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
1108                         sprintf_hexa( hexa, &p_buffer[5], 3 );
1109                     }
1110                     else if( i_nal_type == 8 )
1111                     {
1112                         p_64_pps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
1113                     }
1114                     i_buffer -= i_size;
1115                     p_buffer += i_size;
1116                 }
1117                 /* */
1118                 if( p_64_sps && p_64_pps )
1119                     asprintf( &id->psz_fmtp, "packetization-mode=1;profile-level-id=%s;sprop-parameter-sets=%s,%s;", hexa, p_64_sps, p_64_pps );
1120                 if( p_64_sps )
1121                     free( p_64_sps );
1122                 if( p_64_pps )
1123                     free( p_64_pps );
1124             }
1125             if( !id->psz_fmtp )
1126                 id->psz_fmtp = strdup( "packetization-mode=1" );
1127             break;
1128
1129         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
1130         {
1131             char hexa[2*p_fmt->i_extra +1];
1132
1133             id->i_payload_type = p_sys->i_payload_type++;
1134             id->i_clock_rate = 90000;
1135             id->psz_rtpmap = strdup( "MP4V-ES/90000" );
1136             id->pf_packetize = rtp_packetize_split;
1137             if( p_fmt->i_extra > 0 )
1138             {
1139                 id->psz_fmtp = malloc( 100 + 2 * p_fmt->i_extra );
1140                 sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
1141                 sprintf( id->psz_fmtp,
1142                          "profile-level-id=3; config=%s;", hexa );
1143             }
1144             break;
1145         }
1146         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
1147         {
1148             id->i_payload_type = p_sys->i_payload_type++;
1149             id->i_clock_rate = p_fmt->audio.i_rate;
1150
1151             if(!p_sys->b_latm)
1152             {
1153                 char hexa[2*p_fmt->i_extra +1];
1154
1155                 id->psz_rtpmap = malloc( strlen( "mpeg4-generic/" ) + 12 );
1156                 sprintf( id->psz_rtpmap, "mpeg4-generic/%d", p_fmt->audio.i_rate );
1157                 id->pf_packetize = rtp_packetize_mp4a;
1158                 id->psz_fmtp = malloc( 200 + 2 * p_fmt->i_extra );
1159                 sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
1160                 sprintf( id->psz_fmtp,
1161                         "streamtype=5; profile-level-id=15; mode=AAC-hbr; "
1162                         "config=%s; SizeLength=13;IndexLength=3; "
1163                         "IndexDeltaLength=3; Profile=1;", hexa );
1164             }
1165             else
1166             {
1167                 char hexa[13];
1168                 int i;
1169                 unsigned char config[6];
1170                 unsigned int aacsrates[15] = {
1171                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1172                     16000, 12000, 11025, 8000, 7350, 0, 0 };
1173
1174                 for( i = 0; i < 15; i++ )
1175                     if( p_fmt->audio.i_rate == aacsrates[i] )
1176                         break;
1177
1178                 config[0]=0x40;
1179                 config[1]=0;
1180                 config[2]=0x20|i;
1181                 config[3]=p_fmt->audio.i_channels<<4;
1182                 config[4]=0x3f;
1183                 config[5]=0xc0;
1184
1185                 asprintf( &id->psz_rtpmap, "MP4A-LATM/%d/%d",
1186                           p_fmt->audio.i_rate, p_fmt->audio.i_channels );
1187                 id->pf_packetize = rtp_packetize_mp4a_latm;
1188                 sprintf_hexa( hexa, config, 6 );
1189                 asprintf( &id->psz_fmtp, "profile-level-id=15; "
1190                           "object=2; cpresent=0; config=%s", hexa );
1191             }
1192             break;
1193         }
1194         case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1195             id->i_payload_type = p_sys->i_payload_type++;
1196             id->psz_rtpmap = strdup( p_fmt->audio.i_channels == 2 ?
1197                                      "AMR/8000/2" : "AMR/8000" );
1198             id->psz_fmtp = strdup( "octet-align=1" );
1199             id->i_clock_rate = p_fmt->audio.i_rate;
1200             id->pf_packetize = rtp_packetize_amr;
1201             break; 
1202         case VLC_FOURCC( 's', 'a', 'w', 'b' ):
1203             id->i_payload_type = p_sys->i_payload_type++;
1204             id->psz_rtpmap = strdup( p_fmt->audio.i_channels == 2 ?
1205                                      "AMR-WB/16000/2" : "AMR-WB/16000" );
1206             id->psz_fmtp = strdup( "octet-align=1" );
1207             id->i_clock_rate = p_fmt->audio.i_rate;
1208             id->pf_packetize = rtp_packetize_amr;
1209             break; 
1210
1211         default:
1212             msg_Err( p_stream, "cannot add this stream (unsupported "
1213                      "codec:%4.4s)", (char*)&p_fmt->i_codec );
1214             if( p_access )
1215             {
1216                 sout_AccessOutDelete( p_access );
1217             }
1218             free( id );
1219             return NULL;
1220     }
1221     id->i_cat = p_fmt->i_cat;
1222
1223     id->ssrc[0] = rand()&0xff;
1224     id->ssrc[1] = rand()&0xff;
1225     id->ssrc[2] = rand()&0xff;
1226     id->ssrc[3] = rand()&0xff;
1227     id->i_sequence = rand()&0xffff;
1228     id->i_timestamp_start = rand()&0xffffffff;
1229     id->i_bitrate = p_fmt->i_bitrate/1000; /* Stream bitrate in kbps */
1230
1231     id->i_mtu    = config_GetInt( p_stream, "mtu" );  /* XXX beuk */
1232     if( id->i_mtu <= 16 + MTU_REDUCE )
1233     {
1234         /* better than nothing */
1235         id->i_mtu = 1500;
1236     }
1237     id->i_mtu -= MTU_REDUCE;
1238     msg_Dbg( p_stream, "maximum RTP packet size: %d bytes", id->i_mtu );
1239
1240     if( p_sys->p_rtsp_url )
1241     {
1242         char psz_urlc[strlen( p_sys->psz_rtsp_control ) + 1 + 10];
1243
1244         sprintf( psz_urlc, "%s/trackID=%d", p_sys->psz_rtsp_path, p_sys->i_es );
1245         msg_Dbg( p_stream, "rtsp: adding %s\n", psz_urlc );
1246         id->p_rtsp_url = httpd_UrlNewUnique( p_sys->p_rtsp_host, psz_urlc, NULL, NULL, NULL );
1247
1248         if( id->p_rtsp_url )
1249         {
1250             httpd_UrlCatch( id->p_rtsp_url, HTTPD_MSG_SETUP,    RtspCallbackId, (void*)id );
1251             //httpd_UrlCatch( id->p_rtsp_url, HTTPD_MSG_PLAY,     RtspCallback, (void*)p_stream );
1252             //httpd_UrlCatch( id->p_rtsp_url, HTTPD_MSG_PAUSE,    RtspCallback, (void*)p_stream );
1253         }
1254     }
1255
1256
1257     /* Update p_sys context */
1258     vlc_mutex_lock( &p_sys->lock_es );
1259     TAB_APPEND( p_sys->i_es, p_sys->es, id );
1260     vlc_mutex_unlock( &p_sys->lock_es );
1261
1262     psz_sdp = SDPGenerate( p_stream, p_sys->psz_destination, VLC_FALSE );
1263
1264     vlc_mutex_lock( &p_sys->lock_sdp );
1265     free( p_sys->psz_sdp );
1266     p_sys->psz_sdp = psz_sdp;
1267     vlc_mutex_unlock( &p_sys->lock_sdp );
1268
1269     p_sys->i_sdp_version++;
1270
1271     msg_Dbg( p_stream, "sdp=%s", p_sys->psz_sdp );
1272
1273     /* Update SDP (sap/file) */
1274     if( p_sys->b_export_sap ) SapSetup( p_stream );
1275     if( p_sys->b_export_sdp_file ) FileSetup( p_stream );
1276
1277     return id;
1278 }
1279
1280 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
1281 {
1282     sout_stream_sys_t *p_sys = p_stream->p_sys;
1283
1284     vlc_mutex_lock( &p_sys->lock_es );
1285     TAB_REMOVE( p_sys->i_es, p_sys->es, id );
1286     vlc_mutex_unlock( &p_sys->lock_es );
1287
1288     /* Release port */
1289     if( id->i_port > 0 )
1290     {
1291         if( id->i_cat == AUDIO_ES && p_sys->i_port_audio == 0 )
1292             p_sys->i_port_audio = id->i_port;
1293         else if( id->i_cat == VIDEO_ES && p_sys->i_port_video == 0 )
1294             p_sys->i_port_video = id->i_port;
1295     }
1296
1297     if( id->p_access )
1298     {
1299         if( id->psz_rtpmap )
1300         {
1301             free( id->psz_rtpmap );
1302         }
1303         if( id->psz_fmtp )
1304         {
1305             free( id->psz_fmtp );
1306         }
1307         if( id->psz_destination )
1308             free( id->psz_destination );
1309         sout_AccessOutDelete( id->p_access );
1310     }
1311     else if( id->p_input )
1312     {
1313         sout_MuxDeleteStream( p_sys->p_mux, id->p_input );
1314     }
1315     if( id->p_rtsp_url )
1316     {
1317         httpd_UrlDelete( id->p_rtsp_url );
1318     }
1319     vlc_mutex_destroy( &id->lock_rtsp );
1320     if( id->rtsp_access ) free( id->rtsp_access );
1321
1322     /* Update SDP (sap/file) */
1323     if( p_sys->b_export_sap && !p_sys->p_mux ) SapSetup( p_stream );
1324     if( p_sys->b_export_sdp_file ) FileSetup( p_stream );
1325
1326     free( id );
1327     return VLC_SUCCESS;
1328 }
1329
1330 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
1331                  block_t *p_buffer )
1332 {
1333     block_t *p_next;
1334
1335     if( p_stream->p_sys->p_mux )
1336     {
1337         sout_MuxSendBuffer( p_stream->p_sys->p_mux, id->p_input, p_buffer );
1338     }
1339     else
1340     {
1341         while( p_buffer )
1342         {
1343             p_next = p_buffer->p_next;
1344             if( id->pf_packetize( p_stream, id, p_buffer ) )
1345             {
1346                 break;
1347             }
1348             block_Release( p_buffer );
1349             p_buffer = p_next;
1350         }
1351     }
1352     return VLC_SUCCESS;
1353 }
1354
1355
1356 static int AccessOutGrabberWriteBuffer( sout_stream_t *p_stream,
1357                                         block_t *p_buffer )
1358 {
1359     sout_stream_sys_t *p_sys = p_stream->p_sys;
1360
1361     int64_t  i_dts = p_buffer->i_dts;
1362     uint32_t i_timestamp = i_dts * 9 / 100;
1363
1364     uint8_t         *p_data = p_buffer->p_buffer;
1365     unsigned int    i_data  = p_buffer->i_buffer;
1366     unsigned int    i_max   = p_sys->i_mtu - 12;
1367
1368     unsigned i_packet = ( p_buffer->i_buffer + i_max - 1 ) / i_max;
1369
1370     while( i_data > 0 )
1371     {
1372         unsigned int i_size;
1373
1374         /* output complete packet */
1375         if( p_sys->packet &&
1376             p_sys->packet->i_buffer + i_data > i_max )
1377         {
1378             sout_AccessOutWrite( p_sys->p_access, p_sys->packet );
1379             p_sys->packet = NULL;
1380         }
1381
1382         if( p_sys->packet == NULL )
1383         {
1384             /* allocate a new packet */
1385             p_sys->packet = block_New( p_stream, p_sys->i_mtu );
1386             p_sys->packet->p_buffer[ 0] = 0x80;
1387             p_sys->packet->p_buffer[ 1] = 0x80|p_sys->i_payload_type;
1388             p_sys->packet->p_buffer[ 2] = ( p_sys->i_sequence >> 8)&0xff;
1389             p_sys->packet->p_buffer[ 3] = ( p_sys->i_sequence     )&0xff;
1390             p_sys->packet->p_buffer[ 4] = ( i_timestamp >> 24 )&0xff;
1391             p_sys->packet->p_buffer[ 5] = ( i_timestamp >> 16 )&0xff;
1392             p_sys->packet->p_buffer[ 6] = ( i_timestamp >>  8 )&0xff;
1393             p_sys->packet->p_buffer[ 7] = ( i_timestamp       )&0xff;
1394             p_sys->packet->p_buffer[ 8] = p_sys->ssrc[0];
1395             p_sys->packet->p_buffer[ 9] = p_sys->ssrc[1];
1396             p_sys->packet->p_buffer[10] = p_sys->ssrc[2];
1397             p_sys->packet->p_buffer[11] = p_sys->ssrc[3];
1398             p_sys->packet->i_buffer = 12;
1399
1400             p_sys->packet->i_dts = i_dts;
1401             p_sys->packet->i_length = p_buffer->i_length / i_packet;
1402             i_dts += p_sys->packet->i_length;
1403
1404             p_sys->i_sequence++;
1405         }
1406
1407         i_size = __MIN( i_data,
1408                         (unsigned)(p_sys->i_mtu - p_sys->packet->i_buffer) );
1409
1410         memcpy( &p_sys->packet->p_buffer[p_sys->packet->i_buffer],
1411                 p_data, i_size );
1412
1413         p_sys->packet->i_buffer += i_size;
1414         p_data += i_size;
1415         i_data -= i_size;
1416     }
1417
1418     return VLC_SUCCESS;
1419 }
1420
1421 static int AccessOutGrabberWrite( sout_access_out_t *p_access,
1422                                   block_t *p_buffer )
1423 {
1424     sout_stream_t *p_stream = (sout_stream_t*)p_access->p_sys;
1425
1426     //fprintf( stderr, "received buffer size=%d\n", p_buffer->i_buffer );
1427     //
1428     while( p_buffer )
1429     {
1430         block_t *p_next;
1431
1432         AccessOutGrabberWriteBuffer( p_stream, p_buffer );
1433
1434         p_next = p_buffer->p_next;
1435         block_Release( p_buffer );
1436         p_buffer = p_next;
1437     }
1438
1439     return VLC_SUCCESS;
1440 }
1441
1442 /****************************************************************************
1443  * SAP:
1444  ****************************************************************************/
1445 static int SapSetup( sout_stream_t *p_stream )
1446 {
1447     sout_stream_sys_t *p_sys = p_stream->p_sys;
1448     sout_instance_t   *p_sout = p_stream->p_sout;
1449     announce_method_t *p_method = sout_SAPMethod();
1450
1451     /* Remove the previous session */
1452     if( p_sys->p_session != NULL)
1453     {
1454         sout_AnnounceUnRegister( p_sout, p_sys->p_session);
1455         sout_AnnounceSessionDestroy( p_sys->p_session );
1456         p_sys->p_session = NULL;
1457     }
1458
1459     if( ( p_sys->i_es > 0 || p_sys->p_mux ) && p_sys->psz_sdp && *p_sys->psz_sdp )
1460     {
1461         p_sys->p_session = sout_AnnounceRegisterSDP( p_sout, SOUT_CFG_PREFIX,
1462                                                      p_sys->psz_sdp,
1463                                                      p_sys->psz_destination,
1464                                                      p_method );
1465     }
1466
1467     sout_MethodRelease( p_method );
1468     return VLC_SUCCESS;
1469 }
1470
1471 /****************************************************************************
1472 * File:
1473 ****************************************************************************/
1474 static int FileSetup( sout_stream_t *p_stream )
1475 {
1476     sout_stream_sys_t *p_sys = p_stream->p_sys;
1477     FILE            *f;
1478
1479     if( ( f = utf8_fopen( p_sys->psz_sdp_file, "wt" ) ) == NULL )
1480     {
1481         msg_Err( p_stream, "cannot open file '%s' (%s)",
1482                  p_sys->psz_sdp_file, strerror(errno) );
1483         return VLC_EGENERIC;
1484     }
1485
1486     fprintf( f, "%s", p_sys->psz_sdp );
1487     fclose( f );
1488
1489     return VLC_SUCCESS;
1490 }
1491
1492 /****************************************************************************
1493  * HTTP:
1494  ****************************************************************************/
1495 static int  HttpCallback( httpd_file_sys_t *p_args,
1496                           httpd_file_t *, uint8_t *p_request,
1497                           uint8_t **pp_data, int *pi_data );
1498
1499 static int HttpSetup( sout_stream_t *p_stream, vlc_url_t *url)
1500 {
1501     sout_stream_sys_t *p_sys = p_stream->p_sys;
1502
1503     p_sys->p_httpd_host = httpd_HostNew( VLC_OBJECT(p_stream), url->psz_host, url->i_port > 0 ? url->i_port : 80 );
1504     if( p_sys->p_httpd_host )
1505     {
1506         p_sys->p_httpd_file = httpd_FileNew( p_sys->p_httpd_host,
1507                                              url->psz_path ? url->psz_path : "/",
1508                                              "application/sdp",
1509                                              NULL, NULL, NULL,
1510                                              HttpCallback, (void*)p_sys );
1511     }
1512     if( p_sys->p_httpd_file == NULL )
1513     {
1514         return VLC_EGENERIC;
1515     }
1516     return VLC_SUCCESS;
1517 }
1518
1519 static int  HttpCallback( httpd_file_sys_t *p_args,
1520                           httpd_file_t *f, uint8_t *p_request,
1521                           uint8_t **pp_data, int *pi_data )
1522 {
1523     sout_stream_sys_t *p_sys = (sout_stream_sys_t*)p_args;
1524
1525     vlc_mutex_lock( &p_sys->lock_sdp );
1526     if( p_sys->psz_sdp && *p_sys->psz_sdp )
1527     {
1528         *pi_data = strlen( p_sys->psz_sdp );
1529         *pp_data = malloc( *pi_data );
1530         memcpy( *pp_data, p_sys->psz_sdp, *pi_data );
1531     }
1532     else
1533     {
1534         *pp_data = NULL;
1535         *pi_data = 0;
1536     }
1537     vlc_mutex_unlock( &p_sys->lock_sdp );
1538
1539     return VLC_SUCCESS;
1540 }
1541
1542 /****************************************************************************
1543  * RTSP:
1544  ****************************************************************************/
1545 static rtsp_client_t *RtspClientNew( sout_stream_t *p_stream, const char *psz_session )
1546 {
1547     rtsp_client_t *rtsp = malloc( sizeof( rtsp_client_t ));
1548
1549     rtsp->psz_session = strdup( psz_session );
1550     rtsp->i_last = 0;
1551     rtsp->b_playing = VLC_FALSE;
1552     rtsp->i_id = 0;
1553     rtsp->id = NULL;
1554     rtsp->i_access = 0;
1555     rtsp->access = NULL;
1556
1557     TAB_APPEND( p_stream->p_sys->i_rtsp, p_stream->p_sys->rtsp, rtsp );
1558
1559     return rtsp;
1560 }
1561 static rtsp_client_t *RtspClientGet( sout_stream_t *p_stream, const char *psz_session )
1562 {
1563     int i;
1564
1565     if( !psz_session ) return NULL;
1566
1567     for( i = 0; i < p_stream->p_sys->i_rtsp; i++ )
1568     {
1569         if( !strcmp( p_stream->p_sys->rtsp[i]->psz_session, psz_session ) )
1570         {
1571             return p_stream->p_sys->rtsp[i];
1572         }
1573     }
1574     return NULL;
1575 }
1576
1577 static void RtspClientDel( sout_stream_t *p_stream, rtsp_client_t *rtsp )
1578 {
1579     int i;
1580     TAB_REMOVE( p_stream->p_sys->i_rtsp, p_stream->p_sys->rtsp, rtsp );
1581
1582     for( i = 0; i < rtsp->i_access; i++ )
1583     {
1584         sout_AccessOutDelete( rtsp->access[i] );
1585     }
1586     if( rtsp->id )     free( rtsp->id );
1587     if( rtsp->access ) free( rtsp->access );
1588
1589     free( rtsp->psz_session );
1590     free( rtsp );
1591 }
1592
1593 static int RtspSetup( sout_stream_t *p_stream, vlc_url_t *url )
1594 {
1595     sout_stream_sys_t *p_sys = p_stream->p_sys;
1596
1597     msg_Dbg( p_stream, "rtsp setup: %s : %d / %s\n", url->psz_host, url->i_port, url->psz_path );
1598
1599     p_sys->p_rtsp_host = httpd_HostNew( VLC_OBJECT(p_stream), url->psz_host, url->i_port > 0 ? url->i_port : 554 );
1600     if( p_sys->p_rtsp_host == NULL )
1601     {
1602         return VLC_EGENERIC;
1603     }
1604
1605     p_sys->psz_rtsp_path = strdup( url->psz_path ? url->psz_path : "/" );
1606     p_sys->psz_rtsp_control = malloc (strlen( url->psz_host ) + 20 + strlen( p_sys->psz_rtsp_path ) + 1 );
1607     sprintf( p_sys->psz_rtsp_control, "rtsp://%s:%d%s",
1608              url->psz_host,  url->i_port > 0 ? url->i_port : 554, p_sys->psz_rtsp_path );
1609
1610     p_sys->p_rtsp_url = httpd_UrlNewUnique( p_sys->p_rtsp_host, p_sys->psz_rtsp_path, NULL, NULL, NULL );
1611     if( p_sys->p_rtsp_url == 0 )
1612     {
1613         return VLC_EGENERIC;
1614     }
1615     httpd_UrlCatch( p_sys->p_rtsp_url, HTTPD_MSG_DESCRIBE, RtspCallback, (void*)p_stream );
1616     httpd_UrlCatch( p_sys->p_rtsp_url, HTTPD_MSG_PLAY,     RtspCallback, (void*)p_stream );
1617     httpd_UrlCatch( p_sys->p_rtsp_url, HTTPD_MSG_PAUSE,    RtspCallback, (void*)p_stream );
1618     httpd_UrlCatch( p_sys->p_rtsp_url, HTTPD_MSG_TEARDOWN, RtspCallback, (void*)p_stream );
1619
1620     return VLC_SUCCESS;
1621 }
1622
1623 static int  RtspCallback( httpd_callback_sys_t *p_args,
1624                           httpd_client_t *cl,
1625                           httpd_message_t *answer, httpd_message_t *query )
1626 {
1627     sout_stream_t *p_stream = (sout_stream_t*)p_args;
1628     sout_stream_sys_t *p_sys = p_stream->p_sys;
1629     char *psz_destination = p_sys->psz_destination;
1630     const char *psz_session = NULL;
1631     const char *psz_cseq = NULL;
1632     int i_cseq = 0;
1633
1634     if( answer == NULL || query == NULL )
1635     {
1636         return VLC_SUCCESS;
1637     }
1638     //fprintf( stderr, "RtspCallback query: type=%d\n", query->i_type );
1639
1640     answer->i_proto = HTTPD_PROTO_RTSP;
1641     answer->i_version= query->i_version;
1642     answer->i_type   = HTTPD_MSG_ANSWER;
1643
1644     switch( query->i_type )
1645     {
1646         case HTTPD_MSG_DESCRIBE:
1647         {
1648             char *psz_sdp = SDPGenerate( p_stream, psz_destination ? psz_destination : "0.0.0.0", VLC_TRUE );
1649
1650             answer->i_status = 200;
1651             answer->psz_status = strdup( "OK" );
1652             httpd_MsgAdd( answer, "Content-type",  "%s", "application/sdp" );
1653             httpd_MsgAdd( answer, "Content-Base",  "%s", p_sys->psz_rtsp_control );
1654             answer->p_body = (uint8_t *)psz_sdp;
1655             answer->i_body = strlen( psz_sdp );
1656             break;
1657         }
1658
1659         case HTTPD_MSG_PLAY:
1660         {
1661             rtsp_client_t *rtsp;
1662             /* for now only multicast so easy */
1663             answer->i_status = 200;
1664             answer->psz_status = strdup( "OK" );
1665             answer->i_body = 0;
1666             answer->p_body = NULL;
1667
1668             psz_session = httpd_MsgGet( query, "Session" );
1669             rtsp = RtspClientGet( p_stream, psz_session );
1670             if( rtsp && !rtsp->b_playing )
1671             {
1672                 int i_id;
1673                 /* FIXME */
1674                 rtsp->b_playing = VLC_TRUE;
1675
1676                 vlc_mutex_lock( &p_sys->lock_es );
1677                 for( i_id = 0; i_id < rtsp->i_id; i_id++ )
1678                 {
1679                     sout_stream_id_t *id = rtsp->id[i_id];
1680                     int i;
1681
1682                     for( i = 0; i < p_sys->i_es; i++ )
1683                     {
1684                         if( id == p_sys->es[i] )
1685                             break;
1686                     }
1687                     if( i >= p_sys->i_es ) continue;
1688
1689                     vlc_mutex_lock( &id->lock_rtsp );
1690                     TAB_APPEND( id->i_rtsp_access, id->rtsp_access, rtsp->access[i_id] );
1691                     vlc_mutex_unlock( &id->lock_rtsp );
1692                 }
1693                 vlc_mutex_unlock( &p_sys->lock_es );
1694             }
1695             break;
1696         }
1697         case HTTPD_MSG_PAUSE:
1698             /* FIXME */
1699             return VLC_EGENERIC;
1700         case HTTPD_MSG_TEARDOWN:
1701         {
1702             rtsp_client_t *rtsp;
1703
1704             /* for now only multicast so easy again */
1705             answer->i_status = 200;
1706             answer->psz_status = strdup( "OK" );
1707             answer->i_body = 0;
1708             answer->p_body = NULL;
1709
1710             psz_session = httpd_MsgGet( query, "Session" );
1711             rtsp = RtspClientGet( p_stream, psz_session );
1712             if( rtsp )
1713             {
1714                 int i_id;
1715
1716                 vlc_mutex_lock( &p_sys->lock_es );
1717                 for( i_id = 0; i_id < rtsp->i_id; i_id++ )
1718                 {
1719                     sout_stream_id_t *id = rtsp->id[i_id];
1720                     int i;
1721
1722                     for( i = 0; i < p_sys->i_es; i++ )
1723                     {
1724                         if( id == p_sys->es[i] )
1725                             break;
1726                     }
1727                     if( i >= p_sys->i_es ) continue;
1728
1729                     vlc_mutex_lock( &id->lock_rtsp );
1730                     TAB_REMOVE( id->i_rtsp_access, id->rtsp_access, rtsp->access[i_id] );
1731                     vlc_mutex_unlock( &id->lock_rtsp );
1732                 }
1733                 vlc_mutex_unlock( &p_sys->lock_es );
1734
1735                 RtspClientDel( p_stream, rtsp );
1736             }
1737             break;
1738         }
1739
1740         default:
1741             return VLC_EGENERIC;
1742     }
1743     httpd_MsgAdd( answer, "Server", PACKAGE_STRING );
1744     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
1745     psz_cseq = httpd_MsgGet( query, "Cseq" );
1746     if( psz_cseq )
1747         i_cseq = atoi( psz_cseq );
1748     else
1749         i_cseq = 0;
1750     httpd_MsgAdd( answer, "Cseq", "%d", i_cseq );
1751     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
1752
1753     if( psz_session )
1754         httpd_MsgAdd( answer, "Session", "%s;timeout=5", psz_session );
1755     return VLC_SUCCESS;
1756 }
1757
1758 static int RtspCallbackId( httpd_callback_sys_t *p_args,
1759                           httpd_client_t *cl,
1760                           httpd_message_t *answer, httpd_message_t *query )
1761 {
1762     sout_stream_id_t *id = (sout_stream_id_t*)p_args;
1763     sout_stream_t    *p_stream = id->p_stream;
1764     sout_stream_sys_t *p_sys = p_stream->p_sys;
1765     char psz_session_init[100];
1766     const char *psz_session = NULL;
1767     const char *psz_cseq = NULL;
1768     int  i_cseq = 0;
1769
1770
1771     if( answer == NULL || query == NULL )
1772         return VLC_SUCCESS;
1773     //fprintf( stderr, "RtspCallback query: type=%d\n", query->i_type );
1774
1775     /* */
1776     snprintf( psz_session_init, sizeof(psz_session_init), "%d", rand() );
1777
1778     /* */
1779     answer->i_proto = HTTPD_PROTO_RTSP;
1780     answer->i_version= query->i_version;
1781     answer->i_type   = HTTPD_MSG_ANSWER;
1782
1783     switch( query->i_type )
1784     {
1785         case HTTPD_MSG_SETUP:
1786         {
1787             const char *psz_transport = httpd_MsgGet( query, "Transport" );
1788
1789             //fprintf( stderr, "HTTPD_MSG_SETUP: transport=%s\n", psz_transport );
1790
1791             if( strstr( psz_transport, "multicast" ) && id->psz_destination )
1792             {
1793                 //fprintf( stderr, "HTTPD_MSG_SETUP: multicast\n" );
1794                 answer->i_status = 200;
1795                 answer->psz_status = strdup( "OK" );
1796                 answer->i_body = 0;
1797                 answer->p_body = NULL;
1798
1799                 psz_session = httpd_MsgGet( query, "Session" );
1800                 if( !psz_session )
1801                     psz_session = psz_session_init;
1802
1803                 httpd_MsgAdd( answer, "Transport",
1804                               "RTP/AVP/UDP;destination=%s;port=%d-%d;ttl=%d",
1805                               id->psz_destination, id->i_port,id->i_port+1,
1806                               p_sys->i_ttl > 0 ? p_sys->i_ttl : 1);
1807             }
1808             else if( strstr( psz_transport, "unicast" ) && strstr( psz_transport, "client_port=" ) )
1809             {
1810                 int  i_port = atoi( strstr( psz_transport, "client_port=" ) + strlen("client_port=") );
1811                 char ip[NI_MAXNUMERICHOST], psz_access[17], psz_url[NI_MAXNUMERICHOST + 8];
1812
1813                 sout_access_out_t *p_access;
1814
1815                 rtsp_client_t *rtsp = NULL;
1816
1817                 if( httpd_ClientIP( cl, ip ) == NULL )
1818                 {
1819                     answer->i_status = 500;
1820                     answer->psz_status = strdup( "Internal server error" );
1821                     answer->i_body = 0;
1822                     answer->p_body = NULL;
1823                     break;
1824                 }
1825
1826                 //fprintf( stderr, "HTTPD_MSG_SETUP: unicast ip=%s port=%d\n", ip, i_port );
1827
1828                 psz_session = httpd_MsgGet( query, "Session" );
1829                 if( !psz_session )
1830                 {
1831                     psz_session = psz_session_init;
1832                     rtsp = RtspClientNew( p_stream, psz_session_init );
1833                 }
1834                 else
1835                 {
1836                     rtsp = RtspClientGet( p_stream, psz_session );
1837                     if( rtsp == NULL )
1838                     {
1839                         answer->i_status = 454;
1840                         answer->psz_status = strdup( "Unknown session id" );
1841                         answer->i_body = 0;
1842                         answer->p_body = NULL;
1843                         break;
1844                     }
1845                 }
1846
1847                 /* first try to create the access out */
1848                 if( p_sys->i_ttl )
1849                     snprintf( psz_access, sizeof( psz_access ),
1850                               "udp{raw,ttl=%d}", p_sys->i_ttl );
1851                 else
1852                     strlcpy( psz_access, "udp{raw}", sizeof( psz_access ) );
1853
1854                 snprintf( psz_url, sizeof( psz_url ),
1855                          ( strchr( ip, ':' ) != NULL ) ? "[%s]:%d" : "%s:%d",
1856                          ip, i_port );
1857
1858                 if( ( p_access = sout_AccessOutNew( p_stream->p_sout, psz_access, psz_url ) ) == NULL )
1859                 {
1860                     msg_Err( p_stream, "cannot create the access out for %s://%s",
1861                              psz_access, psz_url );
1862                     answer->i_status = 500;
1863                     answer->psz_status = strdup( "Internal server error" );
1864                     answer->i_body = 0;
1865                     answer->p_body = NULL;
1866                     break;
1867                 }
1868
1869                 TAB_APPEND( rtsp->i_id, rtsp->id, id );
1870                 TAB_APPEND( rtsp->i_access, rtsp->access, p_access );
1871
1872                 answer->i_status = 200;
1873                 answer->psz_status = strdup( "OK" );
1874                 answer->i_body = 0;
1875                 answer->p_body = NULL;
1876
1877                 httpd_MsgAdd( answer, "Transport",
1878                               "RTP/AVP/UDP;client_port=%d-%d", i_port, i_port + 1 );
1879             }
1880             else /* TODO  strstr( psz_transport, "interleaved" ) ) */
1881             {
1882                 answer->i_status = 461;
1883                 answer->psz_status = strdup( "Unsupported Transport" );
1884                 answer->i_body = 0;
1885                 answer->p_body = NULL;
1886             }
1887             break;
1888         }
1889
1890         default:
1891             return VLC_EGENERIC;
1892     }
1893     httpd_MsgAdd( answer, "Server", "VLC Server" );
1894     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
1895     psz_cseq = httpd_MsgGet( query, "Cseq" );
1896     if( psz_cseq )
1897         i_cseq = atoi( psz_cseq );
1898     else
1899         i_cseq = 0;
1900     httpd_MsgAdd( answer, "Cseq", "%d", i_cseq );
1901     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
1902
1903     if( psz_session )
1904         httpd_MsgAdd( answer, "Session", "%s"/*;timeout=5*/, psz_session );
1905     return VLC_SUCCESS;
1906 }
1907
1908 /****************************************************************************
1909  * rtp_packetize_*:
1910  ****************************************************************************/
1911 static void rtp_packetize_common( sout_stream_id_t *id, block_t *out,
1912                                   int b_marker, int64_t i_pts )
1913 {
1914     uint32_t i_timestamp = i_pts * (int64_t)id->i_clock_rate / I64C(1000000);
1915
1916     out->p_buffer[0] = 0x80;
1917     out->p_buffer[1] = (b_marker?0x80:0x00)|id->i_payload_type;
1918     out->p_buffer[2] = ( id->i_sequence >> 8)&0xff;
1919     out->p_buffer[3] = ( id->i_sequence     )&0xff;
1920     out->p_buffer[4] = ( i_timestamp >> 24 )&0xff;
1921     out->p_buffer[5] = ( i_timestamp >> 16 )&0xff;
1922     out->p_buffer[6] = ( i_timestamp >>  8 )&0xff;
1923     out->p_buffer[7] = ( i_timestamp       )&0xff;
1924
1925     out->p_buffer[ 8] = id->ssrc[0];
1926     out->p_buffer[ 9] = id->ssrc[1];
1927     out->p_buffer[10] = id->ssrc[2];
1928     out->p_buffer[11] = id->ssrc[3];
1929
1930     out->i_buffer = 12;
1931     id->i_sequence++;
1932 }
1933
1934 static void rtp_packetize_send( sout_stream_id_t *id, block_t *out )
1935 {
1936     int i;
1937     vlc_mutex_lock( &id->lock_rtsp );
1938     for( i = 0; i < id->i_rtsp_access; i++ )
1939     {
1940         sout_AccessOutWrite( id->rtsp_access[i], block_Duplicate( out ) );
1941     }
1942     vlc_mutex_unlock( &id->lock_rtsp );
1943
1944     if( id->p_access )
1945     {
1946         sout_AccessOutWrite( id->p_access, out );
1947     }
1948     else
1949     {
1950         block_Release( out );
1951     }
1952 }
1953
1954 static int rtp_packetize_mpa( sout_stream_t *p_stream, sout_stream_id_t *id,
1955                               block_t *in )
1956 {
1957     int     i_max   = id->i_mtu - 12 - 4; /* payload max in one packet */
1958     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1959
1960     uint8_t *p_data = in->p_buffer;
1961     int     i_data  = in->i_buffer;
1962     int     i;
1963
1964     for( i = 0; i < i_count; i++ )
1965     {
1966         int           i_payload = __MIN( i_max, i_data );
1967         block_t *out = block_New( p_stream, 16 + i_payload );
1968
1969         /* rtp common header */
1970         rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts );
1971         /* mbz set to 0 */
1972         out->p_buffer[12] = 0;
1973         out->p_buffer[13] = 0;
1974         /* fragment offset in the current frame */
1975         out->p_buffer[14] = ( (i*i_max) >> 8 )&0xff;
1976         out->p_buffer[15] = ( (i*i_max)      )&0xff;
1977         memcpy( &out->p_buffer[16], p_data, i_payload );
1978
1979         out->i_buffer   = 16 + i_payload;
1980         out->i_dts    = in->i_dts + i * in->i_length / i_count;
1981         out->i_length = in->i_length / i_count;
1982
1983         rtp_packetize_send( id, out );
1984
1985         p_data += i_payload;
1986         i_data -= i_payload;
1987     }
1988
1989     return VLC_SUCCESS;
1990 }
1991
1992 /* rfc2250 */
1993 static int rtp_packetize_mpv( sout_stream_t *p_stream, sout_stream_id_t *id,
1994                               block_t *in )
1995 {
1996     int     i_max   = id->i_mtu - 12 - 4; /* payload max in one packet */
1997     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
1998
1999     uint8_t *p_data = in->p_buffer;
2000     int     i_data  = in->i_buffer;
2001     int     i;
2002     int     b_sequence_start = 0;
2003     int     i_temporal_ref = 0;
2004     int     i_picture_coding_type = 0;
2005     int     i_fbv = 0, i_bfc = 0, i_ffv = 0, i_ffc = 0;
2006     int     b_start_slice = 0;
2007
2008     /* preparse this packet to get some info */
2009     if( in->i_buffer > 4 )
2010     {
2011         uint8_t *p = p_data;
2012         int      i_rest = in->i_buffer;
2013
2014         for( ;; )
2015         {
2016             while( i_rest > 4 &&
2017                    ( p[0] != 0x00 || p[1] != 0x00 || p[2] != 0x01 ) )
2018             {
2019                 p++;
2020                 i_rest--;
2021             }
2022             if( i_rest <= 4 )
2023             {
2024                 break;
2025             }
2026             p += 3;
2027             i_rest -= 4;
2028
2029             if( *p == 0xb3 )
2030             {
2031                 /* sequence start code */
2032                 b_sequence_start = 1;
2033             }
2034             else if( *p == 0x00 && i_rest >= 4 )
2035             {
2036                 /* picture */
2037                 i_temporal_ref = ( p[1] << 2) |((p[2]>>6)&0x03);
2038                 i_picture_coding_type = (p[2] >> 3)&0x07;
2039
2040                 if( i_rest >= 4 && ( i_picture_coding_type == 2 ||
2041                                     i_picture_coding_type == 3 ) )
2042                 {
2043                     i_ffv = (p[3] >> 2)&0x01;
2044                     i_ffc = ((p[3]&0x03) << 1)|((p[4]>>7)&0x01);
2045                     if( i_rest > 4 && i_picture_coding_type == 3 )
2046                     {
2047                         i_fbv = (p[4]>>6)&0x01;
2048                         i_bfc = (p[4]>>3)&0x07;
2049                     }
2050                 }
2051             }
2052             else if( *p <= 0xaf )
2053             {
2054                 b_start_slice = 1;
2055             }
2056         }
2057     }
2058
2059     for( i = 0; i < i_count; i++ )
2060     {
2061         int           i_payload = __MIN( i_max, i_data );
2062         block_t *out = block_New( p_stream,
2063                                              16 + i_payload );
2064         uint32_t      h = ( i_temporal_ref << 16 )|
2065                           ( b_sequence_start << 13 )|
2066                           ( b_start_slice << 12 )|
2067                           ( i == i_count - 1 ? 1 << 11 : 0 )|
2068                           ( i_picture_coding_type << 8 )|
2069                           ( i_fbv << 7 )|( i_bfc << 4 )|( i_ffv << 3 )|i_ffc;
2070
2071         /* rtp common header */
2072         rtp_packetize_common( id, out, (i == i_count - 1)?1:0,
2073                               in->i_pts > 0 ? in->i_pts : in->i_dts );
2074
2075         /* 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 */
2076         out->p_buffer[12] = ( h >> 24 )&0xff;
2077         out->p_buffer[13] = ( h >> 16 )&0xff;
2078         out->p_buffer[14] = ( h >>  8 )&0xff;
2079         out->p_buffer[15] = ( h       )&0xff;
2080
2081         memcpy( &out->p_buffer[16], p_data, i_payload );
2082
2083         out->i_buffer   = 16 + i_payload;
2084         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2085         out->i_length = in->i_length / i_count;
2086
2087         rtp_packetize_send( id, out );
2088
2089         p_data += i_payload;
2090         i_data -= i_payload;
2091     }
2092
2093     return VLC_SUCCESS;
2094 }
2095
2096 static int rtp_packetize_ac3( sout_stream_t *p_stream, sout_stream_id_t *id,
2097                               block_t *in )
2098 {
2099     int     i_max   = id->i_mtu - 12 - 2; /* payload max in one packet */
2100     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2101
2102     uint8_t *p_data = in->p_buffer;
2103     int     i_data  = in->i_buffer;
2104     int     i;
2105
2106     for( i = 0; i < i_count; i++ )
2107     {
2108         int           i_payload = __MIN( i_max, i_data );
2109         block_t *out = block_New( p_stream, 14 + i_payload );
2110
2111         /* rtp common header */
2112         rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts );
2113         /* unit count */
2114         out->p_buffer[12] = 1;
2115         /* unit header */
2116         out->p_buffer[13] = 0x00;
2117         /* data */
2118         memcpy( &out->p_buffer[14], p_data, i_payload );
2119
2120         out->i_buffer   = 14 + i_payload;
2121         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2122         out->i_length = in->i_length / i_count;
2123
2124         rtp_packetize_send( id, out );
2125
2126         p_data += i_payload;
2127         i_data -= i_payload;
2128     }
2129
2130     return VLC_SUCCESS;
2131 }
2132
2133 static int rtp_packetize_split( sout_stream_t *p_stream, sout_stream_id_t *id,
2134                                 block_t *in )
2135 {
2136     int     i_max   = id->i_mtu - 12; /* payload max in one packet */
2137     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2138
2139     uint8_t *p_data = in->p_buffer;
2140     int     i_data  = in->i_buffer;
2141     int     i;
2142
2143     for( i = 0; i < i_count; i++ )
2144     {
2145         int           i_payload = __MIN( i_max, i_data );
2146         block_t *out = block_New( p_stream, 12 + i_payload );
2147
2148         /* rtp common header */
2149         rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
2150                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2151         memcpy( &out->p_buffer[12], p_data, i_payload );
2152
2153         out->i_buffer   = 12 + i_payload;
2154         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2155         out->i_length = in->i_length / i_count;
2156
2157         rtp_packetize_send( id, out );
2158
2159         p_data += i_payload;
2160         i_data -= i_payload;
2161     }
2162
2163     return VLC_SUCCESS;
2164 }
2165
2166 /* rfc3016 */
2167 static int rtp_packetize_mp4a_latm( sout_stream_t *p_stream, sout_stream_id_t *id,
2168                                 block_t *in )
2169 {
2170     int     i_max   = id->i_mtu - 14;              /* payload max in one packet */
2171     int     latmhdrsize = in->i_buffer / 0xff + 1;
2172     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2173
2174     uint8_t *p_data = in->p_buffer, *p_header = NULL;
2175     int     i_data  = in->i_buffer;
2176     int     i;
2177
2178     for( i = 0; i < i_count; i++ )
2179     {
2180         int     i_payload = __MIN( i_max, i_data );
2181         block_t *out;
2182
2183         if( i != 0 )
2184             latmhdrsize = 0;
2185         out = block_New( p_stream, 12 + latmhdrsize + i_payload );
2186
2187         /* rtp common header */
2188         rtp_packetize_common( id, out, ((i == i_count - 1) ? 1 : 0),
2189                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2190
2191         if( i == 0 )
2192         {
2193             int tmp = in->i_buffer;
2194
2195             p_header=out->p_buffer+12;
2196             while( tmp > 0xfe )
2197             {
2198                 *p_header = 0xff;
2199                 p_header++;
2200                 tmp -= 0xff;
2201             }
2202             *p_header = tmp;
2203         }
2204
2205         memcpy( &out->p_buffer[12+latmhdrsize], p_data, i_payload );
2206
2207         out->i_buffer   = 12 + latmhdrsize + i_payload;
2208         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2209         out->i_length = in->i_length / i_count;
2210
2211         rtp_packetize_send( id, out );
2212
2213         p_data += i_payload;
2214         i_data -= i_payload;
2215     }
2216
2217     return VLC_SUCCESS;
2218 }
2219
2220 static int rtp_packetize_l16( sout_stream_t *p_stream, sout_stream_id_t *id,
2221                               block_t *in )
2222 {
2223     int     i_max   = id->i_mtu - 12; /* payload max in one packet */
2224     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2225
2226     uint8_t *p_data = in->p_buffer;
2227     int     i_data  = in->i_buffer;
2228     int     i_packet = 0;
2229
2230     while( i_data > 0 )
2231     {
2232         int           i_payload = (__MIN( i_max, i_data )/4)*4;
2233         block_t *out = block_New( p_stream, 12 + i_payload );
2234
2235         /* rtp common header */
2236         rtp_packetize_common( id, out, 0,
2237                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2238         memcpy( &out->p_buffer[12], p_data, i_payload );
2239
2240         out->i_buffer   = 12 + i_payload;
2241         out->i_dts    = in->i_dts + i_packet * in->i_length / i_count;
2242         out->i_length = in->i_length / i_count;
2243
2244         rtp_packetize_send( id, out );
2245
2246         p_data += i_payload;
2247         i_data -= i_payload;
2248         i_packet++;
2249     }
2250
2251     return VLC_SUCCESS;
2252 }
2253
2254 static int rtp_packetize_l8( sout_stream_t *p_stream, sout_stream_id_t *id,
2255                              block_t *in )
2256 {
2257     int     i_max   = id->i_mtu - 12; /* payload max in one packet */
2258     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2259
2260     uint8_t *p_data = in->p_buffer;
2261     int     i_data  = in->i_buffer;
2262     int     i_packet = 0;
2263
2264     while( i_data > 0 )
2265     {
2266         int           i_payload = (__MIN( i_max, i_data )/2)*2;
2267         block_t *out = block_New( p_stream, 12 + i_payload );
2268
2269         /* rtp common header */
2270         rtp_packetize_common( id, out, 0,
2271                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2272         memcpy( &out->p_buffer[12], p_data, i_payload );
2273
2274         out->i_buffer   = 12 + i_payload;
2275         out->i_dts    = in->i_dts + i_packet * in->i_length / i_count;
2276         out->i_length = in->i_length / i_count;
2277
2278         rtp_packetize_send( id, out );
2279
2280         p_data += i_payload;
2281         i_data -= i_payload;
2282         i_packet++;
2283     }
2284
2285     return VLC_SUCCESS;
2286 }
2287 static int rtp_packetize_mp4a( sout_stream_t *p_stream, sout_stream_id_t *id,
2288                                block_t *in )
2289 {
2290     int     i_max   = id->i_mtu - 16; /* payload max in one packet */
2291     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2292
2293     uint8_t *p_data = in->p_buffer;
2294     int     i_data  = in->i_buffer;
2295     int     i;
2296
2297     for( i = 0; i < i_count; i++ )
2298     {
2299         int           i_payload = __MIN( i_max, i_data );
2300         block_t *out = block_New( p_stream, 16 + i_payload );
2301
2302         /* rtp common header */
2303         rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
2304                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2305         /* AU headers */
2306         /* AU headers length (bits) */
2307         out->p_buffer[12] = 0;
2308         out->p_buffer[13] = 2*8;
2309         /* for each AU length 13 bits + idx 3bits, */
2310         out->p_buffer[14] = ( in->i_buffer >> 5 )&0xff;
2311         out->p_buffer[15] = ( (in->i_buffer&0xff)<<3 )|0;
2312
2313         memcpy( &out->p_buffer[16], p_data, i_payload );
2314
2315         out->i_buffer   = 16 + i_payload;
2316         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2317         out->i_length = in->i_length / i_count;
2318
2319         rtp_packetize_send( id, out );
2320
2321         p_data += i_payload;
2322         i_data -= i_payload;
2323     }
2324
2325     return VLC_SUCCESS;
2326 }
2327
2328
2329 /* rfc2429 */
2330 #define RTP_H263_HEADER_SIZE (2)  // plen = 0
2331 #define RTP_H263_PAYLOAD_START (14)  // plen = 0
2332 static int rtp_packetize_h263( sout_stream_t *p_stream, sout_stream_id_t *id,
2333                                block_t *in )
2334 {
2335     uint8_t *p_data = in->p_buffer;
2336     int     i_data  = in->i_buffer;
2337     int     i;
2338     int     i_max   = id->i_mtu - 12 - RTP_H263_HEADER_SIZE; /* payload max in one packet */
2339     int     i_count;
2340     int     b_p_bit;
2341     int     b_v_bit = 0; // no pesky error resilience
2342     int     i_plen = 0; // normally plen=0 for PSC packet
2343     int     i_pebit = 0; // because plen=0
2344     uint16_t h;
2345
2346     if( i_data < 2 )
2347     {
2348         return VLC_EGENERIC;
2349     }
2350     if( p_data[0] || p_data[1] )
2351     {
2352         return VLC_EGENERIC;
2353     }
2354     /* remove 2 leading 0 bytes */
2355     p_data += 2;
2356     i_data -= 2;
2357     i_count = ( i_data + i_max - 1 ) / i_max;
2358
2359     for( i = 0; i < i_count; i++ )
2360     {
2361         int      i_payload = __MIN( i_max, i_data );
2362         block_t *out = block_New( p_stream,
2363                                   RTP_H263_PAYLOAD_START + i_payload );
2364         b_p_bit = (i == 0) ? 1 : 0;
2365         h = ( b_p_bit << 10 )|
2366             ( b_v_bit << 9  )|
2367             ( i_plen  << 3  )|
2368               i_pebit;
2369
2370         /* rtp common header */
2371         //b_m_bit = 1; // always contains end of frame
2372         rtp_packetize_common( id, out, (i == i_count - 1)?1:0,
2373                               in->i_pts > 0 ? in->i_pts : in->i_dts );
2374
2375         /* h263 header */
2376         out->p_buffer[12] = ( h >>  8 )&0xff;
2377         out->p_buffer[13] = ( h       )&0xff;
2378         memcpy( &out->p_buffer[RTP_H263_PAYLOAD_START], p_data, i_payload );
2379
2380         out->i_buffer = RTP_H263_PAYLOAD_START + i_payload;
2381         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2382         out->i_length = in->i_length / i_count;
2383
2384         rtp_packetize_send( id, out );
2385
2386         p_data += i_payload;
2387         i_data -= i_payload;
2388     }
2389
2390     return VLC_SUCCESS;
2391 }
2392
2393 /* rfc3984 */
2394 static int rtp_packetize_h264_nal( sout_stream_t *p_stream, sout_stream_id_t *id,
2395                                    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 )
2396 {
2397     const int i_max = id->i_mtu - 12; /* payload max in one packet */
2398     int i_nal_hdr;
2399     int i_nal_type;
2400
2401     if( i_data < 5 )
2402         return VLC_SUCCESS;
2403
2404     i_nal_hdr = p_data[3];
2405     i_nal_type = i_nal_hdr&0x1f;
2406     if( i_nal_type == 7 || i_nal_type == 8 )
2407     {
2408         /* XXX Why do you want to remove them ? It will break streaming with 
2409          * SPS/PPS change (broadcast) ? */
2410         return VLC_SUCCESS;
2411     }
2412
2413     /* Skip start code */
2414     p_data += 3;
2415     i_data -= 3;
2416
2417     /* */
2418     if( i_data <= i_max )
2419     {
2420         /* Single NAL unit packet */
2421         block_t *out = block_New( p_stream, 12 + i_data );
2422         out->i_dts    = i_dts;
2423         out->i_length = i_length;
2424
2425         /* */
2426         rtp_packetize_common( id, out, b_last, i_pts );
2427         out->i_buffer = 12 + i_data;
2428
2429         memcpy( &out->p_buffer[12], p_data, i_data );
2430
2431         rtp_packetize_send( id, out );
2432     }
2433     else
2434     {
2435         /* FU-A Fragmentation Unit without interleaving */
2436         const int i_count = ( i_data-1 + i_max-2 - 1 ) / (i_max-2);
2437         int i;
2438
2439         p_data++;
2440         i_data--;
2441
2442         for( i = 0; i < i_count; i++ )
2443         {
2444             const int i_payload = __MIN( i_data, i_max-2 );
2445             block_t *out = block_New( p_stream, 12 + 2 + i_payload );
2446             out->i_dts    = i_dts + i * i_length / i_count;
2447             out->i_length = i_length / i_count;
2448
2449             /* */
2450             rtp_packetize_common( id, out, (b_last && i_payload == i_data), i_pts );
2451             out->i_buffer = 14 + i_payload;
2452
2453             /* FU indicator */
2454             out->p_buffer[12] = 0x00 | (i_nal_hdr & 0x60) | 28;
2455             /* FU header */
2456             out->p_buffer[13] = ( i == 0 ? 0x80 : 0x00 ) | ( (i == i_count-1) ? 0x40 : 0x00 )  | i_nal_type;
2457             memcpy( &out->p_buffer[14], p_data, i_payload );
2458
2459             rtp_packetize_send( id, out );
2460
2461             i_data -= i_payload;
2462             p_data += i_payload;
2463         }
2464     }
2465     return VLC_SUCCESS;
2466 }
2467
2468 static int rtp_packetize_h264( sout_stream_t *p_stream, sout_stream_id_t *id,
2469                                block_t *in )
2470 {
2471     const uint8_t *p_buffer = in->p_buffer;
2472     int i_buffer = in->i_buffer;
2473
2474     while( i_buffer > 4 && ( p_buffer[0] != 0 || p_buffer[1] != 0 || p_buffer[2] != 1 ) )
2475     {
2476         i_buffer--;
2477         p_buffer++;
2478     }
2479
2480     /* Split nal units */
2481     while( i_buffer > 4 )
2482     {
2483         int i_offset;
2484         int i_size = i_buffer;
2485         int i_skip = i_buffer;
2486
2487         /* search nal end */
2488         for( i_offset = 4; i_offset+2 < i_buffer ; i_offset++)
2489         {
2490             if( p_buffer[i_offset] == 0 && p_buffer[i_offset+1] == 0 && p_buffer[i_offset+2] == 1 )
2491             {
2492                 /* we found another startcode */
2493                 i_size = i_offset - ( p_buffer[i_offset-1] == 0 ? 1 : 0);
2494                 i_skip = i_offset;
2495                 break;
2496             } 
2497         }
2498         /* TODO add STAP-A to remove a lot of overhead with small slice/sei/... */
2499         rtp_packetize_h264_nal( p_stream, id, p_buffer, i_size,
2500                                 (in->i_pts > 0 ? in->i_pts : in->i_dts), in->i_dts,
2501                                 (i_size >= i_buffer), in->i_length * i_size / in->i_buffer );
2502
2503         i_buffer -= i_skip;
2504         p_buffer += i_skip;
2505     }
2506     return VLC_SUCCESS;
2507 }
2508
2509 static int rtp_packetize_amr( sout_stream_t *p_stream, sout_stream_id_t *id,
2510                               block_t *in )
2511 {
2512     int     i_max   = id->i_mtu - 14; /* payload max in one packet */
2513     int     i_count = ( in->i_buffer + i_max - 1 ) / i_max;
2514
2515     uint8_t *p_data = in->p_buffer;
2516     int     i_data  = in->i_buffer;
2517     int     i;
2518
2519     /* Only supports octet-aligned mode */
2520     for( i = 0; i < i_count; i++ )
2521     {
2522         int           i_payload = __MIN( i_max, i_data );
2523         block_t *out = block_New( p_stream, 14 + i_payload );
2524
2525         /* rtp common header */
2526         rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
2527                               (in->i_pts > 0 ? in->i_pts : in->i_dts) );
2528         /* Payload header */
2529         out->p_buffer[12] = 0xF0; /* CMR */
2530         out->p_buffer[13] = p_data[0]&0x7C; /* ToC */ /* FIXME: frame type */
2531
2532         /* FIXME: are we fed multiple frames ? */
2533         memcpy( &out->p_buffer[14], p_data+1, i_payload-1 );
2534
2535         out->i_buffer   = 14 + i_payload-1;
2536         out->i_dts    = in->i_dts + i * in->i_length / i_count;
2537         out->i_length = in->i_length / i_count;
2538
2539         rtp_packetize_send( id, out );
2540
2541         p_data += i_payload;
2542         i_data -= i_payload;
2543     }
2544
2545     return VLC_SUCCESS;
2546 }