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