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