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