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