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