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