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