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