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