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