fcb8b32e95f4cf7b030377586cb367bff98ac6ed
[vlc.git] / modules / misc / rtsp.c
1 /*****************************************************************************
2  * rtsp.c: rtsp VoD server module
3  *****************************************************************************
4  * Copyright (C) 2003-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #define _GNU_SOURCE
29 #include <stdlib.h>
30
31 #include <errno.h>
32
33 #include <vlc/vlc.h>
34 #include <vlc_input.h>
35 #include <vlc_sout.h>
36 #include <vlc_block.h>
37
38 #include "vlc_httpd.h"
39 #include "vlc_vod.h"
40 #include "vlc_url.h"
41 #include <vlc_network.h>
42 #include <vlc_charset.h>
43
44 /*****************************************************************************
45  * Module descriptor
46  *****************************************************************************/
47 static int  Open ( vlc_object_t * );
48 static void Close( vlc_object_t * );
49
50 #define HOST_TEXT N_( "RTSP host address" )
51 #define HOST_LONGTEXT N_( \
52     "This defines the address, port and path the RTSP VOD server will listen " \
53     "on.\nSyntax is address:port/path. The default is to listen on all "\
54     "interfaces (address 0.0.0.0), on port 554, with no path.\nTo listen " \
55     "only on the local interface, use \"localhost\" as address." )
56
57 #define THROTLE_TEXT N_( "Maximum number of connections" )
58 #define THROTLE_LONGTEXT N_( "This limits the maximum number of clients " \
59     "that can connect to the RTSP VOD. 0 means no limit."  )
60
61 #define RAWMUX_TEXT N_( "MUX for RAW RTSP transport" )
62
63 #define SESSION_TIMEOUT_TEXT N_( "Sets the timeout option in the RTSP " \
64     "session string" )
65 #define SESSION_TIMEOUT_LONGTEXT N_( "Defines what timeout option to add " \
66     "to the RTSP session ID string. Setting it to a negative number removes " \
67     "the timeout option entirely. This is needed by some IPTV STBs (such as " \
68     "those made by HansunTech) which get confused by it. The default is 5." )
69
70 vlc_module_begin();
71     set_shortname( _("RTSP VoD" ) );
72     set_description( _("RTSP VoD server") );
73     set_category( CAT_SOUT );
74     set_subcategory( SUBCAT_SOUT_VOD );
75     set_capability( "vod server", 1 );
76     set_callbacks( Open, Close );
77     add_shortcut( "rtsp" );
78     add_string ( "rtsp-host", NULL, NULL, HOST_TEXT, HOST_LONGTEXT, VLC_TRUE );
79     add_string( "rtsp-raw-mux", "ts", NULL, RAWMUX_TEXT, RAWMUX_TEXT, VLC_TRUE );
80     add_integer( "rtsp-throttle-users", 0, NULL, THROTLE_TEXT,
81                                            THROTLE_LONGTEXT, VLC_TRUE );
82     add_integer( "rtsp-session-timeout", 5, NULL, SESSION_TIMEOUT_TEXT,
83                  SESSION_TIMEOUT_LONGTEXT, VLC_TRUE );
84 vlc_module_end();
85
86 /*****************************************************************************
87  * Exported prototypes
88  *****************************************************************************/
89
90 typedef struct media_es_t media_es_t;
91
92 typedef struct
93 {
94     media_es_t *p_media_es;
95     char *psz_ip;
96     int i_port;
97
98 } rtsp_client_es_t;
99
100 typedef struct
101 {
102     char *psz_session;
103     int64_t i_last; /* for timeout */
104
105     vlc_bool_t b_playing; /* is it in "play" state */
106     vlc_bool_t b_paused; /* is it in "pause" state */
107
108     int i_es;
109     rtsp_client_es_t **es;
110
111 } rtsp_client_t;
112
113 struct media_es_t
114 {
115     /* VoD server */
116     vod_t *p_vod;
117
118     /* RTSP server */
119     httpd_url_t *p_rtsp_url;
120
121     vod_media_t *p_media;
122
123     es_format_t fmt;
124     int         i_port;
125     uint8_t     i_payload_type;
126     char        *psz_rtpmap;
127     char        *psz_fmtp;
128
129 };
130
131 struct vod_media_t
132 {
133     int id;
134
135     /* VoD server */
136     vod_t *p_vod;
137
138     /* RTSP server */
139     httpd_url_t  *p_rtsp_url;
140     char         *psz_rtsp_control_v4;
141     char         *psz_rtsp_control_v6;
142     char         *psz_rtsp_path;
143
144     int  i_port;
145     int  i_port_audio;
146     int  i_port_video;
147     int  i_ttl;
148     int  i_payload_type;
149
150     int64_t i_sdp_id;
151     int     i_sdp_version;
152
153     vlc_bool_t b_multicast;
154
155     vlc_mutex_t lock;
156
157     /* ES list */
158     int        i_es;
159     media_es_t **es;
160     char       *psz_mux;
161     vlc_bool_t  b_raw;
162
163     /* RTSP client */
164     int           i_rtsp;
165     rtsp_client_t **rtsp;
166
167     /* Infos */
168     char *psz_session_name;
169     char *psz_session_description;
170     char *psz_session_url;
171     char *psz_session_email;
172     mtime_t i_length;
173 };
174
175 struct vod_sys_t
176 {
177     /* RTSP server */
178     httpd_host_t *p_rtsp_host;
179     char *psz_path;
180     int i_port;
181     int i_throttle_users;
182     int i_connections;
183
184     char *psz_raw_mux;
185
186     int i_session_timeout;
187
188     /* List of media */
189     vlc_mutex_t lock_media;
190     int i_media_id;
191     int i_media;
192     vod_media_t **media;
193
194     /* */
195     block_fifo_t *p_fifo_cmd;
196 };
197
198 /* rtsp delayed command (to avoid deadlock between vlm/httpd) */
199 typedef enum
200 {
201     RTSP_CMD_TYPE_NONE,  /* Exit requested */
202
203     RTSP_CMD_TYPE_PLAY,
204     RTSP_CMD_TYPE_PAUSE,
205     RTSP_CMD_TYPE_STOP,
206     RTSP_CMD_TYPE_SEEK,
207     RTSP_CMD_TYPE_REWIND,
208     RTSP_CMD_TYPE_FORWARD,
209 } rtsp_cmd_type_t;
210
211 static vod_media_t *MediaNew( vod_t *, const char *, input_item_t * );
212 static void         MediaDel( vod_t *, vod_media_t * );
213 static int          MediaAddES( vod_t *, vod_media_t *, es_format_t * );
214 static void         MediaDelES( vod_t *, vod_media_t *, es_format_t * );
215
216 static void CommandThread( vlc_object_t *p_this );
217 static void CommandPush( vod_t *, rtsp_cmd_type_t, vod_media_t *, const char *psz_session,
218                          double f_arg, const char *psz_arg );
219
220 static rtsp_client_t *RtspClientNew( vod_media_t *, char * );
221 static rtsp_client_t *RtspClientGet( vod_media_t *, const char * );
222 static void           RtspClientDel( vod_media_t *, rtsp_client_t * );
223
224 static int RtspCallback( httpd_callback_sys_t *, httpd_client_t *,
225                          httpd_message_t *, httpd_message_t * );
226 static int RtspCallbackES( httpd_callback_sys_t *, httpd_client_t *,
227                            httpd_message_t *, httpd_message_t * );
228
229 static char *SDPGenerate( const vod_media_t *, httpd_client_t *cl );
230
231 static void sprintf_hexa( char *s, uint8_t *p_data, int i_data )
232 {
233     static const char hex[16] = "0123456789abcdef";
234     int i;
235
236     for( i = 0; i < i_data; i++ )
237     {
238         s[2*i+0] = hex[(p_data[i]>>4)&0xf];
239         s[2*i+1] = hex[(p_data[i]   )&0xf];
240     }
241     s[2*i_data] = '\0';
242 }
243
244 /*****************************************************************************
245  * Open: Starts the RTSP server module
246  *****************************************************************************/
247 static int Open( vlc_object_t *p_this )
248 {
249     vod_t *p_vod = (vod_t *)p_this;
250     vod_sys_t *p_sys = 0;
251     char *psz_url = 0;
252     vlc_url_t url;
253
254     psz_url = config_GetPsz( p_vod, "rtsp-host" );
255     vlc_UrlParse( &url, psz_url, 0 );
256     if( psz_url ) free( psz_url );
257
258     if( url.i_port <= 0 ) url.i_port = 554;
259
260     p_vod->p_sys = p_sys = malloc( sizeof( vod_sys_t ) );
261     if( !p_sys ) goto error;
262     p_sys->p_rtsp_host = 0;
263
264     p_sys->i_session_timeout = var_CreateGetInteger( p_this, "rtsp-session-timeout" );
265
266     p_sys->i_throttle_users = var_CreateGetInteger( p_this, "rtsp-throttle-users" );
267     msg_Dbg( p_this, "allowing up to %d connections", p_sys->i_throttle_users );
268     p_sys->i_connections = 0;
269
270     p_sys->psz_raw_mux = var_CreateGetString( p_this, "rtsp-raw-mux" );
271
272     p_sys->p_rtsp_host =
273         httpd_HostNew( VLC_OBJECT(p_vod), url.psz_host, url.i_port );
274     if( !p_sys->p_rtsp_host )
275     {
276         msg_Err( p_vod, "cannot create RTSP server (%s:%i)",
277                  url.psz_host, url.i_port );
278         goto error;
279     }
280
281     p_sys->psz_path = strdup( url.psz_path ? url.psz_path : "/" );
282     p_sys->i_port = url.i_port;
283
284     vlc_UrlClean( &url );
285
286     vlc_mutex_init( p_vod, &p_sys->lock_media );
287
288     TAB_INIT( p_sys->i_media, p_sys->media );
289     p_sys->i_media_id = 0;
290
291     p_vod->pf_media_new = MediaNew;
292     p_vod->pf_media_del = MediaDel;
293     p_vod->pf_media_add_es = MediaAddES;
294     p_vod->pf_media_del_es = MediaDelES;
295
296     p_sys->p_fifo_cmd = block_FifoNew( p_vod );
297     if( vlc_thread_create( p_vod, "rtsp vod thread", CommandThread,
298                            VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
299     {
300         msg_Err( p_vod, "cannot spawn rtsp vod thread" );
301         block_FifoRelease( p_sys->p_fifo_cmd );
302         free( p_sys->psz_path );
303         goto error;
304     }
305
306     return VLC_SUCCESS;
307
308 error:
309     if( p_sys && p_sys->p_rtsp_host ) httpd_HostDelete( p_sys->p_rtsp_host );
310     if( p_sys && p_sys->psz_raw_mux ) free( p_sys->psz_raw_mux );
311     if( p_sys ) free( p_sys );
312     vlc_UrlClean( &url );
313
314     return VLC_EGENERIC;
315 }
316
317 /*****************************************************************************
318  * Close:
319  *****************************************************************************/
320 static void Close( vlc_object_t * p_this )
321 {
322     vod_t *p_vod = (vod_t *)p_this;
323     vod_sys_t *p_sys = p_vod->p_sys;
324
325     /* Stop command thread */
326     p_vod->b_die = VLC_TRUE;
327     CommandPush( p_vod, RTSP_CMD_TYPE_NONE, NULL, NULL, 0.0, NULL );
328     vlc_thread_join( p_vod );
329
330     block_FifoRelease( p_sys->p_fifo_cmd );
331
332     httpd_HostDelete( p_sys->p_rtsp_host );
333     var_Destroy( p_this, "rtsp-session-timeout" );
334     var_Destroy( p_this, "rtsp-throttle-users" );
335     var_Destroy( p_this, "rtsp-raw-mux" );
336
337     /* Check VLM is not buggy */
338     if( p_sys->i_media > 0 )
339         msg_Err( p_vod, "rtsp vod leaking %d medias", p_sys->i_media );
340     TAB_CLEAN( p_sys->i_media, p_sys->media );
341
342     vlc_mutex_destroy( &p_sys->lock_media );
343
344     free( p_sys->psz_path );
345     free( p_sys->psz_raw_mux );
346     free( p_sys );
347 }
348
349 /*****************************************************************************
350  * Media handling
351  *****************************************************************************/
352 static vod_media_t *MediaNew( vod_t *p_vod, const char *psz_name,
353                               input_item_t *p_item )
354 {
355     vod_sys_t *p_sys = p_vod->p_sys;
356     vod_media_t *p_media = malloc( sizeof(vod_media_t) );
357     int i;
358
359     if( !p_media )
360     {
361         msg_Err( p_vod, "not enough memory" );
362         return NULL;
363     }
364
365     memset( p_media, 0, sizeof(vod_media_t) );
366     p_media->id = p_sys->i_media_id++;
367     TAB_INIT( p_media->i_es, p_media->es );
368     p_media->psz_mux = 0;
369     TAB_INIT( p_media->i_rtsp, p_media->rtsp );
370     p_media->b_raw = VLC_FALSE;
371
372     asprintf( &p_media->psz_rtsp_path, "%s%s", p_sys->psz_path, psz_name );
373     p_media->p_rtsp_url =
374         httpd_UrlNewUnique( p_sys->p_rtsp_host, p_media->psz_rtsp_path, NULL,
375                             NULL, NULL );
376
377     if( !p_media->p_rtsp_url )
378     {
379         msg_Err( p_vod, "cannot create RTSP url (%s)", p_media->psz_rtsp_path);
380         free( p_media->psz_rtsp_path );
381         free( p_media );
382         return NULL;
383     }
384
385     msg_Dbg( p_vod, "created RTSP url: %s", p_media->psz_rtsp_path );
386
387     asprintf( &p_media->psz_rtsp_control_v4,
388                "a=control:rtsp://%%s:%d%s/trackID=%%d\r\n",
389                p_sys->i_port, p_media->psz_rtsp_path );
390     asprintf( &p_media->psz_rtsp_control_v6,
391                "a=control:rtsp://[%%s]:%d%s/trackID=%%d\r\n",
392               p_sys->i_port, p_media->psz_rtsp_path );
393
394     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_SETUP,
395                     RtspCallback, (void*)p_media );
396     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_DESCRIBE,
397                     RtspCallback, (void*)p_media );
398     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_PLAY,
399                     RtspCallback, (void*)p_media );
400     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_PAUSE,
401                     RtspCallback, (void*)p_media );
402     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_GETPARAMETER,
403                     RtspCallback, (void*)p_media );
404     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_TEARDOWN,
405                     RtspCallback, (void*)p_media );
406
407     p_media->p_vod = p_vod;
408
409     vlc_mutex_lock( &p_sys->lock_media );
410     TAB_APPEND( p_sys->i_media, p_sys->media, p_media );
411     vlc_mutex_unlock( &p_sys->lock_media );
412
413     vlc_mutex_init( p_vod, &p_media->lock );
414     p_media->psz_session_name = strdup("");
415     p_media->psz_session_description = strdup("");
416     p_media->psz_session_url = strdup("");
417     p_media->psz_session_email = strdup("");
418
419     p_media->i_port_audio = 1234;
420     p_media->i_port_video = 1236;
421     p_media->i_port       = 1238;
422     p_media->i_payload_type = 96;
423
424     p_media->i_sdp_id = mdate();
425     p_media->i_sdp_version = 1;
426     p_media->i_length = p_item->i_duration;
427
428     vlc_mutex_lock( &p_item->lock );
429     msg_Dbg( p_vod, "media has %i declared ES", p_item->i_es );
430     for( i = 0; i < p_item->i_es; i++ )
431     {
432         MediaAddES( p_vod, p_media, p_item->es[i] );
433     }
434     vlc_mutex_unlock( &p_item->lock );
435
436     return p_media;
437 }
438
439 static void MediaDel( vod_t *p_vod, vod_media_t *p_media )
440 {
441     vod_sys_t *p_sys = p_vod->p_sys;
442
443     msg_Dbg( p_vod, "deleting media: %s", p_media->psz_rtsp_path );
444
445     vlc_mutex_lock( &p_sys->lock_media );
446     TAB_REMOVE( p_sys->i_media, p_sys->media, p_media );
447     vlc_mutex_unlock( &p_sys->lock_media );
448
449     while( p_media->i_rtsp > 0 )
450         RtspClientDel( p_media, p_media->rtsp[0] );
451     TAB_CLEAN( p_media->i_rtsp, p_media->rtsp );
452
453     httpd_UrlDelete( p_media->p_rtsp_url );
454     if( p_media->psz_rtsp_path ) free( p_media->psz_rtsp_path );
455     if( p_media->psz_rtsp_control_v6 ) free( p_media->psz_rtsp_control_v6 );
456     if( p_media->psz_rtsp_control_v4 ) free( p_media->psz_rtsp_control_v4 );
457
458     while( p_media->i_es )
459         MediaDelES( p_vod, p_media, &p_media->es[0]->fmt );
460     TAB_CLEAN( p_media->i_es, p_media->es );
461
462     vlc_mutex_destroy( &p_media->lock );
463
464     if( p_media->psz_session_name ) free( p_media->psz_session_name );
465     if( p_media->psz_session_description ) free( p_media->psz_session_description );
466     if( p_media->psz_session_url ) free( p_media->psz_session_url );
467     if( p_media->psz_session_email ) free( p_media->psz_session_email );
468     if( p_media->psz_mux ) free( p_media->psz_mux );
469     free( p_media );
470 }
471
472 static int MediaAddES( vod_t *p_vod, vod_media_t *p_media, es_format_t *p_fmt )
473 {
474     media_es_t *p_es = malloc( sizeof(media_es_t) );
475     char *psz_urlc;
476
477     if( !p_es ) return VLC_ENOMEM;
478     memset( p_es, 0, sizeof(media_es_t) );
479
480     if( p_media->psz_mux ) free( p_media->psz_mux );
481     p_media->psz_mux = NULL;
482
483     /* TODO: update SDP, etc... */
484     asprintf( &psz_urlc, "%s/trackID=%d",
485               p_media->psz_rtsp_path, p_media->i_es );
486     msg_Dbg( p_vod, "  - ES %4.4s (%s)", (char *)&p_fmt->i_codec, psz_urlc );
487
488     switch( p_fmt->i_codec )
489     {
490         case VLC_FOURCC( 's', '1', '6', 'b' ):
491             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 44100 )
492             {
493                 p_es->i_payload_type = 11;
494             }
495             else if( p_fmt->audio.i_channels == 2 && p_fmt->audio.i_rate == 44100 )
496             {
497                 p_es->i_payload_type = 10;
498             }
499             else
500             {
501                 p_es->i_payload_type = p_media->i_payload_type++;
502             }
503             p_es->psz_rtpmap = malloc( strlen( "L16/*/*" ) + 20+1 );
504             sprintf( p_es->psz_rtpmap, "L16/%d/%d", p_fmt->audio.i_rate,
505                     p_fmt->audio.i_channels );
506             break;
507         case VLC_FOURCC( 'u', '8', ' ', ' ' ):
508             p_es->i_payload_type = p_media->i_payload_type++;
509             p_es->psz_rtpmap = malloc( strlen( "L8/*/*" ) + 20+1 );
510             sprintf( p_es->psz_rtpmap, "L8/%d/%d", p_fmt->audio.i_rate,
511                     p_fmt->audio.i_channels );
512             break;
513         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
514             p_es->i_payload_type = 14;
515             p_es->psz_rtpmap = strdup( "MPA/90000" );
516             break;
517         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
518             p_es->i_payload_type = 32;
519             p_es->psz_rtpmap = strdup( "MPV/90000" );
520             break;
521         case VLC_FOURCC( 'a', '5', '2', ' ' ):
522             p_es->i_payload_type = p_media->i_payload_type++;
523             p_es->psz_rtpmap = strdup( "ac3/90000" );
524             break;
525         case VLC_FOURCC( 'H', '2', '6', '3' ):
526             p_es->i_payload_type = p_media->i_payload_type++;
527             p_es->psz_rtpmap = strdup( "H263-1998/90000" );
528             break;
529         case VLC_FOURCC( 'h', '2', '6', '4' ):
530             p_es->i_payload_type = p_media->i_payload_type++;
531             p_es->psz_rtpmap = strdup( "H264/90000" );
532             p_es->psz_fmtp = NULL;
533             /* FIXME AAAAAAAAAAAARRRRRRRRGGGG copied from stream_out/rtp.c */
534             if( p_fmt->i_extra > 0 )
535             {
536                 uint8_t *p_buffer = p_fmt->p_extra;
537                 int     i_buffer = p_fmt->i_extra;
538                 char    *p_64_sps = NULL;
539                 char    *p_64_pps = NULL;
540                 char    hexa[6+1];
541
542                 while( i_buffer > 4 &&
543                        p_buffer[0] == 0 && p_buffer[1] == 0 &&
544                        p_buffer[2] == 0 && p_buffer[3] == 1 )
545                 {
546                     const int i_nal_type = p_buffer[4]&0x1f;
547                     int i_offset;
548                     int i_size      = 0;
549
550                     i_size = i_buffer;
551                     for( i_offset = 4; i_offset+3 < i_buffer ; i_offset++)
552                     {
553                         if( p_buffer[i_offset] == 0 && p_buffer[i_offset+1] == 0 && p_buffer[i_offset+2] == 0 && p_buffer[i_offset+3] == 1 )
554                         {
555                             /* we found another startcode */
556                             i_size = i_offset;
557                             break;
558                         }
559                     }
560                     if( i_nal_type == 7 )
561                     {
562                         p_64_sps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
563                         sprintf_hexa( hexa, &p_buffer[5], 3 );
564                     }
565                     else if( i_nal_type == 8 )
566                     {
567                         p_64_pps = vlc_b64_encode_binary( &p_buffer[4], i_size - 4 );
568                     }
569                     i_buffer -= i_size;
570                     p_buffer += i_size;
571                 }
572                 /* */
573                 if( p_64_sps && p_64_pps )
574                     asprintf( &p_es->psz_fmtp, "packetization-mode=1;profile-level-id=%s;sprop-parameter-sets=%s,%s;", hexa, p_64_sps, p_64_pps );
575                 if( p_64_sps )
576                     free( p_64_sps );
577                 if( p_64_pps )
578                     free( p_64_pps );
579             }
580             if( !p_es->psz_fmtp )
581                 p_es->psz_fmtp = strdup( "packetization-mode=1" );
582             break;
583         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
584             p_es->i_payload_type = p_media->i_payload_type++;
585             p_es->psz_rtpmap = strdup( "MP4V-ES/90000" );
586             if( p_fmt->i_extra > 0 )
587             {
588                 char *p_hexa = malloc( 2 * p_fmt->i_extra + 1 );
589                 p_es->psz_fmtp = malloc( 100 + 2 * p_fmt->i_extra );
590                 sprintf_hexa( p_hexa, p_fmt->p_extra, p_fmt->i_extra );
591                 sprintf( p_es->psz_fmtp,
592                         "profile-level-id=3; config=%s;", p_hexa );
593                 free( p_hexa );
594             }
595             break;
596         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
597             p_es->i_payload_type = p_media->i_payload_type++;
598             p_es->psz_rtpmap = malloc( strlen( "mpeg4-generic/" ) + 12 );
599             sprintf( p_es->psz_rtpmap, "mpeg4-generic/%d", p_fmt->audio.i_rate );
600             if( p_fmt->i_extra > 0 )
601             {
602                 char *p_hexa = malloc( 2 * p_fmt->i_extra + 1 );
603                 p_es->psz_fmtp = malloc( 200 + 2 * p_fmt->i_extra );
604                 sprintf_hexa( p_hexa, p_fmt->p_extra, p_fmt->i_extra );
605                 sprintf( p_es->psz_fmtp,
606                         "streamtype=5; profile-level-id=15; mode=AAC-hbr; "
607                         "config=%s; SizeLength=13;IndexLength=3; "
608                         "IndexDeltaLength=3; Profile=1;", p_hexa );
609                 free( p_hexa );
610             }
611             break;
612         case VLC_FOURCC( 'm', 'p', '2', 't' ):
613             p_media->psz_mux = strdup("ts");
614             p_es->i_payload_type = 33;
615             p_es->psz_rtpmap = strdup( "MP2T/90000" );
616             break;
617         case VLC_FOURCC( 'm', 'p', '2', 'p' ):
618             p_media->psz_mux = strdup("ps");
619             p_es->i_payload_type = p_media->i_payload_type++;
620             p_es->psz_rtpmap = strdup( "MP2P/90000" );
621             break;
622         case VLC_FOURCC( 's', 'a', 'm', 'r' ):
623             p_es->i_payload_type = p_media->i_payload_type++;
624             p_es->psz_rtpmap = strdup( p_fmt->audio.i_channels == 2 ?
625                                     "AMR/8000/2" : "AMR/8000" );
626             p_es->psz_fmtp = strdup( "octet-align=1" );
627             break;
628         case VLC_FOURCC( 's', 'a', 'w', 'b' ):
629             p_es->i_payload_type = p_media->i_payload_type++;
630             p_es->psz_rtpmap = strdup( p_fmt->audio.i_channels == 2 ?
631                                     "AMR-WB/16000/2" : "AMR-WB/16000" );
632             p_es->psz_fmtp = strdup( "octet-align=1" );
633             break;
634
635         default:
636             msg_Err( p_vod, "cannot add this stream (unsupported "
637                     "codec: %4.4s)", (char*)&p_fmt->i_codec );
638             free( p_es );
639             return VLC_EGENERIC;
640     }
641
642     p_es->p_rtsp_url =
643         httpd_UrlNewUnique( p_vod->p_sys->p_rtsp_host, psz_urlc, NULL, NULL,
644                             NULL );
645
646     if( !p_es->p_rtsp_url )
647     {
648         msg_Err( p_vod, "cannot create RTSP url (%s)", psz_urlc );
649         free( psz_urlc );
650         free( p_es );
651         return VLC_EGENERIC;
652     }
653     free( psz_urlc );
654
655     httpd_UrlCatch( p_es->p_rtsp_url, HTTPD_MSG_SETUP,
656                     RtspCallbackES, (void*)p_es );
657     httpd_UrlCatch( p_es->p_rtsp_url, HTTPD_MSG_TEARDOWN,
658                     RtspCallbackES, (void*)p_es );
659     httpd_UrlCatch( p_es->p_rtsp_url, HTTPD_MSG_PLAY,
660                     RtspCallbackES, (void*)p_es );
661     httpd_UrlCatch( p_es->p_rtsp_url, HTTPD_MSG_PAUSE,
662                     RtspCallbackES, (void*)p_es );
663
664     es_format_Copy( &p_es->fmt, p_fmt );
665     p_es->p_vod = p_vod;
666     p_es->p_media = p_media;
667
668 #if 0
669     /* Choose the port */
670     if( p_fmt->i_cat == AUDIO_ES && p_media->i_port_audio > 0 )
671     {
672         p_es->i_port = p_media->i_port_audio;
673         p_media->i_port_audio = 0;
674     }
675     else if( p_fmt->i_cat == VIDEO_ES && p_media->i_port_video > 0 )
676     {
677         p_es->i_port = p_media->i_port_video;
678         p_media->i_port_video = 0;
679     }
680     while( !p_es->i_port )
681     {
682         if( p_media->i_port != p_media->i_port_audio &&
683             p_media->i_port != p_media->i_port_video )
684         {
685             p_es->i_port = p_media->i_port;
686             p_media->i_port += 2;
687             break;
688         }
689         p_media->i_port += 2;
690     }
691 #else
692
693     p_es->i_port = 0;
694 #endif
695
696     vlc_mutex_lock( &p_media->lock );
697     TAB_APPEND( p_media->i_es, p_media->es, p_es );
698     vlc_mutex_unlock( &p_media->lock );
699
700     p_media->i_sdp_version++;
701
702     return VLC_SUCCESS;
703 }
704
705 static void MediaDelES( vod_t *p_vod, vod_media_t *p_media, es_format_t *p_fmt)
706 {
707     media_es_t *p_es = NULL;
708     int i;
709
710     /* Find the ES */
711     for( i = 0; i < p_media->i_es; i++ )
712     {
713         if( p_media->es[i]->fmt.i_cat == p_fmt->i_cat &&
714             p_media->es[i]->fmt.i_codec == p_fmt->i_codec &&
715             p_media->es[i]->fmt.i_id == p_fmt->i_id )
716         {
717             p_es = p_media->es[i];
718         }
719     }
720     if( !p_es ) return;
721
722     msg_Dbg( p_vod, "  - Removing ES %4.4s", (char *)&p_fmt->i_codec );
723
724     vlc_mutex_lock( &p_media->lock );
725     TAB_REMOVE( p_media->i_es, p_media->es, p_es );
726     vlc_mutex_unlock( &p_media->lock );
727
728     if( p_es->psz_rtpmap ) free( p_es->psz_rtpmap );
729     if( p_es->psz_fmtp ) free( p_es->psz_fmtp );
730     p_media->i_sdp_version++;
731
732     if( p_es->p_rtsp_url ) httpd_UrlDelete( p_es->p_rtsp_url );
733     es_format_Clean( &p_es->fmt );
734     free( p_es );
735 }
736
737 /* */
738 typedef struct
739 {
740     int i_type;
741     int i_media_id;
742     //vod_media_t *p_media;
743     char *psz_session;
744     char *psz_arg;
745     double f_arg;
746 } rtsp_cmd_t;
747
748 static void CommandPush( vod_t *p_vod, rtsp_cmd_type_t i_type, vod_media_t *p_media, const char *psz_session,
749                          double f_arg, const char *psz_arg )
750 {
751     rtsp_cmd_t cmd;
752     block_t *p_cmd;
753
754     memset( &cmd, 0, sizeof(cmd) );
755     cmd.i_type = i_type;
756     if( p_media )
757         cmd.i_media_id = p_media->id;
758     if( psz_session )
759         cmd.psz_session = strdup(psz_session);
760     cmd.f_arg = f_arg;
761     if( psz_arg )
762         cmd.psz_arg = strdup(psz_arg);
763
764     p_cmd = block_New( p_vod, sizeof(rtsp_cmd_t) );
765     memcpy( p_cmd->p_buffer, &cmd, sizeof(cmd) );
766
767     block_FifoPut( p_vod->p_sys->p_fifo_cmd, p_cmd );
768 }
769
770 static void CommandThread( vlc_object_t *p_this )
771 {
772     vod_t *p_vod = (vod_t*)p_this;
773     vod_sys_t *p_sys = p_vod->p_sys;
774
775     while( !p_vod->b_die )
776     {
777         block_t *p_block_cmd = block_FifoGet( p_sys->p_fifo_cmd );
778         rtsp_cmd_t cmd;
779         vod_media_t *p_media = NULL;
780         int i;
781
782         if( !p_block_cmd )
783             break;
784
785         memcpy( &cmd, p_block_cmd->p_buffer, sizeof(cmd) );
786         block_Release( p_block_cmd );
787
788         if( cmd.i_type == RTSP_CMD_TYPE_NONE )
789             break;
790
791         /* */
792         vlc_mutex_lock( &p_sys->lock_media );
793         for( i = 0; i < p_sys->i_media; i++ )
794         {
795             if( p_sys->media[i]->id == cmd.i_media_id )
796                 break;
797         }
798         if( i >= p_sys->i_media )
799             goto next;
800         p_media = p_sys->media[i];
801
802         switch( cmd.i_type )
803         {
804         case RTSP_CMD_TYPE_PLAY:
805             vod_MediaControl( p_vod, p_media, cmd.psz_session,
806                               VOD_MEDIA_PLAY, cmd.psz_arg );
807             break;
808         case RTSP_CMD_TYPE_PAUSE:
809             vod_MediaControl( p_vod, p_media, cmd.psz_session,
810                               VOD_MEDIA_PAUSE );
811             break;
812
813         case RTSP_CMD_TYPE_STOP:
814             vod_MediaControl( p_vod, p_media, cmd.psz_session, VOD_MEDIA_STOP );
815             break;
816
817         case RTSP_CMD_TYPE_SEEK:
818             vod_MediaControl( p_vod, p_media, cmd.psz_session,
819                               VOD_MEDIA_SEEK, cmd.f_arg );
820             break;
821
822         case RTSP_CMD_TYPE_REWIND:
823             vod_MediaControl( p_vod, p_media, cmd.psz_session,
824                               VOD_MEDIA_REWIND, cmd.f_arg );
825             break;
826
827         case RTSP_CMD_TYPE_FORWARD:
828             vod_MediaControl( p_vod, p_media, cmd.psz_session,
829                               VOD_MEDIA_FORWARD, cmd.f_arg );
830             break;
831
832         default:
833             break;
834         }
835
836     next:
837         vlc_mutex_unlock( &p_sys->lock_media );
838         if( cmd.psz_session )
839             free( cmd.psz_session );
840         if( cmd.psz_arg )
841             free( cmd.psz_arg );
842     }
843 }
844
845 /****************************************************************************
846  * RTSP server implementation
847  ****************************************************************************/
848 static rtsp_client_t *RtspClientNew( vod_media_t *p_media, char *psz_session )
849 {
850     rtsp_client_t *p_rtsp = malloc( sizeof(rtsp_client_t) );
851
852     if( !p_rtsp ) return NULL;
853     memset( p_rtsp, 0, sizeof(rtsp_client_t) );
854     p_rtsp->es = 0;
855
856     p_rtsp->psz_session = psz_session;
857     TAB_APPEND( p_media->i_rtsp, p_media->rtsp, p_rtsp );
858
859     p_media->p_vod->p_sys->i_connections++;
860     msg_Dbg( p_media->p_vod, "new session: %s, connections: %d",
861              psz_session, p_media->p_vod->p_sys->i_throttle_users );
862
863     return p_rtsp;
864 }
865
866 static rtsp_client_t *RtspClientGet( vod_media_t *p_media, const char *psz_session )
867 {
868     int i;
869
870     for( i = 0; psz_session && i < p_media->i_rtsp; i++ )
871     {
872         if( !strcmp( p_media->rtsp[i]->psz_session, psz_session ) )
873             return p_media->rtsp[i];
874     }
875
876     return NULL;
877 }
878
879 static void RtspClientDel( vod_media_t *p_media, rtsp_client_t *p_rtsp )
880 {
881     p_media->p_vod->p_sys->i_connections--;
882     msg_Dbg( p_media->p_vod, "closing session: %s, connections: %d",
883              p_rtsp->psz_session, p_media->p_vod->p_sys->i_throttle_users );
884
885     while( p_rtsp->i_es-- )
886     {
887         if( p_rtsp->es[p_rtsp->i_es]->psz_ip )
888             free( p_rtsp->es[p_rtsp->i_es]->psz_ip );
889         free( p_rtsp->es[p_rtsp->i_es] );
890         if( !p_rtsp->i_es ) free( p_rtsp->es );
891     }
892
893     TAB_REMOVE( p_media->i_rtsp, p_media->rtsp, p_rtsp );
894
895     free( p_rtsp->psz_session );
896     free( p_rtsp );
897 }
898
899 static int RtspCallback( httpd_callback_sys_t *p_args, httpd_client_t *cl,
900                          httpd_message_t *answer, httpd_message_t *query )
901 {
902     vod_media_t *p_media = (vod_media_t*)p_args;
903     vod_t *p_vod = p_media->p_vod;
904     const char *psz_transport = NULL;
905     const char *psz_playnow = NULL; /* support option: x-playNow */
906     const char *psz_session = NULL;
907     const char *psz_cseq = NULL;
908     rtsp_client_t *p_rtsp;
909     int i_port = 0;
910     int i_cseq = 0;
911
912     if( answer == NULL || query == NULL ) return VLC_SUCCESS;
913
914     msg_Dbg( p_vod, "RtspCallback query: type=%d", query->i_type );
915
916     answer->i_proto   = HTTPD_PROTO_RTSP;
917     answer->i_version = query->i_version;
918     answer->i_type    = HTTPD_MSG_ANSWER;
919     answer->i_body    = 0;
920     answer->p_body    = NULL;
921
922     switch( query->i_type )
923     {
924         case HTTPD_MSG_SETUP:
925         {
926             psz_playnow = httpd_MsgGet( query, "x-playNow" );
927             psz_transport = httpd_MsgGet( query, "Transport" );
928             msg_Dbg( p_vod, "HTTPD_MSG_SETUP: transport=%s", psz_transport );
929
930             if( strstr( psz_transport, "unicast" ) &&
931                 strstr( psz_transport, "client_port=" ) )
932             {
933                 rtsp_client_t *p_rtsp = NULL;
934                 char ip[NI_MAXNUMERICHOST];
935                 i_port = atoi( strstr( psz_transport, "client_port=" ) +
936                                 strlen("client_port=") );
937
938                 if( strstr( psz_transport, "MP2T/H2221/UDP" ) ||
939                     strstr( psz_transport, "RAW/RAW/UDP" ) )
940                 {
941                     if( p_media->psz_mux ) free( p_media->psz_mux );
942                     p_media->psz_mux = NULL;
943                     p_media->psz_mux = strdup( p_vod->p_sys->psz_raw_mux );
944                     p_media->b_raw = VLC_TRUE;
945                 }
946
947                 if( httpd_ClientIP( cl, ip ) == NULL )
948                 {
949                     answer->i_status = 500;
950                     answer->psz_status = strdup( "Internal server error" );
951                     answer->i_body = 0;
952                     answer->p_body = NULL;
953                     break;
954                 }
955
956                 msg_Dbg( p_vod, "HTTPD_MSG_SETUP: unicast ip=%s port=%d",
957                          ip, i_port );
958
959                 psz_session = httpd_MsgGet( query, "Session" );
960                 if( !psz_session || !*psz_session )
961                 {
962                     char *psz_new;
963                     if( ( p_vod->p_sys->i_throttle_users > 0 ) &&
964                         ( p_vod->p_sys->i_connections >= p_vod->p_sys->i_throttle_users ) )
965                     {
966                         answer->i_status = 503;
967                         answer->psz_status = strdup( "Too many connections" );
968                         answer->i_body = 0;
969                         answer->p_body = NULL;
970                         break;
971                     }
972                     asprintf( &psz_new, "%d", rand() );
973                     psz_session = psz_new;
974
975                     p_rtsp = RtspClientNew( p_media, psz_new );
976                     if( !p_rtsp )
977                     {
978                         answer->i_status = 454;
979                         answer->psz_status = strdup( "Unknown session id" );
980                         answer->i_body = 0;
981                         answer->p_body = NULL;
982                         break;
983                     }
984                 }
985                 else
986                 {
987                     p_rtsp = RtspClientGet( p_media, psz_session );
988                     if( !p_rtsp )
989                     {
990                         answer->i_status = 454;
991                         answer->psz_status = strdup( "Unknown session id" );
992                         answer->i_body = 0;
993                         answer->p_body = NULL;
994                         break;
995                     }
996                 }
997
998                 answer->i_status = 200;
999                 answer->psz_status = strdup( "OK" );
1000                 answer->i_body = 0;
1001                 answer->p_body = NULL;
1002
1003                 if( p_media->b_raw )
1004                 {
1005                     if( strstr( psz_transport, "MP2T/H2221/UDP" ) )
1006                     {
1007                         httpd_MsgAdd( answer, "Transport", "MP2T/H2221/UDP;client_port=%d-%d",
1008                                       i_port, i_port + 1 );
1009                     }
1010                     else if( strstr( psz_transport, "RAW/RAW/UDP" ) )
1011                     {
1012                         httpd_MsgAdd( answer, "Transport", "RAW/RAW/UDP;client_port=%d-%d",
1013                                       i_port, i_port + 1 );
1014                     }
1015                 }
1016                 else
1017                     httpd_MsgAdd( answer, "Transport", "RTP/AVP/UDP;client_port=%d-%d",
1018                                   i_port, i_port + 1 );
1019             }
1020             else /* TODO  strstr( psz_transport, "interleaved" ) ) */
1021             {
1022                 answer->i_status = 461;
1023                 answer->psz_status = strdup( "Unsupported Transport" );
1024                 answer->i_body = 0;
1025                 answer->p_body = NULL;
1026             }
1027
1028             /* Intentional fall-through on x-playNow option in RTSP request */
1029             if( !psz_playnow )
1030                 break;
1031         }
1032
1033         case HTTPD_MSG_PLAY:
1034         {
1035             char *psz_output, ip[NI_MAXNUMERICHOST];
1036             int i, i_port_audio = 0, i_port_video = 0;
1037
1038             /* for now only multicast so easy */
1039             if( !psz_playnow )
1040             {
1041                 answer->i_status = 200;
1042                 answer->psz_status = strdup( "OK" );
1043                 answer->i_body = 0;
1044                 answer->p_body = NULL;
1045             }
1046
1047             if( !psz_session )
1048                 psz_session = httpd_MsgGet( query, "Session" );
1049             msg_Dbg( p_vod, "HTTPD_MSG_PLAY for session: %s", psz_session );
1050
1051             p_rtsp = RtspClientGet( p_media, psz_session );
1052             if( !p_rtsp )
1053             {
1054                 answer->i_status = 500;
1055                 answer->psz_status = strdup( "Internal server error" );
1056                 answer->i_body = 0;
1057                 answer->p_body = NULL;
1058                 break;
1059             }
1060
1061             if( p_rtsp->b_playing )
1062             {
1063                 const char *psz_position = httpd_MsgGet( query, "Range" );
1064                 const char *psz_scale = httpd_MsgGet( query, "Scale" );
1065                 if( psz_position ) psz_position = strstr( psz_position, "npt=" );
1066                 if( psz_position && !psz_scale )
1067                 {
1068                     double f_pos;
1069                     char *end;
1070
1071                     msg_Dbg( p_vod, "seeking request: %s", psz_position );
1072                     psz_position += 4;
1073                     /* FIXME: npt= is not necessarily formatted as a float */
1074                     f_pos = us_strtod( psz_position, &end );
1075                     if( end > psz_position )
1076                     {
1077                         f_pos /= ((double)(p_media->i_length))/1000 /1000 / 100;
1078                         CommandPush( p_vod, RTSP_CMD_TYPE_SEEK, p_media, psz_session, f_pos, NULL );
1079                     }
1080                     break;
1081                 }
1082                 if( psz_scale )
1083                 {
1084                     double f_scale = 0.0;
1085                     char *end;
1086
1087                     f_scale = us_strtod( psz_scale, &end );
1088                     if( end > psz_scale )
1089                     {
1090                         f_scale = (f_scale * 30.0);
1091                         if( psz_scale[0] == '-' ) /* rewind */
1092                         {
1093                             msg_Dbg( p_vod, "rewind request: %s", psz_scale );
1094                             CommandPush( p_vod, RTSP_CMD_TYPE_REWIND, p_media, psz_session, f_scale, NULL );
1095                         }
1096                         else if(psz_scale[0] != '1' ) /* fast-forward */
1097                         {
1098                             msg_Dbg( p_vod, "fastforward request: %s", psz_scale );
1099                             CommandPush( p_vod, RTSP_CMD_TYPE_FORWARD, p_media, psz_session, f_scale, NULL );
1100                         }
1101
1102                         if( p_rtsp->b_paused == VLC_TRUE )
1103                         {
1104                             p_rtsp->b_paused = VLC_FALSE;
1105                             CommandPush( p_vod, RTSP_CMD_TYPE_PAUSE, p_media, psz_session, 0, NULL );
1106                         }
1107                     }
1108                     break;
1109                 }
1110             }
1111
1112             if( p_rtsp->b_playing && p_rtsp->b_paused )
1113             {
1114                 CommandPush( p_vod, RTSP_CMD_TYPE_PAUSE, p_media, psz_session, 0, NULL );
1115                 p_rtsp->b_paused = VLC_FALSE;
1116                 break;
1117             }
1118             else if( p_rtsp->b_playing ) break;
1119
1120             if( httpd_ClientIP( cl, ip ) == NULL ) break;
1121
1122             p_rtsp->b_playing = VLC_TRUE;
1123
1124             /* FIXME for != 1 video and 1 audio */
1125             for( i = 0; i < p_rtsp->i_es; i++ )
1126             {
1127                 if( p_rtsp->es[i]->p_media_es->fmt.i_cat == AUDIO_ES )
1128                     i_port_audio = p_rtsp->es[i]->i_port;
1129                 if( p_rtsp->es[i]->p_media_es->fmt.i_cat == VIDEO_ES )
1130                     i_port_video = p_rtsp->es[i]->i_port;
1131             }
1132
1133             if( p_media->psz_mux )
1134             {
1135                 if( p_media->b_raw )
1136                 {
1137                     asprintf( &psz_output, "std{access=udp,dst=%s:%i,mux=%s}",
1138                               ip, i_port, p_media->psz_mux );
1139                 }
1140                 else
1141                 {
1142                     asprintf( &psz_output, "rtp{dst=%s,port=%i,mux=%s}",
1143                               ip, i_port_video, p_media->psz_mux );
1144                 }
1145             }
1146             else
1147             {
1148                 asprintf( &psz_output, "rtp{dst=%s,port-video=%i,"
1149                           "port-audio=%i}", ip, i_port_video, i_port_audio );
1150             }
1151
1152             CommandPush( p_vod, RTSP_CMD_TYPE_PLAY, p_media, psz_session, 0, psz_output );
1153             free( psz_output );
1154             break;
1155         }
1156
1157         case HTTPD_MSG_DESCRIBE:
1158         {
1159             char *psz_sdp =
1160                 SDPGenerate( p_media, cl );
1161
1162             if( psz_sdp != NULL )
1163             {
1164                 answer->i_status = 200;
1165                 answer->psz_status = strdup( "OK" );
1166                 httpd_MsgAdd( answer, "Content-type",  "%s", "application/sdp" );
1167
1168                 answer->p_body = (uint8_t *)psz_sdp;
1169                 answer->i_body = strlen( psz_sdp );
1170             }
1171             else
1172             {
1173                 answer->i_status = 500;
1174                 answer->psz_status = strdup( "Internal server error" );
1175                 answer->p_body = NULL;
1176                 answer->i_body = 0;
1177             }
1178             break;
1179         }
1180
1181         case HTTPD_MSG_PAUSE:
1182             psz_session = httpd_MsgGet( query, "Session" );
1183             msg_Dbg( p_vod, "HTTPD_MSG_PAUSE for session: %s", psz_session );
1184
1185             p_rtsp = RtspClientGet( p_media, psz_session );
1186             if( !p_rtsp ) break;
1187
1188             CommandPush( p_vod, RTSP_CMD_TYPE_PAUSE, p_media, psz_session, 0, NULL );
1189             p_rtsp->b_paused = VLC_TRUE;
1190
1191             answer->i_status = 200;
1192             answer->psz_status = strdup( "OK" );
1193             answer->i_body = 0;
1194             answer->p_body = NULL;
1195             break;
1196
1197         case HTTPD_MSG_TEARDOWN:
1198             /* for now only multicast so easy again */
1199             answer->i_status = 200;
1200             answer->psz_status = strdup( "OK" );
1201             answer->i_body = 0;
1202             answer->p_body = NULL;
1203
1204             psz_session = httpd_MsgGet( query, "Session" );
1205             msg_Dbg( p_vod, "HTTPD_MSG_TEARDOWN for session: %s", psz_session);
1206
1207             p_rtsp = RtspClientGet( p_media, psz_session );
1208             if( !p_rtsp ) break;
1209
1210             CommandPush( p_vod, RTSP_CMD_TYPE_STOP, p_media, psz_session, 0, NULL );
1211             RtspClientDel( p_media, p_rtsp );
1212             break;
1213
1214         case HTTPD_MSG_GETPARAMETER:
1215             answer->i_status = 200;
1216             answer->psz_status = strdup( "OK" );
1217             answer->i_body = 0;
1218             answer->p_body = NULL;
1219             break;
1220
1221         default:
1222             return VLC_EGENERIC;
1223     }
1224
1225     httpd_MsgAdd( answer, "Server", "VLC Server" );
1226     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
1227     psz_cseq = httpd_MsgGet( query, "Cseq" );
1228     psz_cseq ? i_cseq = atoi( psz_cseq ) : 0;
1229     httpd_MsgAdd( answer, "CSeq", "%d", i_cseq );
1230     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
1231
1232     if( psz_session )
1233     {
1234          if( p_media->p_vod->p_sys->i_session_timeout >= 0 )
1235              httpd_MsgAdd( answer, "Session", "%s;timeout=%i", psz_session,
1236                p_media->p_vod->p_sys->i_session_timeout );
1237          else
1238               httpd_MsgAdd( answer, "Session", "%s", psz_session );
1239     } 
1240
1241     return VLC_SUCCESS;
1242 }
1243
1244 static int RtspCallbackES( httpd_callback_sys_t *p_args, httpd_client_t *cl,
1245                            httpd_message_t *answer, httpd_message_t *query )
1246 {
1247     media_es_t *p_es = (media_es_t*)p_args;
1248     vod_media_t *p_media = p_es->p_media;
1249     vod_t *p_vod = p_media->p_vod;
1250     rtsp_client_t *p_rtsp = NULL;
1251     const char *psz_transport = NULL;
1252     const char *psz_playnow = NULL; /* support option: x-playNow */
1253     const char *psz_session = NULL;
1254     const char *psz_position = NULL;
1255     const char *psz_cseq = NULL;
1256     int i_cseq = 0;
1257     int i;
1258
1259     if( answer == NULL || query == NULL ) return VLC_SUCCESS;
1260
1261     msg_Dbg( p_vod, "RtspCallback query: type=%d", query->i_type );
1262
1263     answer->i_proto   = HTTPD_PROTO_RTSP;
1264     answer->i_version = query->i_version;
1265     answer->i_type    = HTTPD_MSG_ANSWER;
1266     answer->i_body    = 0;
1267     answer->p_body      = NULL;
1268
1269     switch( query->i_type )
1270     {
1271         case HTTPD_MSG_SETUP:
1272             psz_playnow = httpd_MsgGet( query, "x-playNow" );
1273             psz_transport = httpd_MsgGet( query, "Transport" );
1274
1275             msg_Dbg( p_vod, "HTTPD_MSG_SETUP: transport=%s", psz_transport );
1276
1277             if( strstr( psz_transport, "unicast" ) &&
1278                 strstr( psz_transport, "client_port=" ) )
1279             {
1280                 rtsp_client_t *p_rtsp = NULL;
1281                 rtsp_client_es_t *p_rtsp_es = NULL;
1282                 char ip[NI_MAXNUMERICHOST];
1283                 int i_port = atoi( strstr( psz_transport, "client_port=" ) +
1284                                 strlen("client_port=") );
1285
1286                 if( httpd_ClientIP( cl, ip ) == NULL )
1287                 {
1288                     answer->i_status = 500;
1289                     answer->psz_status = strdup( "Internal server error" );
1290                     answer->i_body = 0;
1291                     answer->p_body = NULL;
1292                     break;
1293                 }
1294
1295                 msg_Dbg( p_vod, "HTTPD_MSG_SETUP: unicast ip=%s port=%d",
1296                         ip, i_port );
1297
1298                 psz_session = httpd_MsgGet( query, "Session" );
1299                 if( !psz_session || !*psz_session )
1300                 {
1301                     char *psz_new;
1302                     if( ( p_vod->p_sys->i_throttle_users > 0 ) &&
1303                         ( p_vod->p_sys->i_connections >= p_vod->p_sys->i_throttle_users ) )
1304                     {
1305                         answer->i_status = 503;
1306                         answer->psz_status = strdup( "Too many connections" );
1307                         answer->i_body = 0;
1308                         answer->p_body = NULL;
1309                         break;
1310                     }
1311                     asprintf( &psz_new, "%d", rand() );
1312                     psz_session = psz_new;
1313
1314                     p_rtsp = RtspClientNew( p_media, psz_new );
1315                 }
1316                 else
1317                 {
1318                     p_rtsp = RtspClientGet( p_media, psz_session );
1319                     if( !p_rtsp )
1320                     {
1321                         answer->i_status = 454;
1322                         answer->psz_status = strdup( "Unknown session id" );
1323                         answer->i_body = 0;
1324                         answer->p_body = NULL;
1325                         break;
1326                     }
1327                 }
1328
1329                 p_rtsp_es = malloc( sizeof(rtsp_client_es_t) );
1330                 if( !p_rtsp_es )
1331                 {
1332                     answer->i_status = 500;
1333                     answer->psz_status = strdup( "Internal server error" );
1334                     answer->i_body = 0;
1335                     answer->p_body = NULL;
1336                     break;
1337                 }
1338                 p_rtsp_es->i_port = i_port;
1339                 p_rtsp_es->psz_ip = strdup( ip );
1340                 p_rtsp_es->p_media_es = p_es;
1341                 TAB_APPEND( p_rtsp->i_es, p_rtsp->es, p_rtsp_es );
1342
1343                 answer->i_status = 200;
1344                 answer->psz_status = strdup( "OK" );
1345                 answer->i_body = 0;
1346                 answer->p_body = NULL;
1347
1348                 if( p_media->b_raw )
1349                 {
1350                     if( strstr( psz_transport, "MP2T/H2221/UDP" ) )
1351                     {
1352                         httpd_MsgAdd( answer, "Transport", "MP2T/H2221/UDP;client_port=%d-%d",
1353                                       p_rtsp_es->i_port, p_rtsp_es->i_port + 1 );
1354                     }
1355                     else if( strstr( psz_transport, "RAW/RAW/UDP" ) )
1356                     {
1357                         httpd_MsgAdd( answer, "Transport", "RAW/RAW/UDP;client_port=%d-%d",
1358                                       p_rtsp_es->i_port, p_rtsp_es->i_port + 1 );
1359                     }
1360                 }
1361                 else
1362                 {
1363                     httpd_MsgAdd( answer, "Transport", "RTP/AVP/UDP;client_port=%d-%d",
1364                                   p_rtsp_es->i_port, p_rtsp_es->i_port + 1 );
1365                 }
1366             }
1367             else /* TODO  strstr( psz_transport, "interleaved" ) ) */
1368             {
1369                 answer->i_status = 461;
1370                 answer->psz_status = strdup( "Unsupported Transport" );
1371                 answer->i_body = 0;
1372                 answer->p_body = NULL;
1373             }
1374
1375             /* Intentional fall-through on x-playNow option in RTSP request */
1376             if( !psz_playnow )
1377                 break;
1378
1379         case HTTPD_MSG_PLAY:
1380             /* This is kind of a kludge. Should we only support Aggregate
1381              * Operations ? */
1382             psz_session = httpd_MsgGet( query, "Session" );
1383             msg_Dbg( p_vod, "HTTPD_MSG_PLAY for session: %s", psz_session );
1384
1385             p_rtsp = RtspClientGet( p_media, psz_session );
1386
1387             psz_position = httpd_MsgGet( query, "Range" );
1388             if( psz_position ) psz_position = strstr( psz_position, "npt=" );
1389             if( psz_position )
1390             {
1391                 double f_pos;
1392                 char *end;
1393
1394                 msg_Dbg( p_vod, "seeking request: %s", psz_position );
1395
1396                 psz_position += 4;
1397                 /* FIXME: npt= is not necessarily formatted as a float */
1398                 f_pos = us_strtod( psz_position, &end );
1399                 if( end > psz_position )
1400                 {
1401                     f_pos /= ((double)(p_media->i_length))/1000 /1000 / 100;
1402                     CommandPush( p_vod, RTSP_CMD_TYPE_SEEK, p_media, psz_session, f_pos, NULL );
1403                 }
1404             }
1405
1406             if( !psz_playnow )
1407             {
1408                 answer->i_status = 200;
1409                 answer->psz_status = strdup( "OK" );
1410                 answer->i_body = 0;
1411                 answer->p_body = NULL;
1412             }
1413             break;
1414
1415         case HTTPD_MSG_TEARDOWN:
1416             answer->i_status = 200;
1417             answer->psz_status = strdup( "OK" );
1418             answer->i_body = 0;
1419             answer->p_body = NULL;
1420
1421             psz_session = httpd_MsgGet( query, "Session" );
1422             msg_Dbg( p_vod, "HTTPD_MSG_TEARDOWN for session: %s", psz_session);
1423
1424             p_rtsp = RtspClientGet( p_media, psz_session );
1425             if( !p_rtsp ) break;
1426
1427             for( i = 0; i < p_rtsp->i_es; i++ )
1428             {
1429                 if( p_rtsp->es[i]->p_media_es == p_es )
1430                 {
1431                     if( p_rtsp->es[i]->psz_ip ) free( p_rtsp->es[i]->psz_ip );
1432                     TAB_REMOVE( p_rtsp->i_es, p_rtsp->es, p_rtsp->es[i] );
1433                     break;
1434                 }
1435             }
1436
1437             if( !p_rtsp->i_es )
1438             {
1439                 CommandPush( p_vod, RTSP_CMD_TYPE_STOP, p_media, psz_session, 0, NULL );
1440                 RtspClientDel( p_media, p_rtsp );
1441             }
1442             break;
1443
1444         case HTTPD_MSG_PAUSE:
1445             /* This is kind of a kludge. Should we only support Aggregate
1446              * Operations ? */
1447             psz_session = httpd_MsgGet( query, "Session" );
1448             msg_Dbg( p_vod, "HTTPD_MSG_PAUSE for session: %s", psz_session );
1449
1450             p_rtsp = RtspClientGet( p_media, psz_session );
1451             if( !p_rtsp ) break;
1452
1453             CommandPush( p_vod, RTSP_CMD_TYPE_PAUSE, p_media, psz_session, 0, NULL );
1454             p_rtsp->b_paused = VLC_TRUE;
1455
1456             answer->i_status = 200;
1457             answer->psz_status = strdup( "OK" );
1458             answer->i_body = 0;
1459             answer->p_body = NULL;
1460             break;
1461
1462         default:
1463             return VLC_EGENERIC;
1464             break;
1465     }
1466
1467     httpd_MsgAdd( answer, "Server", "VLC Server" );
1468     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
1469     psz_cseq = httpd_MsgGet( query, "Cseq" );
1470     if (psz_cseq)
1471         i_cseq = atoi( psz_cseq );
1472     else
1473         i_cseq = 0;
1474     httpd_MsgAdd( answer, "Cseq", "%d", i_cseq );
1475     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
1476
1477     if( psz_session )
1478         httpd_MsgAdd( answer, "Session", "%s"/*;timeout=5*/, psz_session );
1479
1480     return VLC_SUCCESS;
1481 }
1482
1483 /*****************************************************************************
1484  * SDPGenerate: TODO
1485  * FIXME: need to be moved to a common place ?
1486  *****************************************************************************/
1487 static char *SDPGenerate( const vod_media_t *p_media, httpd_client_t *cl )
1488 {
1489     int i, i_size;
1490     char *p, *psz_sdp, ip[NI_MAXNUMERICHOST], ipv;
1491     const char *psz_control;
1492
1493     if( httpd_ServerIP( cl, ip ) == NULL )
1494         return NULL;
1495
1496     p = strchr( ip, '%' );
1497     if( p != NULL )
1498         *p = '\0'; /* remove scope if present */
1499
1500     ipv = ( strchr( ip, ':' ) != NULL ) ? '6' : '4';
1501
1502     /* Calculate size */
1503     i_size = sizeof( "v=0\r\n" ) +
1504         sizeof( "o=- * * IN IP4 \r\n" ) + 10 + NI_MAXNUMERICHOST +
1505         sizeof( "s=*\r\n" ) + strlen( p_media->psz_session_name ) +
1506         sizeof( "i=*\r\n" ) + strlen( p_media->psz_session_description ) +
1507         sizeof( "u=*\r\n" ) + strlen( p_media->psz_session_url ) +
1508         sizeof( "e=*\r\n" ) + strlen( p_media->psz_session_email ) +
1509         sizeof( "c=IN IP4 0.0.0.0\r\n" ) + 20 + 10 +
1510         sizeof( "t=0 0\r\n" ) + /* FIXME */
1511         sizeof( "a=tool:"PACKAGE_STRING"\r\n" ) +
1512         sizeof( "a=range:npt=0-1000000000.000\r\n" );
1513
1514     psz_control = (ipv == '6') ? p_media->psz_rtsp_control_v6
1515                                : p_media->psz_rtsp_control_v4;
1516     for( i = 0; i < p_media->i_es; i++ )
1517     {
1518         media_es_t *p_es = p_media->es[i];
1519
1520         i_size += sizeof( "m=**d*o * RTP/AVP *\r\n" ) + 19;
1521         if( p_es->psz_rtpmap )
1522         {
1523             i_size += sizeof( "a=rtpmap:* *\r\n" ) +
1524                 strlen( p_es->psz_rtpmap ) + 9;
1525         }
1526         if( p_es->psz_fmtp )
1527         {
1528             i_size += sizeof( "a=fmtp:* *\r\n" ) +
1529                 strlen( p_es->psz_fmtp ) + 9;
1530         }
1531     }
1532     i_size += (strlen( psz_control ) + strlen( ip ) + 9) * p_media->i_es;
1533
1534     p = psz_sdp = malloc( i_size );
1535     p += sprintf( p, "v=0\r\n" );
1536     p += sprintf( p, "o=- "I64Fd" %d IN IP%c %s\r\n",
1537                   p_media->i_sdp_id, p_media->i_sdp_version, ipv, ip );
1538     if( *p_media->psz_session_name )
1539         p += sprintf( p, "s=%s\r\n", p_media->psz_session_name );
1540     if( *p_media->psz_session_description )
1541         p += sprintf( p, "i=%s\r\n", p_media->psz_session_description );
1542     if( *p_media->psz_session_url )
1543         p += sprintf( p, "u=%s\r\n", p_media->psz_session_url );
1544     if( *p_media->psz_session_email )
1545         p += sprintf( p, "e=%s\r\n", p_media->psz_session_email );
1546
1547     p += sprintf( p, "c=IN IP%c %s\r\n", ipv, ipv == '6' ? "::" : "0.0.0.0" );
1548     p += sprintf( p, "t=0 0\r\n" ); /* FIXME */
1549     p += sprintf( p, "a=tool:"PACKAGE_STRING"\r\n" );
1550
1551     if( p_media->i_length > 0 )
1552     {
1553         lldiv_t d = lldiv( p_media->i_length / 1000, 1000 );
1554         p += sprintf( p, "a=range:npt=0-%lld.%03u\r\n", d.quot,
1555                       (unsigned)d.rem );
1556     }
1557
1558     for( i = 0; i < p_media->i_es; i++ )
1559     {
1560         media_es_t *p_es = p_media->es[i];
1561
1562         if( p_es->fmt.i_cat == AUDIO_ES )
1563         {
1564             p += sprintf( p, "m=audio %d RTP/AVP %d\r\n",
1565                           p_es->i_port, p_es->i_payload_type );
1566         }
1567         else if( p_es->fmt.i_cat == VIDEO_ES )
1568         {
1569             p += sprintf( p, "m=video %d RTP/AVP %d\r\n",
1570                           p_es->i_port, p_es->i_payload_type );
1571         }
1572         else
1573         {
1574             continue;
1575         }
1576
1577         if( p_es->psz_rtpmap )
1578         {
1579             p += sprintf( p, "a=rtpmap:%d %s\r\n", p_es->i_payload_type,
1580                           p_es->psz_rtpmap );
1581         }
1582         if( p_es->psz_fmtp )
1583         {
1584             p += sprintf( p, "a=fmtp:%d %s\r\n", p_es->i_payload_type,
1585                           p_es->psz_fmtp );
1586         }
1587
1588         p += sprintf( p, psz_control, ip, i );
1589     }
1590
1591     return psz_sdp;
1592 }