h264/aarch64: optimize neon loop filter
[libav.git] / libavformat / rtspdec.c
CommitLineData
0526c6f7
MS
1/*
2 * RTSP demuxer
3 * Copyright (c) 2002 Fabrice Bellard
4 *
2912e87a 5 * This file is part of Libav.
0526c6f7 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
0526c6f7
MS
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 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
0526c6f7
MS
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
2912e87a 18 * License along with Libav; if not, write to the Free Software
0526c6f7
MS
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "libavutil/avstring.h"
23#include "libavutil/intreadwrite.h"
0ebcdf5c 24#include "libavutil/mathematics.h"
a8ad6ffa 25#include "libavutil/random_seed.h"
c4ef6a3e 26#include "libavutil/time.h"
0526c6f7
MS
27#include "avformat.h"
28
29#include "internal.h"
30#include "network.h"
31#include "os_support.h"
b7e6da98 32#include "rtpproto.h"
0526c6f7
MS
33#include "rtsp.h"
34#include "rdt.h"
d8ffb205 35#include "tls.h"
dce37564 36#include "url.h"
0526c6f7 37
a8ad6ffa
JO
38static const struct RTSPStatusMessage {
39 enum RTSPStatusCode code;
40 const char *message;
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" },
53 { 0, "NULL" }
54};
55
6bbb3622
JO
56static int rtsp_read_close(AVFormatContext *s)
57{
58 RTSPState *rt = s->priv_data;
59
a8ad6ffa
JO
60 if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN))
61 ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
6bbb3622
JO
62
63 ff_rtsp_close_streams(s);
64 ff_rtsp_close_connections(s);
65 ff_network_close();
66 rt->real_setup = NULL;
67 av_freep(&rt->real_setup_cache);
68 return 0;
69}
70
a8ad6ffa
JO
71static inline int read_line(AVFormatContext *s, char *rbuf, const int rbufsize,
72 int *rbuflen)
73{
74 RTSPState *rt = s->priv_data;
75 int idx = 0;
76 int ret = 0;
77 *rbuflen = 0;
78
79 do {
80 ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1);
eae35ead
MN
81 if (ret <= 0)
82 return ret ? ret : AVERROR_EOF;
a8ad6ffa
JO
83 if (rbuf[idx] == '\r') {
84 /* Ignore */
85 } else if (rbuf[idx] == '\n') {
86 rbuf[idx] = '\0';
87 *rbuflen = idx;
88 return 0;
89 } else
90 idx++;
91 } while (idx < rbufsize);
92 av_log(s, AV_LOG_ERROR, "Message too long\n");
93 return AVERROR(EIO);
94}
95
96static int rtsp_send_reply(AVFormatContext *s, enum RTSPStatusCode code,
97 const char *extracontent, uint16_t seq)
98{
99 RTSPState *rt = s->priv_data;
100 char message[4096];
101 int index = 0;
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);
106 break;
107 }
108 index++;
109 }
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);
114 if (extracontent)
115 av_strlcat(message, extracontent, sizeof(message));
116 av_strlcat(message, "\r\n", sizeof(message));
1a3eb042 117 av_log(s, AV_LOG_TRACE, "Sending response:\n%s", message);
91089675 118 ffurl_write(rt->rtsp_hd_out, message, strlen(message));
a8ad6ffa
JO
119
120 return 0;
121}
122
123static inline int check_sessionid(AVFormatContext *s,
124 RTSPMessageHeader *request)
125{
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");
130 return 0;
131 }
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;
137 }
138 return 0;
139}
140
141static inline int rtsp_read_request(AVFormatContext *s,
142 RTSPMessageHeader *request,
143 const char *method)
144{
145 RTSPState *rt = s->priv_data;
146 char rbuf[1024];
147 int rbuflen, ret;
148 do {
149 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
150 if (ret)
151 return ret;
152 if (rbuflen > 1) {
1a3eb042 153 av_log(s, AV_LOG_TRACE, "Parsing[%d]: %s\n", rbuflen, rbuf);
2c17fb61 154 ff_rtsp_parse_line(s, request, rbuf, rt, method);
a8ad6ffa
JO
155 }
156 } while (rbuflen > 0);
157 if (request->seq != rt->seq + 1) {
158 av_log(s, AV_LOG_ERROR, "Unexpected Sequence number %d\n",
159 request->seq);
160 return AVERROR(EINVAL);
161 }
162 if (rt->session_id[0] && strcmp(method, "OPTIONS")) {
163 ret = check_sessionid(s, request);
164 if (ret)
165 return ret;
166 }
167
168 return 0;
169}
170
171static int rtsp_read_announce(AVFormatContext *s)
172{
173 RTSPState *rt = s->priv_data;
174 RTSPMessageHeader request = { 0 };
175 char sdp[4096];
176 int ret;
177
178 ret = rtsp_read_request(s, &request, "ANNOUNCE");
179 if (ret)
180 return ret;
181 rt->seq++;
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;
187 }
188 if (request.content_length && request.content_length < sizeof(sdp) - 1) {
189 /* Read SDP */
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);
195 return AVERROR(EIO);
196 }
197 sdp[request.content_length] = '\0';
198 av_log(s, AV_LOG_VERBOSE, "SDP: %s\n", sdp);
199 ret = ff_sdp_parse(s, sdp);
200 if (ret)
201 return ret;
202 rtsp_send_reply(s, RTSP_STATUS_OK, NULL, request.seq);
203 return 0;
204 }
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);
209 return AVERROR(EIO);
210}
211
212static int rtsp_read_options(AVFormatContext *s)
213{
214 RTSPState *rt = s->priv_data;
215 RTSPMessageHeader request = { 0 };
216 int ret = 0;
217
218 /* Parsing headers */
219 ret = rtsp_read_request(s, &request, "OPTIONS");
220 if (ret)
221 return ret;
222 rt->seq++;
223 /* Send Reply */
224 rtsp_send_reply(s, RTSP_STATUS_OK,
225 "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, RECORD\r\n",
226 request.seq);
227 return 0;
228}
229
230static int rtsp_read_setup(AVFormatContext *s, char* host, char *controlurl)
231{
232 RTSPState *rt = s->priv_data;
233 RTSPMessageHeader request = { 0 };
234 int ret = 0;
235 char url[1024];
236 RTSPStream *rtsp_st;
237 char responseheaders[1024];
238 int localport = -1;
239 int transportidx = 0;
240 int streamid = 0;
241
242 ret = rtsp_read_request(s, &request, "SETUP");
243 if (ret)
244 return ret;
245 rt->seq++;
246 if (!request.nb_transports) {
247 av_log(s, AV_LOG_ERROR, "No transport defined in SETUP\n");
248 return AVERROR_INVALIDDATA;
249 }
250 for (transportidx = 0; transportidx < request.nb_transports;
251 transportidx++) {
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;
260 }
261 }
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,
267 controlurl))
268 break;
269 }
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;
273 }
274 rtsp_st = rt->rtsp_streams[streamid];
275 localport = rt->rtp_port_min;
276
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);
281 return ret;
282 }
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);
289 } else {
290 do {
e3ec6fe7
LB
291 AVDictionary *opts = NULL;
292 char buf[256];
293 snprintf(buf, sizeof(buf), "%d", rt->buffer_size);
294 av_dict_set(&opts, "buffer_size", buf, 0);
a8ad6ffa 295 ff_url_join(url, sizeof(url), "rtp", NULL, host, localport, NULL);
1a3eb042 296 av_log(s, AV_LOG_TRACE, "Opening: %s", url);
a8ad6ffa 297 ret = ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
fab8156b 298 &s->interrupt_callback, &opts, rt->protocols, NULL);
e3ec6fe7 299 av_dict_free(&opts);
a8ad6ffa
JO
300 if (ret)
301 localport += 2;
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);
305 return ret;
306 }
307
1a3eb042 308 av_log(s, AV_LOG_TRACE, "Listening on: %d",
a8ad6ffa
JO
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);
312 return ret;
313 }
314
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,
321 localport + 1);
322 }
323
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());
329
330 av_strlcatf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
331 rt->session_id);
332 /* Send Reply */
333 rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
334
335 rt->state = RTSP_STATE_PAUSED;
336 return 0;
337}
338
339static int rtsp_read_record(AVFormatContext *s)
340{
341 RTSPState *rt = s->priv_data;
342 RTSPMessageHeader request = { 0 };
343 int ret = 0;
344 char responseheaders[1024];
345
346 ret = rtsp_read_request(s, &request, "RECORD");
347 if (ret)
348 return ret;
349 ret = check_sessionid(s, &request);
350 if (ret)
351 return ret;
352 rt->seq++;
353 snprintf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
354 rt->session_id);
355 rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
356
357 rt->state = RTSP_STATE_STREAMING;
358 return 0;
359}
360
361static 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)
365{
366 RTSPState *rt = s->priv_data;
367 const char *linept, *searchlinept;
368 linept = strchr(line, ' ');
c27328e7
LB
369
370 if (!linept)
371 return AVERROR_INVALIDDATA;
372
a8ad6ffa
JO
373 if (linept - line > methodsize - 1) {
374 av_log(s, AV_LOG_ERROR, "Method string too long\n");
375 return AVERROR(EIO);
376 }
377 memcpy(method, line, linept - line);
378 method[linept - line] = '\0';
379 linept++;
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"))
387 *methodcode = SETUP;
388 else if (!strcmp(method, "PAUSE"))
389 *methodcode = PAUSE;
390 else if (!strcmp(method, "TEARDOWN"))
391 *methodcode = TEARDOWN;
392 else
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",
398 line);
399 return AVERROR_PROTOCOL_NOT_FOUND;
400 }
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",
405 line);
406 return AVERROR_PROTOCOL_NOT_FOUND;
407 }
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"
412 " %s\n", line);
413 return AVERROR_PROTOCOL_NOT_FOUND;
414 }
415 } else {
416 av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
417 return AVERROR_BUG;
418 }
419
420 searchlinept = strchr(linept, ' ');
f929ab05 421 if (!searchlinept) {
a8ad6ffa
JO
422 av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
423 return AVERROR_INVALIDDATA;
424 }
425 if (searchlinept - linept > urisize - 1) {
426 av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
427 return AVERROR(EIO);
428 }
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];
433 int port;
434 char ctl_host[128], ctl_path[512], ctl_auth[128];
435 int ctl_port;
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),
440 rt->control_uri);
441 if (strcmp(host, ctl_host))
442 av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
443 host, ctl_host);
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);
d5ef9354 450 av_strlcpy(rt->control_uri, uri, sizeof(rt->control_uri));
a8ad6ffa
JO
451 }
452 }
453
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;
458 }
459 return 0;
460}
461
462int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
463{
464 RTSPState *rt = s->priv_data;
465 unsigned char rbuf[4096];
466 unsigned char method[10];
467 char uri[500];
468 int ret;
469 int rbuflen = 0;
470 RTSPMessageHeader request = { 0 };
471 enum RTSPMethod methodcode;
472
473 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
474 if (ret < 0)
475 return ret;
476 ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
477 sizeof(method), &methodcode);
478 if (ret) {
479 av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
480 return ret;
481 }
482
483 ret = rtsp_read_request(s, &request, method);
484 if (ret)
485 return ret;
486 rt->seq++;
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);
498 return 0;
499 }
500 return ret;
501}
502
0526c6f7
MS
503static int rtsp_read_play(AVFormatContext *s)
504{
505 RTSPState *rt = s->priv_data;
506 RTSPMessageHeader reply1, *reply = &reply1;
507 int i;
508 char cmd[1024];
509
510 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
511 rt->nb_byes = 0;
512
cdcc3702
GC
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.
519 */
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);
523 }
524 }
0526c6f7 525 if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1726813f
MS
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;
530 if (!rtpctx)
531 continue;
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;
12348ca2
JB
536 rtpctx->timestamp = 0;
537 rtpctx->unwrapped_timestamp = 0;
1726813f
MS
538 rtpctx->rtcp_ts_offset = 0;
539 }
540 }
0526c6f7
MS
541 if (rt->state == RTSP_STATE_PAUSED) {
542 cmd[0] = 0;
543 } else {
544 snprintf(cmd, sizeof(cmd),
78e99e0f
CEH
545 "Range: npt=%"PRId64".%03"PRId64"-\r\n",
546 rt->seek_timestamp / AV_TIME_BASE,
547 rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
0526c6f7
MS
548 }
549 ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
550 if (reply->status_code != RTSP_STATUS_OK) {
551 return -1;
552 }
91d96bd3
MS
553 if (rt->transport == RTSP_TRANSPORT_RTP &&
554 reply->range_start != AV_NOPTS_VALUE) {
0526c6f7
MS
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;
558 AVStream *st = NULL;
91d96bd3 559 if (!rtpctx || rtsp_st->stream_index < 0)
0526c6f7 560 continue;
91d96bd3 561 st = s->streams[rtsp_st->stream_index];
4cb06874
MS
562 rtpctx->range_start_offset =
563 av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
564 st->time_base);
0526c6f7
MS
565 }
566 }
567 }
568 rt->state = RTSP_STATE_STREAMING;
569 return 0;
570}
571
e836b1b0
MS
572/* pause the stream */
573static int rtsp_read_pause(AVFormatContext *s)
574{
575 RTSPState *rt = s->priv_data;
576 RTSPMessageHeader reply1, *reply = &reply1;
577
578 if (rt->state != RTSP_STATE_STREAMING)
579 return 0;
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) {
583 return -1;
584 }
585 }
586 rt->state = RTSP_STATE_PAUSED;
587 return 0;
588}
589
0526c6f7
MS
590int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
591{
592 RTSPState *rt = s->priv_data;
593 char cmd[1024];
594 unsigned char *content = NULL;
595 int ret;
596
597 /* describe the stream */
598 snprintf(cmd, sizeof(cmd),
599 "Accept: application/sdp\r\n");
600 if (rt->server_type == RTSP_SERVER_REAL) {
601 /**
602 * The Require: attribute is needed for proper streaming from
603 * Realmedia servers.
604 */
605 av_strlcat(cmd,
606 "Require: com.real.retain-entity-for-setup\r\n",
607 sizeof(cmd));
608 }
609 ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
610 if (!content)
611 return AVERROR_INVALIDDATA;
612 if (reply->status_code != RTSP_STATUS_OK) {
613 av_freep(&content);
614 return AVERROR_INVALIDDATA;
615 }
616
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);
620 av_freep(&content);
621 if (ret < 0)
f81c7ac7 622 return ret;
0526c6f7
MS
623
624 return 0;
625}
626
a8ad6ffa
JO
627static int rtsp_listen(AVFormatContext *s)
628{
629 RTSPState *rt = s->priv_data;
c839b043 630 char proto[128], host[128], path[512], auth[128];
a8ad6ffa
JO
631 char uri[500];
632 int port;
c839b043 633 int default_port = RTSP_DEFAULT_PORT;
a8ad6ffa 634 char tcpname[500];
c839b043 635 const char *lower_proto = "tcp";
a8ad6ffa
JO
636 unsigned char rbuf[4096];
637 unsigned char method[10];
638 int rbuflen = 0;
639 int ret;
640 enum RTSPMethod methodcode;
641
8c0ceafb 642 if (!rt->protocols) {
ec4c4839
AK
643 rt->protocols = ffurl_get_protocols(s->protocol_whitelist,
644 s->protocol_blacklist);
8c0ceafb
AK
645 if (!rt->protocols)
646 return AVERROR(ENOMEM);
647 }
648
a8ad6ffa 649 /* extract hostname and port */
c839b043
LB
650 av_url_split(proto, sizeof(proto), auth, sizeof(auth), host, sizeof(host),
651 &port, path, sizeof(path), s->filename);
a8ad6ffa
JO
652
653 /* ff_url_join. No authorization by now (NULL) */
c839b043 654 ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL, host,
a8ad6ffa 655 port, "%s", path);
5a2cb782 656
c839b043
LB
657 if (!strcmp(proto, "rtsps")) {
658 lower_proto = "tls";
659 default_port = RTSPS_DEFAULT_PORT;
660 }
661
5a2cb782 662 if (port < 0)
c839b043 663 port = default_port;
5a2cb782 664
a8ad6ffa 665 /* Create TCP connection */
c839b043 666 ff_url_join(tcpname, sizeof(tcpname), lower_proto, NULL, host, port,
a8ad6ffa
JO
667 "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
668
669 if (ret = ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
fab8156b 670 &s->interrupt_callback, NULL, rt->protocols, NULL)) {
a8ad6ffa
JO
671 av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
672 return ret;
673 }
674 rt->state = RTSP_STATE_IDLE;
675 rt->rtsp_hd_out = rt->rtsp_hd;
676 for (;;) { /* Wait for incoming RTSP messages */
677 ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
678 if (ret < 0)
679 return ret;
680 ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
681 sizeof(method), &methodcode);
682 if (ret) {
683 av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
684 return ret;
685 }
686
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);
694 if (!ret)
695 return 0; // We are ready for streaming
696 } else if (methodcode == SETUP)
697 ret = rtsp_read_setup(s, host, uri);
698 if (ret) {
699 ffurl_close(rt->rtsp_hd);
700 return AVERROR_INVALIDDATA;
701 }
702 }
a8ad6ffa
JO
703}
704
0526c6f7
MS
705static int rtsp_probe(AVProbeData *p)
706{
3df8d52f
LB
707 if (
708#if CONFIG_TLS_PROTOCOL
709 av_strstart(p->filename, "rtsps:", NULL) ||
710#endif
711 av_strstart(p->filename, "rtsp:", NULL))
0526c6f7
MS
712 return AVPROBE_SCORE_MAX;
713 return 0;
714}
715
6e9651d1 716static int rtsp_read_header(AVFormatContext *s)
0526c6f7
MS
717{
718 RTSPState *rt = s->priv_data;
719 int ret;
720
a8ad6ffa
JO
721 if (rt->initial_timeout > 0)
722 rt->rtsp_flags |= RTSP_FLAG_LISTEN;
0526c6f7 723
a8ad6ffa
JO
724 if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
725 ret = rtsp_listen(s);
726 if (ret)
727 return ret;
0526c6f7 728 } else {
a8ad6ffa
JO
729 ret = ff_rtsp_connect(s);
730 if (ret)
731 return ret;
732
733 rt->real_setup_cache = !s->nb_streams ? NULL :
734 av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
735 if (!rt->real_setup_cache && s->nb_streams)
736 return AVERROR(ENOMEM);
737 rt->real_setup = rt->real_setup_cache + s->nb_streams;
738
739 if (rt->initial_pause) {
740 /* do not start immediately */
741 } else {
742 if (rtsp_read_play(s) < 0) {
743 ff_rtsp_close_streams(s);
744 ff_rtsp_close_connections(s);
745 return AVERROR_INVALIDDATA;
746 }
0526c6f7
MS
747 }
748 }
749
750 return 0;
751}
752
753int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
754 uint8_t *buf, int buf_size)
755{
756 RTSPState *rt = s->priv_data;
757 int id, len, i, ret;
758 RTSPStream *rtsp_st;
759
1a3eb042 760 av_log(s, AV_LOG_TRACE, "tcp_read_packet:\n");
0526c6f7
MS
761redo:
762 for (;;) {
763 RTSPMessageHeader reply;
764
3df54c6b 765 ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
0526c6f7
MS
766 if (ret < 0)
767 return ret;
768 if (ret == 1) /* received '$' */
769 break;
770 /* XXX: parse message */
771 if (rt->state != RTSP_STATE_STREAMING)
772 return 0;
773 }
dce37564 774 ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
0526c6f7
MS
775 if (ret != 3)
776 return -1;
777 id = buf[0];
778 len = AV_RB16(buf + 1);
1a3eb042 779 av_log(s, AV_LOG_TRACE, "id=%d len=%d\n", id, len);
0526c6f7
MS
780 if (len > buf_size || len < 12)
781 goto redo;
782 /* get the data */
dce37564 783 ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
0526c6f7
MS
784 if (ret != len)
785 return -1;
786 if (rt->transport == RTSP_TRANSPORT_RDT &&
787 ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
788 return -1;
789
790 /* find the matching stream */
791 for (i = 0; i < rt->nb_rtsp_streams; i++) {
792 rtsp_st = rt->rtsp_streams[i];
793 if (id >= rtsp_st->interleaved_min &&
794 id <= rtsp_st->interleaved_max)
795 goto found;
796 }
797 goto redo;
798found:
799 *prtsp_st = rtsp_st;
800 return len;
801}
2762a7a2
MS
802
803static int resetup_tcp(AVFormatContext *s)
804{
805 RTSPState *rt = s->priv_data;
806 char host[1024];
807 int port;
808
809 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
810 s->filename);
50aef03b 811 ff_rtsp_undo_setup(s, 0);
2762a7a2
MS
812 return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
813 rt->real_challenge);
814}
815
0526c6f7
MS
816static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
817{
818 RTSPState *rt = s->priv_data;
819 int ret;
820 RTSPMessageHeader reply1, *reply = &reply1;
821 char cmd[1024];
822
2762a7a2 823retry:
0526c6f7
MS
824 if (rt->server_type == RTSP_SERVER_REAL) {
825 int i;
826
827 for (i = 0; i < s->nb_streams; i++)
828 rt->real_setup[i] = s->streams[i]->discard;
829
830 if (!rt->need_subscription) {
831 if (memcmp (rt->real_setup, rt->real_setup_cache,
832 sizeof(enum AVDiscard) * s->nb_streams)) {
833 snprintf(cmd, sizeof(cmd),
834 "Unsubscribe: %s\r\n",
835 rt->last_subscription);
836 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
837 cmd, reply, NULL);
838 if (reply->status_code != RTSP_STATUS_OK)
839 return AVERROR_INVALIDDATA;
840 rt->need_subscription = 1;
841 }
842 }
843
844 if (rt->need_subscription) {
845 int r, rule_nr, first = 1;
846
847 memcpy(rt->real_setup_cache, rt->real_setup,
848 sizeof(enum AVDiscard) * s->nb_streams);
849 rt->last_subscription[0] = 0;
850
851 snprintf(cmd, sizeof(cmd),
852 "Subscribe: ");
853 for (i = 0; i < rt->nb_rtsp_streams; i++) {
854 rule_nr = 0;
855 for (r = 0; r < s->nb_streams; r++) {
b2dd842d 856 if (s->streams[r]->id == i) {
0526c6f7
MS
857 if (s->streams[r]->discard != AVDISCARD_ALL) {
858 if (!first)
859 av_strlcat(rt->last_subscription, ",",
860 sizeof(rt->last_subscription));
861 ff_rdt_subscribe_rule(
862 rt->last_subscription,
863 sizeof(rt->last_subscription), i, rule_nr);
864 first = 0;
865 }
866 rule_nr++;
867 }
868 }
869 }
870 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
871 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
872 cmd, reply, NULL);
873 if (reply->status_code != RTSP_STATUS_OK)
874 return AVERROR_INVALIDDATA;
875 rt->need_subscription = 0;
876
877 if (rt->state == RTSP_STATE_STREAMING)
878 rtsp_read_play (s);
879 }
880 }
881
882 ret = ff_rtsp_fetch_packet(s, pkt);
2762a7a2 883 if (ret < 0) {
28c4741a 884 if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
2762a7a2
MS
885 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
886 rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
887 RTSPMessageHeader reply1, *reply = &reply1;
888 av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
889 if (rtsp_read_pause(s) != 0)
890 return -1;
891 // TEARDOWN is required on Real-RTSP, but might make
892 // other servers close the connection.
893 if (rt->server_type == RTSP_SERVER_REAL)
894 ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
895 reply, NULL);
896 rt->session_id[0] = '\0';
897 if (resetup_tcp(s) == 0) {
898 rt->state = RTSP_STATE_IDLE;
899 rt->need_subscription = 1;
900 if (rtsp_read_play(s) != 0)
901 return -1;
902 goto retry;
903 }
904 }
905 }
0526c6f7 906 return ret;
2762a7a2
MS
907 }
908 rt->packets++;
0526c6f7 909
a8ad6ffa
JO
910 if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) {
911 /* send dummy request to keep TCP connection alive */
6df9d9b5 912 if ((av_gettime_relative() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
a8ad6ffa
JO
913 rt->auth_state.stale) {
914 if (rt->server_type == RTSP_SERVER_WMS ||
915 (rt->server_type != RTSP_SERVER_REAL &&
916 rt->get_parameter_supported)) {
917 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
918 } else {
70e981cf 919 ff_rtsp_send_cmd_async(s, "OPTIONS", rt->control_uri, NULL);
a8ad6ffa
JO
920 }
921 /* The stale flag should be reset when creating the auth response in
922 * ff_rtsp_send_cmd_async, but reset it here just in case we never
923 * called the auth code (if we didn't have any credentials set). */
924 rt->auth_state.stale = 0;
0526c6f7
MS
925 }
926 }
927
928 return 0;
929}
930
0526c6f7
MS
931static int rtsp_read_seek(AVFormatContext *s, int stream_index,
932 int64_t timestamp, int flags)
933{
934 RTSPState *rt = s->priv_data;
935
936 rt->seek_timestamp = av_rescale_q(timestamp,
937 s->streams[stream_index]->time_base,
938 AV_TIME_BASE_Q);
939 switch(rt->state) {
940 default:
941 case RTSP_STATE_IDLE:
942 break;
943 case RTSP_STATE_STREAMING:
944 if (rtsp_read_pause(s) != 0)
945 return -1;
946 rt->state = RTSP_STATE_SEEKING;
947 if (rtsp_read_play(s) != 0)
948 return -1;
949 break;
950 case RTSP_STATE_PAUSED:
951 rt->state = RTSP_STATE_IDLE;
952 break;
953 }
954 return 0;
955}
956
735be9cd 957static const AVClass rtsp_demuxer_class = {
4779f593
AK
958 .class_name = "RTSP demuxer",
959 .item_name = av_default_item_name,
17fff881 960 .option = ff_rtsp_options,
4779f593
AK
961 .version = LIBAVUTIL_VERSION_INT,
962};
963
c6610a21 964AVInputFormat ff_rtsp_demuxer = {
dfc2c4d9 965 .name = "rtsp",
6774247a 966 .long_name = NULL_IF_CONFIG_SMALL("RTSP input"),
dfc2c4d9
AK
967 .priv_data_size = sizeof(RTSPState),
968 .read_probe = rtsp_probe,
969 .read_header = rtsp_read_header,
970 .read_packet = rtsp_read_packet,
971 .read_close = rtsp_read_close,
972 .read_seek = rtsp_read_seek,
17934c18
MS
973 .flags = AVFMT_NOFILE,
974 .read_play = rtsp_read_play,
975 .read_pause = rtsp_read_pause,
976 .priv_class = &rtsp_demuxer_class,
0526c6f7 977};