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