]> git.sesse.net Git - ffmpeg/blob - libavformat/rtspdec.c
Merge commit '13e4f2c7f7857feb6885f0c2ea8c9ddf438f46ea'
[ffmpeg] / libavformat / rtspdec.c
1 /*
2  * RTSP demuxer
3  * Copyright (c) 2002 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/avstring.h"
23 #include "libavutil/intreadwrite.h"
24 #include "libavutil/mathematics.h"
25 #include "libavutil/random_seed.h"
26 #include "libavutil/time.h"
27 #include "avformat.h"
28
29 #include "internal.h"
30 #include "network.h"
31 #include "os_support.h"
32 #include "rtpproto.h"
33 #include "rtsp.h"
34 #include "rdt.h"
35 #include "url.h"
36
37 static const struct RTSPStatusMessage {
38     enum RTSPStatusCode code;
39     const char *message;
40 } status_messages[] = {
41     { RTSP_STATUS_OK,             "OK"                               },
42     { RTSP_STATUS_METHOD,         "Method Not Allowed"               },
43     { RTSP_STATUS_BANDWIDTH,      "Not Enough Bandwidth"             },
44     { RTSP_STATUS_SESSION,        "Session Not Found"                },
45     { RTSP_STATUS_STATE,          "Method Not Valid in This State"   },
46     { RTSP_STATUS_AGGREGATE,      "Aggregate operation not allowed"  },
47     { RTSP_STATUS_ONLY_AGGREGATE, "Only aggregate operation allowed" },
48     { RTSP_STATUS_TRANSPORT,      "Unsupported transport"            },
49     { RTSP_STATUS_INTERNAL,       "Internal Server Error"            },
50     { RTSP_STATUS_SERVICE,        "Service Unavailable"              },
51     { RTSP_STATUS_VERSION,        "RTSP Version not supported"       },
52     { 0,                          "NULL"                             }
53 };
54
55 static int rtsp_read_close(AVFormatContext *s)
56 {
57     RTSPState *rt = s->priv_data;
58
59     if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN))
60         ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
61
62     ff_rtsp_close_streams(s);
63     ff_rtsp_close_connections(s);
64     ff_network_close();
65     rt->real_setup = NULL;
66     av_freep(&rt->real_setup_cache);
67     return 0;
68 }
69
70 static inline int read_line(AVFormatContext *s, char *rbuf, const int rbufsize,
71                             int *rbuflen)
72 {
73     RTSPState *rt = s->priv_data;
74     int idx       = 0;
75     int ret       = 0;
76     *rbuflen      = 0;
77
78     do {
79         ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1);
80         if (ret <= 0)
81             return ret ? ret : AVERROR_EOF;
82         if (rbuf[idx] == '\r') {
83             /* Ignore */
84         } else if (rbuf[idx] == '\n') {
85             rbuf[idx] = '\0';
86             *rbuflen  = idx;
87             return 0;
88         } else
89             idx++;
90     } while (idx < rbufsize);
91     av_log(s, AV_LOG_ERROR, "Message too long\n");
92     return AVERROR(EIO);
93 }
94
95 static int rtsp_send_reply(AVFormatContext *s, enum RTSPStatusCode code,
96                            const char *extracontent, uint16_t seq)
97 {
98     RTSPState *rt = s->priv_data;
99     char message[4096];
100     int index = 0;
101     while (status_messages[index].code) {
102         if (status_messages[index].code == code) {
103             snprintf(message, sizeof(message), "RTSP/1.0 %d %s\r\n",
104                      code, status_messages[index].message);
105             break;
106         }
107         index++;
108     }
109     if (!status_messages[index].code)
110         return AVERROR(EINVAL);
111     av_strlcatf(message, sizeof(message), "CSeq: %d\r\n", seq);
112     av_strlcatf(message, sizeof(message), "Server: %s\r\n", LIBAVFORMAT_IDENT);
113     if (extracontent)
114         av_strlcat(message, extracontent, sizeof(message));
115     av_strlcat(message, "\r\n", sizeof(message));
116     av_dlog(s, "Sending response:\n%s", message);
117     ffurl_write(rt->rtsp_hd_out, message, strlen(message));
118
119     return 0;
120 }
121
122 static inline int check_sessionid(AVFormatContext *s,
123                                   RTSPMessageHeader *request)
124 {
125     RTSPState *rt = s->priv_data;
126     unsigned char *session_id = rt->session_id;
127     if (!session_id[0]) {
128         av_log(s, AV_LOG_WARNING, "There is no session-id at the moment\n");
129         return 0;
130     }
131     if (strcmp(session_id, request->session_id)) {
132         av_log(s, AV_LOG_ERROR, "Unexpected session-id %s\n",
133                request->session_id);
134         rtsp_send_reply(s, RTSP_STATUS_SESSION, NULL, request->seq);
135         return AVERROR_STREAM_NOT_FOUND;
136     }
137     return 0;
138 }
139
140 static inline int rtsp_read_request(AVFormatContext *s,
141                                     RTSPMessageHeader *request,
142                                     const char *method)
143 {
144     RTSPState *rt = s->priv_data;
145     char rbuf[1024];
146     int rbuflen, ret;
147     do {
148         ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
149         if (ret)
150             return ret;
151         if (rbuflen > 1) {
152             av_dlog(s, "Parsing[%d]: %s\n", rbuflen, rbuf);
153             ff_rtsp_parse_line(request, rbuf, rt, method);
154         }
155     } while (rbuflen > 0);
156     if (request->seq != rt->seq + 1) {
157         av_log(s, AV_LOG_ERROR, "Unexpected Sequence number %d\n",
158                request->seq);
159         return AVERROR(EINVAL);
160     }
161     if (rt->session_id[0] && strcmp(method, "OPTIONS")) {
162         ret = check_sessionid(s, request);
163         if (ret)
164             return ret;
165     }
166
167     return 0;
168 }
169
170 static int rtsp_read_announce(AVFormatContext *s)
171 {
172     RTSPState *rt             = s->priv_data;
173     RTSPMessageHeader request = { 0 };
174     char sdp[4096];
175     int  ret;
176
177     ret = rtsp_read_request(s, &request, "ANNOUNCE");
178     if (ret)
179         return ret;
180     rt->seq++;
181     if (strcmp(request.content_type, "application/sdp")) {
182         av_log(s, AV_LOG_ERROR, "Unexpected content type %s\n",
183                request.content_type);
184         rtsp_send_reply(s, RTSP_STATUS_SERVICE, NULL, request.seq);
185         return AVERROR_OPTION_NOT_FOUND;
186     }
187     if (request.content_length && request.content_length < sizeof(sdp) - 1) {
188         /* Read SDP */
189         if (ffurl_read_complete(rt->rtsp_hd, sdp, request.content_length)
190             < request.content_length) {
191             av_log(s, AV_LOG_ERROR,
192                    "Unable to get complete SDP Description in ANNOUNCE\n");
193             rtsp_send_reply(s, RTSP_STATUS_INTERNAL, NULL, request.seq);
194             return AVERROR(EIO);
195         }
196         sdp[request.content_length] = '\0';
197         av_log(s, AV_LOG_VERBOSE, "SDP: %s\n", sdp);
198         ret = ff_sdp_parse(s, sdp);
199         if (ret)
200             return ret;
201         rtsp_send_reply(s, RTSP_STATUS_OK, NULL, request.seq);
202         return 0;
203     }
204     av_log(s, AV_LOG_ERROR,
205            "Content-Length header value exceeds sdp allocated buffer (4KB)\n");
206     rtsp_send_reply(s, RTSP_STATUS_INTERNAL,
207                     "Content-Length exceeds buffer size", request.seq);
208     return AVERROR(EIO);
209 }
210
211 static int rtsp_read_options(AVFormatContext *s)
212 {
213     RTSPState *rt             = s->priv_data;
214     RTSPMessageHeader request = { 0 };
215     int ret                   = 0;
216
217     /* Parsing headers */
218     ret = rtsp_read_request(s, &request, "OPTIONS");
219     if (ret)
220         return ret;
221     rt->seq++;
222     /* Send Reply */
223     rtsp_send_reply(s, RTSP_STATUS_OK,
224                     "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, RECORD\r\n",
225                     request.seq);
226     return 0;
227 }
228
229 static int rtsp_read_setup(AVFormatContext *s, char* host, char *controlurl)
230 {
231     RTSPState *rt             = s->priv_data;
232     RTSPMessageHeader request = { 0 };
233     int ret                   = 0;
234     char url[1024];
235     RTSPStream *rtsp_st;
236     char responseheaders[1024];
237     int localport    = -1;
238     int transportidx = 0;
239     int streamid     = 0;
240
241     ret = rtsp_read_request(s, &request, "SETUP");
242     if (ret)
243         return ret;
244     rt->seq++;
245     if (!request.nb_transports) {
246         av_log(s, AV_LOG_ERROR, "No transport defined in SETUP\n");
247         return AVERROR_INVALIDDATA;
248     }
249     for (transportidx = 0; transportidx < request.nb_transports;
250          transportidx++) {
251         if (!request.transports[transportidx].mode_record ||
252             (request.transports[transportidx].lower_transport !=
253              RTSP_LOWER_TRANSPORT_UDP &&
254              request.transports[transportidx].lower_transport !=
255              RTSP_LOWER_TRANSPORT_TCP)) {
256             av_log(s, AV_LOG_ERROR, "mode=record/receive not set or transport"
257                    " protocol not supported (yet)\n");
258             return AVERROR_INVALIDDATA;
259         }
260     }
261     if (request.nb_transports > 1)
262         av_log(s, AV_LOG_WARNING, "More than one transport not supported, "
263                "using first of all\n");
264     for (streamid = 0; streamid < rt->nb_rtsp_streams; streamid++) {
265         if (!strcmp(rt->rtsp_streams[streamid]->control_url,
266                     controlurl))
267             break;
268     }
269     if (streamid == rt->nb_rtsp_streams) {
270         av_log(s, AV_LOG_ERROR, "Unable to find requested track\n");
271         return AVERROR_STREAM_NOT_FOUND;
272     }
273     rtsp_st   = rt->rtsp_streams[streamid];
274     localport = rt->rtp_port_min;
275
276     if (request.transports[0].lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
277         rt->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
278         if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
279             rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
280             return ret;
281         }
282         rtsp_st->interleaved_min = request.transports[0].interleaved_min;
283         rtsp_st->interleaved_max = request.transports[0].interleaved_max;
284         snprintf(responseheaders, sizeof(responseheaders), "Transport: "
285                  "RTP/AVP/TCP;unicast;mode=receive;interleaved=%d-%d"
286                  "\r\n", request.transports[0].interleaved_min,
287                  request.transports[0].interleaved_max);
288     } else {
289         do {
290             AVDictionary *opts = NULL;
291             char buf[256];
292             snprintf(buf, sizeof(buf), "%d", rt->buffer_size);
293             av_dict_set(&opts, "buffer_size", buf, 0);
294             ff_url_join(url, sizeof(url), "rtp", NULL, host, localport, NULL);
295             av_dlog(s, "Opening: %s", url);
296             ret = ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
297                              &s->interrupt_callback, &opts);
298             av_dict_free(&opts);
299             if (ret)
300                 localport += 2;
301         } while (ret || localport > rt->rtp_port_max);
302         if (localport > rt->rtp_port_max) {
303             rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
304             return ret;
305         }
306
307         av_dlog(s, "Listening on: %d",
308                 ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle));
309         if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
310             rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
311             return ret;
312         }
313
314         localport = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
315         snprintf(responseheaders, sizeof(responseheaders), "Transport: "
316                  "RTP/AVP/UDP;unicast;mode=receive;source=%s;"
317                  "client_port=%d-%d;server_port=%d-%d\r\n",
318                  host, request.transports[0].client_port_min,
319                  request.transports[0].client_port_max, localport,
320                  localport + 1);
321     }
322
323     /* Establish sessionid if not previously set */
324     /* Put this in a function? */
325     /* RFC 2326: session id must be at least 8 digits */
326     while (strlen(rt->session_id) < 8)
327         av_strlcatf(rt->session_id, 512, "%u", av_get_random_seed());
328
329     av_strlcatf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
330                 rt->session_id);
331     /* Send Reply */
332     rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
333
334     rt->state = RTSP_STATE_PAUSED;
335     return 0;
336 }
337
338 static int rtsp_read_record(AVFormatContext *s)
339 {
340     RTSPState *rt             = s->priv_data;
341     RTSPMessageHeader request = { 0 };
342     int ret                   = 0;
343     char responseheaders[1024];
344
345     ret = rtsp_read_request(s, &request, "RECORD");
346     if (ret)
347         return ret;
348     ret = check_sessionid(s, &request);
349     if (ret)
350         return ret;
351     rt->seq++;
352     snprintf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
353              rt->session_id);
354     rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
355
356     rt->state = RTSP_STATE_STREAMING;
357     return 0;
358 }
359
360 static inline int parse_command_line(AVFormatContext *s, const char *line,
361                                      int linelen, char *uri, int urisize,
362                                      char *method, int methodsize,
363                                      enum RTSPMethod *methodcode)
364 {
365     RTSPState *rt = s->priv_data;
366     const char *linept, *searchlinept;
367     linept = strchr(line, ' ');
368
369     if (!linept) {
370         av_log(s, AV_LOG_ERROR, "Error parsing method string\n");
371         return AVERROR_INVALIDDATA;
372     }
373
374     if (linept - line > methodsize - 1) {
375         av_log(s, AV_LOG_ERROR, "Method string too long\n");
376         return AVERROR(EIO);
377     }
378     memcpy(method, line, linept - line);
379     method[linept - line] = '\0';
380     linept++;
381     if (!strcmp(method, "ANNOUNCE"))
382         *methodcode = ANNOUNCE;
383     else if (!strcmp(method, "OPTIONS"))
384         *methodcode = OPTIONS;
385     else if (!strcmp(method, "RECORD"))
386         *methodcode = RECORD;
387     else if (!strcmp(method, "SETUP"))
388         *methodcode = SETUP;
389     else if (!strcmp(method, "PAUSE"))
390         *methodcode = PAUSE;
391     else if (!strcmp(method, "TEARDOWN"))
392         *methodcode = TEARDOWN;
393     else
394         *methodcode = UNKNOWN;
395     /* Check method with the state  */
396     if (rt->state == RTSP_STATE_IDLE) {
397         if ((*methodcode != ANNOUNCE) && (*methodcode != OPTIONS)) {
398             av_log(s, AV_LOG_ERROR, "Unexpected command in Idle State %s\n",
399                    line);
400             return AVERROR_PROTOCOL_NOT_FOUND;
401         }
402     } else if (rt->state == RTSP_STATE_PAUSED) {
403         if ((*methodcode != OPTIONS) && (*methodcode != RECORD)
404             && (*methodcode != SETUP)) {
405             av_log(s, AV_LOG_ERROR, "Unexpected command in Paused State %s\n",
406                    line);
407             return AVERROR_PROTOCOL_NOT_FOUND;
408         }
409     } else if (rt->state == RTSP_STATE_STREAMING) {
410         if ((*methodcode != PAUSE) && (*methodcode != OPTIONS)
411             && (*methodcode != TEARDOWN)) {
412             av_log(s, AV_LOG_ERROR, "Unexpected command in Streaming State"
413                    " %s\n", line);
414             return AVERROR_PROTOCOL_NOT_FOUND;
415         }
416     } else {
417         av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
418         return AVERROR_BUG;
419     }
420
421     searchlinept = strchr(linept, ' ');
422     if (!searchlinept) {
423         av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
424         return AVERROR_INVALIDDATA;
425     }
426     if (searchlinept - linept > urisize - 1) {
427         av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
428         return AVERROR(EIO);
429     }
430     memcpy(uri, linept, searchlinept - linept);
431     uri[searchlinept - linept] = '\0';
432     if (strcmp(rt->control_uri, uri)) {
433         char host[128], path[512], auth[128];
434         int port;
435         char ctl_host[128], ctl_path[512], ctl_auth[128];
436         int ctl_port;
437         av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
438                      path, sizeof(path), uri);
439         av_url_split(NULL, 0, ctl_auth, sizeof(ctl_auth), ctl_host,
440                      sizeof(ctl_host), &ctl_port, ctl_path, sizeof(ctl_path),
441                      rt->control_uri);
442         if (strcmp(host, ctl_host))
443             av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
444                    host, ctl_host);
445         if (strcmp(path, ctl_path) && *methodcode != SETUP)
446             av_log(s, AV_LOG_WARNING, "WARNING: Path %s differs from expected"
447                    " %s\n", path, ctl_path);
448         if (*methodcode == ANNOUNCE) {
449             av_log(s, AV_LOG_INFO,
450                    "Updating control URI to %s\n", uri);
451             av_strlcpy(rt->control_uri, uri, sizeof(rt->control_uri));
452         }
453     }
454
455     linept = searchlinept + 1;
456     if (!av_strstart(linept, "RTSP/1.0", NULL)) {
457         av_log(s, AV_LOG_ERROR, "Error parsing protocol or version\n");
458         return AVERROR_PROTOCOL_NOT_FOUND;
459     }
460     return 0;
461 }
462
463 int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
464 {
465     RTSPState *rt = s->priv_data;
466     unsigned char rbuf[4096];
467     unsigned char method[10];
468     char uri[500];
469     int ret;
470     int rbuflen               = 0;
471     RTSPMessageHeader request = { 0 };
472     enum RTSPMethod methodcode;
473
474     ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
475     if (ret < 0)
476         return ret;
477     ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
478                              sizeof(method), &methodcode);
479     if (ret) {
480         av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
481         return ret;
482     }
483
484     ret = rtsp_read_request(s, &request, method);
485     if (ret)
486         return ret;
487     rt->seq++;
488     if (methodcode == PAUSE) {
489         rt->state = RTSP_STATE_PAUSED;
490         ret       = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
491         // TODO: Missing date header in response
492     } else if (methodcode == OPTIONS) {
493         ret = rtsp_send_reply(s, RTSP_STATUS_OK,
494                               "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, "
495                               "RECORD\r\n", request.seq);
496     } else if (methodcode == TEARDOWN) {
497         rt->state = RTSP_STATE_IDLE;
498         ret       = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
499         return 0;
500     }
501     return ret;
502 }
503
504 static int rtsp_read_play(AVFormatContext *s)
505 {
506     RTSPState *rt = s->priv_data;
507     RTSPMessageHeader reply1, *reply = &reply1;
508     int i;
509     char cmd[1024];
510
511     av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
512     rt->nb_byes = 0;
513
514     if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
515         for (i = 0; i < rt->nb_rtsp_streams; i++) {
516             RTSPStream *rtsp_st = rt->rtsp_streams[i];
517             /* Try to initialize the connection state in a
518              * potential NAT router by sending dummy packets.
519              * RTP/RTCP dummy packets are used for RDT, too.
520              */
521             if (rtsp_st->rtp_handle &&
522                 !(rt->server_type == RTSP_SERVER_WMS && i > 1))
523                 ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
524         }
525     }
526     if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
527         if (rt->transport == RTSP_TRANSPORT_RTP) {
528             for (i = 0; i < rt->nb_rtsp_streams; i++) {
529                 RTSPStream *rtsp_st = rt->rtsp_streams[i];
530                 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
531                 if (!rtpctx)
532                     continue;
533                 ff_rtp_reset_packet_queue(rtpctx);
534                 rtpctx->last_rtcp_ntp_time  = AV_NOPTS_VALUE;
535                 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
536                 rtpctx->base_timestamp      = 0;
537                 rtpctx->timestamp           = 0;
538                 rtpctx->unwrapped_timestamp = 0;
539                 rtpctx->rtcp_ts_offset      = 0;
540             }
541         }
542         if (rt->state == RTSP_STATE_PAUSED) {
543             cmd[0] = 0;
544         } else {
545             snprintf(cmd, sizeof(cmd),
546                      "Range: npt=%"PRId64".%03"PRId64"-\r\n",
547                      rt->seek_timestamp / AV_TIME_BASE,
548                      rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
549         }
550         ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
551         if (reply->status_code != RTSP_STATUS_OK) {
552             return ff_rtsp_averror(reply->status_code, -1);
553         }
554         if (rt->transport == RTSP_TRANSPORT_RTP &&
555             reply->range_start != AV_NOPTS_VALUE) {
556             for (i = 0; i < rt->nb_rtsp_streams; i++) {
557                 RTSPStream *rtsp_st = rt->rtsp_streams[i];
558                 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
559                 AVStream *st = NULL;
560                 if (!rtpctx || rtsp_st->stream_index < 0)
561                     continue;
562
563                 st = s->streams[rtsp_st->stream_index];
564                 rtpctx->range_start_offset =
565                     av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
566                                  st->time_base);
567             }
568         }
569     }
570     rt->state = RTSP_STATE_STREAMING;
571     return 0;
572 }
573
574 /* pause the stream */
575 static int rtsp_read_pause(AVFormatContext *s)
576 {
577     RTSPState *rt = s->priv_data;
578     RTSPMessageHeader reply1, *reply = &reply1;
579
580     if (rt->state != RTSP_STATE_STREAMING)
581         return 0;
582     else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
583         ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
584         if (reply->status_code != RTSP_STATUS_OK) {
585             return ff_rtsp_averror(reply->status_code, -1);
586         }
587     }
588     rt->state = RTSP_STATE_PAUSED;
589     return 0;
590 }
591
592 int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
593 {
594     RTSPState *rt = s->priv_data;
595     char cmd[1024];
596     unsigned char *content = NULL;
597     int ret;
598
599     /* describe the stream */
600     snprintf(cmd, sizeof(cmd),
601              "Accept: application/sdp\r\n");
602     if (rt->server_type == RTSP_SERVER_REAL) {
603         /**
604          * The Require: attribute is needed for proper streaming from
605          * Realmedia servers.
606          */
607         av_strlcat(cmd,
608                    "Require: com.real.retain-entity-for-setup\r\n",
609                    sizeof(cmd));
610     }
611     ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
612     if (reply->status_code != RTSP_STATUS_OK) {
613         av_freep(&content);
614         return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
615     }
616     if (!content)
617         return AVERROR_INVALIDDATA;
618
619     av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
620     /* now we got the SDP description, we parse it */
621     ret = ff_sdp_parse(s, (const char *)content);
622     av_freep(&content);
623     if (ret < 0)
624         return ret;
625
626     return 0;
627 }
628
629 static int rtsp_listen(AVFormatContext *s)
630 {
631     RTSPState *rt = s->priv_data;
632     char proto[128], host[128], path[512], auth[128];
633     char uri[500];
634     int port;
635     int default_port = RTSP_DEFAULT_PORT;
636     char tcpname[500];
637     const char *lower_proto = "tcp";
638     unsigned char rbuf[4096];
639     unsigned char method[10];
640     int rbuflen = 0;
641     int ret;
642     enum RTSPMethod methodcode;
643
644     /* extract hostname and port */
645     av_url_split(proto, sizeof(proto), auth, sizeof(auth), host, sizeof(host),
646                  &port, path, sizeof(path), s->filename);
647
648     /* ff_url_join. No authorization by now (NULL) */
649     ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL, host,
650                 port, "%s", path);
651
652     if (!strcmp(proto, "rtsps")) {
653         lower_proto  = "tls";
654         default_port = RTSPS_DEFAULT_PORT;
655     }
656
657     if (port < 0)
658         port = default_port;
659
660     /* Create TCP connection */
661     ff_url_join(tcpname, sizeof(tcpname), lower_proto, NULL, host, port,
662                 "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
663
664     if (ret = ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
665                          &s->interrupt_callback, NULL)) {
666         av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
667         return ret;
668     }
669     rt->state       = RTSP_STATE_IDLE;
670     rt->rtsp_hd_out = rt->rtsp_hd;
671     for (;;) { /* Wait for incoming RTSP messages */
672         ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
673         if (ret < 0)
674             return ret;
675         ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
676                                  sizeof(method), &methodcode);
677         if (ret) {
678             av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
679             return ret;
680         }
681
682         if (methodcode == ANNOUNCE) {
683             ret       = rtsp_read_announce(s);
684             rt->state = RTSP_STATE_PAUSED;
685         } else if (methodcode == OPTIONS) {
686             ret = rtsp_read_options(s);
687         } else if (methodcode == RECORD) {
688             ret = rtsp_read_record(s);
689             if (!ret)
690                 return 0; // We are ready for streaming
691         } else if (methodcode == SETUP)
692             ret = rtsp_read_setup(s, host, uri);
693         if (ret) {
694             ffurl_close(rt->rtsp_hd);
695             return AVERROR_INVALIDDATA;
696         }
697     }
698     return 0;
699 }
700
701 static int rtsp_probe(AVProbeData *p)
702 {
703     if (
704 #if CONFIG_TLS_PROTOCOL
705         av_strstart(p->filename, "rtsps:", NULL) ||
706 #endif
707         av_strstart(p->filename, "rtsp:", NULL))
708         return AVPROBE_SCORE_MAX;
709     return 0;
710 }
711
712 static int rtsp_read_header(AVFormatContext *s)
713 {
714     RTSPState *rt = s->priv_data;
715     int ret;
716
717     if (rt->initial_timeout > 0)
718         rt->rtsp_flags |= RTSP_FLAG_LISTEN;
719
720     if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
721         ret = rtsp_listen(s);
722         if (ret)
723             return ret;
724     } else {
725         ret = ff_rtsp_connect(s);
726         if (ret)
727             return ret;
728
729         rt->real_setup_cache = !s->nb_streams ? NULL :
730             av_mallocz_array(s->nb_streams, 2 * sizeof(*rt->real_setup_cache));
731         if (!rt->real_setup_cache && s->nb_streams)
732             return AVERROR(ENOMEM);
733         rt->real_setup = rt->real_setup_cache + s->nb_streams;
734
735         if (rt->initial_pause) {
736             /* do not start immediately */
737         } else {
738             if ((ret = rtsp_read_play(s)) < 0) {
739                 ff_rtsp_close_streams(s);
740                 ff_rtsp_close_connections(s);
741                 return ret;
742             }
743         }
744     }
745
746     return 0;
747 }
748
749 int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
750                             uint8_t *buf, int buf_size)
751 {
752     RTSPState *rt = s->priv_data;
753     int id, len, i, ret;
754     RTSPStream *rtsp_st;
755
756     av_dlog(s, "tcp_read_packet:\n");
757 redo:
758     for (;;) {
759         RTSPMessageHeader reply;
760
761         ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
762         if (ret < 0)
763             return ret;
764         if (ret == 1) /* received '$' */
765             break;
766         /* XXX: parse message */
767         if (rt->state != RTSP_STATE_STREAMING)
768             return 0;
769     }
770     ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
771     if (ret != 3)
772         return -1;
773     id  = buf[0];
774     len = AV_RB16(buf + 1);
775     av_dlog(s, "id=%d len=%d\n", id, len);
776     if (len > buf_size || len < 8)
777         goto redo;
778     /* get the data */
779     ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
780     if (ret != len)
781         return -1;
782     if (rt->transport == RTSP_TRANSPORT_RDT &&
783         ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
784         return -1;
785
786     /* find the matching stream */
787     for (i = 0; i < rt->nb_rtsp_streams; i++) {
788         rtsp_st = rt->rtsp_streams[i];
789         if (id >= rtsp_st->interleaved_min &&
790             id <= rtsp_st->interleaved_max)
791             goto found;
792     }
793     goto redo;
794 found:
795     *prtsp_st = rtsp_st;
796     return len;
797 }
798
799 static int resetup_tcp(AVFormatContext *s)
800 {
801     RTSPState *rt = s->priv_data;
802     char host[1024];
803     int port;
804
805     av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
806                  s->filename);
807     ff_rtsp_undo_setup(s, 0);
808     return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
809                                       rt->real_challenge);
810 }
811
812 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
813 {
814     RTSPState *rt = s->priv_data;
815     int ret;
816     RTSPMessageHeader reply1, *reply = &reply1;
817     char cmd[1024];
818
819 retry:
820     if (rt->server_type == RTSP_SERVER_REAL) {
821         int i;
822
823         for (i = 0; i < s->nb_streams; i++)
824             rt->real_setup[i] = s->streams[i]->discard;
825
826         if (!rt->need_subscription) {
827             if (memcmp (rt->real_setup, rt->real_setup_cache,
828                         sizeof(enum AVDiscard) * s->nb_streams)) {
829                 snprintf(cmd, sizeof(cmd),
830                          "Unsubscribe: %s\r\n",
831                          rt->last_subscription);
832                 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
833                                  cmd, reply, NULL);
834                 if (reply->status_code != RTSP_STATUS_OK)
835                     return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
836                 rt->need_subscription = 1;
837             }
838         }
839
840         if (rt->need_subscription) {
841             int r, rule_nr, first = 1;
842
843             memcpy(rt->real_setup_cache, rt->real_setup,
844                    sizeof(enum AVDiscard) * s->nb_streams);
845             rt->last_subscription[0] = 0;
846
847             snprintf(cmd, sizeof(cmd),
848                      "Subscribe: ");
849             for (i = 0; i < rt->nb_rtsp_streams; i++) {
850                 rule_nr = 0;
851                 for (r = 0; r < s->nb_streams; r++) {
852                     if (s->streams[r]->id == i) {
853                         if (s->streams[r]->discard != AVDISCARD_ALL) {
854                             if (!first)
855                                 av_strlcat(rt->last_subscription, ",",
856                                            sizeof(rt->last_subscription));
857                             ff_rdt_subscribe_rule(
858                                 rt->last_subscription,
859                                 sizeof(rt->last_subscription), i, rule_nr);
860                             first = 0;
861                         }
862                         rule_nr++;
863                     }
864                 }
865             }
866             av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
867             ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
868                              cmd, reply, NULL);
869             if (reply->status_code != RTSP_STATUS_OK)
870                 return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
871             rt->need_subscription = 0;
872
873             if (rt->state == RTSP_STATE_STREAMING)
874                 rtsp_read_play (s);
875         }
876     }
877
878     ret = ff_rtsp_fetch_packet(s, pkt);
879     if (ret < 0) {
880         if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
881             if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
882                 rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
883                 RTSPMessageHeader reply1, *reply = &reply1;
884                 av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
885                 if (rtsp_read_pause(s) != 0)
886                     return -1;
887                 // TEARDOWN is required on Real-RTSP, but might make
888                 // other servers close the connection.
889                 if (rt->server_type == RTSP_SERVER_REAL)
890                     ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
891                                      reply, NULL);
892                 rt->session_id[0] = '\0';
893                 if (resetup_tcp(s) == 0) {
894                     rt->state = RTSP_STATE_IDLE;
895                     rt->need_subscription = 1;
896                     if (rtsp_read_play(s) != 0)
897                         return -1;
898                     goto retry;
899                 }
900             }
901         }
902         return ret;
903     }
904     rt->packets++;
905
906     if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) {
907         /* send dummy request to keep TCP connection alive */
908         if ((av_gettime_relative() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
909             rt->auth_state.stale) {
910             if (rt->server_type == RTSP_SERVER_WMS ||
911                 (rt->server_type != RTSP_SERVER_REAL &&
912                  rt->get_parameter_supported)) {
913                 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
914             } else {
915                 ff_rtsp_send_cmd_async(s, "OPTIONS", rt->control_uri, NULL);
916             }
917             /* The stale flag should be reset when creating the auth response in
918              * ff_rtsp_send_cmd_async, but reset it here just in case we never
919              * called the auth code (if we didn't have any credentials set). */
920             rt->auth_state.stale = 0;
921         }
922     }
923
924     return 0;
925 }
926
927 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
928                           int64_t timestamp, int flags)
929 {
930     RTSPState *rt = s->priv_data;
931     int ret;
932
933     rt->seek_timestamp = av_rescale_q(timestamp,
934                                       s->streams[stream_index]->time_base,
935                                       AV_TIME_BASE_Q);
936     switch(rt->state) {
937     default:
938     case RTSP_STATE_IDLE:
939         break;
940     case RTSP_STATE_STREAMING:
941         if ((ret = rtsp_read_pause(s)) != 0)
942             return ret;
943         rt->state = RTSP_STATE_SEEKING;
944         if ((ret = rtsp_read_play(s)) != 0)
945             return ret;
946         break;
947     case RTSP_STATE_PAUSED:
948         rt->state = RTSP_STATE_IDLE;
949         break;
950     }
951     return 0;
952 }
953
954 static const AVClass rtsp_demuxer_class = {
955     .class_name     = "RTSP demuxer",
956     .item_name      = av_default_item_name,
957     .option         = ff_rtsp_options,
958     .version        = LIBAVUTIL_VERSION_INT,
959 };
960
961 AVInputFormat ff_rtsp_demuxer = {
962     .name           = "rtsp",
963     .long_name      = NULL_IF_CONFIG_SMALL("RTSP input"),
964     .priv_data_size = sizeof(RTSPState),
965     .read_probe     = rtsp_probe,
966     .read_header    = rtsp_read_header,
967     .read_packet    = rtsp_read_packet,
968     .read_close     = rtsp_read_close,
969     .read_seek      = rtsp_read_seek,
970     .flags          = AVFMT_NOFILE,
971     .read_play      = rtsp_read_play,
972     .read_pause     = rtsp_read_pause,
973     .priv_class     = &rtsp_demuxer_class,
974 };