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