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