3 * Copyright (c) 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; 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 };
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;
293 snprintf(buf, sizeof(buf), "%d", rt->buffer_size);
294 av_dict_set(&opts, "buffer_size", buf, 0);
295 ff_url_join(url, sizeof(url), "rtp", NULL, host, localport, NULL);
296 av_log(s, AV_LOG_TRACE, "Opening: %s", url);
297 ret = ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
298 &s->interrupt_callback, &opts);
302 } while (ret || localport > rt->rtp_port_max);
303 if (localport > rt->rtp_port_max) {
304 rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
308 av_log(s, AV_LOG_TRACE, "Listening on: %d",
309 ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle));
310 if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
311 rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
315 localport = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
316 snprintf(responseheaders, sizeof(responseheaders), "Transport: "
317 "RTP/AVP/UDP;unicast;mode=receive;source=%s;"
318 "client_port=%d-%d;server_port=%d-%d\r\n",
319 host, request.transports[0].client_port_min,
320 request.transports[0].client_port_max, localport,
324 /* Establish sessionid if not previously set */
325 /* Put this in a function? */
326 /* RFC 2326: session id must be at least 8 digits */
327 while (strlen(rt->session_id) < 8)
328 av_strlcatf(rt->session_id, 512, "%u", av_get_random_seed());
330 av_strlcatf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
333 rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
335 rt->state = RTSP_STATE_PAUSED;
339 static int rtsp_read_record(AVFormatContext *s)
341 RTSPState *rt = s->priv_data;
342 RTSPMessageHeader request = { 0 };
344 char responseheaders[1024];
346 ret = rtsp_read_request(s, &request, "RECORD");
349 ret = check_sessionid(s, &request);
353 snprintf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
355 rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
357 rt->state = RTSP_STATE_STREAMING;
361 static inline int parse_command_line(AVFormatContext *s, const char *line,
362 int linelen, char *uri, int urisize,
363 char *method, int methodsize,
364 enum RTSPMethod *methodcode)
366 RTSPState *rt = s->priv_data;
367 const char *linept, *searchlinept;
368 linept = strchr(line, ' ');
371 return AVERROR_INVALIDDATA;
373 if (linept - line > methodsize - 1) {
374 av_log(s, AV_LOG_ERROR, "Method string too long\n");
377 memcpy(method, line, linept - line);
378 method[linept - line] = '\0';
380 if (!strcmp(method, "ANNOUNCE"))
381 *methodcode = ANNOUNCE;
382 else if (!strcmp(method, "OPTIONS"))
383 *methodcode = OPTIONS;
384 else if (!strcmp(method, "RECORD"))
385 *methodcode = RECORD;
386 else if (!strcmp(method, "SETUP"))
388 else if (!strcmp(method, "PAUSE"))
390 else if (!strcmp(method, "TEARDOWN"))
391 *methodcode = TEARDOWN;
393 *methodcode = UNKNOWN;
394 /* Check method with the state */
395 if (rt->state == RTSP_STATE_IDLE) {
396 if ((*methodcode != ANNOUNCE) && (*methodcode != OPTIONS)) {
397 av_log(s, AV_LOG_ERROR, "Unexpected command in Idle State %s\n",
399 return AVERROR_PROTOCOL_NOT_FOUND;
401 } else if (rt->state == RTSP_STATE_PAUSED) {
402 if ((*methodcode != OPTIONS) && (*methodcode != RECORD)
403 && (*methodcode != SETUP)) {
404 av_log(s, AV_LOG_ERROR, "Unexpected command in Paused State %s\n",
406 return AVERROR_PROTOCOL_NOT_FOUND;
408 } else if (rt->state == RTSP_STATE_STREAMING) {
409 if ((*methodcode != PAUSE) && (*methodcode != OPTIONS)
410 && (*methodcode != TEARDOWN)) {
411 av_log(s, AV_LOG_ERROR, "Unexpected command in Streaming State"
413 return AVERROR_PROTOCOL_NOT_FOUND;
416 av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
420 searchlinept = strchr(linept, ' ');
422 av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
423 return AVERROR_INVALIDDATA;
425 if (searchlinept - linept > urisize - 1) {
426 av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
429 memcpy(uri, linept, searchlinept - linept);
430 uri[searchlinept - linept] = '\0';
431 if (strcmp(rt->control_uri, uri)) {
432 char host[128], path[512], auth[128];
434 char ctl_host[128], ctl_path[512], ctl_auth[128];
436 av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
437 path, sizeof(path), uri);
438 av_url_split(NULL, 0, ctl_auth, sizeof(ctl_auth), ctl_host,
439 sizeof(ctl_host), &ctl_port, ctl_path, sizeof(ctl_path),
441 if (strcmp(host, ctl_host))
442 av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
444 if (strcmp(path, ctl_path) && *methodcode != SETUP)
445 av_log(s, AV_LOG_WARNING, "WARNING: Path %s differs from expected"
446 " %s\n", path, ctl_path);
447 if (*methodcode == ANNOUNCE) {
448 av_log(s, AV_LOG_INFO,
449 "Updating control URI to %s\n", uri);
450 av_strlcpy(rt->control_uri, uri, sizeof(rt->control_uri));
454 linept = searchlinept + 1;
455 if (!av_strstart(linept, "RTSP/1.0", NULL)) {
456 av_log(s, AV_LOG_ERROR, "Error parsing protocol or version\n");
457 return AVERROR_PROTOCOL_NOT_FOUND;
462 int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
464 RTSPState *rt = s->priv_data;
465 unsigned char rbuf[4096];
466 unsigned char method[10];
470 RTSPMessageHeader request = { 0 };
471 enum RTSPMethod methodcode;
473 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
476 ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
477 sizeof(method), &methodcode);
479 av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
483 ret = rtsp_read_request(s, &request, method);
487 if (methodcode == PAUSE) {
488 rt->state = RTSP_STATE_PAUSED;
489 ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
490 // TODO: Missing date header in response
491 } else if (methodcode == OPTIONS) {
492 ret = rtsp_send_reply(s, RTSP_STATUS_OK,
493 "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, "
494 "RECORD\r\n", request.seq);
495 } else if (methodcode == TEARDOWN) {
496 rt->state = RTSP_STATE_IDLE;
497 ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
503 static int rtsp_read_play(AVFormatContext *s)
505 RTSPState *rt = s->priv_data;
506 RTSPMessageHeader reply1, *reply = &reply1;
510 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
513 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
514 for (i = 0; i < rt->nb_rtsp_streams; i++) {
515 RTSPStream *rtsp_st = rt->rtsp_streams[i];
516 /* Try to initialize the connection state in a
517 * potential NAT router by sending dummy packets.
518 * RTP/RTCP dummy packets are used for RDT, too.
520 if (rtsp_st->rtp_handle &&
521 !(rt->server_type == RTSP_SERVER_WMS && i > 1))
522 ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
525 if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
526 if (rt->transport == RTSP_TRANSPORT_RTP) {
527 for (i = 0; i < rt->nb_rtsp_streams; i++) {
528 RTSPStream *rtsp_st = rt->rtsp_streams[i];
529 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
532 ff_rtp_reset_packet_queue(rtpctx);
533 rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
534 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
535 rtpctx->base_timestamp = 0;
536 rtpctx->timestamp = 0;
537 rtpctx->unwrapped_timestamp = 0;
538 rtpctx->rtcp_ts_offset = 0;
541 if (rt->state == RTSP_STATE_PAUSED) {
544 snprintf(cmd, sizeof(cmd),
545 "Range: npt=%"PRId64".%03"PRId64"-\r\n",
546 rt->seek_timestamp / AV_TIME_BASE,
547 rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
549 ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
550 if (reply->status_code != RTSP_STATUS_OK) {
553 if (rt->transport == RTSP_TRANSPORT_RTP &&
554 reply->range_start != AV_NOPTS_VALUE) {
555 for (i = 0; i < rt->nb_rtsp_streams; i++) {
556 RTSPStream *rtsp_st = rt->rtsp_streams[i];
557 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
559 if (!rtpctx || rtsp_st->stream_index < 0)
561 st = s->streams[rtsp_st->stream_index];
562 rtpctx->range_start_offset =
563 av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
568 rt->state = RTSP_STATE_STREAMING;
572 /* pause the stream */
573 static int rtsp_read_pause(AVFormatContext *s)
575 RTSPState *rt = s->priv_data;
576 RTSPMessageHeader reply1, *reply = &reply1;
578 if (rt->state != RTSP_STATE_STREAMING)
580 else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
581 ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
582 if (reply->status_code != RTSP_STATUS_OK) {
586 rt->state = RTSP_STATE_PAUSED;
590 int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
592 RTSPState *rt = s->priv_data;
594 unsigned char *content = NULL;
597 /* describe the stream */
598 snprintf(cmd, sizeof(cmd),
599 "Accept: application/sdp\r\n");
600 if (rt->server_type == RTSP_SERVER_REAL) {
602 * The Require: attribute is needed for proper streaming from
606 "Require: com.real.retain-entity-for-setup\r\n",
609 ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
611 return AVERROR_INVALIDDATA;
612 if (reply->status_code != RTSP_STATUS_OK) {
614 return AVERROR_INVALIDDATA;
617 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
618 /* now we got the SDP description, we parse it */
619 ret = ff_sdp_parse(s, (const char *)content);
627 static int rtsp_listen(AVFormatContext *s)
629 RTSPState *rt = s->priv_data;
630 char proto[128], host[128], path[512], auth[128];
633 int default_port = RTSP_DEFAULT_PORT;
635 const char *lower_proto = "tcp";
636 unsigned char rbuf[4096];
637 unsigned char method[10];
640 enum RTSPMethod methodcode;
642 /* extract hostname and port */
643 av_url_split(proto, sizeof(proto), auth, sizeof(auth), host, sizeof(host),
644 &port, path, sizeof(path), s->filename);
646 /* ff_url_join. No authorization by now (NULL) */
647 ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL, host,
650 if (!strcmp(proto, "rtsps")) {
652 default_port = RTSPS_DEFAULT_PORT;
658 /* Create TCP connection */
659 ff_url_join(tcpname, sizeof(tcpname), lower_proto, NULL, host, port,
660 "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
662 if (ret = ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
663 &s->interrupt_callback, NULL)) {
664 av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
667 rt->state = RTSP_STATE_IDLE;
668 rt->rtsp_hd_out = rt->rtsp_hd;
669 for (;;) { /* Wait for incoming RTSP messages */
670 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
673 ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
674 sizeof(method), &methodcode);
676 av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
680 if (methodcode == ANNOUNCE) {
681 ret = rtsp_read_announce(s);
682 rt->state = RTSP_STATE_PAUSED;
683 } else if (methodcode == OPTIONS) {
684 ret = rtsp_read_options(s);
685 } else if (methodcode == RECORD) {
686 ret = rtsp_read_record(s);
688 return 0; // We are ready for streaming
689 } else if (methodcode == SETUP)
690 ret = rtsp_read_setup(s, host, uri);
692 ffurl_close(rt->rtsp_hd);
693 return AVERROR_INVALIDDATA;
699 static int rtsp_probe(AVProbeData *p)
702 #if CONFIG_TLS_PROTOCOL
703 av_strstart(p->filename, "rtsps:", NULL) ||
705 av_strstart(p->filename, "rtsp:", NULL))
706 return AVPROBE_SCORE_MAX;
710 static int rtsp_read_header(AVFormatContext *s)
712 RTSPState *rt = s->priv_data;
715 if (rt->initial_timeout > 0)
716 rt->rtsp_flags |= RTSP_FLAG_LISTEN;
718 if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
719 ret = rtsp_listen(s);
723 ret = ff_rtsp_connect(s);
727 rt->real_setup_cache = !s->nb_streams ? NULL :
728 av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
729 if (!rt->real_setup_cache && s->nb_streams)
730 return AVERROR(ENOMEM);
731 rt->real_setup = rt->real_setup_cache + s->nb_streams;
733 if (rt->initial_pause) {
734 /* do not start immediately */
736 if (rtsp_read_play(s) < 0) {
737 ff_rtsp_close_streams(s);
738 ff_rtsp_close_connections(s);
739 return AVERROR_INVALIDDATA;
747 int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
748 uint8_t *buf, int buf_size)
750 RTSPState *rt = s->priv_data;
754 av_log(s, AV_LOG_TRACE, "tcp_read_packet:\n");
757 RTSPMessageHeader reply;
759 ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
762 if (ret == 1) /* received '$' */
764 /* XXX: parse message */
765 if (rt->state != RTSP_STATE_STREAMING)
768 ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
772 len = AV_RB16(buf + 1);
773 av_log(s, AV_LOG_TRACE, "id=%d len=%d\n", id, len);
774 if (len > buf_size || len < 12)
777 ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
780 if (rt->transport == RTSP_TRANSPORT_RDT &&
781 ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
784 /* find the matching stream */
785 for (i = 0; i < rt->nb_rtsp_streams; i++) {
786 rtsp_st = rt->rtsp_streams[i];
787 if (id >= rtsp_st->interleaved_min &&
788 id <= rtsp_st->interleaved_max)
797 static int resetup_tcp(AVFormatContext *s)
799 RTSPState *rt = s->priv_data;
803 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
805 ff_rtsp_undo_setup(s, 0);
806 return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
810 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
812 RTSPState *rt = s->priv_data;
814 RTSPMessageHeader reply1, *reply = &reply1;
818 if (rt->server_type == RTSP_SERVER_REAL) {
821 for (i = 0; i < s->nb_streams; i++)
822 rt->real_setup[i] = s->streams[i]->discard;
824 if (!rt->need_subscription) {
825 if (memcmp (rt->real_setup, rt->real_setup_cache,
826 sizeof(enum AVDiscard) * s->nb_streams)) {
827 snprintf(cmd, sizeof(cmd),
828 "Unsubscribe: %s\r\n",
829 rt->last_subscription);
830 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
832 if (reply->status_code != RTSP_STATUS_OK)
833 return AVERROR_INVALIDDATA;
834 rt->need_subscription = 1;
838 if (rt->need_subscription) {
839 int r, rule_nr, first = 1;
841 memcpy(rt->real_setup_cache, rt->real_setup,
842 sizeof(enum AVDiscard) * s->nb_streams);
843 rt->last_subscription[0] = 0;
845 snprintf(cmd, sizeof(cmd),
847 for (i = 0; i < rt->nb_rtsp_streams; i++) {
849 for (r = 0; r < s->nb_streams; r++) {
850 if (s->streams[r]->id == i) {
851 if (s->streams[r]->discard != AVDISCARD_ALL) {
853 av_strlcat(rt->last_subscription, ",",
854 sizeof(rt->last_subscription));
855 ff_rdt_subscribe_rule(
856 rt->last_subscription,
857 sizeof(rt->last_subscription), i, rule_nr);
864 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
865 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
867 if (reply->status_code != RTSP_STATUS_OK)
868 return AVERROR_INVALIDDATA;
869 rt->need_subscription = 0;
871 if (rt->state == RTSP_STATE_STREAMING)
876 ret = ff_rtsp_fetch_packet(s, pkt);
878 if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
879 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
880 rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
881 RTSPMessageHeader reply1, *reply = &reply1;
882 av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
883 if (rtsp_read_pause(s) != 0)
885 // TEARDOWN is required on Real-RTSP, but might make
886 // other servers close the connection.
887 if (rt->server_type == RTSP_SERVER_REAL)
888 ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
890 rt->session_id[0] = '\0';
891 if (resetup_tcp(s) == 0) {
892 rt->state = RTSP_STATE_IDLE;
893 rt->need_subscription = 1;
894 if (rtsp_read_play(s) != 0)
904 if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) {
905 /* send dummy request to keep TCP connection alive */
906 if ((av_gettime_relative() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
907 rt->auth_state.stale) {
908 if (rt->server_type == RTSP_SERVER_WMS ||
909 (rt->server_type != RTSP_SERVER_REAL &&
910 rt->get_parameter_supported)) {
911 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
913 ff_rtsp_send_cmd_async(s, "OPTIONS", rt->control_uri, NULL);
915 /* The stale flag should be reset when creating the auth response in
916 * ff_rtsp_send_cmd_async, but reset it here just in case we never
917 * called the auth code (if we didn't have any credentials set). */
918 rt->auth_state.stale = 0;
925 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
926 int64_t timestamp, int flags)
928 RTSPState *rt = s->priv_data;
930 rt->seek_timestamp = av_rescale_q(timestamp,
931 s->streams[stream_index]->time_base,
935 case RTSP_STATE_IDLE:
937 case RTSP_STATE_STREAMING:
938 if (rtsp_read_pause(s) != 0)
940 rt->state = RTSP_STATE_SEEKING;
941 if (rtsp_read_play(s) != 0)
944 case RTSP_STATE_PAUSED:
945 rt->state = RTSP_STATE_IDLE;
951 static const AVClass rtsp_demuxer_class = {
952 .class_name = "RTSP demuxer",
953 .item_name = av_default_item_name,
954 .option = ff_rtsp_options,
955 .version = LIBAVUTIL_VERSION_INT,
958 AVInputFormat ff_rtsp_demuxer = {
960 .long_name = NULL_IF_CONFIG_SMALL("RTSP input"),
961 .priv_data_size = sizeof(RTSPState),
962 .read_probe = rtsp_probe,
963 .read_header = rtsp_read_header,
964 .read_packet = rtsp_read_packet,
965 .read_close = rtsp_read_close,
966 .read_seek = rtsp_read_seek,
967 .flags = AVFMT_NOFILE,
968 .read_play = rtsp_read_play,
969 .read_pause = rtsp_read_pause,
970 .priv_class = &rtsp_demuxer_class,