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