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