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