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