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