52bc54fc9bad2cc83e78ad187414cf7a223078fb
[vlc.git] / modules / stream_out / rtsp.c
1 /*****************************************************************************
2  * rtsp.c: RTSP support for RTP stream output module
3  *****************************************************************************
4  * Copyright (C) 2003-2004, 2010 VLC authors and VideoLAN
5  * Copyright © 2007 Rémi Denis-Courmont
6  *
7  * $Id$
8  *
9  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
10  *          Pierre Ynard
11  *
12  * This program is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU Lesser General Public License as published by
14  * the Free Software Foundation; either version 2.1 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20  * GNU Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <vlc_common.h>
35 #include <vlc_sout.h>
36
37 #include <vlc_httpd.h>
38 #include <vlc_url.h>
39 #include <vlc_charset.h>
40 #include <vlc_fs.h>
41 #include <vlc_network.h>
42 #include <vlc_rand.h>
43 #include <assert.h>
44 #include <errno.h>
45 #include <stdlib.h>
46 #include <time.h>
47
48 #ifndef _WIN32
49 # include <locale.h>
50 #endif
51 #ifdef HAVE_XLOCALE_H
52 # include <xlocale.h>
53 #endif
54
55 #include "rtp.h"
56
57 typedef struct rtsp_session_t rtsp_session_t;
58
59 struct rtsp_stream_t
60 {
61     vlc_mutex_t     lock;
62     vlc_object_t   *owner;
63     vod_media_t    *vod_media;
64     httpd_host_t   *host;
65     httpd_url_t    *url;
66     char           *psz_path;
67     unsigned        track_id;
68
69     int             sessionc;
70     rtsp_session_t **sessionv;
71
72     int             timeout;
73     vlc_timer_t     timer;
74 };
75
76
77 static int  RtspCallback( httpd_callback_sys_t *p_args,
78                           httpd_client_t *cl, httpd_message_t *answer,
79                           const httpd_message_t *query );
80 static int  RtspCallbackId( httpd_callback_sys_t *p_args,
81                             httpd_client_t *cl, httpd_message_t *answer,
82                             const httpd_message_t *query );
83 static void RtspClientDel( rtsp_stream_t *rtsp, rtsp_session_t *session );
84
85 static void RtspTimeOut( void *data );
86
87 rtsp_stream_t *RtspSetup( vlc_object_t *owner, vod_media_t *media,
88                           const char *path )
89 {
90     rtsp_stream_t *rtsp = calloc( 1, sizeof( *rtsp ) );
91
92     if( unlikely(rtsp == NULL) )
93         return NULL;
94
95     rtsp->owner = owner;
96     rtsp->vod_media = media;
97     vlc_mutex_init( &rtsp->lock );
98
99     rtsp->timeout = var_InheritInteger(owner, "rtsp-timeout");
100     if (rtsp->timeout > 0)
101     {
102         if (vlc_timer_create(&rtsp->timer, RtspTimeOut, rtsp))
103             goto error;
104     }
105
106     rtsp->psz_path = strdup( (path != NULL) ? path : "/" );
107     if( rtsp->psz_path == NULL )
108         goto error;
109
110     msg_Dbg( owner, "RTSP stream at %s", rtsp->psz_path );
111
112     rtsp->host = vlc_rtsp_HostNew( VLC_OBJECT(owner) );
113     if( rtsp->host == NULL )
114         goto error;
115
116     char *user = var_InheritString(owner, "sout-rtsp-user");
117     char *pwd = var_InheritString(owner, "sout-rtsp-pwd");
118
119     rtsp->url = httpd_UrlNew( rtsp->host, rtsp->psz_path, user, pwd );
120     free(user);
121     free(pwd);
122     if( rtsp->url == NULL )
123         goto error;
124
125     httpd_UrlCatch( rtsp->url, HTTPD_MSG_DESCRIBE, RtspCallback, (void*)rtsp );
126     httpd_UrlCatch( rtsp->url, HTTPD_MSG_SETUP,    RtspCallback, (void*)rtsp );
127     httpd_UrlCatch( rtsp->url, HTTPD_MSG_PLAY,     RtspCallback, (void*)rtsp );
128     httpd_UrlCatch( rtsp->url, HTTPD_MSG_PAUSE,    RtspCallback, (void*)rtsp );
129     httpd_UrlCatch( rtsp->url, HTTPD_MSG_GETPARAMETER, RtspCallback,
130                     (void*)rtsp );
131     httpd_UrlCatch( rtsp->url, HTTPD_MSG_TEARDOWN, RtspCallback, (void*)rtsp );
132     return rtsp;
133
134 error:
135     RtspUnsetup( rtsp );
136     return NULL;
137 }
138
139
140 void RtspUnsetup( rtsp_stream_t *rtsp )
141 {
142     if( rtsp->url )
143         httpd_UrlDelete( rtsp->url );
144
145     if( rtsp->host )
146         httpd_HostDelete( rtsp->host );
147
148     while( rtsp->sessionc > 0 )
149         RtspClientDel( rtsp, rtsp->sessionv[0] );
150
151     if (rtsp->timeout > 0)
152         vlc_timer_destroy(rtsp->timer);
153
154     free( rtsp->psz_path );
155     vlc_mutex_destroy( &rtsp->lock );
156
157     free( rtsp );
158 }
159
160
161 struct rtsp_stream_id_t
162 {
163     rtsp_stream_t    *stream;
164     sout_stream_id_sys_t *sout_id;
165     httpd_url_t      *url;
166     unsigned          track_id;
167     uint32_t          ssrc;
168     unsigned          clock_rate; /* needed to compute rtptime in RTP-Info */
169     int               mcast_fd;
170 };
171
172
173 typedef struct rtsp_strack_t rtsp_strack_t;
174
175 /* For unicast streaming */
176 struct rtsp_session_t
177 {
178     rtsp_stream_t *stream;
179     uint64_t       id;
180     mtime_t        last_seen; /* for timeouts */
181
182     /* output (id-access) */
183     int            trackc;
184     rtsp_strack_t *trackv;
185 };
186
187
188 /* Unicast session track */
189 struct rtsp_strack_t
190 {
191     rtsp_stream_id_t  *id;
192     sout_stream_id_sys_t  *sout_id;
193     int          setup_fd;  /* socket created by the SETUP request */
194     int          rtp_fd;    /* socket used by the RTP output, when playing */
195     uint32_t     ssrc;
196     uint16_t     seq_init;
197 };
198
199 static void RtspTrackClose( rtsp_strack_t *tr );
200
201 #define TRACK_PATH_SIZE (sizeof("/trackID=999") - 1)
202
203 char *RtspAppendTrackPath( rtsp_stream_id_t *id, const char *base )
204 {
205     const char *sep = strlen( base ) > 0 && base[strlen( base ) - 1] == '/' ?
206                       "" : "/";
207     char *url;
208
209     if( asprintf( &url, "%s%strackID=%u", base, sep, id->track_id ) == -1 )
210         url = NULL;
211     return url;
212 }
213
214
215 rtsp_stream_id_t *RtspAddId( rtsp_stream_t *rtsp, sout_stream_id_sys_t *sid,
216                              uint32_t ssrc, unsigned clock_rate,
217                              int mcast_fd)
218 {
219     if (rtsp->track_id > 999)
220     {
221         msg_Err(rtsp->owner, "RTSP: too many IDs!");
222         return NULL;
223     }
224
225     char *urlbuf;
226     rtsp_stream_id_t *id = malloc( sizeof( *id ) );
227     httpd_url_t *url;
228
229     if( id == NULL )
230         return NULL;
231
232     id->stream = rtsp;
233     id->sout_id = sid;
234     id->track_id = rtsp->track_id;
235     id->ssrc = ssrc;
236     id->clock_rate = clock_rate;
237     id->mcast_fd = mcast_fd;
238
239     urlbuf = RtspAppendTrackPath( id, rtsp->psz_path );
240     if( urlbuf == NULL )
241     {
242         free( id );
243         return NULL;
244     }
245
246     msg_Dbg( rtsp->owner, "RTSP: adding %s", urlbuf );
247
248     char *user = var_InheritString(rtsp->owner, "sout-rtsp-user");
249     char *pwd = var_InheritString(rtsp->owner, "sout-rtsp-pwd");
250
251     url = id->url = httpd_UrlNew( rtsp->host, urlbuf, user, pwd );
252     free( user );
253     free( pwd );
254     free( urlbuf );
255
256     if( url == NULL )
257     {
258         free( id );
259         return NULL;
260     }
261
262     httpd_UrlCatch( url, HTTPD_MSG_DESCRIBE, RtspCallbackId, (void *)id );
263     httpd_UrlCatch( url, HTTPD_MSG_SETUP,    RtspCallbackId, (void *)id );
264     httpd_UrlCatch( url, HTTPD_MSG_PLAY,     RtspCallbackId, (void *)id );
265     httpd_UrlCatch( url, HTTPD_MSG_PAUSE,    RtspCallbackId, (void *)id );
266     httpd_UrlCatch( url, HTTPD_MSG_GETPARAMETER, RtspCallbackId, (void *)id );
267     httpd_UrlCatch( url, HTTPD_MSG_TEARDOWN, RtspCallbackId, (void *)id );
268
269     rtsp->track_id++;
270
271     return id;
272 }
273
274
275 void RtspDelId( rtsp_stream_t *rtsp, rtsp_stream_id_t *id )
276 {
277     httpd_UrlDelete( id->url );
278
279     vlc_mutex_lock( &rtsp->lock );
280     for( int i = 0; i < rtsp->sessionc; i++ )
281     {
282         rtsp_session_t *ses = rtsp->sessionv[i];
283
284         for( int j = 0; j < ses->trackc; j++ )
285         {
286             if( ses->trackv[j].id == id )
287             {
288                 rtsp_strack_t *tr = ses->trackv + j;
289                 RtspTrackClose( tr );
290                 TAB_ERASE(ses->trackc, ses->trackv, j);
291             }
292         }
293     }
294
295     vlc_mutex_unlock( &rtsp->lock );
296     free( id );
297 }
298
299
300 /** rtsp must be locked */
301 static void RtspUpdateTimer( rtsp_stream_t *rtsp )
302 {
303     if (rtsp->timeout <= 0)
304         return;
305
306     mtime_t timeout = 0;
307     for (int i = 0; i < rtsp->sessionc; i++)
308     {
309         if (timeout == 0 || rtsp->sessionv[i]->last_seen < timeout)
310             timeout = rtsp->sessionv[i]->last_seen;
311     }
312     if (timeout != 0)
313         timeout += rtsp->timeout * CLOCK_FREQ;
314     vlc_timer_schedule(rtsp->timer, true, timeout, 0);
315 }
316
317
318 static void RtspTimeOut( void *data )
319 {
320     rtsp_stream_t *rtsp = data;
321
322     vlc_mutex_lock(&rtsp->lock);
323     mtime_t now = mdate();
324     for (int i = rtsp->sessionc - 1; i >= 0; i--)
325     {
326         if (rtsp->sessionv[i]->last_seen + rtsp->timeout * CLOCK_FREQ < now)
327         {
328             if (rtsp->vod_media != NULL)
329             {
330                 char psz_sesbuf[17];
331                 snprintf( psz_sesbuf, sizeof( psz_sesbuf ), "%"PRIx64,
332                           rtsp->sessionv[i]->id );
333                 vod_stop(rtsp->vod_media, psz_sesbuf);
334             }
335             RtspClientDel(rtsp, rtsp->sessionv[i]);
336         }
337     }
338     RtspUpdateTimer(rtsp);
339     vlc_mutex_unlock(&rtsp->lock);
340 }
341
342
343 /** rtsp must be locked */
344 static
345 rtsp_session_t *RtspClientNew( rtsp_stream_t *rtsp )
346 {
347     rtsp_session_t *s = malloc( sizeof( *s ) );
348     if( s == NULL )
349         return NULL;
350
351     s->stream = rtsp;
352     vlc_rand_bytes (&s->id, sizeof (s->id));
353     s->trackc = 0;
354     s->trackv = NULL;
355
356     TAB_APPEND( rtsp->sessionc, rtsp->sessionv, s );
357
358     return s;
359 }
360
361
362 /** rtsp must be locked */
363 static
364 rtsp_session_t *RtspClientGet( rtsp_stream_t *rtsp, const char *name )
365 {
366     char *end;
367     uint64_t id;
368     int i;
369
370     if( name == NULL )
371         return NULL;
372
373     errno = 0;
374     id = strtoull( name, &end, 0x10 );
375     if( errno || *end )
376         return NULL;
377
378     /* FIXME: use a hash/dictionary */
379     for( i = 0; i < rtsp->sessionc; i++ )
380     {
381         if( rtsp->sessionv[i]->id == id )
382             return rtsp->sessionv[i];
383     }
384     return NULL;
385 }
386
387
388 /** rtsp must be locked */
389 static
390 void RtspClientDel( rtsp_stream_t *rtsp, rtsp_session_t *session )
391 {
392     int i;
393     TAB_REMOVE( rtsp->sessionc, rtsp->sessionv, session );
394
395     for( i = 0; i < session->trackc; i++ )
396         RtspTrackClose( &session->trackv[i] );
397
398     free( session->trackv );
399     free( session );
400 }
401
402
403 /** rtsp must be locked */
404 static void RtspClientAlive( rtsp_session_t *session )
405 {
406     if (session->stream->timeout <= 0)
407         return;
408
409     session->last_seen = mdate();
410     RtspUpdateTimer(session->stream);
411 }
412
413 static int dup_socket(int oldfd)
414 {
415     int newfd;
416 #ifndef _WIN32
417     newfd = vlc_dup(oldfd);
418 #else
419     WSAPROTOCOL_INFO info;
420     WSADuplicateSocket (oldfd, GetCurrentProcessId (), &info);
421     newfd = WSASocket (info.iAddressFamily, info.iSocketType,
422                        info.iProtocol, &info, 0, 0);
423 #endif
424     return newfd;
425 }
426
427 /* Attach a starting VoD RTP id to its RTSP track, and let it
428  * initialize with the parameters of the SETUP request */
429 int RtspTrackAttach( rtsp_stream_t *rtsp, const char *name,
430                      rtsp_stream_id_t *id, sout_stream_id_sys_t *sout_id,
431                      uint32_t *ssrc, uint16_t *seq_init )
432 {
433     int val = VLC_EGENERIC;
434     rtsp_session_t *session;
435
436     vlc_mutex_lock(&rtsp->lock);
437     session = RtspClientGet(rtsp, name);
438
439     if (session == NULL)
440         goto out;
441
442     rtsp_strack_t *tr = NULL;
443     for (int i = 0; i < session->trackc; i++)
444     {
445         if (session->trackv[i].id == id)
446         {
447             tr = session->trackv + i;
448             break;
449         }
450     }
451
452     if (tr != NULL)
453     {
454         tr->sout_id = sout_id;
455         tr->rtp_fd = dup_socket(tr->setup_fd);
456     }
457     else
458     {
459         /* The track was not SETUP. We still create one because we'll
460          * need the sout_id if we set it up later. */
461         rtsp_strack_t track = { .id = id, .sout_id = sout_id,
462                                 .setup_fd = -1, .rtp_fd = -1 };
463         vlc_rand_bytes (&track.seq_init, sizeof (track.seq_init));
464         vlc_rand_bytes (&track.ssrc, sizeof (track.ssrc));
465
466         TAB_APPEND(session->trackc, session->trackv, track);
467         tr = session->trackv + session->trackc - 1;
468     }
469
470     *ssrc = ntohl(tr->ssrc);
471     *seq_init = tr->seq_init;
472
473     if (tr->rtp_fd != -1)
474     {
475         uint16_t seq;
476         rtp_add_sink(tr->sout_id, tr->rtp_fd, false, &seq);
477         /* To avoid race conditions, sout_id->i_seq_sent_next must
478          * be set here and now. Make sure the caller did its job
479          * properly when passing seq_init. */
480         assert(tr->seq_init == seq);
481     }
482
483     val = VLC_SUCCESS;
484 out:
485     vlc_mutex_unlock(&rtsp->lock);
486     return val;
487 }
488
489
490 /* Remove references to the RTP id when it is stopped */
491 void RtspTrackDetach( rtsp_stream_t *rtsp, const char *name,
492                       sout_stream_id_sys_t *sout_id )
493 {
494     rtsp_session_t *session;
495
496     vlc_mutex_lock(&rtsp->lock);
497     session = RtspClientGet(rtsp, name);
498
499     if (session == NULL)
500         goto out;
501
502     for (int i = 0; i < session->trackc; i++)
503     {
504         rtsp_strack_t *tr = session->trackv + i;
505         if (tr->sout_id == sout_id)
506         {
507             if (tr->setup_fd == -1)
508             {
509                 /* No (more) SETUP information: better get rid of the
510                  * track so that we can have new random ssrc and
511                  * seq_init next time. */
512                 TAB_ERASE(session->trackc, session->trackv, i);
513                 break;
514             }
515             /* We keep the SETUP information of the track, but stop it */
516             if (tr->rtp_fd != -1)
517             {
518                 rtp_del_sink(tr->sout_id, tr->rtp_fd);
519                 tr->rtp_fd = -1;
520             }
521             tr->sout_id = NULL;
522             break;
523         }
524     }
525
526 out:
527     vlc_mutex_unlock(&rtsp->lock);
528 }
529
530
531 /** rtsp must be locked */
532 static void RtspTrackClose( rtsp_strack_t *tr )
533 {
534     if (tr->setup_fd != -1)
535     {
536         if (tr->rtp_fd != -1)
537         {
538             rtp_del_sink(tr->sout_id, tr->rtp_fd);
539             tr->rtp_fd = -1;
540         }
541         net_Close(tr->setup_fd);
542         tr->setup_fd = -1;
543     }
544 }
545
546
547 /** Finds the next transport choice */
548 static inline const char *transport_next( const char *str )
549 {
550     /* Looks for comma */
551     str = strchr( str, ',' );
552     if( str == NULL )
553         return NULL; /* No more transport options */
554
555     str++; /* skips comma */
556     while( strchr( "\r\n\t ", *str ) )
557         str++;
558
559     return (*str) ? str : NULL;
560 }
561
562
563 /** Finds the next transport parameter */
564 static inline const char *parameter_next( const char *str )
565 {
566     while( strchr( ",;", *str ) == NULL )
567         str++;
568
569     return (*str == ';') ? (str + 1) : NULL;
570 }
571
572
573 static int64_t ParseNPT (const char *str)
574 {
575     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
576     locale_t oldloc = uselocale (loc);
577     unsigned hour, min;
578     float sec;
579
580     if (sscanf (str, "%u:%u:%f", &hour, &min, &sec) == 3)
581         sec += ((hour * 60) + min) * 60;
582     else
583     if (sscanf (str, "%f", &sec) != 1)
584         sec = -1;
585
586     if (loc != (locale_t)0)
587     {
588         uselocale (oldloc);
589         freelocale (loc);
590     }
591     return sec < 0 ? -1 : sec * CLOCK_FREQ;
592 }
593
594
595 /** RTSP requests handler
596  * @param id selected track for non-aggregate URLs,
597  *           NULL for aggregate URLs
598  */
599 static int RtspHandler( rtsp_stream_t *rtsp, rtsp_stream_id_t *id,
600                         httpd_client_t *cl,
601                         httpd_message_t *answer,
602                         const httpd_message_t *query )
603 {
604     vlc_object_t *owner = rtsp->owner;
605     char psz_sesbuf[17];
606     const char *psz_session = NULL, *psz;
607     char control[sizeof("rtsp://[]:12345") + NI_MAXNUMERICHOST
608                   + strlen( rtsp->psz_path )];
609     bool vod = rtsp->vod_media != NULL;
610     time_t now;
611
612     time (&now);
613
614     if( answer == NULL || query == NULL || cl == NULL )
615         return VLC_SUCCESS;
616     else
617     {
618         /* Build self-referential control URL */
619         char ip[NI_MAXNUMERICHOST], *ptr;
620         int port;
621
622         httpd_ServerIP( cl, ip, &port );
623         ptr = strchr( ip, '%' );
624         if( ptr != NULL )
625             *ptr = '\0';
626
627         if( strchr( ip, ':' ) != NULL )
628             sprintf( control, "rtsp://[%s]:%d%s", ip, port, rtsp->psz_path );
629         else
630             sprintf( control, "rtsp://%s:%d%s", ip, port, rtsp->psz_path );
631     }
632
633     /* */
634     answer->i_proto = HTTPD_PROTO_RTSP;
635     answer->i_version= 0;
636     answer->i_type   = HTTPD_MSG_ANSWER;
637     answer->i_body = 0;
638     answer->p_body = NULL;
639
640     httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
641
642     /* Date: is always allowed, and sometimes mandatory with RTSP/2.0. */
643     struct tm ut;
644     if (gmtime_r (&now, &ut) != NULL)
645     {   /* RFC1123 format, GMT is mandatory */
646         static const char wdays[7][4] = {
647             "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
648         static const char mons[12][4] = {
649             "Jan", "Feb", "Mar", "Apr", "May", "Jun",
650             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
651         httpd_MsgAdd (answer, "Date", "%s, %02u %s %04u %02u:%02u:%02u GMT",
652                       wdays[ut.tm_wday], ut.tm_mday, mons[ut.tm_mon],
653                       1900 + ut.tm_year, ut.tm_hour, ut.tm_min, ut.tm_sec);
654     }
655
656     if( query->i_proto != HTTPD_PROTO_RTSP )
657     {
658         answer->i_status = 505;
659     }
660     else
661     if( httpd_MsgGet( query, "Require" ) != NULL )
662     {
663         answer->i_status = 551;
664         httpd_MsgAdd( answer, "Unsupported", "%s",
665                       httpd_MsgGet( query, "Require" ) );
666     }
667     else
668     switch( query->i_type )
669     {
670         case HTTPD_MSG_DESCRIBE:
671         {   /* Aggregate-only */
672             if( id != NULL )
673             {
674                 answer->i_status = 460;
675                 break;
676             }
677
678             answer->i_status = 200;
679             httpd_MsgAdd( answer, "Content-Type",  "%s", "application/sdp" );
680             httpd_MsgAdd( answer, "Content-Base",  "%s", control );
681
682             answer->p_body = (uint8_t *) ( vod ?
683                 SDPGenerateVoD( rtsp->vod_media, control ) :
684                 SDPGenerate( (sout_stream_t *)owner, control ) );
685             if( answer->p_body != NULL )
686                 answer->i_body = strlen( (char *)answer->p_body );
687             else
688                 answer->i_status = 500;
689             break;
690         }
691
692         case HTTPD_MSG_SETUP:
693             /* Non-aggregate-only */
694             if( id == NULL )
695             {
696                 answer->i_status = 459;
697                 break;
698             }
699
700             psz_session = httpd_MsgGet( query, "Session" );
701             answer->i_status = 461;
702
703             for( const char *tpt = httpd_MsgGet( query, "Transport" );
704                  tpt != NULL;
705                  tpt = transport_next( tpt ) )
706             {
707                 bool b_multicast = true, b_unsupp = false;
708                 bool b_multicast_port_set = false;
709                 unsigned loport = 5004, hiport; /* from RFC3551 */
710                 unsigned mloport = 5004, mhiport = mloport + 1;
711
712                 /* Check transport protocol. */
713                 /* Currently, we only support RTP/AVP over UDP */
714                 if( strncmp( tpt, "RTP/AVP", 7 ) )
715                     continue;
716                 tpt += 7;
717                 if( strncmp( tpt, "/UDP", 4 ) == 0 )
718                     tpt += 4;
719                 if( strchr( ";,", *tpt ) == NULL )
720                     continue;
721
722                 /* Parse transport options */
723                 for( const char *opt = parameter_next( tpt );
724                      opt != NULL;
725                      opt = parameter_next( opt ) )
726                 {
727                     if( strncmp( opt, "multicast", 9 ) == 0)
728                         b_multicast = true;
729                     else
730                     if( strncmp( opt, "unicast", 7 ) == 0 )
731                         b_multicast = false;
732                     else
733                     if( sscanf( opt, "client_port=%u-%u", &loport, &hiport )
734                                 == 2 )
735                         ;
736                     else
737                     if( sscanf( opt, "port=%u-%u", &mloport, &mhiport )
738                                 == 2 )
739                         b_multicast_port_set = true;
740                     else
741                     if( strncmp( opt, "mode=", 5 ) == 0 )
742                     {
743                         if( strncasecmp( opt + 5, "play", 4 )
744                          && strncasecmp( opt + 5, "\"PLAY\"", 6 ) )
745                         {
746                             /* Not playing?! */
747                             b_unsupp = true;
748                             break;
749                         }
750                     }
751                     else
752                     if( strncmp( opt,"destination=", 12 ) == 0 )
753                     {
754                         answer->i_status = 403;
755                         b_unsupp = true;
756                     }
757                     else
758                     {
759                     /*
760                      * Every other option is unsupported:
761                      *
762                      * "source" and "append" are invalid (server-only);
763                      * "ssrc" also (as clarified per RFC2326bis).
764                      *
765                      * For multicast, "layers", "ttl" are set by the
766                      * stream output configuration.
767                      *
768                      * For unicast, we want to decide "server_port" values.
769                      *
770                      * "interleaved" is not implemented.
771                      */
772                         b_unsupp = true;
773                         break;
774                     }
775                 }
776
777                 if( b_unsupp )
778                     continue;
779
780                 if( b_multicast )
781                 {
782                     char dst[NI_MAXNUMERICHOST];
783                     int dport, ttl;
784                     if( id->mcast_fd == -1 )
785                         continue;
786
787                     net_GetPeerAddress(id->mcast_fd, dst, &dport);
788
789                     /* Checking for multicast port override */
790                     if( b_multicast_port_set
791                      && ((unsigned)dport != mloport
792                       || (unsigned)dport + 1 != mhiport))
793                     {
794                         answer->i_status = 551;
795                         continue;
796                     }
797
798                     ttl = var_InheritInteger(owner, "ttl");
799                     if (ttl <= 0)
800                     /* FIXME: the TTL is left to the OS default, we can
801                      * only guess that it's 1. */
802                         ttl = 1;
803
804                     if( psz_session == NULL )
805                     {
806                         /* Create a dummy session ID */
807                         snprintf( psz_sesbuf, sizeof( psz_sesbuf ), "%lu",
808                                   vlc_mrand48() );
809                         psz_session = psz_sesbuf;
810                     }
811                     answer->i_status = 200;
812
813                     httpd_MsgAdd( answer, "Transport",
814                                   "RTP/AVP/UDP;destination=%s;port=%u-%u;"
815                                   "ttl=%d;mode=play",
816                                   dst, dport, dport + 1, ttl );
817                      /* FIXME: this doesn't work with RTP + RTCP mux */
818                 }
819                 else
820                 {
821                     char ip[NI_MAXNUMERICHOST], src[NI_MAXNUMERICHOST];
822                     rtsp_session_t *ses = NULL;
823                     int fd, sport;
824                     uint32_t ssrc;
825
826                     if( httpd_ClientIP( cl, ip, NULL ) == NULL )
827                     {
828                         answer->i_status = 500;
829                         continue;
830                     }
831
832                     fd = net_ConnectDgram( owner, ip, loport, -1,
833                                            IPPROTO_UDP );
834                     if( fd == -1 )
835                     {
836                         msg_Err( owner,
837                                  "cannot create RTP socket for %s port %u",
838                                  ip, loport );
839                         answer->i_status = 500;
840                         continue;
841                     }
842
843                     /* Ignore any unexpected incoming packet */
844                     setsockopt (fd, SOL_SOCKET, SO_RCVBUF, &(int){ 0 },
845                                 sizeof (int));
846                     net_GetSockAddress( fd, src, &sport );
847
848                     vlc_mutex_lock( &rtsp->lock );
849                     if( psz_session == NULL )
850                     {
851                         ses = RtspClientNew( rtsp );
852                         snprintf( psz_sesbuf, sizeof( psz_sesbuf ), "%"PRIx64,
853                                   ses->id );
854                         psz_session = psz_sesbuf;
855                     }
856                     else
857                     {
858                         ses = RtspClientGet( rtsp, psz_session );
859                         if( ses == NULL )
860                         {
861                             answer->i_status = 454;
862                             vlc_mutex_unlock( &rtsp->lock );
863                             net_Close( fd );
864                             continue;
865                         }
866                     }
867                     RtspClientAlive(ses);
868
869                     rtsp_strack_t *tr = NULL;
870                     for (int i = 0; i < ses->trackc; i++)
871                     {
872                         if (ses->trackv[i].id == id)
873                         {
874                             tr = ses->trackv + i;
875                             break;
876                         }
877                     }
878
879                     if (tr == NULL)
880                     {
881                         /* Set up a new track */
882                         rtsp_strack_t track = { .id = id,
883                                                 .sout_id = id->sout_id,
884                                                 .setup_fd = fd,
885                                                 .rtp_fd = -1 };
886
887                         if (vod)
888                         {
889                             vlc_rand_bytes (&track.seq_init,
890                                             sizeof (track.seq_init));
891                             vlc_rand_bytes (&track.ssrc, sizeof (track.ssrc));
892                             ssrc = track.ssrc;
893                         }
894                         else
895                             ssrc = id->ssrc;
896
897                         TAB_APPEND(ses->trackc, ses->trackv, track);
898                     }
899                     else if (tr->setup_fd == -1)
900                     {
901                         /* The track was not SETUP, but it exists
902                          * because there is a sout_id running for it */
903                         tr->setup_fd = fd;
904                         ssrc = tr->ssrc;
905                     }
906                     else
907                     {
908                         /* The track is already set up, and we don't
909                          * support changing the transport parameters on
910                          * the fly */
911                         vlc_mutex_unlock( &rtsp->lock );
912                         answer->i_status = 455;
913                         net_Close( fd );
914                         break;
915                     }
916                     vlc_mutex_unlock( &rtsp->lock );
917
918                     httpd_ServerIP( cl, ip, NULL );
919
920                     /* Specify source IP only if it is different from the
921                      * RTSP control connection server address */
922                     if( strcmp( src, ip ) )
923                     {
924                         char *ptr = strchr( src, '%' );
925                         if( ptr != NULL ) *ptr = '\0'; /* remove scope ID */
926                     }
927                     else
928                         src[0] = '\0';
929
930                     httpd_MsgAdd( answer, "Transport",
931                                   "RTP/AVP/UDP;unicast%s%s;"
932                                   "client_port=%u-%u;server_port=%u-%u;"
933                                   "ssrc=%08X;mode=play",
934                                   src[0] ? ";source=" : "", src,
935                                   loport, loport + 1, sport, sport + 1, ssrc );
936
937                     answer->i_status = 200;
938                 }
939                 break;
940             }
941             break;
942
943         case HTTPD_MSG_PLAY:
944         {
945             rtsp_session_t *ses;
946             answer->i_status = 200;
947
948             psz_session = httpd_MsgGet( query, "Session" );
949             int64_t start = -1, end = -1, npt;
950             const char *range = httpd_MsgGet (query, "Range");
951             if (range != NULL)
952             {
953                 if (strncmp (range, "npt=", 4))
954                 {
955                     answer->i_status = 501;
956                     break;
957                 }
958
959                 start = ParseNPT (range + 4);
960                 range = strchr(range, '-');
961                 if (range != NULL && *(range + 1))
962                     end = ParseNPT (range + 1);
963
964                 if (end >= 0 && end < start)
965                 {
966                     answer->i_status = 457;
967                     break;
968                 }
969
970                 if (vod)
971                 {
972                     if (vod_check_range(rtsp->vod_media, psz_session,
973                                         start, end) != VLC_SUCCESS)
974                     {
975                         answer->i_status = 457;
976                         break;
977                     }
978                 }
979                 /* We accept start times of 0 even for broadcast streams
980                  * that already started */
981                 else if (start > 0 || end >= 0)
982                 {
983                     answer->i_status = 456;
984                     break;
985                 }
986             }
987             vlc_mutex_lock( &rtsp->lock );
988             ses = RtspClientGet( rtsp, psz_session );
989             if( ses != NULL )
990             {
991                 char info[ses->trackc * ( strlen( control ) + TRACK_PATH_SIZE
992                           + sizeof("url=;seq=65535;rtptime=4294967295, ")
993                                           - 1 ) + 1];
994                 size_t infolen = 0;
995                 RtspClientAlive(ses);
996
997                 sout_stream_id_sys_t *sout_id = NULL;
998                 if (vod)
999                 {
1000                     /* We don't keep a reference to the sout_stream_t,
1001                      * so we check if a sout_id is available instead. */
1002                     for (int i = 0; i < ses->trackc; i++)
1003                     {
1004                         sout_id = ses->trackv[i].sout_id;
1005                         if (sout_id != NULL)
1006                             break;
1007                     }
1008                 }
1009                 int64_t ts = rtp_get_ts(vod ? NULL : (sout_stream_t *)owner,
1010                                         sout_id, rtsp->vod_media, psz_session,
1011                                         vod ? NULL : &npt);
1012
1013                 for( int i = 0; i < ses->trackc; i++ )
1014                 {
1015                     rtsp_strack_t *tr = ses->trackv + i;
1016                     if( ( id == NULL ) || ( tr->id == id ) )
1017                     {
1018                         if (tr->setup_fd == -1)
1019                             /* Track not SETUP */
1020                             continue;
1021
1022                         uint16_t seq;
1023                         if( tr->rtp_fd == -1 )
1024                         {
1025                             /* Track not PLAYing yet */
1026                             if (tr->sout_id == NULL)
1027                                 /* Instance not running yet (VoD) */
1028                                 seq = tr->seq_init;
1029                             else
1030                             {
1031                                 /* Instance running, add a sink to it */
1032                                 tr->rtp_fd = dup_socket(tr->setup_fd);
1033                                 if (tr->rtp_fd == -1)
1034                                     continue;
1035
1036                                 rtp_add_sink( tr->sout_id, tr->rtp_fd,
1037                                               false, &seq );
1038                             }
1039                         }
1040                         else
1041                         {
1042                             /* Track already playing */
1043                             assert( tr->sout_id != NULL );
1044                             seq = rtp_get_seq( tr->sout_id );
1045                         }
1046                         char *url = RtspAppendTrackPath( tr->id, control );
1047                         infolen += sprintf( info + infolen,
1048                                     "url=%s;seq=%u;rtptime=%u, ",
1049                                     url != NULL ? url : "", seq,
1050                                     rtp_compute_ts( tr->id->clock_rate, ts ) );
1051                         free( url );
1052                     }
1053                 }
1054                 if( infolen > 0 )
1055                 {
1056                     info[infolen - 2] = '\0'; /* remove trailing ", " */
1057                     httpd_MsgAdd( answer, "RTP-Info", "%s", info );
1058                 }
1059             }
1060             vlc_mutex_unlock( &rtsp->lock );
1061
1062             if (ses != NULL)
1063             {
1064                 if (vod)
1065                 {
1066                     vod_play(rtsp->vod_media, psz_session, &start, end);
1067                     npt = start;
1068                 }
1069
1070                 double f_npt = (double) npt / CLOCK_FREQ;
1071                 httpd_MsgAdd( answer, "Range", "npt=%f-", f_npt );
1072             }
1073
1074             if( httpd_MsgGet( query, "Scale" ) != NULL )
1075                 httpd_MsgAdd( answer, "Scale", "1." );
1076             break;
1077         }
1078
1079         case HTTPD_MSG_PAUSE:
1080         {
1081             if (id == NULL && !vod)
1082             {
1083                 answer->i_status = 405;
1084                 httpd_MsgAdd( answer, "Allow",
1085                               "DESCRIBE, TEARDOWN, PLAY, GET_PARAMETER" );
1086                 break;
1087             }
1088
1089             rtsp_session_t *ses;
1090             answer->i_status = 200;
1091             psz_session = httpd_MsgGet( query, "Session" );
1092             vlc_mutex_lock( &rtsp->lock );
1093             ses = RtspClientGet( rtsp, psz_session );
1094             if (ses != NULL)
1095             {
1096                 if (id != NULL) /* "Mute" the selected track */
1097                 {
1098                     bool found = false;
1099                     for (int i = 0; i < ses->trackc; i++)
1100                     {
1101                         rtsp_strack_t *tr = ses->trackv + i;;
1102                         if (tr->id == id)
1103                         {
1104                             if (tr->setup_fd == -1)
1105                                 break;
1106
1107                             found = true;
1108                             if (tr->rtp_fd != -1)
1109                             {
1110                                 rtp_del_sink(tr->sout_id, tr->rtp_fd);
1111                                 tr->rtp_fd = -1;
1112                             }
1113                             break;
1114                         }
1115                     }
1116                     if (!found)
1117                         answer->i_status = 455;
1118                 }
1119                 RtspClientAlive(ses);
1120             }
1121             vlc_mutex_unlock( &rtsp->lock );
1122
1123             if (ses != NULL && id == NULL)
1124             {
1125                 assert(vod);
1126                 int64_t npt = 0;
1127                 vod_pause(rtsp->vod_media, psz_session, &npt);
1128                 double f_npt = (double) npt / CLOCK_FREQ;
1129                 httpd_MsgAdd( answer, "Range", "npt=%f-", f_npt );
1130             }
1131             break;
1132         }
1133
1134         case HTTPD_MSG_GETPARAMETER:
1135             if( query->i_body > 0 )
1136             {
1137                 answer->i_status = 451;
1138                 break;
1139             }
1140
1141             psz_session = httpd_MsgGet( query, "Session" );
1142             answer->i_status = 200;
1143             vlc_mutex_lock( &rtsp->lock );
1144             rtsp_session_t *ses = RtspClientGet( rtsp, psz_session );
1145             if (ses != NULL)
1146                 RtspClientAlive(ses);
1147             vlc_mutex_unlock( &rtsp->lock );
1148             break;
1149
1150         case HTTPD_MSG_TEARDOWN:
1151         {
1152             rtsp_session_t *ses;
1153
1154             answer->i_status = 200;
1155
1156             psz_session = httpd_MsgGet( query, "Session" );
1157
1158             vlc_mutex_lock( &rtsp->lock );
1159             ses = RtspClientGet( rtsp, psz_session );
1160             if( ses != NULL )
1161             {
1162                 if( id == NULL ) /* Delete the entire session */
1163                 {
1164                     RtspClientDel( rtsp, ses );
1165                     if (vod)
1166                         vod_stop(rtsp->vod_media, psz_session);
1167                     RtspUpdateTimer(rtsp);
1168                 }
1169                 else /* Delete one track from the session */
1170                 {
1171                     for( int i = 0; i < ses->trackc; i++ )
1172                     {
1173                         if( ses->trackv[i].id == id )
1174                         {
1175                             RtspTrackClose( &ses->trackv[i] );
1176                             /* Keep VoD tracks whose instance is still
1177                              * running */
1178                             if (!(vod && ses->trackv[i].sout_id != NULL))
1179                                 TAB_ERASE(ses->trackc, ses->trackv, i);
1180                         }
1181                     }
1182                     RtspClientAlive(ses);
1183                 }
1184             }
1185             vlc_mutex_unlock( &rtsp->lock );
1186             break;
1187         }
1188
1189         default:
1190             return VLC_EGENERIC;
1191     }
1192
1193     if( psz_session )
1194     {
1195         if (rtsp->timeout > 0)
1196             httpd_MsgAdd( answer, "Session", "%s;timeout=%d", psz_session,
1197                                                               rtsp->timeout );
1198         else
1199             httpd_MsgAdd( answer, "Session", "%s", psz_session );
1200     }
1201
1202     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
1203     httpd_MsgAdd( answer, "Cache-Control", "no-cache" );
1204
1205     psz = httpd_MsgGet( query, "Cseq" );
1206     if( psz != NULL )
1207         httpd_MsgAdd( answer, "Cseq", "%s", psz );
1208     psz = httpd_MsgGet( query, "Timestamp" );
1209     if( psz != NULL )
1210         httpd_MsgAdd( answer, "Timestamp", "%s", psz );
1211
1212     return VLC_SUCCESS;
1213 }
1214
1215
1216 /** Aggregate RTSP callback */
1217 static int RtspCallback( httpd_callback_sys_t *p_args,
1218                          httpd_client_t *cl,
1219                          httpd_message_t *answer,
1220                          const httpd_message_t *query )
1221 {
1222     return RtspHandler( (rtsp_stream_t *)p_args, NULL, cl, answer, query );
1223 }
1224
1225
1226 /** Non-aggregate RTSP callback */
1227 static int RtspCallbackId( httpd_callback_sys_t *p_args,
1228                            httpd_client_t *cl,
1229                            httpd_message_t *answer,
1230                            const httpd_message_t *query )
1231 {
1232     rtsp_stream_id_t *id = (rtsp_stream_id_t *)p_args;
1233     return RtspHandler( id->stream, id, cl, answer, query );
1234 }