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