3 * Copyright (c) 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
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"
31 #include "os_support.h"
38 static const struct RTSPStatusMessage {
39 enum RTSPStatusCode code;
41 } status_messages[] = {
42 { RTSP_STATUS_OK, "OK" },
43 { RTSP_STATUS_METHOD, "Method Not Allowed" },
44 { RTSP_STATUS_BANDWIDTH, "Not Enough Bandwidth" },
45 { RTSP_STATUS_SESSION, "Session Not Found" },
46 { RTSP_STATUS_STATE, "Method Not Valid in This State" },
47 { RTSP_STATUS_AGGREGATE, "Aggregate operation not allowed" },
48 { RTSP_STATUS_ONLY_AGGREGATE, "Only aggregate operation allowed" },
49 { RTSP_STATUS_TRANSPORT, "Unsupported transport" },
50 { RTSP_STATUS_INTERNAL, "Internal Server Error" },
51 { RTSP_STATUS_SERVICE, "Service Unavailable" },
52 { RTSP_STATUS_VERSION, "RTSP Version not supported" },
56 static int rtsp_read_close(AVFormatContext *s)
58 RTSPState *rt = s->priv_data;
60 if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN))
61 ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
63 ff_rtsp_close_streams(s);
64 ff_rtsp_close_connections(s);
66 rt->real_setup = NULL;
67 av_freep(&rt->real_setup_cache);
71 static inline int read_line(AVFormatContext *s, char *rbuf, const int rbufsize,
74 RTSPState *rt = s->priv_data;
80 ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1);
82 return ret ? ret : AVERROR_EOF;
83 if (rbuf[idx] == '\r') {
85 } else if (rbuf[idx] == '\n') {
91 } while (idx < rbufsize);
92 av_log(s, AV_LOG_ERROR, "Message too long\n");
96 static int rtsp_send_reply(AVFormatContext *s, enum RTSPStatusCode code,
97 const char *extracontent, uint16_t seq)
99 RTSPState *rt = s->priv_data;
102 while (status_messages[index].code) {
103 if (status_messages[index].code == code) {
104 snprintf(message, sizeof(message), "RTSP/1.0 %d %s\r\n",
105 code, status_messages[index].message);
110 if (!status_messages[index].code)
111 return AVERROR(EINVAL);
112 av_strlcatf(message, sizeof(message), "CSeq: %d\r\n", seq);
113 av_strlcatf(message, sizeof(message), "Server: %s\r\n", LIBAVFORMAT_IDENT);
115 av_strlcat(message, extracontent, sizeof(message));
116 av_strlcat(message, "\r\n", sizeof(message));
117 av_log(s, AV_LOG_TRACE, "Sending response:\n%s", message);
118 ffurl_write(rt->rtsp_hd_out, message, strlen(message));
123 static inline int check_sessionid(AVFormatContext *s,
124 RTSPMessageHeader *request)
126 RTSPState *rt = s->priv_data;
127 unsigned char *session_id = rt->session_id;
128 if (!session_id[0]) {
129 av_log(s, AV_LOG_WARNING, "There is no session-id at the moment\n");
132 if (strcmp(session_id, request->session_id)) {
133 av_log(s, AV_LOG_ERROR, "Unexpected session-id %s\n",
134 request->session_id);
135 rtsp_send_reply(s, RTSP_STATUS_SESSION, NULL, request->seq);
136 return AVERROR_STREAM_NOT_FOUND;
141 static inline int rtsp_read_request(AVFormatContext *s,
142 RTSPMessageHeader *request,
145 RTSPState *rt = s->priv_data;
149 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
153 av_log(s, AV_LOG_TRACE, "Parsing[%d]: %s\n", rbuflen, rbuf);
154 ff_rtsp_parse_line(s, request, rbuf, rt, method);
156 } while (rbuflen > 0);
157 if (request->seq != rt->seq + 1) {
158 av_log(s, AV_LOG_ERROR, "Unexpected Sequence number %d\n",
160 return AVERROR(EINVAL);
162 if (rt->session_id[0] && strcmp(method, "OPTIONS")) {
163 ret = check_sessionid(s, request);
171 static int rtsp_read_announce(AVFormatContext *s)
173 RTSPState *rt = s->priv_data;
174 RTSPMessageHeader request = { 0 };
175 char sdp[SDP_MAX_SIZE];
178 ret = rtsp_read_request(s, &request, "ANNOUNCE");
182 if (strcmp(request.content_type, "application/sdp")) {
183 av_log(s, AV_LOG_ERROR, "Unexpected content type %s\n",
184 request.content_type);
185 rtsp_send_reply(s, RTSP_STATUS_SERVICE, NULL, request.seq);
186 return AVERROR_OPTION_NOT_FOUND;
188 if (request.content_length && request.content_length < sizeof(sdp) - 1) {
190 if (ffurl_read_complete(rt->rtsp_hd, sdp, request.content_length)
191 < request.content_length) {
192 av_log(s, AV_LOG_ERROR,
193 "Unable to get complete SDP Description in ANNOUNCE\n");
194 rtsp_send_reply(s, RTSP_STATUS_INTERNAL, NULL, request.seq);
197 sdp[request.content_length] = '\0';
198 av_log(s, AV_LOG_VERBOSE, "SDP: %s\n", sdp);
199 ret = ff_sdp_parse(s, sdp);
202 rtsp_send_reply(s, RTSP_STATUS_OK, NULL, request.seq);
205 av_log(s, AV_LOG_ERROR,
206 "Content-Length header value exceeds sdp allocated buffer (4KB)\n");
207 rtsp_send_reply(s, RTSP_STATUS_INTERNAL,
208 "Content-Length exceeds buffer size", request.seq);
212 static int rtsp_read_options(AVFormatContext *s)
214 RTSPState *rt = s->priv_data;
215 RTSPMessageHeader request = { 0 };
218 /* Parsing headers */
219 ret = rtsp_read_request(s, &request, "OPTIONS");
224 rtsp_send_reply(s, RTSP_STATUS_OK,
225 "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, RECORD\r\n",
230 static int rtsp_read_setup(AVFormatContext *s, char* host, char *controlurl)
232 RTSPState *rt = s->priv_data;
233 RTSPMessageHeader request = { 0 };
237 char responseheaders[1024];
239 int transportidx = 0;
242 ret = rtsp_read_request(s, &request, "SETUP");
246 if (!request.nb_transports) {
247 av_log(s, AV_LOG_ERROR, "No transport defined in SETUP\n");
248 return AVERROR_INVALIDDATA;
250 for (transportidx = 0; transportidx < request.nb_transports;
252 if (!request.transports[transportidx].mode_record ||
253 (request.transports[transportidx].lower_transport !=
254 RTSP_LOWER_TRANSPORT_UDP &&
255 request.transports[transportidx].lower_transport !=
256 RTSP_LOWER_TRANSPORT_TCP)) {
257 av_log(s, AV_LOG_ERROR, "mode=record/receive not set or transport"
258 " protocol not supported (yet)\n");
259 return AVERROR_INVALIDDATA;
262 if (request.nb_transports > 1)
263 av_log(s, AV_LOG_WARNING, "More than one transport not supported, "
264 "using first of all\n");
265 for (streamid = 0; streamid < rt->nb_rtsp_streams; streamid++) {
266 if (!strcmp(rt->rtsp_streams[streamid]->control_url,
270 if (streamid == rt->nb_rtsp_streams) {
271 av_log(s, AV_LOG_ERROR, "Unable to find requested track\n");
272 return AVERROR_STREAM_NOT_FOUND;
274 rtsp_st = rt->rtsp_streams[streamid];
275 localport = rt->rtp_port_min;
277 if (request.transports[0].lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
278 rt->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
279 if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
280 rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
283 rtsp_st->interleaved_min = request.transports[0].interleaved_min;
284 rtsp_st->interleaved_max = request.transports[0].interleaved_max;
285 snprintf(responseheaders, sizeof(responseheaders), "Transport: "
286 "RTP/AVP/TCP;unicast;mode=receive;interleaved=%d-%d"
287 "\r\n", request.transports[0].interleaved_min,
288 request.transports[0].interleaved_max);
291 AVDictionary *opts = NULL;
292 av_dict_set_int(&opts, "buffer_size", rt->buffer_size, 0);
293 ff_url_join(url, sizeof(url), "rtp", NULL, host, localport, NULL);
294 av_log(s, AV_LOG_TRACE, "Opening: %s\n", url);
295 ret = ffurl_open_whitelist(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
296 &s->interrupt_callback, &opts,
297 s->protocol_whitelist, s->protocol_blacklist, NULL);
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);
307 av_log(s, AV_LOG_TRACE, "Listening on: %d\n",
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);
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,
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());
329 av_strlcatf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
332 rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
334 rt->state = RTSP_STATE_PAUSED;
338 static int rtsp_read_record(AVFormatContext *s)
340 RTSPState *rt = s->priv_data;
341 RTSPMessageHeader request = { 0 };
343 char responseheaders[1024];
345 ret = rtsp_read_request(s, &request, "RECORD");
348 ret = check_sessionid(s, &request);
352 snprintf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
354 rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
356 rt->state = RTSP_STATE_STREAMING;
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)
365 RTSPState *rt = s->priv_data;
366 const char *linept, *searchlinept;
367 linept = strchr(line, ' ');
370 av_log(s, AV_LOG_ERROR, "Error parsing method string\n");
371 return AVERROR_INVALIDDATA;
374 if (linept - line > methodsize - 1) {
375 av_log(s, AV_LOG_ERROR, "Method string too long\n");
378 memcpy(method, line, linept - line);
379 method[linept - line] = '\0';
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"))
389 else if (!strcmp(method, "PAUSE"))
391 else if (!strcmp(method, "TEARDOWN"))
392 *methodcode = TEARDOWN;
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",
400 return AVERROR_PROTOCOL_NOT_FOUND;
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",
407 return AVERROR_PROTOCOL_NOT_FOUND;
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"
414 return AVERROR_PROTOCOL_NOT_FOUND;
417 av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
421 searchlinept = strchr(linept, ' ');
423 av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
424 return AVERROR_INVALIDDATA;
426 if (searchlinept - linept > urisize - 1) {
427 av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
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];
435 char ctl_host[128], ctl_path[512], ctl_auth[128];
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),
442 if (strcmp(host, ctl_host))
443 av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
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));
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;
463 int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
465 RTSPState *rt = s->priv_data;
466 unsigned char rbuf[4096];
467 unsigned char method[10];
471 RTSPMessageHeader request = { 0 };
472 enum RTSPMethod methodcode;
474 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
477 av_log(s, AV_LOG_TRACE, "Parsing[%d]: %s\n", rbuflen, rbuf);
478 ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
479 sizeof(method), &methodcode);
481 av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
485 ret = rtsp_read_request(s, &request, method);
489 if (methodcode == PAUSE) {
490 rt->state = RTSP_STATE_PAUSED;
491 ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
492 // TODO: Missing date header in response
493 } else if (methodcode == OPTIONS) {
494 ret = rtsp_send_reply(s, RTSP_STATUS_OK,
495 "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, "
496 "RECORD\r\n", request.seq);
497 } else if (methodcode == TEARDOWN) {
498 rt->state = RTSP_STATE_IDLE;
499 ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
504 static int rtsp_read_play(AVFormatContext *s)
506 RTSPState *rt = s->priv_data;
507 RTSPMessageHeader reply1, *reply = &reply1;
511 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
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.
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);
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;
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;
542 if (rt->state == RTSP_STATE_PAUSED) {
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);
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);
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;
560 if (!rtpctx || rtsp_st->stream_index < 0)
563 st = s->streams[rtsp_st->stream_index];
564 rtpctx->range_start_offset =
565 av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
570 rt->state = RTSP_STATE_STREAMING;
574 /* pause the stream */
575 static int rtsp_read_pause(AVFormatContext *s)
577 RTSPState *rt = s->priv_data;
578 RTSPMessageHeader reply1, *reply = &reply1;
580 if (rt->state != RTSP_STATE_STREAMING)
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);
588 rt->state = RTSP_STATE_PAUSED;
592 int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
594 RTSPState *rt = s->priv_data;
596 unsigned char *content = NULL;
599 /* describe the stream */
600 snprintf(cmd, sizeof(cmd),
601 "Accept: application/sdp\r\n");
602 if (rt->server_type == RTSP_SERVER_REAL) {
604 * The Require: attribute is needed for proper streaming from
608 "Require: com.real.retain-entity-for-setup\r\n",
611 ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
612 if (reply->status_code != RTSP_STATUS_OK) {
614 return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
617 return AVERROR_INVALIDDATA;
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);
629 static int rtsp_listen(AVFormatContext *s)
631 RTSPState *rt = s->priv_data;
632 char proto[128], host[128], path[512], auth[128];
635 int default_port = RTSP_DEFAULT_PORT;
637 const char *lower_proto = "tcp";
638 unsigned char rbuf[4096];
639 unsigned char method[10];
642 enum RTSPMethod methodcode;
644 if (!ff_network_init())
647 /* extract hostname and port */
648 av_url_split(proto, sizeof(proto), auth, sizeof(auth), host, sizeof(host),
649 &port, path, sizeof(path), s->url);
651 /* ff_url_join. No authorization by now (NULL) */
652 ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL, host,
655 if (!strcmp(proto, "rtsps")) {
657 default_port = RTSPS_DEFAULT_PORT;
663 /* Create TCP connection */
664 ff_url_join(tcpname, sizeof(tcpname), lower_proto, NULL, host, port,
665 "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
667 if (ret = ffurl_open_whitelist(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
668 &s->interrupt_callback, NULL,
669 s->protocol_whitelist, s->protocol_blacklist, NULL)) {
670 av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
673 rt->state = RTSP_STATE_IDLE;
674 rt->rtsp_hd_out = rt->rtsp_hd;
675 for (;;) { /* Wait for incoming RTSP messages */
676 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
679 av_log(s, AV_LOG_TRACE, "Parsing[%d]: %s\n", rbuflen, rbuf);
680 ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
681 sizeof(method), &methodcode);
683 av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
687 if (methodcode == ANNOUNCE) {
688 ret = rtsp_read_announce(s);
689 rt->state = RTSP_STATE_PAUSED;
690 } else if (methodcode == OPTIONS) {
691 ret = rtsp_read_options(s);
692 } else if (methodcode == RECORD) {
693 ret = rtsp_read_record(s);
695 return 0; // We are ready for streaming
696 } else if (methodcode == SETUP)
697 ret = rtsp_read_setup(s, host, uri);
699 ret = AVERROR_INVALIDDATA;
704 ff_rtsp_close_streams(s);
705 ff_rtsp_close_connections(s);
710 static int rtsp_probe(const AVProbeData *p)
713 #if CONFIG_TLS_PROTOCOL
714 av_strstart(p->filename, "rtsps:", NULL) ||
716 av_strstart(p->filename, "rtsp:", NULL))
717 return AVPROBE_SCORE_MAX;
721 static int rtsp_read_header(AVFormatContext *s)
723 RTSPState *rt = s->priv_data;
726 if (rt->initial_timeout > 0)
727 rt->rtsp_flags |= RTSP_FLAG_LISTEN;
729 if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
730 ret = rtsp_listen(s);
734 ret = ff_rtsp_connect(s);
738 rt->real_setup_cache = !s->nb_streams ? NULL :
739 av_mallocz_array(s->nb_streams, 2 * sizeof(*rt->real_setup_cache));
740 if (!rt->real_setup_cache && s->nb_streams) {
741 ret = AVERROR(ENOMEM);
744 rt->real_setup = rt->real_setup_cache + s->nb_streams;
746 if (rt->initial_pause) {
747 /* do not start immediately */
749 ret = rtsp_read_play(s);
762 int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
763 uint8_t *buf, int buf_size)
765 RTSPState *rt = s->priv_data;
769 av_log(s, AV_LOG_TRACE, "tcp_read_packet:\n");
772 RTSPMessageHeader reply;
774 ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
777 if (ret == 1) /* received '$' */
779 /* XXX: parse message */
780 if (rt->state != RTSP_STATE_STREAMING)
783 ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
787 len = AV_RB16(buf + 1);
788 av_log(s, AV_LOG_TRACE, "id=%d len=%d\n", id, len);
789 if (len > buf_size || len < 8)
792 ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
795 if (rt->transport == RTSP_TRANSPORT_RDT &&
796 (ret = ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL)) < 0)
799 /* find the matching stream */
800 for (i = 0; i < rt->nb_rtsp_streams; i++) {
801 rtsp_st = rt->rtsp_streams[i];
802 if (id >= rtsp_st->interleaved_min &&
803 id <= rtsp_st->interleaved_max)
812 static int resetup_tcp(AVFormatContext *s)
814 RTSPState *rt = s->priv_data;
818 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
820 ff_rtsp_undo_setup(s, 0);
821 return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
825 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
827 RTSPState *rt = s->priv_data;
829 RTSPMessageHeader reply1, *reply = &reply1;
833 if (rt->server_type == RTSP_SERVER_REAL) {
836 for (i = 0; i < s->nb_streams; i++)
837 rt->real_setup[i] = s->streams[i]->discard;
839 if (!rt->need_subscription) {
840 if (memcmp (rt->real_setup, rt->real_setup_cache,
841 sizeof(enum AVDiscard) * s->nb_streams)) {
842 snprintf(cmd, sizeof(cmd),
843 "Unsubscribe: %s\r\n",
844 rt->last_subscription);
845 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
847 if (reply->status_code != RTSP_STATUS_OK)
848 return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
849 rt->need_subscription = 1;
853 if (rt->need_subscription) {
854 int r, rule_nr, first = 1;
856 memcpy(rt->real_setup_cache, rt->real_setup,
857 sizeof(enum AVDiscard) * s->nb_streams);
858 rt->last_subscription[0] = 0;
860 snprintf(cmd, sizeof(cmd),
862 for (i = 0; i < rt->nb_rtsp_streams; i++) {
864 for (r = 0; r < s->nb_streams; r++) {
865 if (s->streams[r]->id == i) {
866 if (s->streams[r]->discard != AVDISCARD_ALL) {
868 av_strlcat(rt->last_subscription, ",",
869 sizeof(rt->last_subscription));
870 ff_rdt_subscribe_rule(
871 rt->last_subscription,
872 sizeof(rt->last_subscription), i, rule_nr);
879 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
880 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
882 if (reply->status_code != RTSP_STATUS_OK)
883 return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
884 rt->need_subscription = 0;
886 if (rt->state == RTSP_STATE_STREAMING)
891 ret = ff_rtsp_fetch_packet(s, pkt);
893 if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
894 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
895 rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
896 RTSPMessageHeader reply1, *reply = &reply1;
897 av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
898 if (rtsp_read_pause(s) != 0)
900 // TEARDOWN is required on Real-RTSP, but might make
901 // other servers close the connection.
902 if (rt->server_type == RTSP_SERVER_REAL)
903 ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
905 rt->session_id[0] = '\0';
906 if (resetup_tcp(s) == 0) {
907 rt->state = RTSP_STATE_IDLE;
908 rt->need_subscription = 1;
909 if (rtsp_read_play(s) != 0)
919 if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) {
920 /* send dummy request to keep TCP connection alive */
921 if ((av_gettime_relative() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
922 rt->auth_state.stale) {
923 if (rt->server_type == RTSP_SERVER_WMS ||
924 (rt->server_type != RTSP_SERVER_REAL &&
925 rt->get_parameter_supported)) {
926 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
928 ff_rtsp_send_cmd_async(s, "OPTIONS", rt->control_uri, NULL);
930 /* The stale flag should be reset when creating the auth response in
931 * ff_rtsp_send_cmd_async, but reset it here just in case we never
932 * called the auth code (if we didn't have any credentials set). */
933 rt->auth_state.stale = 0;
940 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
941 int64_t timestamp, int flags)
943 RTSPState *rt = s->priv_data;
946 rt->seek_timestamp = av_rescale_q(timestamp,
947 s->streams[stream_index]->time_base,
951 case RTSP_STATE_IDLE:
953 case RTSP_STATE_STREAMING:
954 if ((ret = rtsp_read_pause(s)) != 0)
956 rt->state = RTSP_STATE_SEEKING;
957 if ((ret = rtsp_read_play(s)) != 0)
960 case RTSP_STATE_PAUSED:
961 rt->state = RTSP_STATE_IDLE;
967 static const AVClass rtsp_demuxer_class = {
968 .class_name = "RTSP demuxer",
969 .item_name = av_default_item_name,
970 .option = ff_rtsp_options,
971 .version = LIBAVUTIL_VERSION_INT,
974 AVInputFormat ff_rtsp_demuxer = {
976 .long_name = NULL_IF_CONFIG_SMALL("RTSP input"),
977 .priv_data_size = sizeof(RTSPState),
978 .read_probe = rtsp_probe,
979 .read_header = rtsp_read_header,
980 .read_packet = rtsp_read_packet,
981 .read_close = rtsp_read_close,
982 .read_seek = rtsp_read_seek,
983 .flags = AVFMT_NOFILE,
984 .read_play = rtsp_read_play,
985 .read_pause = rtsp_read_pause,
986 .priv_class = &rtsp_demuxer_class,