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