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