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