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