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