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