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