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