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"
30 #include "os_support.h"
35 static const struct RTSPStatusMessage {
36 enum RTSPStatusCode code;
38 } status_messages[] = {
39 { RTSP_STATUS_OK, "OK" },
40 { RTSP_STATUS_METHOD, "Method Not Allowed" },
41 { RTSP_STATUS_BANDWIDTH, "Not Enough Bandwidth" },
42 { RTSP_STATUS_SESSION, "Session Not Found" },
43 { RTSP_STATUS_STATE, "Method Not Valid in This State" },
44 { RTSP_STATUS_AGGREGATE, "Aggregate operation not allowed" },
45 { RTSP_STATUS_ONLY_AGGREGATE, "Only aggregate operation allowed" },
46 { RTSP_STATUS_TRANSPORT, "Unsupported transport" },
47 { RTSP_STATUS_INTERNAL, "Internal Server Error" },
48 { RTSP_STATUS_SERVICE, "Service Unavailable" },
49 { RTSP_STATUS_VERSION, "RTSP Version not supported" },
53 static int rtsp_read_close(AVFormatContext *s)
55 RTSPState *rt = s->priv_data;
57 if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN))
58 ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
60 ff_rtsp_close_streams(s);
61 ff_rtsp_close_connections(s);
63 rt->real_setup = NULL;
64 av_freep(&rt->real_setup_cache);
68 static inline int read_line(AVFormatContext *s, char *rbuf, const int rbufsize,
71 RTSPState *rt = s->priv_data;
77 ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1);
80 if (rbuf[idx] == '\r') {
82 } else if (rbuf[idx] == '\n') {
88 } while (idx < rbufsize);
89 av_log(s, AV_LOG_ERROR, "Message too long\n");
93 static int rtsp_send_reply(AVFormatContext *s, enum RTSPStatusCode code,
94 const char *extracontent, uint16_t seq)
96 RTSPState *rt = s->priv_data;
99 while (status_messages[index].code) {
100 if (status_messages[index].code == code) {
101 snprintf(message, sizeof(message), "RTSP/1.0 %d %s\r\n",
102 code, status_messages[index].message);
107 if (!status_messages[index].code)
108 return AVERROR(EINVAL);
109 av_strlcatf(message, sizeof(message), "CSeq: %d\r\n", seq);
110 av_strlcatf(message, sizeof(message), "Server: %s\r\n", LIBAVFORMAT_IDENT);
112 av_strlcat(message, extracontent, sizeof(message));
113 av_strlcat(message, "\r\n", sizeof(message));
114 av_dlog(s, "Sending response:\n%s", message);
115 ffurl_write(rt->rtsp_hd, message, strlen(message));
120 static inline int check_sessionid(AVFormatContext *s,
121 RTSPMessageHeader *request)
123 RTSPState *rt = s->priv_data;
124 unsigned char *session_id = rt->session_id;
125 if (!session_id[0]) {
126 av_log(s, AV_LOG_WARNING, "There is no session-id at the moment\n");
129 if (strcmp(session_id, request->session_id)) {
130 av_log(s, AV_LOG_ERROR, "Unexpected session-id %s\n",
131 request->session_id);
132 rtsp_send_reply(s, RTSP_STATUS_SESSION, NULL, request->seq);
133 return AVERROR_STREAM_NOT_FOUND;
138 static inline int rtsp_read_request(AVFormatContext *s,
139 RTSPMessageHeader *request,
142 RTSPState *rt = s->priv_data;
146 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
150 av_dlog(s, "Parsing[%d]: %s\n", rbuflen, rbuf);
151 ff_rtsp_parse_line(request, rbuf, rt, method);
153 } while (rbuflen > 0);
154 if (request->seq != rt->seq + 1) {
155 av_log(s, AV_LOG_ERROR, "Unexpected Sequence number %d\n",
157 return AVERROR(EINVAL);
159 if (rt->session_id[0] && strcmp(method, "OPTIONS")) {
160 ret = check_sessionid(s, request);
168 static int rtsp_read_announce(AVFormatContext *s)
170 RTSPState *rt = s->priv_data;
171 RTSPMessageHeader request = { 0 };
175 ret = rtsp_read_request(s, &request, "ANNOUNCE");
179 if (strcmp(request.content_type, "application/sdp")) {
180 av_log(s, AV_LOG_ERROR, "Unexpected content type %s\n",
181 request.content_type);
182 rtsp_send_reply(s, RTSP_STATUS_SERVICE, NULL, request.seq);
183 return AVERROR_OPTION_NOT_FOUND;
185 if (request.content_length && request.content_length < sizeof(sdp) - 1) {
187 if (ffurl_read_complete(rt->rtsp_hd, sdp, request.content_length)
188 < request.content_length) {
189 av_log(s, AV_LOG_ERROR,
190 "Unable to get complete SDP Description in ANNOUNCE\n");
191 rtsp_send_reply(s, RTSP_STATUS_INTERNAL, NULL, request.seq);
194 sdp[request.content_length] = '\0';
195 av_log(s, AV_LOG_VERBOSE, "SDP: %s\n", sdp);
196 ret = ff_sdp_parse(s, sdp);
199 rtsp_send_reply(s, RTSP_STATUS_OK, NULL, request.seq);
202 av_log(s, AV_LOG_ERROR,
203 "Content-Length header value exceeds sdp allocated buffer (4KB)\n");
204 rtsp_send_reply(s, RTSP_STATUS_INTERNAL,
205 "Content-Length exceeds buffer size", request.seq);
209 static int rtsp_read_options(AVFormatContext *s)
211 RTSPState *rt = s->priv_data;
212 RTSPMessageHeader request = { 0 };
215 /* Parsing headers */
216 ret = rtsp_read_request(s, &request, "OPTIONS");
221 rtsp_send_reply(s, RTSP_STATUS_OK,
222 "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, RECORD\r\n",
227 static int rtsp_read_setup(AVFormatContext *s, char* host, char *controlurl)
229 RTSPState *rt = s->priv_data;
230 RTSPMessageHeader request = { 0 };
234 char responseheaders[1024];
236 int transportidx = 0;
239 ret = rtsp_read_request(s, &request, "SETUP");
243 if (!request.nb_transports) {
244 av_log(s, AV_LOG_ERROR, "No transport defined in SETUP\n");
245 return AVERROR_INVALIDDATA;
247 for (transportidx = 0; transportidx < request.nb_transports;
249 if (!request.transports[transportidx].mode_record ||
250 (request.transports[transportidx].lower_transport !=
251 RTSP_LOWER_TRANSPORT_UDP &&
252 request.transports[transportidx].lower_transport !=
253 RTSP_LOWER_TRANSPORT_TCP)) {
254 av_log(s, AV_LOG_ERROR, "mode=record/receive not set or transport"
255 " protocol not supported (yet)\n");
256 return AVERROR_INVALIDDATA;
259 if (request.nb_transports > 1)
260 av_log(s, AV_LOG_WARNING, "More than one transport not supported, "
261 "using first of all\n");
262 for (streamid = 0; streamid < rt->nb_rtsp_streams; streamid++) {
263 if (!strcmp(rt->rtsp_streams[streamid]->control_url,
267 if (streamid == rt->nb_rtsp_streams) {
268 av_log(s, AV_LOG_ERROR, "Unable to find requested track\n");
269 return AVERROR_STREAM_NOT_FOUND;
271 rtsp_st = rt->rtsp_streams[streamid];
272 localport = rt->rtp_port_min;
274 if (request.transports[0].lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
275 rt->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
276 if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
277 rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
280 rtsp_st->interleaved_min = request.transports[0].interleaved_min;
281 rtsp_st->interleaved_max = request.transports[0].interleaved_max;
282 snprintf(responseheaders, sizeof(responseheaders), "Transport: "
283 "RTP/AVP/TCP;unicast;mode=receive;interleaved=%d-%d"
284 "\r\n", request.transports[0].interleaved_min,
285 request.transports[0].interleaved_max);
288 ff_url_join(url, sizeof(url), "rtp", NULL, host, localport, NULL);
289 av_dlog(s, "Opening: %s", url);
290 ret = ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
291 &s->interrupt_callback, NULL);
294 } while (ret || localport > rt->rtp_port_max);
295 if (localport > rt->rtp_port_max) {
296 rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
300 av_dlog(s, "Listening on: %d",
301 ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle));
302 if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
303 rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
307 localport = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
308 snprintf(responseheaders, sizeof(responseheaders), "Transport: "
309 "RTP/AVP/UDP;unicast;mode=receive;source=%s;"
310 "client_port=%d-%d;server_port=%d-%d\r\n",
311 host, request.transports[0].client_port_min,
312 request.transports[0].client_port_max, localport,
316 /* Establish sessionid if not previously set */
317 /* Put this in a function? */
318 /* RFC 2326: session id must be at least 8 digits */
319 while (strlen(rt->session_id) < 8)
320 av_strlcatf(rt->session_id, 512, "%u", av_get_random_seed());
322 av_strlcatf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
325 rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
327 rt->state = RTSP_STATE_PAUSED;
331 static int rtsp_read_record(AVFormatContext *s)
333 RTSPState *rt = s->priv_data;
334 RTSPMessageHeader request = { 0 };
336 char responseheaders[1024];
338 ret = rtsp_read_request(s, &request, "RECORD");
341 ret = check_sessionid(s, &request);
345 snprintf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
347 rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
349 rt->state = RTSP_STATE_STREAMING;
353 static inline int parse_command_line(AVFormatContext *s, const char *line,
354 int linelen, char *uri, int urisize,
355 char *method, int methodsize,
356 enum RTSPMethod *methodcode)
358 RTSPState *rt = s->priv_data;
359 const char *linept, *searchlinept;
360 linept = strchr(line, ' ');
361 if (linept - line > methodsize - 1) {
362 av_log(s, AV_LOG_ERROR, "Method string too long\n");
365 memcpy(method, line, linept - line);
366 method[linept - line] = '\0';
368 if (!strcmp(method, "ANNOUNCE"))
369 *methodcode = ANNOUNCE;
370 else if (!strcmp(method, "OPTIONS"))
371 *methodcode = OPTIONS;
372 else if (!strcmp(method, "RECORD"))
373 *methodcode = RECORD;
374 else if (!strcmp(method, "SETUP"))
376 else if (!strcmp(method, "PAUSE"))
378 else if (!strcmp(method, "TEARDOWN"))
379 *methodcode = TEARDOWN;
381 *methodcode = UNKNOWN;
382 /* Check method with the state */
383 if (rt->state == RTSP_STATE_IDLE) {
384 if ((*methodcode != ANNOUNCE) && (*methodcode != OPTIONS)) {
385 av_log(s, AV_LOG_ERROR, "Unexpected command in Idle State %s\n",
387 return AVERROR_PROTOCOL_NOT_FOUND;
389 } else if (rt->state == RTSP_STATE_PAUSED) {
390 if ((*methodcode != OPTIONS) && (*methodcode != RECORD)
391 && (*methodcode != SETUP)) {
392 av_log(s, AV_LOG_ERROR, "Unexpected command in Paused State %s\n",
394 return AVERROR_PROTOCOL_NOT_FOUND;
396 } else if (rt->state == RTSP_STATE_STREAMING) {
397 if ((*methodcode != PAUSE) && (*methodcode != OPTIONS)
398 && (*methodcode != TEARDOWN)) {
399 av_log(s, AV_LOG_ERROR, "Unexpected command in Streaming State"
401 return AVERROR_PROTOCOL_NOT_FOUND;
404 av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
408 searchlinept = strchr(linept, ' ');
409 if (searchlinept == NULL) {
410 av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
411 return AVERROR_INVALIDDATA;
413 if (searchlinept - linept > urisize - 1) {
414 av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
417 memcpy(uri, linept, searchlinept - linept);
418 uri[searchlinept - linept] = '\0';
419 if (strcmp(rt->control_uri, uri)) {
420 char host[128], path[512], auth[128];
422 char ctl_host[128], ctl_path[512], ctl_auth[128];
424 av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
425 path, sizeof(path), uri);
426 av_url_split(NULL, 0, ctl_auth, sizeof(ctl_auth), ctl_host,
427 sizeof(ctl_host), &ctl_port, ctl_path, sizeof(ctl_path),
429 if (strcmp(host, ctl_host))
430 av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
432 if (strcmp(path, ctl_path) && *methodcode != SETUP)
433 av_log(s, AV_LOG_WARNING, "WARNING: Path %s differs from expected"
434 " %s\n", path, ctl_path);
435 if (*methodcode == ANNOUNCE) {
436 av_log(s, AV_LOG_INFO,
437 "Updating control URI to %s\n", uri);
438 strcpy(rt->control_uri, uri);
442 linept = searchlinept + 1;
443 if (!av_strstart(linept, "RTSP/1.0", NULL)) {
444 av_log(s, AV_LOG_ERROR, "Error parsing protocol or version\n");
445 return AVERROR_PROTOCOL_NOT_FOUND;
450 int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
452 RTSPState *rt = s->priv_data;
453 unsigned char rbuf[4096];
454 unsigned char method[10];
458 RTSPMessageHeader request = { 0 };
459 enum RTSPMethod methodcode;
461 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
464 ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
465 sizeof(method), &methodcode);
467 av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
471 ret = rtsp_read_request(s, &request, method);
475 if (methodcode == PAUSE) {
476 rt->state = RTSP_STATE_PAUSED;
477 ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
478 // TODO: Missing date header in response
479 } else if (methodcode == OPTIONS) {
480 ret = rtsp_send_reply(s, RTSP_STATUS_OK,
481 "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, "
482 "RECORD\r\n", request.seq);
483 } else if (methodcode == TEARDOWN) {
484 rt->state = RTSP_STATE_IDLE;
485 ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
491 static int rtsp_read_play(AVFormatContext *s)
493 RTSPState *rt = s->priv_data;
494 RTSPMessageHeader reply1, *reply = &reply1;
498 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
501 if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
502 if (rt->transport == RTSP_TRANSPORT_RTP) {
503 for (i = 0; i < rt->nb_rtsp_streams; i++) {
504 RTSPStream *rtsp_st = rt->rtsp_streams[i];
505 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
508 ff_rtp_reset_packet_queue(rtpctx);
509 rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
510 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
511 rtpctx->base_timestamp = 0;
512 rtpctx->timestamp = 0;
513 rtpctx->unwrapped_timestamp = 0;
514 rtpctx->rtcp_ts_offset = 0;
517 if (rt->state == RTSP_STATE_PAUSED) {
520 snprintf(cmd, sizeof(cmd),
521 "Range: npt=%"PRId64".%03"PRId64"-\r\n",
522 rt->seek_timestamp / AV_TIME_BASE,
523 rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
525 ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
526 if (reply->status_code != RTSP_STATUS_OK) {
529 if (rt->transport == RTSP_TRANSPORT_RTP &&
530 reply->range_start != AV_NOPTS_VALUE) {
531 for (i = 0; i < rt->nb_rtsp_streams; i++) {
532 RTSPStream *rtsp_st = rt->rtsp_streams[i];
533 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
535 if (!rtpctx || rtsp_st->stream_index < 0)
537 st = s->streams[rtsp_st->stream_index];
538 rtpctx->range_start_offset =
539 av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
544 rt->state = RTSP_STATE_STREAMING;
548 /* pause the stream */
549 static int rtsp_read_pause(AVFormatContext *s)
551 RTSPState *rt = s->priv_data;
552 RTSPMessageHeader reply1, *reply = &reply1;
554 if (rt->state != RTSP_STATE_STREAMING)
556 else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
557 ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
558 if (reply->status_code != RTSP_STATUS_OK) {
562 rt->state = RTSP_STATE_PAUSED;
566 int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
568 RTSPState *rt = s->priv_data;
570 unsigned char *content = NULL;
573 /* describe the stream */
574 snprintf(cmd, sizeof(cmd),
575 "Accept: application/sdp\r\n");
576 if (rt->server_type == RTSP_SERVER_REAL) {
578 * The Require: attribute is needed for proper streaming from
582 "Require: com.real.retain-entity-for-setup\r\n",
585 ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
587 return AVERROR_INVALIDDATA;
588 if (reply->status_code != RTSP_STATUS_OK) {
590 return AVERROR_INVALIDDATA;
593 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
594 /* now we got the SDP description, we parse it */
595 ret = ff_sdp_parse(s, (const char *)content);
603 static int rtsp_listen(AVFormatContext *s)
605 RTSPState *rt = s->priv_data;
606 char host[128], path[512], auth[128];
610 unsigned char rbuf[4096];
611 unsigned char method[10];
614 enum RTSPMethod methodcode;
616 /* extract hostname and port */
617 av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
618 path, sizeof(path), s->filename);
620 /* ff_url_join. No authorization by now (NULL) */
621 ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL, host,
623 /* Create TCP connection */
624 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port,
625 "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
627 if (ret = ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
628 &s->interrupt_callback, NULL)) {
629 av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
632 rt->state = RTSP_STATE_IDLE;
633 rt->rtsp_hd_out = rt->rtsp_hd;
634 for (;;) { /* Wait for incoming RTSP messages */
635 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
638 ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
639 sizeof(method), &methodcode);
641 av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
645 if (methodcode == ANNOUNCE) {
646 ret = rtsp_read_announce(s);
647 rt->state = RTSP_STATE_PAUSED;
648 } else if (methodcode == OPTIONS) {
649 ret = rtsp_read_options(s);
650 } else if (methodcode == RECORD) {
651 ret = rtsp_read_record(s);
653 return 0; // We are ready for streaming
654 } else if (methodcode == SETUP)
655 ret = rtsp_read_setup(s, host, uri);
657 ffurl_close(rt->rtsp_hd);
658 return AVERROR_INVALIDDATA;
664 static int rtsp_probe(AVProbeData *p)
666 if (av_strstart(p->filename, "rtsp:", NULL))
667 return AVPROBE_SCORE_MAX;
671 static int rtsp_read_header(AVFormatContext *s)
673 RTSPState *rt = s->priv_data;
676 if (rt->initial_timeout > 0)
677 rt->rtsp_flags |= RTSP_FLAG_LISTEN;
679 if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
680 ret = rtsp_listen(s);
684 ret = ff_rtsp_connect(s);
688 rt->real_setup_cache = !s->nb_streams ? NULL :
689 av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
690 if (!rt->real_setup_cache && s->nb_streams)
691 return AVERROR(ENOMEM);
692 rt->real_setup = rt->real_setup_cache + s->nb_streams;
694 if (rt->initial_pause) {
695 /* do not start immediately */
697 if (rtsp_read_play(s) < 0) {
698 ff_rtsp_close_streams(s);
699 ff_rtsp_close_connections(s);
700 return AVERROR_INVALIDDATA;
708 int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
709 uint8_t *buf, int buf_size)
711 RTSPState *rt = s->priv_data;
715 av_dlog(s, "tcp_read_packet:\n");
718 RTSPMessageHeader reply;
720 ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
723 if (ret == 1) /* received '$' */
725 /* XXX: parse message */
726 if (rt->state != RTSP_STATE_STREAMING)
729 ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
733 len = AV_RB16(buf + 1);
734 av_dlog(s, "id=%d len=%d\n", id, len);
735 if (len > buf_size || len < 8)
738 ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
741 if (rt->transport == RTSP_TRANSPORT_RDT &&
742 ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
745 /* find the matching stream */
746 for (i = 0; i < rt->nb_rtsp_streams; i++) {
747 rtsp_st = rt->rtsp_streams[i];
748 if (id >= rtsp_st->interleaved_min &&
749 id <= rtsp_st->interleaved_max)
758 static int resetup_tcp(AVFormatContext *s)
760 RTSPState *rt = s->priv_data;
764 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
766 ff_rtsp_undo_setup(s);
767 return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
771 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
773 RTSPState *rt = s->priv_data;
775 RTSPMessageHeader reply1, *reply = &reply1;
779 if (rt->server_type == RTSP_SERVER_REAL) {
782 for (i = 0; i < s->nb_streams; i++)
783 rt->real_setup[i] = s->streams[i]->discard;
785 if (!rt->need_subscription) {
786 if (memcmp (rt->real_setup, rt->real_setup_cache,
787 sizeof(enum AVDiscard) * s->nb_streams)) {
788 snprintf(cmd, sizeof(cmd),
789 "Unsubscribe: %s\r\n",
790 rt->last_subscription);
791 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
793 if (reply->status_code != RTSP_STATUS_OK)
794 return AVERROR_INVALIDDATA;
795 rt->need_subscription = 1;
799 if (rt->need_subscription) {
800 int r, rule_nr, first = 1;
802 memcpy(rt->real_setup_cache, rt->real_setup,
803 sizeof(enum AVDiscard) * s->nb_streams);
804 rt->last_subscription[0] = 0;
806 snprintf(cmd, sizeof(cmd),
808 for (i = 0; i < rt->nb_rtsp_streams; i++) {
810 for (r = 0; r < s->nb_streams; r++) {
811 if (s->streams[r]->id == i) {
812 if (s->streams[r]->discard != AVDISCARD_ALL) {
814 av_strlcat(rt->last_subscription, ",",
815 sizeof(rt->last_subscription));
816 ff_rdt_subscribe_rule(
817 rt->last_subscription,
818 sizeof(rt->last_subscription), i, rule_nr);
825 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
826 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
828 if (reply->status_code != RTSP_STATUS_OK)
829 return AVERROR_INVALIDDATA;
830 rt->need_subscription = 0;
832 if (rt->state == RTSP_STATE_STREAMING)
837 ret = ff_rtsp_fetch_packet(s, pkt);
839 if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
840 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
841 rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
842 RTSPMessageHeader reply1, *reply = &reply1;
843 av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
844 if (rtsp_read_pause(s) != 0)
846 // TEARDOWN is required on Real-RTSP, but might make
847 // other servers close the connection.
848 if (rt->server_type == RTSP_SERVER_REAL)
849 ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
851 rt->session_id[0] = '\0';
852 if (resetup_tcp(s) == 0) {
853 rt->state = RTSP_STATE_IDLE;
854 rt->need_subscription = 1;
855 if (rtsp_read_play(s) != 0)
865 if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) {
866 /* send dummy request to keep TCP connection alive */
867 if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
868 rt->auth_state.stale) {
869 if (rt->server_type == RTSP_SERVER_WMS ||
870 (rt->server_type != RTSP_SERVER_REAL &&
871 rt->get_parameter_supported)) {
872 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
874 ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
876 /* The stale flag should be reset when creating the auth response in
877 * ff_rtsp_send_cmd_async, but reset it here just in case we never
878 * called the auth code (if we didn't have any credentials set). */
879 rt->auth_state.stale = 0;
886 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
887 int64_t timestamp, int flags)
889 RTSPState *rt = s->priv_data;
891 rt->seek_timestamp = av_rescale_q(timestamp,
892 s->streams[stream_index]->time_base,
896 case RTSP_STATE_IDLE:
898 case RTSP_STATE_STREAMING:
899 if (rtsp_read_pause(s) != 0)
901 rt->state = RTSP_STATE_SEEKING;
902 if (rtsp_read_play(s) != 0)
905 case RTSP_STATE_PAUSED:
906 rt->state = RTSP_STATE_IDLE;
912 static const AVClass rtsp_demuxer_class = {
913 .class_name = "RTSP demuxer",
914 .item_name = av_default_item_name,
915 .option = ff_rtsp_options,
916 .version = LIBAVUTIL_VERSION_INT,
919 AVInputFormat ff_rtsp_demuxer = {
921 .long_name = NULL_IF_CONFIG_SMALL("RTSP input format"),
922 .priv_data_size = sizeof(RTSPState),
923 .read_probe = rtsp_probe,
924 .read_header = rtsp_read_header,
925 .read_packet = rtsp_read_packet,
926 .read_close = rtsp_read_close,
927 .read_seek = rtsp_read_seek,
928 .flags = AVFMT_NOFILE,
929 .read_play = rtsp_read_play,
930 .read_pause = rtsp_read_pause,
931 .priv_class = &rtsp_demuxer_class,