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