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