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