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