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