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