]> git.sesse.net Git - vlc/blob - modules/misc/rtsp.c
opus: update i_buffer when memmoving decoder output
[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         return NULL;
373     p_media->p_rtsp_url =
374         httpd_UrlNew( p_sys->p_rtsp_host, p_media->psz_rtsp_path, NULL, NULL );
375
376     if( !p_media->p_rtsp_url )
377     {
378         msg_Err( p_vod, "cannot create RTSP url (%s)", p_media->psz_rtsp_path);
379         free( p_media->psz_rtsp_path );
380         free( p_media );
381         return NULL;
382     }
383
384     msg_Dbg( p_vod, "created RTSP url: %s", p_media->psz_rtsp_path );
385
386     if( asprintf( &p_media->psz_rtsp_control_v4,
387                   "rtsp://%%s:%%d%s/trackID=%%d",
388                   p_media->psz_rtsp_path ) < 0 )
389     {
390         httpd_UrlDelete( p_media->p_rtsp_url );
391         free( p_media->psz_rtsp_path );
392         free( p_media );
393         return NULL;
394     }
395     if( asprintf( &p_media->psz_rtsp_control_v6,
396                   "rtsp://[%%s]:%%d%s/trackID=%%d",
397                   p_media->psz_rtsp_path ) < 0 )
398     {
399         httpd_UrlDelete( p_media->p_rtsp_url );
400         free( p_media->psz_rtsp_path );
401         free( p_media );
402         return NULL;
403     }
404
405     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_SETUP,
406                     RtspCallback, (void*)p_media );
407     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_DESCRIBE,
408                     RtspCallback, (void*)p_media );
409     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_PLAY,
410                     RtspCallback, (void*)p_media );
411     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_PAUSE,
412                     RtspCallback, (void*)p_media );
413     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_GETPARAMETER,
414                     RtspCallback, (void*)p_media );
415     httpd_UrlCatch( p_media->p_rtsp_url, HTTPD_MSG_TEARDOWN,
416                     RtspCallback, (void*)p_media );
417
418     p_media->p_vod = p_vod;
419
420     vlc_mutex_init( &p_media->lock );
421
422     p_media->i_length = input_item_GetDuration( p_item );
423
424     vlc_mutex_lock( &p_item->lock );
425     msg_Dbg( p_vod, "media has %i declared ES", p_item->i_es );
426     for( int i = 0; i < p_item->i_es; i++ )
427     {
428         MediaAddES( p_vod, p_media, p_item->es[i] );
429     }
430     vlc_mutex_unlock( &p_item->lock );
431
432     CommandPush( p_vod, RTSP_CMD_TYPE_ADD, p_media, NULL, 0, 0.0, NULL );
433     return p_media;
434 }
435
436 static void MediaAskDel ( vod_t *p_vod, vod_media_t *p_media )
437 {
438     CommandPush( p_vod, RTSP_CMD_TYPE_DEL, p_media, NULL, 0, 0.0, NULL );
439 }
440
441 static void MediaDel( vod_t *p_vod, vod_media_t *p_media )
442 {
443     vod_sys_t *p_sys = p_vod->p_sys;
444
445     msg_Dbg( p_vod, "deleting media: %s", p_media->psz_rtsp_path );
446
447     TAB_REMOVE( p_sys->i_media, p_sys->media, p_media );
448
449     httpd_UrlDelete( p_media->p_rtsp_url );
450
451     while( p_media->i_rtsp > 0 )
452         RtspClientDel( p_media, p_media->rtsp[0] );
453     TAB_CLEAN( p_media->i_rtsp, p_media->rtsp );
454
455     free( p_media->psz_rtsp_path );
456     free( p_media->psz_rtsp_control_v6 );
457     free( p_media->psz_rtsp_control_v4 );
458
459     while( p_media->i_es )
460         MediaDelES( p_vod, p_media, &p_media->es[0]->fmt );
461     TAB_CLEAN( p_media->i_es, p_media->es );
462
463     vlc_mutex_destroy( &p_media->lock );
464
465     free( p_media );
466 }
467
468 static int MediaAddES( vod_t *p_vod, vod_media_t *p_media, es_format_t *p_fmt )
469 {
470     char *psz_urlc;
471
472     media_es_t *p_es = calloc( 1, sizeof(media_es_t) );
473     if( !p_es )
474         return VLC_ENOMEM;
475
476     p_media->psz_mux = NULL;
477
478     /* TODO: update SDP, etc... */
479     if( asprintf( &psz_urlc, "%s/trackID=%d",
480               p_media->psz_rtsp_path, p_media->i_es ) < 0 )
481     {
482         free( p_es );
483         return VLC_ENOMEM;
484     }
485     msg_Dbg( p_vod, "  - ES %4.4s (%s)", (char *)&p_fmt->i_codec, psz_urlc );
486
487     /* Dynamic payload. No conflict since we put each ES in its own
488      * RTP session */
489     p_es->i_payload_type = 96;
490     p_es->i_clock_rate = 90000;
491     p_es->i_channels = 1;
492
493     switch( p_fmt->i_codec )
494     {
495         case VLC_CODEC_S16B:
496             if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 44100 )
497             {
498                 p_es->i_payload_type = 11;
499             }
500             else if( p_fmt->audio.i_channels == 2 &&
501                      p_fmt->audio.i_rate == 44100 )
502             {
503                 p_es->i_payload_type = 10;
504             }
505             p_es->psz_ptname = "L16";
506             p_es->i_clock_rate = p_fmt->audio.i_rate;
507             p_es->i_channels = p_fmt->audio.i_channels;
508             break;
509         case VLC_CODEC_U8:
510             p_es->psz_ptname = "L8";
511             p_es->i_clock_rate = p_fmt->audio.i_rate;
512             p_es->i_channels = p_fmt->audio.i_channels;
513             break;
514         case VLC_CODEC_MPGA:
515             p_es->i_payload_type = 14;
516             p_es->psz_ptname = "MPA";
517             break;
518         case VLC_CODEC_MPGV:
519             p_es->i_payload_type = 32;
520             p_es->psz_ptname = "MPV";
521             break;
522         case VLC_CODEC_A52:
523             p_es->psz_ptname = "ac3";
524             p_es->i_clock_rate = p_fmt->audio.i_rate;
525             break;
526         case VLC_CODEC_H263:
527             p_es->psz_ptname = "H263-1998";
528             break;
529         case VLC_CODEC_H264:
530             p_es->psz_ptname = "H264";
531             p_es->psz_fmtp = NULL;
532             /* FIXME AAAAAAAAAAAARRRRRRRRGGGG copied from stream_out/rtp.c */
533             if( p_fmt->i_extra > 0 )
534             {
535                 uint8_t *p_buffer = p_fmt->p_extra;
536                 int     i_buffer = p_fmt->i_extra;
537                 char    *p_64_sps = NULL;
538                 char    *p_64_pps = NULL;
539                 char    hexa[6+1];
540
541                 while( i_buffer > 4 )
542                 {
543                     int i_offset    = 0;
544                     int i_size      = 0;
545
546                     while( p_buffer[0] != 0 || p_buffer[1] != 0 ||
547                            p_buffer[2] != 1 )
548                     {
549                         p_buffer++;
550                         i_buffer--;
551                         if( i_buffer == 0 ) break;
552                     }
553
554                     if( i_buffer < 4 || memcmp(p_buffer, "\x00\x00\x01", 3 ) )
555                     {
556                         /* No startcode found.. */
557                         break;
558                     }
559                     p_buffer += 3;
560                     i_buffer -= 3;
561
562                     const int i_nal_type = p_buffer[0]&0x1f;
563
564                     i_size = i_buffer;
565                     for( i_offset = 0; i_offset+2 < i_buffer ; i_offset++)
566                     {
567                         if( !memcmp(p_buffer + i_offset, "\x00\x00\x01", 3 ) )
568                         {
569                             /* we found another startcode */
570                             while( i_offset > 0 && 0 == p_buffer[ i_offset - 1 ] )
571                                 i_offset--;
572                             i_size = i_offset;
573                             break;
574                         }
575                     }
576
577                     if( i_size == 0 )
578                     {
579                         /* No-info found in nal */
580                         continue;
581                     }
582
583                     if( i_nal_type == 7 )
584                     {
585                         free( p_64_sps );
586                         p_64_sps = vlc_b64_encode_binary( p_buffer, i_size );
587                         /* XXX: nothing ensures that i_size >= 4 ?? */
588                         sprintf_hexa( hexa, &p_buffer[1], 3 );
589                     }
590                     else if( i_nal_type == 8 )
591                     {
592                         free( p_64_pps );
593                         p_64_pps = vlc_b64_encode_binary( p_buffer, i_size );
594                     }
595                     i_buffer -= i_size;
596                     p_buffer += i_size;
597                 }
598                 /* */
599                 if( p_64_sps && p_64_pps )
600                 {
601                     if( asprintf( &p_es->psz_fmtp,
602                                   "packetization-mode=1;profile-level-id=%s;"
603                                   "sprop-parameter-sets=%s,%s;", hexa, p_64_sps,
604                                   p_64_pps ) < 0 )
605                     {
606                         free( p_64_sps );
607                         free( p_64_pps );
608                         free( psz_urlc );
609                         free( p_es );
610                         return VLC_ENOMEM;
611                     }
612                 }
613                 free( p_64_sps );
614                 free( p_64_pps );
615             }
616             if( !p_es->psz_fmtp )
617                 p_es->psz_fmtp = strdup( "packetization-mode=1" );
618             break;
619         case VLC_CODEC_MP4V:
620             p_es->psz_ptname = "MP4V-ES";
621             if( p_fmt->i_extra > 0 )
622             {
623                 char *p_hexa = malloc( 2 * p_fmt->i_extra + 1 );
624                 sprintf_hexa( p_hexa, p_fmt->p_extra, p_fmt->i_extra );
625                 if( asprintf( &p_es->psz_fmtp,
626                               "profile-level-id=3; config=%s;", p_hexa ) == -1 )
627                     p_es->psz_fmtp = NULL;
628                 free( p_hexa );
629             }
630             break;
631         case VLC_CODEC_MP4A:
632             p_es->psz_ptname = "mpeg4-generic";
633             p_es->i_clock_rate = p_fmt->audio.i_rate;
634             if( p_fmt->i_extra > 0 )
635             {
636                 char *p_hexa = malloc( 2 * p_fmt->i_extra + 1 );
637                 sprintf_hexa( p_hexa, p_fmt->p_extra, p_fmt->i_extra );
638                 if( asprintf( &p_es->psz_fmtp,
639                               "streamtype=5; profile-level-id=15; mode=AAC-hbr; "
640                               "config=%s; SizeLength=13;IndexLength=3; "
641                               "IndexDeltaLength=3; Profile=1;", p_hexa ) == -1 )
642                     p_es->psz_fmtp = NULL;
643                 free( p_hexa );
644             }
645             break;
646         case VLC_FOURCC( 'm', 'p', '2', 't' ):
647             p_media->psz_mux = "ts";
648             p_es->i_payload_type = 33;
649             p_es->psz_ptname = "MP2T";
650             break;
651         case VLC_FOURCC( 'm', 'p', '2', 'p' ):
652             p_media->psz_mux = "ps";
653             p_es->psz_ptname = "MP2P";
654             break;
655         case VLC_CODEC_AMR_NB:
656             p_es->psz_ptname = "AMR";
657             p_es->i_clock_rate = 8000;
658             if(p_fmt->audio.i_channels == 2 )
659                 p_es->i_channels = 2;
660             p_es->psz_fmtp = strdup( "octet-align=1" );
661             break;
662         case VLC_CODEC_AMR_WB:
663             p_es->psz_ptname = "AMR-WB";
664             p_es->i_clock_rate = 16000;
665             if(p_fmt->audio.i_channels == 2 )
666                 p_es->i_channels = 2;
667             p_es->psz_fmtp = strdup( "octet-align=1" );
668             break;
669
670         default:
671             msg_Err( p_vod, "cannot add this stream (unsupported "
672                     "codec: %4.4s)", (char*)&p_fmt->i_codec );
673             free( psz_urlc );
674             free( p_es );
675             return VLC_EGENERIC;
676     }
677
678     p_es->p_rtsp_url =
679         httpd_UrlNew( p_vod->p_sys->p_rtsp_host, psz_urlc, NULL, NULL );
680
681     if( !p_es->p_rtsp_url )
682     {
683         msg_Err( p_vod, "cannot create RTSP url (%s)", psz_urlc );
684         free( psz_urlc );
685         free( p_es );
686         return VLC_EGENERIC;
687     }
688     free( psz_urlc );
689
690     httpd_UrlCatch( p_es->p_rtsp_url, HTTPD_MSG_SETUP,
691                     RtspCallbackES, (void*)p_es );
692     httpd_UrlCatch( p_es->p_rtsp_url, HTTPD_MSG_TEARDOWN,
693                     RtspCallbackES, (void*)p_es );
694     httpd_UrlCatch( p_es->p_rtsp_url, HTTPD_MSG_PLAY,
695                     RtspCallbackES, (void*)p_es );
696     httpd_UrlCatch( p_es->p_rtsp_url, HTTPD_MSG_PAUSE,
697                     RtspCallbackES, (void*)p_es );
698
699     es_format_Copy( &p_es->fmt, p_fmt );
700     p_es->p_vod = p_vod;
701     p_es->p_media = p_media;
702
703     vlc_mutex_lock( &p_media->lock );
704     TAB_APPEND( p_media->i_es, p_media->es, p_es );
705     vlc_mutex_unlock( &p_media->lock );
706
707     return VLC_SUCCESS;
708 }
709
710 static void MediaDelES( vod_t *p_vod, vod_media_t *p_media, es_format_t *p_fmt)
711 {
712     media_es_t *p_es = NULL;
713
714     /* Find the ES */
715     for( int i = 0; i < p_media->i_es; i++ )
716     {
717         if( p_media->es[i]->fmt.i_cat == p_fmt->i_cat &&
718             p_media->es[i]->fmt.i_codec == p_fmt->i_codec &&
719             p_media->es[i]->fmt.i_id == p_fmt->i_id )
720         {
721             p_es = p_media->es[i];
722         }
723     }
724     if( !p_es ) return;
725
726     msg_Dbg( p_vod, "  - Removing ES %4.4s", (char *)&p_fmt->i_codec );
727
728     vlc_mutex_lock( &p_media->lock );
729     TAB_REMOVE( p_media->i_es, p_media->es, p_es );
730     vlc_mutex_unlock( &p_media->lock );
731
732     free( p_es->psz_fmtp );
733
734     if( p_es->p_rtsp_url ) httpd_UrlDelete( p_es->p_rtsp_url );
735     es_format_Clean( &p_es->fmt );
736     free( p_es );
737 }
738
739 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,
740                          double f_arg, const char *psz_arg )
741 {
742     rtsp_cmd_t cmd;
743     block_t *p_cmd;
744
745     memset( &cmd, 0, sizeof(cmd) );
746     cmd.i_type = i_type;
747     cmd.p_media = p_media;
748     if( p_media )
749         cmd.i_media_id = p_media->id;
750     if( psz_session )
751         cmd.psz_session = strdup(psz_session);
752     cmd.i_arg = i_arg;
753     cmd.f_arg = f_arg;
754     if( psz_arg )
755         cmd.psz_arg = strdup(psz_arg);
756
757     p_cmd = block_Alloc( sizeof(rtsp_cmd_t) );
758     memcpy( p_cmd->p_buffer, &cmd, sizeof(cmd) );
759
760     block_FifoPut( p_vod->p_sys->p_fifo_cmd, p_cmd );
761 }
762
763 static void* CommandThread( void *obj )
764 {
765     vod_t *p_vod = (vod_t*)obj;
766     vod_sys_t *p_sys = p_vod->p_sys;
767     int canc = vlc_savecancel ();
768
769     for( ;; )
770     {
771         block_t *p_block_cmd = block_FifoGet( p_sys->p_fifo_cmd );
772         rtsp_cmd_t cmd;
773         vod_media_t *p_media = NULL;
774         int i;
775
776         if( !p_block_cmd )
777             break;
778
779         memcpy( &cmd, p_block_cmd->p_buffer, sizeof(cmd) );
780         block_Release( p_block_cmd );
781
782         if( cmd.i_type == RTSP_CMD_TYPE_NONE )
783             break;
784
785         if ( cmd.i_type == RTSP_CMD_TYPE_ADD )
786         {
787             TAB_APPEND( p_sys->i_media, p_sys->media, cmd.p_media );
788             goto next;
789         }
790
791         if ( cmd.i_type == RTSP_CMD_TYPE_DEL )
792         {
793             MediaDel(p_vod, cmd.p_media);
794             goto next;
795         }
796
797         /* */
798         for( i = 0; i < p_sys->i_media; i++ )
799         {
800             if( p_sys->media[i]->id == cmd.i_media_id )
801                 break;
802         }
803         if( i >= p_sys->i_media )
804         {
805             goto next;
806         }
807         p_media = p_sys->media[i];
808
809         switch( cmd.i_type )
810         {
811         case RTSP_CMD_TYPE_PLAY:
812             cmd.i_arg = -1;
813             vod_MediaControl( p_vod, p_media, cmd.psz_session,
814                               VOD_MEDIA_PLAY, cmd.psz_arg, &cmd.i_arg );
815             break;
816         case RTSP_CMD_TYPE_PAUSE:
817             cmd.i_arg = -1;
818             vod_MediaControl( p_vod, p_media, cmd.psz_session,
819                               VOD_MEDIA_PAUSE, &cmd.i_arg );
820             break;
821
822         case RTSP_CMD_TYPE_STOP:
823             vod_MediaControl( p_vod, p_media, cmd.psz_session, VOD_MEDIA_STOP );
824             break;
825
826         case RTSP_CMD_TYPE_SEEK:
827             vod_MediaControl( p_vod, p_media, cmd.psz_session,
828                               VOD_MEDIA_SEEK, cmd.i_arg );
829             break;
830
831         case RTSP_CMD_TYPE_REWIND:
832             vod_MediaControl( p_vod, p_media, cmd.psz_session,
833                               VOD_MEDIA_REWIND, cmd.f_arg );
834             break;
835
836         case RTSP_CMD_TYPE_FORWARD:
837             vod_MediaControl( p_vod, p_media, cmd.psz_session,
838                               VOD_MEDIA_FORWARD, cmd.f_arg );
839             break;
840
841         default:
842             break;
843         }
844
845     next:
846         free( cmd.psz_session );
847         free( cmd.psz_arg );
848     }
849
850     vlc_restorecancel (canc);
851     return NULL;
852 }
853
854 /****************************************************************************
855  * RTSP server implementation
856  ****************************************************************************/
857 static rtsp_client_t *RtspClientNew( vod_media_t *p_media, char *psz_session )
858 {
859     rtsp_client_t *p_rtsp = calloc( 1, sizeof(rtsp_client_t) );
860
861     if( !p_rtsp )
862         return NULL;
863     p_rtsp->es = 0;
864
865     p_rtsp->psz_session = psz_session;
866     TAB_APPEND( p_media->i_rtsp, p_media->rtsp, p_rtsp );
867
868     p_media->p_vod->p_sys->i_connections++;
869     msg_Dbg( p_media->p_vod, "new session: %s, connections: %d",
870              psz_session, p_media->p_vod->p_sys->i_throttle_users );
871
872     return p_rtsp;
873 }
874
875 static rtsp_client_t *RtspClientGet( vod_media_t *p_media, const char *psz_session )
876 {
877     for( int i = 0; psz_session && i < p_media->i_rtsp; i++ )
878     {
879         if( !strcmp( p_media->rtsp[i]->psz_session, psz_session ) )
880             return p_media->rtsp[i];
881     }
882
883     return NULL;
884 }
885
886 static void RtspClientDel( vod_media_t *p_media, rtsp_client_t *p_rtsp )
887 {
888     p_media->p_vod->p_sys->i_connections--;
889     msg_Dbg( p_media->p_vod, "closing session: %s, connections: %d",
890              p_rtsp->psz_session, p_media->p_vod->p_sys->i_throttle_users );
891
892     while( p_rtsp->i_es )
893     {
894         p_rtsp->i_es--;
895         free( p_rtsp->es[p_rtsp->i_es] );
896     }
897     free( p_rtsp->es );
898
899     TAB_REMOVE( p_media->i_rtsp, p_media->rtsp, p_rtsp );
900
901     free( p_rtsp->psz_session );
902     free( p_rtsp );
903 }
904
905
906 static int64_t ParseNPT (const char *str)
907 {
908     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
909     locale_t oldloc = uselocale (loc);
910     unsigned hour, min;
911     float sec;
912
913     if (sscanf (str, "%u:%u:%f", &hour, &min, &sec) == 3)
914         sec += ((hour * 60) + min) * 60;
915     else
916     if (sscanf (str, "%f", &sec) != 1)
917         sec = 0.;
918
919     if (loc != (locale_t)0)
920     {
921         uselocale (oldloc);
922         freelocale (loc);
923     }
924     return sec * CLOCK_FREQ;
925 }
926
927
928 static int RtspCallback( httpd_callback_sys_t *p_args, httpd_client_t *cl,
929                          httpd_message_t *answer, const httpd_message_t *query )
930 {
931     vod_media_t *p_media = (vod_media_t*)p_args;
932     vod_t *p_vod = p_media->p_vod;
933     const char *psz_transport = NULL;
934     const char *psz_playnow = NULL; /* support option: x-playNow */
935     const char *psz_session = NULL;
936     const char *psz_cseq = NULL;
937     rtsp_client_t *p_rtsp;
938     int i_cseq = 0;
939
940     if( answer == NULL || query == NULL ) return VLC_SUCCESS;
941
942     msg_Dbg( p_vod, "RtspCallback query: type=%d", query->i_type );
943
944     answer->i_proto   = HTTPD_PROTO_RTSP;
945     answer->i_version = query->i_version;
946     answer->i_type    = HTTPD_MSG_ANSWER;
947     answer->i_body    = 0;
948     answer->p_body    = NULL;
949
950     switch( query->i_type )
951     {
952         case HTTPD_MSG_SETUP:
953         {
954             psz_playnow = httpd_MsgGet( query, "x-playNow" );
955             psz_transport = httpd_MsgGet( query, "Transport" );
956             if( psz_transport == NULL )
957             {
958                 answer->i_status = 400;
959                 break;
960             }
961             msg_Dbg( p_vod, "HTTPD_MSG_SETUP: transport=%s", psz_transport );
962
963             if( strstr( psz_transport, "unicast" ) &&
964                 strstr( psz_transport, "client_port=" ) )
965             {
966                 rtsp_client_t *p_rtsp = NULL;
967                 char ip[NI_MAXNUMERICHOST];
968                 int i_port = atoi( strstr( psz_transport, "client_port=" ) +
969                                    strlen("client_port=") );
970
971                 if( strstr( psz_transport, "MP2T/H2221/UDP" ) ||
972                     strstr( psz_transport, "RAW/RAW/UDP" ) )
973                 {
974                     p_media->psz_mux = p_vod->p_sys->psz_raw_mux;
975                     p_media->b_raw = true;
976                 }
977
978                 if( httpd_ClientIP( cl, ip, NULL ) == NULL )
979                 {
980                     answer->i_status = 500;
981                     answer->i_body = 0;
982                     answer->p_body = NULL;
983                     break;
984                 }
985
986                 msg_Dbg( p_vod, "HTTPD_MSG_SETUP: unicast ip=%s port=%d",
987                          ip, i_port );
988
989                 psz_session = httpd_MsgGet( query, "Session" );
990                 if( !psz_session || !*psz_session )
991                 {
992                     char *psz_new;
993                     if( ( p_vod->p_sys->i_throttle_users > 0 ) &&
994                         ( p_vod->p_sys->i_connections >= p_vod->p_sys->i_throttle_users ) )
995                     {
996                         answer->i_status = 503;
997                         answer->i_body = 0;
998                         answer->p_body = NULL;
999                         break;
1000                     }
1001 #warning Should use secure randomness here! (spoofing risk)
1002                     if( asprintf( &psz_new, "%lu", vlc_mrand48() ) < 0 )
1003                         return VLC_ENOMEM;
1004                     psz_session = psz_new;
1005
1006                     p_rtsp = RtspClientNew( p_media, psz_new );
1007                     if( !p_rtsp )
1008                     {
1009                         answer->i_status = 454;
1010                         answer->i_body = 0;
1011                         answer->p_body = NULL;
1012                         break;
1013                     }
1014                 }
1015                 else
1016                 {
1017                     p_rtsp = RtspClientGet( p_media, psz_session );
1018                     if( !p_rtsp )
1019                     {
1020                         answer->i_status = 454;
1021                         answer->i_body = 0;
1022                         answer->p_body = NULL;
1023                         break;
1024                     }
1025                 }
1026
1027                 answer->i_status = 200;
1028                 answer->i_body = 0;
1029                 answer->p_body = NULL;
1030
1031                 if( p_media->b_raw )
1032                 {
1033                     p_rtsp->i_port_raw = i_port;
1034
1035                     if( strstr( psz_transport, "MP2T/H2221/UDP" ) )
1036                     {
1037                         httpd_MsgAdd( answer, "Transport",
1038                                       "MP2T/H2221/UDP;unicast;client_port=%d-%d",
1039                                       i_port, i_port + 1 );
1040                     }
1041                     else if( strstr( psz_transport, "RAW/RAW/UDP" ) )
1042                     {
1043                         httpd_MsgAdd( answer, "Transport",
1044                                       "RAW/RAW/UDP;unicast;client_port=%d-%d",
1045                                       i_port, i_port + 1 );
1046                     }
1047                 }
1048                 else
1049                     httpd_MsgAdd( answer, "Transport",
1050                                   "RTP/AVP/UDP;unicast;client_port=%d-%d",
1051                                   i_port, i_port + 1 );
1052             }
1053             else /* TODO  strstr( psz_transport, "interleaved" ) ) */
1054             {
1055                 answer->i_status = 461;
1056                 answer->i_body = 0;
1057                 answer->p_body = NULL;
1058             }
1059
1060             /* Intentional fall-through on x-playNow option in RTSP request */
1061             if( !psz_playnow )
1062                 break;
1063         }
1064
1065         case HTTPD_MSG_PLAY:
1066         {
1067             char *psz_output, ip[NI_MAXNUMERICHOST];
1068             int i_port_audio = 0, i_port_video = 0;
1069
1070             /* for now only multicast so easy */
1071             if( !psz_playnow )
1072             {
1073                 answer->i_status = 200;
1074                 answer->i_body = 0;
1075                 answer->p_body = NULL;
1076             }
1077
1078             if( !psz_session )
1079                 psz_session = httpd_MsgGet( query, "Session" );
1080             msg_Dbg( p_vod, "HTTPD_MSG_PLAY for session: %s", psz_session );
1081
1082             p_rtsp = RtspClientGet( p_media, psz_session );
1083             if( !p_rtsp )
1084             {
1085                 answer->i_status = 500;
1086                 answer->i_body = 0;
1087                 answer->p_body = NULL;
1088                 break;
1089             }
1090
1091             if( p_rtsp->b_playing )
1092             {
1093                 const char *psz_position = httpd_MsgGet( query, "Range" );
1094                 const char *psz_scale = httpd_MsgGet( query, "Scale" );
1095                 if( psz_position )
1096                     psz_position = strstr( psz_position, "npt=" );
1097                 if( psz_position && !psz_scale )
1098                 {
1099                     int64_t i_time = ParseNPT (psz_position + 4);
1100                     msg_Dbg( p_vod, "seeking request: %s", psz_position );
1101                     CommandPush( p_vod, RTSP_CMD_TYPE_SEEK, p_media,
1102                                  psz_session, i_time, 0.0, NULL );
1103                 }
1104                 else if( psz_scale )
1105                 {
1106                     double f_scale = 0.0;
1107                     char *end;
1108
1109                     f_scale = us_strtod( psz_scale, &end );
1110                     if( end > psz_scale )
1111                     {
1112                         f_scale = (f_scale * 30.0);
1113                         if( psz_scale[0] == '-' ) /* rewind */
1114                         {
1115                             msg_Dbg( p_vod, "rewind request: %s", psz_scale );
1116                             CommandPush( p_vod, RTSP_CMD_TYPE_REWIND, p_media,
1117                                          psz_session, 0, f_scale, NULL );
1118                         }
1119                         else if(psz_scale[0] != '1' ) /* fast-forward */
1120                         {
1121                             msg_Dbg( p_vod, "fastforward request: %s",
1122                                      psz_scale );
1123                             CommandPush( p_vod, RTSP_CMD_TYPE_FORWARD, p_media,
1124                                          psz_session, 0, f_scale, NULL );
1125                         }
1126                     }
1127                 }
1128                 /* unpause, in case it's paused */
1129                 CommandPush( p_vod, RTSP_CMD_TYPE_PLAY, p_media, psz_session,
1130                              0, 0.0, "" );
1131                 break;
1132             }
1133
1134             if( httpd_ClientIP( cl, ip, NULL ) == NULL ) break;
1135
1136             p_rtsp->b_playing = true;
1137
1138             /* FIXME for != 1 video and 1 audio */
1139             for( int i = 0; i < p_rtsp->i_es; i++ )
1140             {
1141                 if( p_rtsp->es[i]->p_media_es->fmt.i_cat == AUDIO_ES )
1142                     i_port_audio = p_rtsp->es[i]->i_port;
1143                 if( p_rtsp->es[i]->p_media_es->fmt.i_cat == VIDEO_ES )
1144                     i_port_video = p_rtsp->es[i]->i_port;
1145             }
1146
1147             if( p_media->psz_mux )
1148             {
1149                 if( p_media->b_raw )
1150                 {
1151                     if( asprintf( &psz_output,
1152                               "std{access=udp,dst=%s:%i,mux=%s}",
1153                               ip, p_rtsp->i_port_raw, p_media->psz_mux ) < 0 )
1154                         return VLC_ENOMEM;
1155                 }
1156                 else
1157                 {
1158                     if( asprintf( &psz_output,
1159                               "rtp{dst=%s,port=%i,mux=%s}",
1160                               ip, i_port_video, p_media->psz_mux ) < 0 )
1161                         return VLC_ENOMEM;
1162                 }
1163             }
1164             else
1165             {
1166                 if( asprintf( &psz_output,
1167                               "rtp{dst=%s,port-video=%i,port-audio=%i}",
1168                               ip, i_port_video, i_port_audio ) < 0 )
1169                     return VLC_ENOMEM;
1170             }
1171
1172             CommandPush( p_vod, RTSP_CMD_TYPE_PLAY, p_media, psz_session,
1173                          0, 0.0, psz_output );
1174             free( psz_output );
1175             break;
1176         }
1177
1178         case HTTPD_MSG_DESCRIBE:
1179         {
1180             char *psz_sdp =
1181                 SDPGenerate( p_media, cl );
1182
1183             if( psz_sdp != NULL )
1184             {
1185                 answer->i_status = 200;
1186                 httpd_MsgAdd( answer, "Content-type",  "%s",
1187                               "application/sdp" );
1188
1189                 answer->p_body = (uint8_t *)psz_sdp;
1190                 answer->i_body = strlen( psz_sdp );
1191             }
1192             else
1193             {
1194                 answer->i_status = 500;
1195                 answer->p_body = NULL;
1196                 answer->i_body = 0;
1197             }
1198             break;
1199         }
1200
1201         case HTTPD_MSG_PAUSE:
1202             psz_session = httpd_MsgGet( query, "Session" );
1203             msg_Dbg( p_vod, "HTTPD_MSG_PAUSE for session: %s", psz_session );
1204
1205             p_rtsp = RtspClientGet( p_media, psz_session );
1206             if( !p_rtsp ) break;
1207
1208             CommandPush( p_vod, RTSP_CMD_TYPE_PAUSE, p_media, psz_session,
1209                          0, 0.0, NULL );
1210
1211             answer->i_status = 200;
1212             answer->i_body = 0;
1213             answer->p_body = NULL;
1214             break;
1215
1216         case HTTPD_MSG_TEARDOWN:
1217             /* for now only multicast so easy again */
1218             answer->i_status = 200;
1219             answer->i_body = 0;
1220             answer->p_body = NULL;
1221
1222             psz_session = httpd_MsgGet( query, "Session" );
1223             msg_Dbg( p_vod, "HTTPD_MSG_TEARDOWN for session: %s", psz_session);
1224
1225             p_rtsp = RtspClientGet( p_media, psz_session );
1226             if( !p_rtsp ) break;
1227
1228             CommandPush( p_vod, RTSP_CMD_TYPE_STOP, p_media, psz_session,
1229                          0, 0.0, NULL );
1230             RtspClientDel( p_media, p_rtsp );
1231             break;
1232
1233         case HTTPD_MSG_GETPARAMETER:
1234             answer->i_status = 200;
1235             answer->i_body = 0;
1236             answer->p_body = NULL;
1237             break;
1238
1239         default:
1240             return VLC_EGENERIC;
1241     }
1242
1243     httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
1244     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
1245     psz_cseq = httpd_MsgGet( query, "Cseq" );
1246     psz_cseq ? i_cseq = atoi( psz_cseq ) : 0;
1247     httpd_MsgAdd( answer, "CSeq", "%d", i_cseq );
1248     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
1249
1250     if( psz_session )
1251     {
1252          if( p_media->p_vod->p_sys->i_session_timeout >= 0 )
1253              httpd_MsgAdd( answer, "Session", "%s;timeout=%i", psz_session,
1254                p_media->p_vod->p_sys->i_session_timeout );
1255          else
1256               httpd_MsgAdd( answer, "Session", "%s", psz_session );
1257     }
1258
1259     return VLC_SUCCESS;
1260 }
1261
1262 static int RtspCallbackES( httpd_callback_sys_t *p_args, httpd_client_t *cl,
1263                            httpd_message_t *answer,
1264                            const httpd_message_t *query )
1265 {
1266     media_es_t *p_es = (media_es_t*)p_args;
1267     vod_media_t *p_media = p_es->p_media;
1268     vod_t *p_vod = p_media->p_vod;
1269     rtsp_client_t *p_rtsp = NULL;
1270     const char *psz_transport = NULL;
1271     const char *psz_playnow = NULL; /* support option: x-playNow */
1272     const char *psz_session = NULL;
1273     const char *psz_position = NULL;
1274     const char *psz_cseq = NULL;
1275     int i_cseq = 0;
1276
1277     if( answer == NULL || query == NULL ) return VLC_SUCCESS;
1278
1279     msg_Dbg( p_vod, "RtspCallback query: type=%d", query->i_type );
1280
1281     answer->i_proto   = HTTPD_PROTO_RTSP;
1282     answer->i_version = query->i_version;
1283     answer->i_type    = HTTPD_MSG_ANSWER;
1284     answer->i_body    = 0;
1285     answer->p_body      = NULL;
1286
1287     switch( query->i_type )
1288     {
1289         case HTTPD_MSG_SETUP:
1290             psz_playnow = httpd_MsgGet( query, "x-playNow" );
1291             psz_transport = httpd_MsgGet( query, "Transport" );
1292
1293             msg_Dbg( p_vod, "HTTPD_MSG_SETUP: transport=%s", psz_transport );
1294
1295             if( strstr( psz_transport, "unicast" ) &&
1296                 strstr( psz_transport, "client_port=" ) )
1297             {
1298                 rtsp_client_t *p_rtsp = NULL;
1299                 rtsp_client_es_t *p_rtsp_es = NULL;
1300                 char ip[NI_MAXNUMERICHOST];
1301                 int i_port = atoi( strstr( psz_transport, "client_port=" ) +
1302                                    strlen("client_port=") );
1303
1304                 if( httpd_ClientIP( cl, ip, NULL ) == NULL )
1305                 {
1306                     answer->i_status = 500;
1307                     answer->i_body = 0;
1308                     answer->p_body = NULL;
1309                     break;
1310                 }
1311
1312                 msg_Dbg( p_vod, "HTTPD_MSG_SETUP: unicast ip=%s port=%d",
1313                         ip, i_port );
1314
1315                 psz_session = httpd_MsgGet( query, "Session" );
1316                 if( !psz_session || !*psz_session )
1317                 {
1318                     char *psz_new;
1319                     if( ( p_vod->p_sys->i_throttle_users > 0 ) &&
1320                         ( p_vod->p_sys->i_connections >= p_vod->p_sys->i_throttle_users ) )
1321                     {
1322                         answer->i_status = 503;
1323                         answer->i_body = 0;
1324                         answer->p_body = NULL;
1325                         break;
1326                     }
1327 #warning Session ID should be securely random (spoofing risk)
1328                     if( asprintf( &psz_new, "%lu", vlc_mrand48() ) < 0 )
1329                         return VLC_ENOMEM;
1330                     psz_session = psz_new;
1331
1332                     p_rtsp = RtspClientNew( p_media, psz_new );
1333                     if( !p_rtsp )
1334                     {
1335                         answer->i_status = 454;
1336                         answer->i_body = 0;
1337                         answer->p_body = NULL;
1338                         break;
1339                     }
1340                 }
1341                 else
1342                 {
1343                     p_rtsp = RtspClientGet( p_media, psz_session );
1344                     if( !p_rtsp )
1345                     {
1346                         answer->i_status = 454;
1347                         answer->i_body = 0;
1348                         answer->p_body = NULL;
1349                         break;
1350                     }
1351                 }
1352
1353                 p_rtsp_es = malloc( sizeof(rtsp_client_es_t) );
1354                 if( !p_rtsp_es )
1355                 {
1356                     answer->i_status = 500;
1357                     answer->i_body = 0;
1358                     answer->p_body = NULL;
1359                     break;
1360                 }
1361                 p_rtsp_es->i_port = i_port;
1362                 p_rtsp_es->p_media_es = p_es;
1363                 TAB_APPEND( p_rtsp->i_es, p_rtsp->es, p_rtsp_es );
1364
1365                 answer->i_status = 200;
1366                 answer->i_body = 0;
1367                 answer->p_body = NULL;
1368
1369                 if( p_media->b_raw )
1370                 {
1371                     if( strstr( psz_transport, "MP2T/H2221/UDP" ) )
1372                     {
1373                         httpd_MsgAdd( answer, "Transport",
1374                                      "MP2T/H2221/UDP;unicast;client_port=%d-%d",
1375                                      p_rtsp_es->i_port, p_rtsp_es->i_port + 1 );
1376                     }
1377                     else if( strstr( psz_transport, "RAW/RAW/UDP" ) )
1378                     {
1379                         httpd_MsgAdd( answer, "Transport",
1380                                      "RAW/RAW/UDP;unicast;client_port=%d-%d",
1381                                      p_rtsp_es->i_port, p_rtsp_es->i_port + 1 );
1382                     }
1383                 }
1384                 else
1385                 {
1386                     httpd_MsgAdd( answer, "Transport",
1387                                   "RTP/AVP/UDP;unicast;client_port=%d-%d",
1388                                   p_rtsp_es->i_port, p_rtsp_es->i_port + 1 );
1389                 }
1390             }
1391             else /* TODO  strstr( psz_transport, "interleaved" ) ) */
1392             {
1393                 answer->i_status = 461;
1394                 answer->i_body = 0;
1395                 answer->p_body = NULL;
1396             }
1397
1398             /* Intentional fall-through on x-playNow option in RTSP request */
1399             if( !psz_playnow )
1400                 break;
1401
1402         case HTTPD_MSG_PLAY:
1403             /* This is kind of a kludge. Should we only support Aggregate
1404              * Operations ? */
1405             psz_session = httpd_MsgGet( query, "Session" );
1406             msg_Dbg( p_vod, "HTTPD_MSG_PLAY for session: %s", psz_session );
1407
1408             p_rtsp = RtspClientGet( p_media, psz_session );
1409
1410             psz_position = httpd_MsgGet( query, "Range" );
1411             if( psz_position ) psz_position = strstr( psz_position, "npt=" );
1412             if( psz_position )
1413             {
1414                 int64_t i_time = ParseNPT (psz_position + 4);
1415                 msg_Dbg( p_vod, "seeking request: %s", psz_position );
1416                 CommandPush( p_vod, RTSP_CMD_TYPE_SEEK, p_media,
1417                              psz_session, i_time, 0.0, NULL );
1418             }
1419
1420             if( !psz_playnow )
1421             {
1422                 answer->i_status = 200;
1423                 answer->i_body = 0;
1424                 answer->p_body = NULL;
1425             }
1426             break;
1427
1428         case HTTPD_MSG_TEARDOWN:
1429             answer->i_status = 200;
1430             answer->i_body = 0;
1431             answer->p_body = NULL;
1432
1433             psz_session = httpd_MsgGet( query, "Session" );
1434             msg_Dbg( p_vod, "HTTPD_MSG_TEARDOWN for session: %s", psz_session);
1435
1436             p_rtsp = RtspClientGet( p_media, psz_session );
1437             if( !p_rtsp ) break;
1438
1439             for( int i = 0; i < p_rtsp->i_es; i++ )
1440             {
1441                 rtsp_client_es_t *es = p_rtsp->es[i];
1442                 if( es->p_media_es == p_es )
1443                 {
1444                     TAB_REMOVE( p_rtsp->i_es, p_rtsp->es, es );
1445                     break;
1446                 }
1447             }
1448
1449             if( !p_rtsp->i_es )
1450             {
1451                 CommandPush( p_vod, RTSP_CMD_TYPE_STOP, p_media, psz_session,
1452                              0, 0.0, NULL );
1453                 RtspClientDel( p_media, p_rtsp );
1454             }
1455             break;
1456
1457         case HTTPD_MSG_PAUSE:
1458             /* This is kind of a kludge. Should we only support Aggregate
1459              * Operations ? */
1460             psz_session = httpd_MsgGet( query, "Session" );
1461             msg_Dbg( p_vod, "HTTPD_MSG_PAUSE for session: %s", psz_session );
1462
1463             p_rtsp = RtspClientGet( p_media, psz_session );
1464             if( !p_rtsp ) break;
1465
1466             CommandPush( p_vod, RTSP_CMD_TYPE_PAUSE, p_media, psz_session,
1467                          0, 0.0, NULL );
1468
1469             answer->i_status = 200;
1470             answer->i_body = 0;
1471             answer->p_body = NULL;
1472             break;
1473
1474         default:
1475             return VLC_EGENERIC;
1476             break;
1477     }
1478
1479     httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
1480     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
1481     psz_cseq = httpd_MsgGet( query, "Cseq" );
1482     if (psz_cseq)
1483         i_cseq = atoi( psz_cseq );
1484     else
1485         i_cseq = 0;
1486     httpd_MsgAdd( answer, "Cseq", "%d", i_cseq );
1487     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
1488
1489     if( psz_session )
1490         httpd_MsgAdd( answer, "Session", "%s"/*;timeout=5*/, psz_session );
1491
1492     return VLC_SUCCESS;
1493 }
1494
1495 /*****************************************************************************
1496  * SDPGenerate: TODO
1497  * FIXME: need to be moved to a common place ?
1498  *****************************************************************************/
1499 static char *SDPGenerate( const vod_media_t *p_media, httpd_client_t *cl )
1500 {
1501     char *psz_sdp, ip[NI_MAXNUMERICHOST];
1502     const char *psz_control;
1503     int port;
1504
1505     if( httpd_ServerIP( cl, ip, &port ) == NULL )
1506         return NULL;
1507
1508     bool ipv6 = ( strchr( ip, ':' ) != NULL );
1509
1510     psz_control = ipv6 ? p_media->psz_rtsp_control_v6
1511                        : p_media->psz_rtsp_control_v4;
1512
1513     /* Dummy destination address for RTSP */
1514     struct sockaddr_storage dst;
1515     socklen_t dstlen = ipv6 ? sizeof( struct sockaddr_in6 )
1516                             : sizeof( struct sockaddr_in );
1517     memset (&dst, 0, dstlen);
1518     dst.ss_family = ipv6 ? AF_INET6 : AF_INET;
1519 #ifdef HAVE_SA_LEN
1520     dst.ss_len = dstlen;
1521 #endif
1522
1523     psz_sdp = vlc_sdp_Start( VLC_OBJECT( p_media->p_vod ), "sout-rtp-",
1524                              NULL, 0, (struct sockaddr *)&dst, dstlen );
1525     if( psz_sdp == NULL )
1526         return NULL;
1527
1528     if( p_media->i_length > 0 )
1529     {
1530         lldiv_t d = lldiv( p_media->i_length / 1000, 1000 );
1531         sdp_AddAttribute( &psz_sdp, "range","npt=0-%lld.%03u", d.quot,
1532                           (unsigned)d.rem );
1533     }
1534
1535     for( int i = 0; i < p_media->i_es; i++ )
1536     {
1537         media_es_t *p_es = p_media->es[i];
1538         const char *mime_major; /* major MIME type */
1539
1540         switch( p_es->fmt.i_cat )
1541         {
1542             case VIDEO_ES:
1543                 mime_major = "video";
1544                 break;
1545             case AUDIO_ES:
1546                 mime_major = "audio";
1547                 break;
1548             case SPU_ES:
1549                 mime_major = "text";
1550                 break;
1551             default:
1552                 continue;
1553         }
1554
1555         sdp_AddMedia( &psz_sdp, mime_major, "RTP/AVP", 0 /* p_es->i_port */,
1556                       p_es->i_payload_type, false, 0,
1557                       p_es->psz_ptname, p_es->i_clock_rate, p_es->i_channels,
1558                       p_es->psz_fmtp );
1559
1560         sdp_AddAttribute( &psz_sdp, "control", psz_control, ip, port, i );
1561     }
1562
1563     return psz_sdp;
1564 }