rtpproto: Support more than one SSM include address, support excludes
[libav.git] / libavformat / rtsp.c
CommitLineData
1617ad97 1/*
93ced3e8 2 * RTSP/SDP client
406792e7 3 * Copyright (c) 2002 Fabrice Bellard
1617ad97 4 *
2912e87a 5 * This file is part of Libav.
b78e7197 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
1617ad97
FB
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
b78e7197 10 * version 2.1 of the License, or (at your option) any later version.
1617ad97 11 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
1617ad97
FB
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
5509bffa 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1617ad97 20 */
245976da 21
f9337897 22#include "libavutil/base64.h"
245976da 23#include "libavutil/avstring.h"
6a5d31ac 24#include "libavutil/intreadwrite.h"
0ebcdf5c 25#include "libavutil/mathematics.h"
9fcae973 26#include "libavutil/parseutils.h"
f5d33f52 27#include "libavutil/random_seed.h"
d2d67e42 28#include "libavutil/dict.h"
d450cc4f 29#include "libavutil/opt.h"
c4ef6a3e 30#include "libavutil/time.h"
1617ad97 31#include "avformat.h"
e731b8d8 32#include "avio_internal.h"
1617ad97 33
a8475bbd
LB
34#if HAVE_POLL_H
35#include <poll.h>
6ad1c9c9 36#endif
e4a9e3cc 37#include "internal.h"
42572ef5 38#include "network.h"
cbfa66d0 39#include "os_support.h"
f5d33f52 40#include "http.h"
c971ff19 41#include "rtsp.h"
1617ad97 42
302879cb 43#include "rtpdec.h"
e9dea59f 44#include "rdt.h"
965a3ddb 45#include "rtpdec_formats.h"
a493f80a 46#include "rtpenc_chain.h"
5652bb94 47#include "url.h"
17fff881 48#include "rtpenc.h"
1243c722 49#include "mpegts.h"
4934884a 50
a8475bbd 51/* Timeout values for socket poll, in ms,
9cba6f5f 52 * and read_packet(), in seconds */
a8475bbd 53#define POLL_TIMEOUT_MS 100
9cba6f5f 54#define READ_PACKET_TIMEOUT_S 10
a8475bbd 55#define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / POLL_TIMEOUT_MS
91af5601 56#define SDP_MAX_SIZE 16384
96a7c975 57#define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
ccfa8aa2 58#define DEFAULT_REORDERING_DELAY 100000
9cba6f5f 59
2c9aa024
MS
60#define OFFSET(x) offsetof(RTSPState, x)
61#define DEC AV_OPT_FLAG_DECODING_PARAM
eca4850c 62#define ENC AV_OPT_FLAG_ENCODING_PARAM
3a6765fb
MS
63
64#define RTSP_FLAG_OPTS(name, longname) \
d58dd4b5 65 { name, longname, OFFSET(rtsp_flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtsp_flags" }, \
124134e4
MS
66 { "filter_src", "Only receive packets from the negotiated peer IP", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_FILTER_SRC}, 0, 0, DEC, "rtsp_flags" }, \
67 { "listen", "Wait for incoming connections", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_LISTEN}, 0, 0, DEC, "rtsp_flags" }
3a6765fb 68
f011fcd6 69#define RTSP_MEDIATYPE_OPTS(name, longname) \
d58dd4b5 70 { name, longname, OFFSET(media_type_mask), AV_OPT_TYPE_FLAGS, { .i64 = (1 << (AVMEDIA_TYPE_DATA+1)) - 1 }, INT_MIN, INT_MAX, DEC, "allowed_media_types" }, \
124134e4
MS
71 { "video", "Video", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_VIDEO}, 0, 0, DEC, "allowed_media_types" }, \
72 { "audio", "Audio", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_AUDIO}, 0, 0, DEC, "allowed_media_types" }, \
73 { "data", "Data", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_DATA}, 0, 0, DEC, "allowed_media_types" }
f011fcd6 74
3f055f8f
MS
75#define RTSP_REORDERING_OPTS() \
76 { "reorder_queue_size", "Number of packets to buffer for handling of reordered packets", OFFSET(reordering_queue_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, DEC }
77
17fff881 78const AVOption ff_rtsp_options[] = {
e6153f17 79 { "initial_pause", "Don't start playing the stream immediately", OFFSET(initial_pause), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
5354a904 80 FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags),
d58dd4b5 81 { "rtsp_transport", "RTSP transport protocols", OFFSET(lower_transport_mask), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, DEC|ENC, "rtsp_transport" }, \
124134e4
MS
82 { "udp", "UDP", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_UDP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
83 { "tcp", "TCP", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_TCP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
84 { "udp_multicast", "UDP multicast", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_UDP_MULTICAST}, 0, 0, DEC, "rtsp_transport" },
85 { "http", "HTTP tunneling", 0, AV_OPT_TYPE_CONST, {.i64 = (1 << RTSP_LOWER_TRANSPORT_HTTP)}, 0, 0, DEC, "rtsp_transport" },
3a6765fb 86 RTSP_FLAG_OPTS("rtsp_flags", "RTSP flags"),
f011fcd6 87 RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
e6153f17
MS
88 { "min_port", "Minimum local UDP port", OFFSET(rtp_port_min), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MIN}, 0, 65535, DEC|ENC },
89 { "max_port", "Maximum local UDP port", OFFSET(rtp_port_max), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MAX}, 0, 65535, DEC|ENC },
90 { "timeout", "Maximum timeout (in seconds) to wait for incoming connections. -1 is infinite. Implies flag listen", OFFSET(initial_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, DEC },
3f055f8f 91 RTSP_REORDERING_OPTS(),
17fff881
MS
92 { NULL },
93};
94
51369f28
MS
95static const AVOption sdp_options[] = {
96 RTSP_FLAG_OPTS("sdp_flags", "SDP flags"),
e96406ed 97 { "custom_io", "Use custom IO", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_CUSTOM_IO}, 0, 0, DEC, "rtsp_flags" },
f011fcd6 98 RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
3f055f8f 99 RTSP_REORDERING_OPTS(),
51369f28
MS
100 { NULL },
101};
102
103static const AVOption rtp_options[] = {
104 RTSP_FLAG_OPTS("rtp_flags", "RTP flags"),
3f055f8f 105 RTSP_REORDERING_OPTS(),
51369f28
MS
106 { NULL },
107};
108
1ef36a70
RB
109static void get_word_until_chars(char *buf, int buf_size,
110 const char *sep, const char **pp)
1617ad97
FB
111{
112 const char *p;
113 char *q;
114
115 p = *pp;
30619e6e 116 p += strspn(p, SPACE_CHARS);
1617ad97
FB
117 q = buf;
118 while (!strchr(sep, *p) && *p != '\0') {
119 if ((q - buf) < buf_size - 1)
120 *q++ = *p;
121 p++;
122 }
123 if (buf_size > 0)
124 *q = '\0';
125 *pp = p;
126}
127
1ef36a70
RB
128static void get_word_sep(char *buf, int buf_size, const char *sep,
129 const char **pp)
1617ad97 130{
1ef36a70
RB
131 if (**pp == '/') (*pp)++;
132 get_word_until_chars(buf, buf_size, sep, pp);
133}
1617ad97 134
1ef36a70
RB
135static void get_word(char *buf, int buf_size, const char **pp)
136{
137 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
1617ad97
FB
138}
139
8bf0f969
MS
140/** Parse a string p in the form of Range:npt=xx-xx, and determine the start
141 * and end time.
142 * Used for seeking in the rtp stream.
143 */
144static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
145{
146 char buf[256];
147
148 p += strspn(p, SPACE_CHARS);
149 if (!av_stristart(p, "npt=", &p))
150 return;
151
152 *start = AV_NOPTS_VALUE;
153 *end = AV_NOPTS_VALUE;
154
155 get_word_sep(buf, sizeof(buf), "-", &p);
9fcae973 156 av_parse_time(start, buf, 1);
8bf0f969
MS
157 if (*p == '-') {
158 p++;
159 get_word_sep(buf, sizeof(buf), "-", &p);
9fcae973 160 av_parse_time(end, buf, 1);
8bf0f969 161 }
8bf0f969
MS
162}
163
164static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
165{
a92be9b8 166 struct addrinfo hints = { 0 }, *ai = NULL;
8bf0f969
MS
167 hints.ai_flags = AI_NUMERICHOST;
168 if (getaddrinfo(buf, NULL, &hints, &ai))
169 return -1;
170 memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
171 freeaddrinfo(ai);
172 return 0;
173}
174
44b70ce5 175#if CONFIG_RTPDEC
003eb642
MS
176static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
177 RTSPStream *rtsp_st, AVCodecContext *codec)
178{
179 if (!handler)
180 return;
2326558d
MS
181 if (codec)
182 codec->codec_id = handler->codec_id;
003eb642 183 rtsp_st->dynamic_handler = handler;
4b3dc857 184 if (handler->alloc) {
9261e6cf 185 rtsp_st->dynamic_protocol_context = handler->alloc();
4b3dc857
MS
186 if (!rtsp_st->dynamic_protocol_context)
187 rtsp_st->dynamic_handler = NULL;
188 }
003eb642
MS
189}
190
c8965800 191/* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
8f3c87f3 192static int sdp_parse_rtpmap(AVFormatContext *s,
86b6e387 193 AVStream *st, RTSPStream *rtsp_st,
c8965800 194 int payload_type, const char *p)
93ced3e8 195{
86b6e387 196 AVCodecContext *codec = st->codec;
93ced3e8 197 char buf[256];
d1ccf0e0
RD
198 int i;
199 AVCodec *c;
7b49ce2e 200 const char *c_name;
93ced3e8 201
3900d53f 202 /* See if we can handle this kind of payload.
9d50d396
RB
203 * The space should normally not be there but some Real streams or
204 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
205 * have a trailing space. */
206 get_word_sep(buf, sizeof(buf), "/ ", &p);
6099543a
MS
207 if (payload_type < RTP_PT_PRIVATE) {
208 /* We are in a standard case
209 * (from http://www.iana.org/assignments/rtp-parameters). */
6099543a
MS
210 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
211 }
212
36ef5369 213 if (codec->codec_id == AV_CODEC_ID_NONE) {
003eb642
MS
214 RTPDynamicProtocolHandler *handler =
215 ff_rtp_handler_find_by_name(buf, codec->codec_type);
216 init_rtp_handler(handler, rtsp_st, codec);
160918d5
MS
217 /* If no dynamic handler was found, check with the list of standard
218 * allocated types, if such a stream for some reason happens to
219 * use a private payload type. This isn't handled in rtpdec.c, since
220 * the format name from the rtpmap line never is passed into rtpdec. */
221 if (!rtsp_st->dynamic_handler)
222 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
d1ccf0e0
RD
223 }
224
225 c = avcodec_find_decoder(codec->codec_id);
226 if (c && c->name)
7b49ce2e 227 c_name = c->name;
d1ccf0e0 228 else
170870b7 229 c_name = "(null)";
d1ccf0e0 230
7515ed0c
RB
231 get_word_sep(buf, sizeof(buf), "/", &p);
232 i = atoi(buf);
233 switch (codec->codec_type) {
72415b2a 234 case AVMEDIA_TYPE_AUDIO:
7515ed0c
RB
235 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
236 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
237 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
238 if (i > 0) {
239 codec->sample_rate = i;
c3f9ebf7 240 avpriv_set_pts_info(st, 32, 1, codec->sample_rate);
7515ed0c
RB
241 get_word_sep(buf, sizeof(buf), "/", &p);
242 i = atoi(buf);
243 if (i > 0)
244 codec->channels = i;
d1ccf0e0 245 }
7515ed0c
RB
246 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
247 codec->sample_rate);
248 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
249 codec->channels);
250 break;
72415b2a 251 case AVMEDIA_TYPE_VIDEO:
7515ed0c 252 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
86b6e387 253 if (i > 0)
c3f9ebf7 254 avpriv_set_pts_info(st, 32, 1, i);
7515ed0c
RB
255 break;
256 default:
257 break;
258 }
25836606
MS
259 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->init)
260 rtsp_st->dynamic_handler->init(s, st->index,
261 rtsp_st->dynamic_protocol_context);
7515ed0c 262 return 0;
93ced3e8
FB
263}
264
c2bfd816 265/* parse the attribute line from the fmtp a line of an sdp response. This
c8965800
RB
266 * is broken out as a function because it is used in rtp_h264.c, which is
267 * forthcoming. */
3307e6ea 268int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
93993933 269 char *value, int value_size)
d0deedcb 270{
30619e6e 271 *p += strspn(*p, SPACE_CHARS);
c8965800 272 if (**p) {
d0deedcb
RM
273 get_word_sep(attr, attr_size, "=", p);
274 if (**p == '=')
275 (*p)++;
276 get_word_sep(value, value_size, ";", p);
277 if (**p == ';')
278 (*p)++;
279 return 1;
280 }
281 return 0;
282}
283
93ced3e8
FB
284typedef struct SDPParseState {
285 /* SDP only */
3fbd12d1 286 struct sockaddr_storage default_ip;
c8965800
RB
287 int default_ttl;
288 int skip_media; ///< set if an unknown m= line occurs
93ced3e8
FB
289} SDPParseState;
290
291static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
1617ad97
FB
292 int letter, const char *buf)
293{
8b1ab7bf 294 RTSPState *rt = s->priv_data;
1617ad97
FB
295 char buf1[64], st_type[64];
296 const char *p;
72415b2a 297 enum AVMediaType codec_type;
fb65d2ca 298 int payload_type, i;
1617ad97
FB
299 AVStream *st;
300 RTSPStream *rtsp_st;
3fbd12d1 301 struct sockaddr_storage sdp_ip;
93ced3e8
FB
302 int ttl;
303
dfd2a005 304 av_dlog(s, "sdp: %c='%s'\n", letter, buf);
1617ad97
FB
305
306 p = buf;
cb760a47
RB
307 if (s1->skip_media && letter != 'm')
308 return;
c8965800 309 switch (letter) {
93ced3e8
FB
310 case 'c':
311 get_word(buf1, sizeof(buf1), &p);
312 if (strcmp(buf1, "IN") != 0)
313 return;
314 get_word(buf1, sizeof(buf1), &p);
3fbd12d1 315 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
93ced3e8
FB
316 return;
317 get_word_sep(buf1, sizeof(buf1), "/", &p);
3fbd12d1 318 if (get_sockaddr(buf1, &sdp_ip))
93ced3e8
FB
319 return;
320 ttl = 16;
321 if (*p == '/') {
322 p++;
323 get_word_sep(buf1, sizeof(buf1), "/", &p);
324 ttl = atoi(buf1);
325 }
326 if (s->nb_streams == 0) {
327 s1->default_ip = sdp_ip;
328 s1->default_ttl = ttl;
329 } else {
d9c0510e 330 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
93ced3e8
FB
331 rtsp_st->sdp_ip = sdp_ip;
332 rtsp_st->sdp_ttl = ttl;
333 }
334 break;
1617ad97 335 case 's':
d2d67e42 336 av_dict_set(&s->metadata, "title", p, 0);
1617ad97
FB
337 break;
338 case 'i':
339 if (s->nb_streams == 0) {
d2d67e42 340 av_dict_set(&s->metadata, "comment", p, 0);
1617ad97
FB
341 break;
342 }
343 break;
344 case 'm':
345 /* new stream */
cb760a47 346 s1->skip_media = 0;
f011fcd6 347 codec_type = AVMEDIA_TYPE_UNKNOWN;
1617ad97
FB
348 get_word(st_type, sizeof(st_type), &p);
349 if (!strcmp(st_type, "audio")) {
72415b2a 350 codec_type = AVMEDIA_TYPE_AUDIO;
1617ad97 351 } else if (!strcmp(st_type, "video")) {
72415b2a 352 codec_type = AVMEDIA_TYPE_VIDEO;
090438cc 353 } else if (!strcmp(st_type, "application")) {
72415b2a 354 codec_type = AVMEDIA_TYPE_DATA;
f011fcd6
JB
355 }
356 if (codec_type == AVMEDIA_TYPE_UNKNOWN || !(rt->media_type_mask & (1 << codec_type))) {
cb760a47 357 s1->skip_media = 1;
1617ad97
FB
358 return;
359 }
1617ad97
FB
360 rtsp_st = av_mallocz(sizeof(RTSPStream));
361 if (!rtsp_st)
362 return;
8b1ab7bf
FB
363 rtsp_st->stream_index = -1;
364 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
93ced3e8
FB
365
366 rtsp_st->sdp_ip = s1->default_ip;
367 rtsp_st->sdp_ttl = s1->default_ttl;
368
93ced3e8
FB
369 get_word(buf1, sizeof(buf1), &p); /* port */
370 rtsp_st->sdp_port = atoi(buf1);
371
df8cf076
MS
372 get_word(buf1, sizeof(buf1), &p); /* protocol */
373 if (!strcmp(buf1, "udp"))
374 rt->transport = RTSP_TRANSPORT_RAW;
86d9181c
MS
375 else if (strstr(buf1, "/AVPF") || strstr(buf1, "/SAVPF"))
376 rtsp_st->feedback = 1;
115329f1 377
93ced3e8
FB
378 /* XXX: handle list of formats */
379 get_word(buf1, sizeof(buf1), &p); /* format list */
380 rtsp_st->sdp_payload_type = atoi(buf1);
93ced3e8 381
7ed19d7f 382 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
8b1ab7bf 383 /* no corresponding stream */
2326558d
MS
384 if (rt->transport == RTSP_TRANSPORT_RAW) {
385 if (!rt->ts && CONFIG_RTPDEC)
386 rt->ts = ff_mpegts_parse_open(s);
387 } else {
388 RTPDynamicProtocolHandler *handler;
389 handler = ff_rtp_handler_find_by_id(
390 rtsp_st->sdp_payload_type, AVMEDIA_TYPE_DATA);
391 init_rtp_handler(handler, rtsp_st, NULL);
392 if (handler && handler->init)
393 handler->init(s, -1, rtsp_st->dynamic_protocol_context);
394 }
45600148
MS
395 } else if (rt->server_type == RTSP_SERVER_WMS &&
396 codec_type == AVMEDIA_TYPE_DATA) {
397 /* RTX stream, a stream that carries all the other actual
398 * audio/video streams. Don't expose this to the callers. */
8b1ab7bf 399 } else {
84ad31ff 400 st = avformat_new_stream(s, NULL);
8b1ab7bf
FB
401 if (!st)
402 return;
84ad31ff 403 st->id = rt->nb_rtsp_streams - 1;
8b1ab7bf 404 rtsp_st->stream_index = st->index;
01f4895c 405 st->codec->codec_type = codec_type;
d1ccf0e0 406 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
6a7e31a9 407 RTPDynamicProtocolHandler *handler;
8b1ab7bf 408 /* if standard payload type, we can find the codec right now */
bf6d9818 409 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
bbd8f547
MS
410 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
411 st->codec->sample_rate > 0)
c3f9ebf7 412 avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);
6a7e31a9
MS
413 /* Even static payload types may need a custom depacketizer */
414 handler = ff_rtp_handler_find_by_id(
415 rtsp_st->sdp_payload_type, st->codec->codec_type);
416 init_rtp_handler(handler, rtsp_st, st->codec);
25836606
MS
417 if (handler && handler->init)
418 handler->init(s, st->index,
419 rtsp_st->dynamic_protocol_context);
8b1ab7bf
FB
420 }
421 }
1617ad97 422 /* put a default control url */
00eb13e0 423 av_strlcpy(rtsp_st->control_url, rt->control_uri,
c8965800 424 sizeof(rtsp_st->control_url));
1617ad97
FB
425 break;
426 case 'a':
00eb13e0
AS
427 if (av_strstart(p, "control:", &p)) {
428 if (s->nb_streams == 0) {
429 if (!strncmp(p, "rtsp://", 7))
430 av_strlcpy(rt->control_uri, p,
431 sizeof(rt->control_uri));
432 } else {
0b6a7ff4
MS
433 char proto[32];
434 /* get the control url */
d9c0510e 435 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
115329f1 436
0b6a7ff4
MS
437 /* XXX: may need to add full url resolution */
438 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
439 NULL, NULL, 0, p);
440 if (proto[0] == '\0') {
441 /* relative control URL */
442 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
443 av_strlcat(rtsp_st->control_url, "/",
444 sizeof(rtsp_st->control_url));
445 av_strlcat(rtsp_st->control_url, p,
446 sizeof(rtsp_st->control_url));
447 } else
448 av_strlcpy(rtsp_st->control_url, p,
449 sizeof(rtsp_st->control_url));
00eb13e0 450 }
83d14c85 451 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
93ced3e8 452 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
115329f1 453 get_word(buf1, sizeof(buf1), &p);
93ced3e8 454 payload_type = atoi(buf1);
d9c0510e 455 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
45600148
MS
456 if (rtsp_st->stream_index >= 0) {
457 st = s->streams[rtsp_st->stream_index];
458 sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
459 }
7fc8ac7f
JA
460 } else if (av_strstart(p, "fmtp:", &p) ||
461 av_strstart(p, "framesize:", &p)) {
93ced3e8 462 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
d0deedcb
RM
463 // let dynamic protocol handlers have a stab at the line.
464 get_word(buf1, sizeof(buf1), &p);
465 payload_type = atoi(buf1);
d9c0510e
MS
466 for (i = 0; i < rt->nb_rtsp_streams; i++) {
467 rtsp_st = rt->rtsp_streams[i];
c8965800
RB
468 if (rtsp_st->sdp_payload_type == payload_type &&
469 rtsp_st->dynamic_handler &&
470 rtsp_st->dynamic_handler->parse_sdp_a_line)
471 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
472 rtsp_st->dynamic_protocol_context, buf);
d0deedcb 473 }
c8965800 474 } else if (av_strstart(p, "range:", &p)) {
31693e00
RM
475 int64_t start, end;
476
477 // this is so that seeking on a streamed file can work.
478 rtsp_parse_range_npt(p, &start, &end);
c8965800
RB
479 s->start_time = start;
480 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
481 s->duration = (end == AV_NOPTS_VALUE) ?
482 AV_NOPTS_VALUE : end - start;
119b4668
RB
483 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
484 if (atoi(p) == 1)
485 rt->transport = RTSP_TRANSPORT_RDT;
bb776f3b
MS
486 } else if (av_strstart(p, "SampleRate:integer;", &p) &&
487 s->nb_streams > 0) {
488 st = s->streams[s->nb_streams - 1];
489 st->codec->sample_rate = atoi(p);
424da308
MS
490 } else if (av_strstart(p, "crypto:", &p) && s->nb_streams > 0) {
491 // RFC 4568
492 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
493 get_word(buf1, sizeof(buf1), &p); // ignore tag
494 get_word(rtsp_st->crypto_suite, sizeof(rtsp_st->crypto_suite), &p);
495 p += strspn(p, SPACE_CHARS);
496 if (av_strstart(p, "inline:", &p))
497 get_word(rtsp_st->crypto_params, sizeof(rtsp_st->crypto_params), &p);
36fb0d02
ET
498 } else if (av_strstart(p, "source-filter:", &p) && s->nb_streams > 0) {
499 get_word(buf1, sizeof(buf1), &p);
500 if (strcmp(buf1, "incl"))
501 return;
502
503 get_word(buf1, sizeof(buf1), &p);
504 if (strcmp(buf1, "IN") != 0)
505 return;
506 get_word(buf1, sizeof(buf1), &p);
507 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
508 return;
509 // not checking that the destination address actually matches
510 get_word(buf1, sizeof(buf1), &p);
511
512 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
513 get_word(rtsp_st->source_addr, sizeof(rtsp_st->source_addr), &p);
1a30d541
RB
514 } else {
515 if (rt->server_type == RTSP_SERVER_WMS)
516 ff_wms_parse_sdp_a_line(s, p);
517 if (s->nb_streams > 0) {
45600148
MS
518 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
519
c4a3d032 520 if (rt->server_type == RTSP_SERVER_REAL)
45600148 521 ff_real_parse_sdp_a_line(s, rtsp_st->stream_index, p);
c4a3d032 522
c4a3d032
RB
523 if (rtsp_st->dynamic_handler &&
524 rtsp_st->dynamic_handler->parse_sdp_a_line)
c8965800 525 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
45600148 526 rtsp_st->stream_index,
c4a3d032 527 rtsp_st->dynamic_protocol_context, buf);
1a30d541 528 }
1617ad97
FB
529 }
530 break;
531 }
532}
533
0526c6f7 534int ff_sdp_parse(AVFormatContext *s, const char *content)
1617ad97 535{
a8475bbd 536 RTSPState *rt = s->priv_data;
1617ad97
FB
537 const char *p;
538 int letter;
9211bcdd
RB
539 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
540 * contain long SDP lines containing complete ASF Headers (several
541 * kB) or arrays of MDPR (RM stream descriptor) headers plus
542 * "rulebooks" describing their properties. Therefore, the SDP line
373afbaf
RB
543 * buffer is large.
544 *
afcea58c
JA
545 * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
546 * in rtpdec_xiph.c. */
373afbaf 547 char buf[16384], *q;
a92be9b8 548 SDPParseState sdp_parse_state = { { 0 } }, *s1 = &sdp_parse_state;
115329f1 549
1617ad97 550 p = content;
c8965800 551 for (;;) {
30619e6e 552 p += strspn(p, SPACE_CHARS);
1617ad97
FB
553 letter = *p;
554 if (letter == '\0')
555 break;
556 p++;
557 if (*p != '=')
558 goto next_line;
559 p++;
560 /* get the content */
561 q = buf;
b6892136 562 while (*p != '\n' && *p != '\r' && *p != '\0') {
1617ad97
FB
563 if ((q - buf) < sizeof(buf) - 1)
564 *q++ = *p;
565 p++;
566 }
567 *q = '\0';
93ced3e8 568 sdp_parse_line(s, s1, letter, buf);
1617ad97
FB
569 next_line:
570 while (*p != '\n' && *p != '\0')
571 p++;
572 if (*p == '\n')
573 p++;
574 }
a8475bbd
LB
575 rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
576 if (!rt->p) return AVERROR(ENOMEM);
1617ad97
FB
577 return 0;
578}
44b70ce5 579#endif /* CONFIG_RTPDEC */
1617ad97 580
93e7490e
MS
581void ff_rtsp_undo_setup(AVFormatContext *s)
582{
583 RTSPState *rt = s->priv_data;
584 int i;
585
586 for (i = 0; i < rt->nb_rtsp_streams; i++) {
587 RTSPStream *rtsp_st = rt->rtsp_streams[i];
588 if (!rtsp_st)
589 continue;
590 if (rtsp_st->transport_priv) {
591 if (s->oformat) {
592 AVFormatContext *rtpctx = rtsp_st->transport_priv;
593 av_write_trailer(rtpctx);
594 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
595 uint8_t *ptr;
6dc7d80d 596 avio_close_dyn_buf(rtpctx->pb, &ptr);
93e7490e
MS
597 av_free(ptr);
598 } else {
22a3212e 599 avio_close(rtpctx->pb);
93e7490e 600 }
b22dbb29 601 avformat_free_context(rtpctx);
93e7490e
MS
602 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
603 ff_rdt_parse_close(rtsp_st->transport_priv);
125c6c07 604 else if (rt->transport == RTSP_TRANSPORT_RTP && CONFIG_RTPDEC)
bfc6db44 605 ff_rtp_parse_close(rtsp_st->transport_priv);
93e7490e
MS
606 }
607 rtsp_st->transport_priv = NULL;
608 if (rtsp_st->rtp_handle)
e52a9145 609 ffurl_close(rtsp_st->rtp_handle);
93e7490e
MS
610 rtsp_st->rtp_handle = NULL;
611 }
612}
613
1ced9da3 614/* close and free RTSP streams */
3307e6ea 615void ff_rtsp_close_streams(AVFormatContext *s)
1ced9da3 616{
52aa4338 617 RTSPState *rt = s->priv_data;
1ced9da3
LA
618 int i;
619 RTSPStream *rtsp_st;
620
93e7490e 621 ff_rtsp_undo_setup(s);
c8965800 622 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1ced9da3
LA
623 rtsp_st = rt->rtsp_streams[i];
624 if (rtsp_st) {
1ced9da3 625 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
9261e6cf 626 rtsp_st->dynamic_handler->free(
c8965800 627 rtsp_st->dynamic_protocol_context);
ea7f0807 628 av_free(rtsp_st);
1ced9da3
LA
629 }
630 }
631 av_free(rt->rtsp_streams);
632 if (rt->asf_ctx) {
cd3716b9 633 avformat_close_input(&rt->asf_ctx);
1ced9da3 634 }
1243c722
MS
635 if (rt->ts && CONFIG_RTPDEC)
636 ff_mpegts_parse_close(rt->ts);
a8475bbd 637 av_free(rt->p);
96a7c975 638 av_free(rt->recvbuf);
1ced9da3
LA
639}
640
6e71c120 641int ff_rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
1ced9da3
LA
642{
643 RTSPState *rt = s->priv_data;
644 AVStream *st = NULL;
3f055f8f
MS
645 int reordering_queue_size = rt->reordering_queue_size;
646 if (reordering_queue_size < 0) {
647 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
648 reordering_queue_size = 0;
649 else
650 reordering_queue_size = RTP_REORDER_QUEUE_DEFAULT_SIZE;
651 }
1ced9da3
LA
652
653 /* open the RTP context */
654 if (rtsp_st->stream_index >= 0)
655 st = s->streams[rtsp_st->stream_index];
656 if (!st)
657 s->ctx_flags |= AVFMTCTX_NOHEADER;
658
44b70ce5 659 if (s->oformat && CONFIG_RTSP_MUXER) {
68c81308
MS
660 int ret = ff_rtp_chain_mux_open(&rtsp_st->transport_priv, s, st,
661 rtsp_st->rtp_handle,
8034130e
LB
662 RTSP_TCP_MAX_PACKET_SIZE,
663 rtsp_st->stream_index);
c2bfd816 664 /* Ownership of rtp_handle is passed to the rtp mux context */
fd450a51 665 rtsp_st->rtp_handle = NULL;
68c81308
MS
666 if (ret < 0)
667 return ret;
df8cf076
MS
668 } else if (rt->transport == RTSP_TRANSPORT_RAW) {
669 return 0; // Don't need to open any parser here
44b70ce5 670 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
1ced9da3
LA
671 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
672 rtsp_st->dynamic_protocol_context,
673 rtsp_st->dynamic_handler);
44b70ce5 674 else if (CONFIG_RTPDEC)
3f95f0dd 675 rtsp_st->transport_priv = ff_rtp_parse_open(s, st,
58ee0991 676 rtsp_st->sdp_payload_type,
3f055f8f 677 reordering_queue_size);
1ced9da3
LA
678
679 if (!rtsp_st->transport_priv) {
680 return AVERROR(ENOMEM);
df8cf076 681 } else if (rt->transport == RTSP_TRANSPORT_RTP && CONFIG_RTPDEC) {
c8965800 682 if (rtsp_st->dynamic_handler) {
bfc6db44
MS
683 ff_rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
684 rtsp_st->dynamic_protocol_context,
685 rtsp_st->dynamic_handler);
1ced9da3 686 }
424da308
MS
687 if (rtsp_st->crypto_suite[0])
688 ff_rtp_parse_set_crypto(rtsp_st->transport_priv,
689 rtsp_st->crypto_suite,
690 rtsp_st->crypto_params);
1ced9da3
LA
691 }
692
693 return 0;
694}
695
6f5a3d0a 696#if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
1617ad97
FB
697static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
698{
ddce7dab
MR
699 const char *q;
700 char *p;
1617ad97
FB
701 int v;
702
ddce7dab
MR
703 q = *pp;
704 q += strspn(q, SPACE_CHARS);
705 v = strtol(q, &p, 10);
1617ad97
FB
706 if (*p == '-') {
707 p++;
708 *min_ptr = v;
ddce7dab 709 v = strtol(p, &p, 10);
1617ad97
FB
710 *max_ptr = v;
711 } else {
712 *min_ptr = v;
713 *max_ptr = v;
714 }
715 *pp = p;
716}
717
718/* XXX: only one transport specification is parsed */
a9e534d5 719static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
1617ad97
FB
720{
721 char transport_protocol[16];
722 char profile[16];
723 char lower_transport[16];
724 char parameter[16];
725 RTSPTransportField *th;
726 char buf[256];
115329f1 727
1617ad97 728 reply->nb_transports = 0;
115329f1 729
c8965800 730 for (;;) {
30619e6e 731 p += strspn(p, SPACE_CHARS);
1617ad97
FB
732 if (*p == '\0')
733 break;
734
735 th = &reply->transports[reply->nb_transports];
736
115329f1 737 get_word_sep(transport_protocol, sizeof(transport_protocol),
1617ad97 738 "/", &p);
bb3244de 739 if (!av_strcasecmp (transport_protocol, "rtp")) {
7ecc634e
LB
740 get_word_sep(profile, sizeof(profile), "/;,", &p);
741 lower_transport[0] = '\0';
742 /* rtp/avp/<protocol> */
743 if (*p == '/') {
7ecc634e
LB
744 get_word_sep(lower_transport, sizeof(lower_transport),
745 ";,", &p);
119b4668
RB
746 }
747 th->transport = RTSP_TRANSPORT_RTP;
bb3244de
RD
748 } else if (!av_strcasecmp (transport_protocol, "x-pn-tng") ||
749 !av_strcasecmp (transport_protocol, "x-real-rdt")) {
7ecc634e 750 /* x-pn-tng/<protocol> */
e1502118
LB
751 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
752 profile[0] = '\0';
119b4668 753 th->transport = RTSP_TRANSPORT_RDT;
df8cf076
MS
754 } else if (!av_strcasecmp(transport_protocol, "raw")) {
755 get_word_sep(profile, sizeof(profile), "/;,", &p);
756 lower_transport[0] = '\0';
757 /* raw/raw/<protocol> */
758 if (*p == '/') {
759 get_word_sep(lower_transport, sizeof(lower_transport),
760 ";,", &p);
761 }
762 th->transport = RTSP_TRANSPORT_RAW;
1617ad97 763 }
bb3244de 764 if (!av_strcasecmp(lower_transport, "TCP"))
90abbdba 765 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
1617ad97 766 else
90abbdba 767 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
115329f1 768
1617ad97
FB
769 if (*p == ';')
770 p++;
771 /* get each parameter */
772 while (*p != '\0' && *p != ',') {
773 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
774 if (!strcmp(parameter, "port")) {
775 if (*p == '=') {
776 p++;
777 rtsp_parse_range(&th->port_min, &th->port_max, &p);
778 }
779 } else if (!strcmp(parameter, "client_port")) {
780 if (*p == '=') {
781 p++;
115329f1 782 rtsp_parse_range(&th->client_port_min,
1617ad97
FB
783 &th->client_port_max, &p);
784 }
785 } else if (!strcmp(parameter, "server_port")) {
786 if (*p == '=') {
787 p++;
115329f1 788 rtsp_parse_range(&th->server_port_min,
1617ad97
FB
789 &th->server_port_max, &p);
790 }
791 } else if (!strcmp(parameter, "interleaved")) {
792 if (*p == '=') {
793 p++;
115329f1 794 rtsp_parse_range(&th->interleaved_min,
1617ad97
FB
795 &th->interleaved_max, &p);
796 }
797 } else if (!strcmp(parameter, "multicast")) {
90abbdba
RB
798 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
799 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
1617ad97
FB
800 } else if (!strcmp(parameter, "ttl")) {
801 if (*p == '=') {
f21d5c90 802 char *end;
1617ad97 803 p++;
f21d5c90
MS
804 th->ttl = strtol(p, &end, 10);
805 p = end;
1617ad97
FB
806 }
807 } else if (!strcmp(parameter, "destination")) {
1617ad97
FB
808 if (*p == '=') {
809 p++;
810 get_word_sep(buf, sizeof(buf), ";,", &p);
7934b15d 811 get_sockaddr(buf, &th->destination);
1617ad97 812 }
619298a8
JW
813 } else if (!strcmp(parameter, "source")) {
814 if (*p == '=') {
815 p++;
816 get_word_sep(buf, sizeof(buf), ";,", &p);
817 av_strlcpy(th->source, buf, sizeof(th->source));
818 }
45b06858
JO
819 } else if (!strcmp(parameter, "mode")) {
820 if (*p == '=') {
821 p++;
822 get_word_sep(buf, sizeof(buf), ";, ", &p);
823 if (!strcmp(buf, "record") ||
824 !strcmp(buf, "receive"))
825 th->mode_record = 1;
826 }
1617ad97 827 }
619298a8 828
1617ad97
FB
829 while (*p != ';' && *p != '\0' && *p != ',')
830 p++;
831 if (*p == ';')
832 p++;
833 }
834 if (*p == ',')
835 p++;
836
837 reply->nb_transports++;
838 }
839}
840
29db7c3a
MS
841static void handle_rtp_info(RTSPState *rt, const char *url,
842 uint32_t seq, uint32_t rtptime)
843{
844 int i;
845 if (!rtptime || !url[0])
846 return;
847 if (rt->transport != RTSP_TRANSPORT_RTP)
848 return;
849 for (i = 0; i < rt->nb_rtsp_streams; i++) {
850 RTSPStream *rtsp_st = rt->rtsp_streams[i];
851 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
852 if (!rtpctx)
853 continue;
854 if (!strcmp(rtsp_st->control_url, url)) {
855 rtpctx->base_timestamp = rtptime;
856 break;
857 }
858 }
859}
860
861static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
862{
863 int read = 0;
864 char key[20], value[1024], url[1024] = "";
865 uint32_t seq = 0, rtptime = 0;
866
867 for (;;) {
868 p += strspn(p, SPACE_CHARS);
869 if (!*p)
870 break;
871 get_word_sep(key, sizeof(key), "=", &p);
872 if (*p != '=')
873 break;
874 p++;
875 get_word_sep(value, sizeof(value), ";, ", &p);
876 read++;
877 if (!strcmp(key, "url"))
878 av_strlcpy(url, value, sizeof(url));
879 else if (!strcmp(key, "seq"))
4515f9b5 880 seq = strtoul(value, NULL, 10);
29db7c3a 881 else if (!strcmp(key, "rtptime"))
4515f9b5 882 rtptime = strtoul(value, NULL, 10);
29db7c3a
MS
883 if (*p == ',') {
884 handle_rtp_info(rt, url, seq, rtptime);
885 url[0] = '\0';
886 seq = rtptime = 0;
887 read = 0;
888 }
889 if (*p)
890 p++;
891 }
892 if (read > 0)
893 handle_rtp_info(rt, url, seq, rtptime);
894}
895
2626308a 896void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
77223c53 897 RTSPState *rt, const char *method)
1617ad97
FB
898{
899 const char *p;
900
901 /* NOTE: we do case independent match for broken servers */
902 p = buf;
f7d78f36 903 if (av_stristart(p, "Session:", &p)) {
30e79845 904 int t;
1617ad97 905 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
30e79845
RB
906 if (av_stristart(p, ";timeout=", &p) &&
907 (t = strtol(p, NULL, 10)) > 0) {
908 reply->timeout = t;
909 }
f7d78f36 910 } else if (av_stristart(p, "Content-Length:", &p)) {
1617ad97 911 reply->content_length = strtol(p, NULL, 10);
f7d78f36 912 } else if (av_stristart(p, "Transport:", &p)) {
1617ad97 913 rtsp_parse_transport(reply, p);
f7d78f36 914 } else if (av_stristart(p, "CSeq:", &p)) {
1617ad97 915 reply->seq = strtol(p, NULL, 10);
f7d78f36 916 } else if (av_stristart(p, "Range:", &p)) {
31693e00 917 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
30aa6aed 918 } else if (av_stristart(p, "RealChallenge1:", &p)) {
30619e6e 919 p += strspn(p, SPACE_CHARS);
30aa6aed 920 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
7a86bafa 921 } else if (av_stristart(p, "Server:", &p)) {
30619e6e 922 p += strspn(p, SPACE_CHARS);
7a86bafa 923 av_strlcpy(reply->server, p, sizeof(reply->server));
fccb1770
RB
924 } else if (av_stristart(p, "Notice:", &p) ||
925 av_stristart(p, "X-Notice:", &p)) {
926 reply->notice = strtol(p, NULL, 10);
d243ba30 927 } else if (av_stristart(p, "Location:", &p)) {
30619e6e 928 p += strspn(p, SPACE_CHARS);
d243ba30 929 av_strlcpy(reply->location, p , sizeof(reply->location));
acc9ed14 930 } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
30619e6e 931 p += strspn(p, SPACE_CHARS);
acc9ed14
MS
932 ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
933 } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
30619e6e 934 p += strspn(p, SPACE_CHARS);
acc9ed14 935 ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
d2995eb9 936 } else if (av_stristart(p, "Content-Base:", &p) && rt) {
dd22cfb1 937 p += strspn(p, SPACE_CHARS);
d2995eb9
MS
938 if (method && !strcmp(method, "DESCRIBE"))
939 av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
29db7c3a
MS
940 } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
941 p += strspn(p, SPACE_CHARS);
942 if (method && !strcmp(method, "PLAY"))
943 rtsp_parse_rtp_info(rt, p);
0b4949b5
MS
944 } else if (av_stristart(p, "Public:", &p) && rt) {
945 if (strstr(p, "GET_PARAMETER") &&
946 method && !strcmp(method, "OPTIONS"))
947 rt->get_parameter_supported = 1;
30eae325
MS
948 } else if (av_stristart(p, "x-Accept-Dynamic-Rate:", &p) && rt) {
949 p += strspn(p, SPACE_CHARS);
950 rt->accept_dynamic_rate = atoi(p);
fcd0298c
JO
951 } else if (av_stristart(p, "Content-Type:", &p)) {
952 p += strspn(p, SPACE_CHARS);
953 av_strlcpy(reply->content_type, p, sizeof(reply->content_type));
1617ad97
FB
954 }
955}
956
b7b8fc34 957/* skip a RTP/TCP interleaved packet */
ec55edba 958void ff_rtsp_skip_packet(AVFormatContext *s)
b7b8fc34
FB
959{
960 RTSPState *rt = s->priv_data;
961 int ret, len, len1;
962 uint8_t buf[1024];
963
dce37564 964 ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
b7b8fc34
FB
965 if (ret != 3)
966 return;
80fb8234 967 len = AV_RB16(buf + 1);
67c9cd69 968
dfd2a005 969 av_dlog(s, "skipping RTP packet len=%d\n", len);
67c9cd69 970
b7b8fc34
FB
971 /* skip payload */
972 while (len > 0) {
973 len1 = len;
974 if (len1 > sizeof(buf))
975 len1 = sizeof(buf);
dce37564 976 ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
b7b8fc34
FB
977 if (ret != len1)
978 return;
979 len -= len1;
980 }
981}
1617ad97 982
3307e6ea 983int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
93993933 984 unsigned char **content_ptr,
3df54c6b 985 int return_on_interleaved_data, const char *method)
1617ad97
FB
986{
987 RTSPState *rt = s->priv_data;
988 char buf[4096], buf1[1024], *q;
989 unsigned char ch;
990 const char *p;
1a6b9a98 991 int ret, content_length, line_count = 0, request = 0;
1617ad97
FB
992 unsigned char *content = NULL;
993
1a6b9a98
TW
994start:
995 line_count = 0;
996 request = 0;
997 content = NULL;
d541a7d2 998 memset(reply, 0, sizeof(*reply));
1617ad97 999
1617ad97 1000 /* parse reply (XXX: use buffers) */
1617ad97 1001 rt->last_reply[0] = '\0';
c8965800 1002 for (;;) {
1617ad97 1003 q = buf;
c8965800 1004 for (;;) {
dce37564 1005 ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
dfd2a005 1006 av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
7e726132 1007 if (ret != 1)
2401660d 1008 return AVERROR_EOF;
1617ad97
FB
1009 if (ch == '\n')
1010 break;
b7b8fc34
FB
1011 if (ch == '$') {
1012 /* XXX: only parse it if first char on line ? */
7e726132
RB
1013 if (return_on_interleaved_data) {
1014 return 1;
1015 } else
ec55edba 1016 ff_rtsp_skip_packet(s);
b7b8fc34 1017 } else if (ch != '\r') {
1617ad97
FB
1018 if ((q - buf) < sizeof(buf) - 1)
1019 *q++ = ch;
1020 }
1021 }
1022 *q = '\0';
67c9cd69 1023
dfd2a005 1024 av_dlog(s, "line='%s'\n", buf);
67c9cd69 1025
1617ad97
FB
1026 /* test if last line */
1027 if (buf[0] == '\0')
1028 break;
1029 p = buf;
1030 if (line_count == 0) {
1031 /* get reply code */
1032 get_word(buf1, sizeof(buf1), &p);
1a6b9a98
TW
1033 if (!strncmp(buf1, "RTSP/", 5)) {
1034 get_word(buf1, sizeof(buf1), &p);
1035 reply->status_code = atoi(buf1);
1036 av_strlcpy(reply->reason, p, sizeof(reply->reason));
1037 } else {
1038 av_strlcpy(reply->reason, buf1, sizeof(reply->reason)); // method
1039 get_word(buf1, sizeof(buf1), &p); // object
1040 request = 1;
1041 }
1617ad97 1042 } else {
77223c53 1043 ff_rtsp_parse_line(reply, p, rt, method);
75e61b0e
MR
1044 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
1045 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
1617ad97
FB
1046 }
1047 line_count++;
1048 }
115329f1 1049
1a6b9a98 1050 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0' && !request)
75e61b0e 1051 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
115329f1 1052
1617ad97
FB
1053 content_length = reply->content_length;
1054 if (content_length > 0) {
1055 /* leave some room for a trailing '\0' (useful for simple parsing) */
1056 content = av_malloc(content_length + 1);
dce37564 1057 ffurl_read_complete(rt->rtsp_hd, content, content_length);
1617ad97
FB
1058 content[content_length] = '\0';
1059 }
1060 if (content_ptr)
1061 *content_ptr = content;
e2e2e7dd
AB
1062 else
1063 av_free(content);
7e726132 1064
1a6b9a98
TW
1065 if (request) {
1066 char buf[1024];
1067 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
1068 const char* ptr = buf;
1069
1070 if (!strcmp(reply->reason, "OPTIONS")) {
1071 snprintf(buf, sizeof(buf), "RTSP/1.0 200 OK\r\n");
1072 if (reply->seq)
1073 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", reply->seq);
1074 if (reply->session_id[0])
1075 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n",
1076 reply->session_id);
1077 } else {
1078 snprintf(buf, sizeof(buf), "RTSP/1.0 501 Not Implemented\r\n");
1079 }
1080 av_strlcat(buf, "\r\n", sizeof(buf));
1081
1082 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1083 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1084 ptr = base64buf;
1085 }
1086 ffurl_write(rt->rtsp_hd_out, ptr, strlen(ptr));
1087
1088 rt->last_cmd_time = av_gettime();
1089 /* Even if the request from the server had data, it is not the data
1090 * that the caller wants or expects. The memory could also be leaked
1091 * if the actual following reply has content data. */
1092 if (content_ptr)
1093 av_freep(content_ptr);
1094 /* If method is set, this is called from ff_rtsp_send_cmd,
1095 * where a reply to exactly this request is awaited. For
705eeb5e 1096 * callers from within packet receiving, we just want to
1a6b9a98
TW
1097 * return to the caller and go back to receiving packets. */
1098 if (method)
1099 goto start;
1100 return 0;
1101 }
1102
7ed8211b
LB
1103 if (rt->seq != reply->seq) {
1104 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
1105 rt->seq, reply->seq);
1106 }
1107
fccb1770
RB
1108 /* EOS */
1109 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
1110 reply->notice == 2104 /* Start-of-Stream Reached */ ||
c8965800 1111 reply->notice == 2306 /* Continuous Feed Terminated */) {
fccb1770 1112 rt->state = RTSP_STATE_IDLE;
c8965800 1113 } else if (reply->notice >= 4400 && reply->notice < 5500) {
fccb1770 1114 return AVERROR(EIO); /* data or server error */
c8965800 1115 } else if (reply->notice == 2401 /* Ticket Expired */ ||
fccb1770
RB
1116 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
1117 return AVERROR(EPERM);
1118
7e726132 1119 return 0;
1617ad97
FB
1120}
1121
57c4d01e
DEP
1122/**
1123 * Send a command to the RTSP server without waiting for the reply.
1124 *
1125 * @param s RTSP (de)muxer context
1126 * @param method the method for the request
1127 * @param url the target url for the request
1128 * @param headers extra header lines to include in the request
1129 * @param send_content if non-null, the data to send as request body content
1130 * @param send_content_length the length of the send_content data, or 0 if
1131 * send_content is null
1132 *
1133 * @return zero if success, nonzero otherwise
1134 */
e926b5ce
DB
1135static int rtsp_send_cmd_with_content_async(AVFormatContext *s,
1136 const char *method, const char *url,
1137 const char *headers,
1138 const unsigned char *send_content,
1139 int send_content_length)
29b9f58b
RB
1140{
1141 RTSPState *rt = s->priv_data;
f5d33f52
JA
1142 char buf[4096], *out_buf;
1143 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
29b9f58b 1144
f5d33f52
JA
1145 /* Add in RTSP headers */
1146 out_buf = buf;
29b9f58b 1147 rt->seq++;
b17d11c6
MS
1148 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
1149 if (headers)
1150 av_strlcat(buf, headers, sizeof(buf));
7b4a3645 1151 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
1dd1b233 1152 av_strlcatf(buf, sizeof(buf), "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
b17d11c6
MS
1153 if (rt->session_id[0] != '\0' && (!headers ||
1154 !strstr(headers, "\nIf-Match:"))) {
7b4a3645 1155 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
29b9f58b 1156 }
aa8bf2fb
MS
1157 if (rt->auth[0]) {
1158 char *str = ff_http_auth_create_response(&rt->auth_state,
1159 rt->auth, url, method);
1160 if (str)
1161 av_strlcat(buf, str, sizeof(buf));
1162 av_free(str);
1163 }
dfd017bf
MS
1164 if (send_content_length > 0 && send_content)
1165 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
29b9f58b 1166 av_strlcat(buf, "\r\n", sizeof(buf));
67c9cd69 1167
f5d33f52
JA
1168 /* base64 encode rtsp if tunneling */
1169 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1170 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1171 out_buf = base64buf;
1172 }
1173
dfd2a005 1174 av_dlog(s, "Sending:\n%s--\n", buf);
67c9cd69 1175
925e908b 1176 ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
f5d33f52
JA
1177 if (send_content_length > 0 && send_content) {
1178 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1179 av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
1180 "with content data not supported\n");
1181 return AVERROR_PATCHWELCOME;
1182 }
925e908b 1183 ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
f5d33f52 1184 }
30e79845 1185 rt->last_cmd_time = av_gettime();
d0382374
JA
1186
1187 return 0;
30e79845
RB
1188}
1189
d0382374 1190int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
fc490fcf 1191 const char *url, const char *headers)
dfd017bf 1192{
e926b5ce 1193 return rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
dfd017bf
MS
1194}
1195
d0382374 1196int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
fc490fcf
MS
1197 const char *headers, RTSPMessageHeader *reply,
1198 unsigned char **content_ptr)
30e79845 1199{
d0382374 1200 return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
fc490fcf 1201 content_ptr, NULL, 0);
29b9f58b
RB
1202}
1203
d0382374 1204int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
fc490fcf
MS
1205 const char *method, const char *url,
1206 const char *header,
1207 RTSPMessageHeader *reply,
1208 unsigned char **content_ptr,
1209 const unsigned char *send_content,
1210 int send_content_length)
dfd017bf 1211{
30af0779
MS
1212 RTSPState *rt = s->priv_data;
1213 HTTPAuthType cur_auth_type;
2f96cc1f 1214 int ret, attempts = 0;
30af0779
MS
1215
1216retry:
1217 cur_auth_type = rt->auth_state.auth_type;
e926b5ce
DB
1218 if ((ret = rtsp_send_cmd_with_content_async(s, method, url, header,
1219 send_content,
1220 send_content_length)))
d0382374 1221 return ret;
dfd017bf 1222
3df54c6b 1223 if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
d0382374 1224 return ret;
2f96cc1f 1225 attempts++;
30af0779 1226
2f96cc1f
MS
1227 if (reply->status_code == 401 &&
1228 (cur_auth_type == HTTP_AUTH_NONE || rt->auth_state.stale) &&
1229 rt->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2)
30af0779 1230 goto retry;
d0382374 1231
bf55cf19 1232 if (reply->status_code > 400){
d93fdcbf 1233 av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
bf55cf19 1234 method,
d93fdcbf
LB
1235 reply->status_code,
1236 reply->reason);
bf55cf19
LB
1237 av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
1238 }
1239
d0382374 1240 return 0;
dfd017bf
MS
1241}
1242
fef5649a 1243int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
c8965800 1244 int lower_transport, const char *real_challenge)
1617ad97
FB
1245{
1246 RTSPState *rt = s->priv_data;
58f09785 1247 int rtx = 0, j, i, err, interleave = 0, port_off;
1617ad97 1248 RTSPStream *rtsp_st;
a9e534d5 1249 RTSPMessageHeader reply1, *reply = &reply1;
53620bba 1250 char cmd[2048];
e9dea59f
RB
1251 const char *trans_pref;
1252
119b4668 1253 if (rt->transport == RTSP_TRANSPORT_RDT)
e9dea59f 1254 trans_pref = "x-pn-tng";
df8cf076
MS
1255 else if (rt->transport == RTSP_TRANSPORT_RAW)
1256 trans_pref = "RAW/RAW";
e9dea59f
RB
1257 else
1258 trans_pref = "RTP/AVP";
115329f1 1259
30e79845
RB
1260 /* default timeout: 1 minute */
1261 rt->timeout = 60;
1262
1617ad97
FB
1263 /* for each stream, make the setup request */
1264 /* XXX: we assume the same server is used for the control of each
c8965800 1265 * RTSP stream */
d1ccf0e0 1266
58f09785
DV
1267 /* Choose a random starting offset within the first half of the
1268 * port range, to allow for a number of ports to try even if the offset
1269 * happens to be at the end of the random range. */
1270 port_off = av_get_random_seed() % ((rt->rtp_port_max - rt->rtp_port_min)/2);
1271 /* even random offset */
1272 port_off -= port_off & 0x01;
1273
1274 for (j = rt->rtp_port_min + port_off, i = 0; i < rt->nb_rtsp_streams; ++i) {
1617ad97
FB
1275 char transport[2048];
1276
f75e3da5 1277 /*
f830c9a4
RB
1278 * WMS serves all UDP data over a single connection, the RTX, which
1279 * isn't necessarily the first in the SDP but has to be the first
1280 * to be set up, else the second/third SETUP will fail with a 461.
1281 */
1282 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1283 rt->server_type == RTSP_SERVER_WMS) {
1284 if (i == 0) {
1285 /* rtx first */
1286 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1287 int len = strlen(rt->rtsp_streams[rtx]->control_url);
1288 if (len >= 4 &&
c8965800
RB
1289 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1290 "/rtx"))
f830c9a4
RB
1291 break;
1292 }
1293 if (rtx == rt->nb_rtsp_streams)
1294 return -1; /* no RTX found */
1295 rtsp_st = rt->rtsp_streams[rtx];
1296 } else
1297 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1298 } else
2fea9650 1299 rtsp_st = rt->rtsp_streams[i];
1617ad97 1300
1617ad97 1301 /* RTP/UDP */
90abbdba 1302 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
85fb7b34 1303 char buf[256];
85fb7b34 1304
f830c9a4
RB
1305 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1306 port = reply->transports[0].client_port_min;
1307 goto have_port;
1308 }
1309
85fb7b34 1310 /* first try in specified port range */
dbb06b8c 1311 while (j <= rt->rtp_port_max) {
bc495bad
DV
1312 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1313 "?localport=%d", j);
1314 /* we will use two ports per rtp stream (rtp and rtcp) */
1315 j += 2;
1316 if (!ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE,
1317 &s->interrupt_callback, NULL))
1318 goto rtp_opened;
1617ad97 1319 }
85fb7b34 1320
a3b058b7
MS
1321 av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
1322 err = AVERROR(EIO);
1323 goto fail;
85fb7b34
FB
1324
1325 rtp_opened:
bfc6db44 1326 port = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
f830c9a4 1327 have_port:
0ad306bc 1328 snprintf(transport, sizeof(transport) - 1,
eee2cbff
RB
1329 "%s/UDP;", trans_pref);
1330 if (rt->server_type != RTSP_SERVER_REAL)
1331 av_strlcat(transport, "unicast;", sizeof(transport));
1332 av_strlcatf(transport, sizeof(transport),
1333 "client_port=%d", port);
f830c9a4
RB
1334 if (rt->transport == RTSP_TRANSPORT_RTP &&
1335 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
e9dea59f 1336 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1617ad97
FB
1337 }
1338
1339 /* RTP/TCP */
90abbdba 1340 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
f75e3da5 1341 /* For WMS streams, the application streams are only used for
090438cc
RB
1342 * UDP. When trying to set it up for TCP streams, the server
1343 * will return an error. Therefore, we skip those streams. */
1344 if (rt->server_type == RTSP_SERVER_WMS &&
45600148
MS
1345 (rtsp_st->stream_index < 0 ||
1346 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1347 AVMEDIA_TYPE_DATA))
090438cc 1348 continue;
0ad306bc 1349 snprintf(transport, sizeof(transport) - 1,
d1c6e47c 1350 "%s/TCP;", trans_pref);
895678f8 1351 if (rt->transport != RTSP_TRANSPORT_RDT)
d1c6e47c
RB
1352 av_strlcat(transport, "unicast;", sizeof(transport));
1353 av_strlcatf(transport, sizeof(transport),
1354 "interleaved=%d-%d",
1355 interleave, interleave + 1);
1356 interleave += 2;
1617ad97
FB
1357 }
1358
90abbdba 1359 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
0ad306bc 1360 snprintf(transport, sizeof(transport) - 1,
e9dea59f 1361 "%s/UDP;multicast", trans_pref);
1617ad97 1362 }
69adcc4f 1363 if (s->oformat) {
bbc80386 1364 av_strlcat(transport, ";mode=record", sizeof(transport));
69adcc4f 1365 } else if (rt->server_type == RTSP_SERVER_REAL ||
2efc97c2 1366 rt->server_type == RTSP_SERVER_WMS)
e9dea59f 1367 av_strlcat(transport, ";mode=play", sizeof(transport));
115329f1 1368 snprintf(cmd, sizeof(cmd),
b6892136 1369 "Transport: %s\r\n",
b17d11c6 1370 transport);
76b0d03d
MS
1371 if (rt->accept_dynamic_rate)
1372 av_strlcat(cmd, "x-Dynamic-Rate: 0\r\n", sizeof(cmd));
44b70ce5 1373 if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
e9dea59f
RB
1374 char real_res[41], real_csum[9];
1375 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1376 real_challenge);
1377 av_strlcatf(cmd, sizeof(cmd),
1378 "If-Match: %s\r\n"
1379 "RealChallenge2: %s, sd=%s\r\n",
1380 rt->session_id, real_res, real_csum);
1381 }
b17d11c6 1382 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
8a8754d8
RB
1383 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1384 err = 1;
1385 goto fail;
7e6ca34f
RB
1386 } else if (reply->status_code != RTSP_STATUS_OK ||
1387 reply->nb_transports != 1) {
1617ad97
FB
1388 err = AVERROR_INVALIDDATA;
1389 goto fail;
1390 }
1391
1392 /* XXX: same protocol for all streams is required */
1393 if (i > 0) {
119b4668
RB
1394 if (reply->transports[0].lower_transport != rt->lower_transport ||
1395 reply->transports[0].transport != rt->transport) {
1617ad97
FB
1396 err = AVERROR_INVALIDDATA;
1397 goto fail;
1398 }
1399 } else {
90abbdba 1400 rt->lower_transport = reply->transports[0].lower_transport;
119b4668 1401 rt->transport = reply->transports[0].transport;
1617ad97
FB
1402 }
1403
8c579c1c
MS
1404 /* Fail if the server responded with another lower transport mode
1405 * than what we requested. */
1406 if (reply->transports[0].lower_transport != lower_transport) {
1407 av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
1408 err = AVERROR_INVALIDDATA;
1409 goto fail;
1617ad97
FB
1410 }
1411
90abbdba
RB
1412 switch(reply->transports[0].lower_transport) {
1413 case RTSP_LOWER_TRANSPORT_TCP:
1617ad97
FB
1414 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1415 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1416 break;
115329f1 1417
c8965800 1418 case RTSP_LOWER_TRANSPORT_UDP: {
a92c30d7 1419 char url[1024], options[30] = "";
c8965800 1420
9867aea5 1421 if (rt->rtsp_flags & RTSP_FLAG_FILTER_SRC)
a92c30d7 1422 av_strlcpy(options, "?connect=1", sizeof(options));
619298a8
JW
1423 /* Use source address if specified */
1424 if (reply->transports[0].source[0]) {
1425 ff_url_join(url, sizeof(url), "rtp", NULL,
1426 reply->transports[0].source,
d8407339 1427 reply->transports[0].server_port_min, "%s", options);
619298a8 1428 } else {
7bac991f 1429 ff_url_join(url, sizeof(url), "rtp", NULL, host,
d8407339 1430 reply->transports[0].server_port_min, "%s", options);
619298a8 1431 }
c8965800 1432 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
bfc6db44 1433 ff_rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
c8965800
RB
1434 err = AVERROR_INVALIDDATA;
1435 goto fail;
1617ad97 1436 }
9c8fa20d
MS
1437 /* Try to initialize the connection state in a
1438 * potential NAT router by sending dummy packets.
1439 * RTP/RTCP dummy packets are used for RDT, too.
1440 */
44b70ce5
MS
1441 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
1442 CONFIG_RTPDEC)
bfc6db44 1443 ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
1617ad97 1444 break;
c8965800
RB
1445 }
1446 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
6294d708 1447 char url[1024], namebuf[50], optbuf[20] = "";
7934b15d 1448 struct sockaddr_storage addr;
c8965800
RB
1449 int port, ttl;
1450
7934b15d
MS
1451 if (reply->transports[0].destination.ss_family) {
1452 addr = reply->transports[0].destination;
c8965800
RB
1453 port = reply->transports[0].port_min;
1454 ttl = reply->transports[0].ttl;
1455 } else {
7934b15d 1456 addr = rtsp_st->sdp_ip;
c8965800
RB
1457 port = rtsp_st->sdp_port;
1458 ttl = rtsp_st->sdp_ttl;
1459 }
6294d708
MS
1460 if (ttl > 0)
1461 snprintf(optbuf, sizeof(optbuf), "?ttl=%d", ttl);
7934b15d
MS
1462 getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1463 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1464 ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
6294d708 1465 port, "%s", optbuf);
6f1b7b39 1466 if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
ddffc2fd 1467 &s->interrupt_callback, NULL) < 0) {
c8965800
RB
1468 err = AVERROR_INVALIDDATA;
1469 goto fail;
1617ad97
FB
1470 }
1471 break;
1472 }
c8965800 1473 }
d1ccf0e0 1474
6e71c120 1475 if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
8b1ab7bf 1476 goto fail;
1617ad97
FB
1477 }
1478
62c3c8ca 1479 if (rt->nb_rtsp_streams && reply->timeout > 0)
30e79845
RB
1480 rt->timeout = reply->timeout;
1481
2e889ae4 1482 if (rt->server_type == RTSP_SERVER_REAL)
1256d16b
RB
1483 rt->need_subscription = 1;
1484
53620bba
RB
1485 return 0;
1486
1487fail:
aeb2de1c 1488 ff_rtsp_undo_setup(s);
53620bba
RB
1489 return err;
1490}
1491
b8c2c41d
JA
1492void ff_rtsp_close_connections(AVFormatContext *s)
1493{
1494 RTSPState *rt = s->priv_data;
e52a9145
AK
1495 if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
1496 ffurl_close(rt->rtsp_hd);
6217b645 1497 rt->rtsp_hd = rt->rtsp_hd_out = NULL;
b8c2c41d
JA
1498}
1499
3307e6ea 1500int ff_rtsp_connect(AVFormatContext *s)
53620bba
RB
1501{
1502 RTSPState *rt = s->priv_data;
921da217 1503 char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
03f8fc08 1504 int port, err, tcp_fd;
354b7573 1505 RTSPMessageHeader reply1 = {0}, *reply = &reply1;
90abbdba 1506 int lower_transport_mask = 0;
2762a7a2 1507 char real_challenge[64] = "";
03f8fc08
MS
1508 struct sockaddr_storage peer;
1509 socklen_t peer_len = sizeof(peer);
57b5555c 1510
dbb06b8c
MS
1511 if (rt->rtp_port_max < rt->rtp_port_min) {
1512 av_log(s, AV_LOG_ERROR, "Invalid UDP port range, max port %d less "
1513 "than min port %d\n", rt->rtp_port_max,
1514 rt->rtp_port_min);
1515 return AVERROR(EINVAL);
1516 }
1517
57b5555c
MS
1518 if (!ff_network_init())
1519 return AVERROR(EIO);
eca4850c 1520
4fa57d52 1521 if (s->max_delay < 0) /* Not set by the caller */
ccfa8aa2 1522 s->max_delay = s->iformat ? DEFAULT_REORDERING_DELAY : 0;
4fa57d52 1523
f5d33f52 1524 rt->control_transport = RTSP_MODE_PLAIN;
eca4850c
MS
1525 if (rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_HTTP)) {
1526 rt->lower_transport_mask = 1 << RTSP_LOWER_TRANSPORT_TCP;
1527 rt->control_transport = RTSP_MODE_TUNNEL;
1528 }
1529 /* Only pass through valid flags from here */
1530 rt->lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
eca4850c
MS
1531
1532redirect:
1533 lower_transport_mask = rt->lower_transport_mask;
53620bba 1534 /* extract hostname and port */
f3bfe388 1535 av_url_split(NULL, 0, auth, sizeof(auth),
f984dcf6 1536 host, sizeof(host), &port, path, sizeof(path), s->filename);
f9337897 1537 if (*auth) {
aa8bf2fb 1538 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
f9337897 1539 }
53620bba
RB
1540 if (port < 0)
1541 port = RTSP_DEFAULT_PORT;
1542
90abbdba 1543 if (!lower_transport_mask)
2a1d51c5 1544 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
53620bba 1545
3e24c770 1546 if (s->oformat) {
b7dc88fc
MS
1547 /* Only UDP or TCP - UDP multicast isn't supported. */
1548 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1549 (1 << RTSP_LOWER_TRANSPORT_TCP);
f5d33f52 1550 if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
3e24c770 1551 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
b7dc88fc 1552 "only UDP and TCP are supported for output.\n");
3e24c770
MS
1553 err = AVERROR(EINVAL);
1554 goto fail;
1555 }
1556 }
1557
4bc5cc23
MS
1558 /* Construct the URI used in request; this is similar to s->filename,
1559 * but with authentication credentials removed and RTSP specific options
1560 * stripped out. */
1561 ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1562 host, port, "%s", path);
1563
f5d33f52
JA
1564 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1565 /* set up initial handshake for tunneling */
1566 char httpname[1024];
1567 char sessioncookie[17];
1568 char headers[1024];
1569
10ed37b5 1570 ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
f5d33f52
JA
1571 snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1572 av_get_random_seed(), av_get_random_seed());
1573
1574 /* GET requests */
6f1b7b39
MS
1575 if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_FLAG_READ,
1576 &s->interrupt_callback) < 0) {
f5d33f52
JA
1577 err = AVERROR(EIO);
1578 goto fail;
1579 }
1580
1581 /* generate GET headers */
1582 snprintf(headers, sizeof(headers),
1583 "x-sessioncookie: %s\r\n"
1584 "Accept: application/x-rtsp-tunnelled\r\n"
1585 "Pragma: no-cache\r\n"
1586 "Cache-Control: no-cache\r\n",
1587 sessioncookie);
196bf28c 1588 av_opt_set(rt->rtsp_hd->priv_data, "headers", headers, 0);
f5d33f52
JA
1589
1590 /* complete the connection */
ddffc2fd 1591 if (ffurl_connect(rt->rtsp_hd, NULL)) {
f5d33f52
JA
1592 err = AVERROR(EIO);
1593 goto fail;
1594 }
1595
1596 /* POST requests */
6f1b7b39
MS
1597 if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_FLAG_WRITE,
1598 &s->interrupt_callback) < 0 ) {
f5d33f52
JA
1599 err = AVERROR(EIO);
1600 goto fail;
1601 }
1602
1603 /* generate POST headers */
1604 snprintf(headers, sizeof(headers),
1605 "x-sessioncookie: %s\r\n"
1606 "Content-Type: application/x-rtsp-tunnelled\r\n"
1607 "Pragma: no-cache\r\n"
1608 "Cache-Control: no-cache\r\n"
1609 "Content-Length: 32767\r\n"
1610 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1611 sessioncookie);
196bf28c 1612 av_opt_set(rt->rtsp_hd_out->priv_data, "headers", headers, 0);
6149485f 1613 av_opt_set(rt->rtsp_hd_out->priv_data, "chunked_post", "0", 0);
f5d33f52 1614
a8ead332
MS
1615 /* Initialize the authentication state for the POST session. The HTTP
1616 * protocol implementation doesn't properly handle multi-pass
1617 * authentication for POST requests, since it would require one of
1618 * the following:
1619 * - implementing Expect: 100-continue, which many HTTP servers
1620 * don't support anyway, even less the RTSP servers that do HTTP
1621 * tunneling
1622 * - sending the whole POST data until getting a 401 reply specifying
1623 * what authentication method to use, then resending all that data
1624 * - waiting for potential 401 replies directly after sending the
1625 * POST header (waiting for some unspecified time)
1626 * Therefore, we copy the full auth state, which works for both basic
1627 * and digest. (For digest, we would have to synchronize the nonce
1628 * count variable between the two sessions, if we'd do more requests
1629 * with the original session, though.)
1630 */
1631 ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1632
9290f15d 1633 /* complete the connection */
ddffc2fd 1634 if (ffurl_connect(rt->rtsp_hd_out, NULL)) {
9290f15d
MS
1635 err = AVERROR(EIO);
1636 goto fail;
1637 }
f5d33f52 1638 } else {
48e77473 1639 /* open the tcp connection */
41874d0a 1640 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
6f1b7b39 1641 if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
ddffc2fd 1642 &s->interrupt_callback, NULL) < 0) {
41874d0a
JA
1643 err = AVERROR(EIO);
1644 goto fail;
1645 }
00e4a1f4 1646 rt->rtsp_hd_out = rt->rtsp_hd;
f5d33f52 1647 }
53620bba
RB
1648 rt->seq = 0;
1649
1869ea03 1650 tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
03f8fc08
MS
1651 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1652 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1653 NULL, 0, NI_NUMERICHOST);
1654 }
1655
c8965800
RB
1656 /* request options supported by the server; this also detects server
1657 * type */
1cf151e9 1658 for (rt->server_type = RTSP_SERVER_RTP;;) {
b17d11c6 1659 cmd[0] = 0;
2e889ae4 1660 if (rt->server_type == RTSP_SERVER_REAL)
1cf151e9 1661 av_strlcat(cmd,
f75e3da5 1662 /*
1cf151e9
RB
1663 * The following entries are required for proper
1664 * streaming from a Realmedia server. They are
1665 * interdependent in some way although we currently
1666 * don't quite understand how. Values were copied
1667 * from mplayer SVN r23589.
f75e3da5
DB
1668 * ClientChallenge is a 16-byte ID in hex
1669 * CompanyID is a 16-byte ID in base64
1cf151e9
RB
1670 */
1671 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1672 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1673 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1674 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1675 sizeof(cmd));
b17d11c6 1676 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1cf151e9
RB
1677 if (reply->status_code != RTSP_STATUS_OK) {
1678 err = AVERROR_INVALIDDATA;
1679 goto fail;
1680 }
1681
1682 /* detect server type if not standard-compliant RTP */
2e889ae4
RB
1683 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1684 rt->server_type = RTSP_SERVER_REAL;
1cf151e9 1685 continue;
bb3244de 1686 } else if (!av_strncasecmp(reply->server, "WMServer/", 9)) {
7a86bafa 1687 rt->server_type = RTSP_SERVER_WMS;
c8965800 1688 } else if (rt->server_type == RTSP_SERVER_REAL)
1cf151e9 1689 strcpy(real_challenge, reply->real_challenge);
1cf151e9
RB
1690 break;
1691 }
1692
44b70ce5 1693 if (s->iformat && CONFIG_RTSP_DEMUXER)
0526c6f7 1694 err = ff_rtsp_setup_input_streams(s, reply);
44b70ce5 1695 else if (CONFIG_RTSP_MUXER)
c2688f3a 1696 err = ff_rtsp_setup_output_streams(s, host);
e23d195d 1697 if (err)
53620bba 1698 goto fail;
53620bba 1699
8a8754d8 1700 do {
c8965800
RB
1701 int lower_transport = ff_log2_tab[lower_transport_mask &
1702 ~(lower_transport_mask - 1)];
8a8754d8 1703
fef5649a 1704 err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
2e889ae4 1705 rt->server_type == RTSP_SERVER_REAL ?
e9dea59f 1706 real_challenge : NULL);
8a8754d8 1707 if (err < 0)
7e6ca34f 1708 goto fail;
90abbdba
RB
1709 lower_transport_mask &= ~(1 << lower_transport);
1710 if (lower_transport_mask == 0 && err == 1) {
28c4741a 1711 err = AVERROR(EPROTONOSUPPORT);
8a8754d8
RB
1712 goto fail;
1713 }
1714 } while (err);
53620bba 1715
2762a7a2
MS
1716 rt->lower_transport_mask = lower_transport_mask;
1717 av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
ff762d6e 1718 rt->state = RTSP_STATE_IDLE;
c8965800 1719 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1617ad97
FB
1720 return 0;
1721 fail:
3307e6ea 1722 ff_rtsp_close_streams(s);
b8c2c41d 1723 ff_rtsp_close_connections(s);
35cfd646 1724 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
d243ba30
LB
1725 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1726 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1727 reply->status_code,
1728 s->filename);
1729 goto redirect;
1730 }
57b5555c 1731 ff_network_close();
1617ad97
FB
1732 return err;
1733}
2e802e38 1734#endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1617ad97 1735
44b70ce5 1736#if CONFIG_RTPDEC
0e59034e 1737static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
321259c1 1738 uint8_t *buf, int buf_size, int64_t wait_end)
0e59034e
RB
1739{
1740 RTSPState *rt = s->priv_data;
1741 RTSPStream *rtsp_st;
a8475bbd
LB
1742 int n, i, ret, tcp_fd, timeout_cnt = 0;
1743 int max_p = 0;
1744 struct pollfd *p = rt->p;
e7993ece 1745 int *fds = NULL, fdsnum, fdsidx;
0e59034e 1746
c8965800 1747 for (;;) {
9957cdbf 1748 if (ff_check_interrupt(&s->interrupt_callback))
c76374c6 1749 return AVERROR_EXIT;
321259c1
MS
1750 if (wait_end && wait_end - av_gettime() < 0)
1751 return AVERROR(EAGAIN);
a8475bbd 1752 max_p = 0;
0e59034e 1753 if (rt->rtsp_hd) {
1869ea03 1754 tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
a8475bbd
LB
1755 p[max_p].fd = tcp_fd;
1756 p[max_p++].events = POLLIN;
0e59034e 1757 } else {
0e59034e
RB
1758 tcp_fd = -1;
1759 }
c8965800 1760 for (i = 0; i < rt->nb_rtsp_streams; i++) {
0e59034e
RB
1761 rtsp_st = rt->rtsp_streams[i];
1762 if (rtsp_st->rtp_handle) {
e7993ece
JO
1763 if (ret = ffurl_get_multi_file_handle(rtsp_st->rtp_handle,
1764 &fds, &fdsnum)) {
1765 av_log(s, AV_LOG_ERROR, "Unable to recover rtp ports\n");
1766 return ret;
1767 }
1768 if (fdsnum != 2) {
1769 av_log(s, AV_LOG_ERROR,
1770 "Number of fds %d not supported\n", fdsnum);
1771 return AVERROR_INVALIDDATA;
1772 }
1773 for (fdsidx = 0; fdsidx < fdsnum; fdsidx++) {
1774 p[max_p].fd = fds[fdsidx];
1775 p[max_p++].events = POLLIN;
1776 }
1777 av_free(fds);
0e59034e
RB
1778 }
1779 }
a8475bbd 1780 n = poll(p, max_p, POLL_TIMEOUT_MS);
0e59034e 1781 if (n > 0) {
a8475bbd 1782 int j = 1 - (tcp_fd == -1);
9cba6f5f 1783 timeout_cnt = 0;
c8965800 1784 for (i = 0; i < rt->nb_rtsp_streams; i++) {
0e59034e
RB
1785 rtsp_st = rt->rtsp_streams[i];
1786 if (rtsp_st->rtp_handle) {
a8475bbd 1787 if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
bc371aca 1788 ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
0e59034e
RB
1789 if (ret > 0) {
1790 *prtsp_st = rtsp_st;
1791 return ret;
1792 }
1793 }
a8475bbd 1794 j+=2;
0e59034e
RB
1795 }
1796 }
5fe8021a 1797#if CONFIG_RTSP_DEMUXER
a8475bbd 1798 if (tcp_fd != -1 && p[0].revents & POLLIN) {
a8ad6ffa
JO
1799 if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
1800 if (rt->state == RTSP_STATE_STREAMING) {
1801 if (!ff_rtsp_parse_streaming_commands(s))
1802 return AVERROR_EOF;
1803 else
1804 av_log(s, AV_LOG_WARNING,
1805 "Unable to answer to TEARDOWN\n");
1806 } else
1807 return 0;
1808 } else {
1809 RTSPMessageHeader reply;
1810 ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
1811 if (ret < 0)
1812 return ret;
1813 /* XXX: parse message */
1814 if (rt->state != RTSP_STATE_STREAMING)
1815 return 0;
1816 }
0e59034e 1817 }
5fe8021a 1818#endif
9cba6f5f 1819 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
28c4741a 1820 return AVERROR(ETIMEDOUT);
9cba6f5f
SG
1821 } else if (n < 0 && errno != EINTR)
1822 return AVERROR(errno);
0e59034e
RB
1823 }
1824}
1825
e96406ed
MS
1826static int pick_stream(AVFormatContext *s, RTSPStream **rtsp_st,
1827 const uint8_t *buf, int len)
1828{
1829 RTSPState *rt = s->priv_data;
1830 int i;
1831 if (len < 0)
1832 return len;
1833 if (rt->nb_rtsp_streams == 1) {
1834 *rtsp_st = rt->rtsp_streams[0];
1835 return len;
1836 }
1837 if (len >= 8 && rt->transport == RTSP_TRANSPORT_RTP) {
1838 if (RTP_PT_IS_RTCP(rt->recvbuf[1])) {
1839 int no_ssrc = 0;
1840 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1841 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
1842 if (!rtpctx)
1843 continue;
1844 if (rtpctx->ssrc == AV_RB32(&buf[4])) {
1845 *rtsp_st = rt->rtsp_streams[i];
1846 return len;
1847 }
1848 if (!rtpctx->ssrc)
1849 no_ssrc = 1;
1850 }
1851 if (no_ssrc) {
1852 av_log(s, AV_LOG_WARNING,
1853 "Unable to pick stream for packet - SSRC not known for "
1854 "all streams\n");
1855 return AVERROR(EAGAIN);
1856 }
1857 } else {
1858 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1859 if ((buf[1] & 0x7f) == rt->rtsp_streams[i]->sdp_payload_type) {
1860 *rtsp_st = rt->rtsp_streams[i];
1861 return len;
1862 }
1863 }
1864 }
1865 }
1866 av_log(s, AV_LOG_WARNING, "Unable to pick stream for packet\n");
1867 return AVERROR(EAGAIN);
1868}
1869
0526c6f7 1870int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
0e59034e
RB
1871{
1872 RTSPState *rt = s->priv_data;
1873 int ret, len;
321259c1
MS
1874 RTSPStream *rtsp_st, *first_queue_st = NULL;
1875 int64_t wait_end = 0;
0e59034e 1876
b20359f5
JA
1877 if (rt->nb_byes == rt->nb_rtsp_streams)
1878 return AVERROR_EOF;
1879
0e59034e
RB
1880 /* get next frames from the same RTP packet */
1881 if (rt->cur_transport_priv) {
c8965800 1882 if (rt->transport == RTSP_TRANSPORT_RDT) {
0e59034e 1883 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1243c722 1884 } else if (rt->transport == RTSP_TRANSPORT_RTP) {
bfc6db44 1885 ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1243c722
MS
1886 } else if (rt->ts && CONFIG_RTPDEC) {
1887 ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf + rt->recvbuf_pos, rt->recvbuf_len - rt->recvbuf_pos);
1888 if (ret >= 0) {
1889 rt->recvbuf_pos += ret;
1890 ret = rt->recvbuf_pos < rt->recvbuf_len;
1891 }
2f41eaa9
MS
1892 } else
1893 ret = -1;
0e59034e
RB
1894 if (ret == 0) {
1895 rt->cur_transport_priv = NULL;
1896 return 0;
1897 } else if (ret == 1) {
1898 return 0;
c8965800 1899 } else
0e59034e 1900 rt->cur_transport_priv = NULL;
0e59034e
RB
1901 }
1902
8729698d 1903redo:
321259c1
MS
1904 if (rt->transport == RTSP_TRANSPORT_RTP) {
1905 int i;
1906 int64_t first_queue_time = 0;
1907 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1908 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
9e99f84f
MS
1909 int64_t queue_time;
1910 if (!rtpctx)
1911 continue;
1912 queue_time = ff_rtp_queued_packet_time(rtpctx);
321259c1
MS
1913 if (queue_time && (queue_time - first_queue_time < 0 ||
1914 !first_queue_time)) {
1915 first_queue_time = queue_time;
1916 first_queue_st = rt->rtsp_streams[i];
1917 }
1918 }
8729698d 1919 if (first_queue_time) {
321259c1 1920 wait_end = first_queue_time + s->max_delay;
8729698d
MS
1921 } else {
1922 wait_end = 0;
1923 first_queue_st = NULL;
1924 }
321259c1
MS
1925 }
1926
0e59034e 1927 /* read next RTP packet */
96a7c975
MS
1928 if (!rt->recvbuf) {
1929 rt->recvbuf = av_malloc(RECVBUF_SIZE);
1930 if (!rt->recvbuf)
1931 return AVERROR(ENOMEM);
1932 }
1933
0e59034e
RB
1934 switch(rt->lower_transport) {
1935 default:
5fe8021a 1936#if CONFIG_RTSP_DEMUXER
0e59034e 1937 case RTSP_LOWER_TRANSPORT_TCP:
0526c6f7 1938 len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
0e59034e 1939 break;
5fe8021a 1940#endif
0e59034e
RB
1941 case RTSP_LOWER_TRANSPORT_UDP:
1942 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
321259c1 1943 len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
2c35a6bd 1944 if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
e96406ed
MS
1945 ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, rtsp_st->rtp_handle, NULL, len);
1946 break;
1947 case RTSP_LOWER_TRANSPORT_CUSTOM:
f811cd2d
MS
1948 if (first_queue_st && rt->transport == RTSP_TRANSPORT_RTP &&
1949 wait_end && wait_end < av_gettime())
1950 len = AVERROR(EAGAIN);
1951 else
1952 len = ffio_read_partial(s->pb, rt->recvbuf, RECVBUF_SIZE);
e96406ed
MS
1953 len = pick_stream(s, &rtsp_st, rt->recvbuf, len);
1954 if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1955 ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, NULL, s->pb, len);
0e59034e
RB
1956 break;
1957 }
321259c1
MS
1958 if (len == AVERROR(EAGAIN) && first_queue_st &&
1959 rt->transport == RTSP_TRANSPORT_RTP) {
1960 rtsp_st = first_queue_st;
bfc6db44 1961 ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
321259c1
MS
1962 goto end;
1963 }
0e59034e
RB
1964 if (len < 0)
1965 return len;
1966 if (len == 0)
1967 return AVERROR_EOF;
c8965800 1968 if (rt->transport == RTSP_TRANSPORT_RDT) {
ad4ad27f 1969 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
df8cf076 1970 } else if (rt->transport == RTSP_TRANSPORT_RTP) {
bfc6db44 1971 ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
86d9181c
MS
1972 if (rtsp_st->feedback) {
1973 AVIOContext *pb = NULL;
1974 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_CUSTOM)
1975 pb = s->pb;
1976 ff_rtp_send_rtcp_feedback(rtsp_st->transport_priv, rtsp_st->rtp_handle, pb);
1977 }
2cab6b48
MS
1978 if (ret < 0) {
1979 /* Either bad packet, or a RTCP packet. Check if the
1980 * first_rtcp_ntp_time field was initialized. */
1981 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1982 if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
1983 /* first_rtcp_ntp_time has been initialized for this stream,
1984 * copy the same value to all other uninitialized streams,
1985 * in order to map their timestamp origin to the same ntp time
1986 * as this one. */
1987 int i;
3a1cdcc7
MS
1988 AVStream *st = NULL;
1989 if (rtsp_st->stream_index >= 0)
1990 st = s->streams[rtsp_st->stream_index];
2cab6b48 1991 for (i = 0; i < rt->nb_rtsp_streams; i++) {
744a882f 1992 RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
3a1cdcc7
MS
1993 AVStream *st2 = NULL;
1994 if (rt->rtsp_streams[i]->stream_index >= 0)
1995 st2 = s->streams[rt->rtsp_streams[i]->stream_index];
1996 if (rtpctx2 && st && st2 &&
1997 rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
2cab6b48 1998 rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
3a1cdcc7
MS
1999 rtpctx2->rtcp_ts_offset = av_rescale_q(
2000 rtpctx->rtcp_ts_offset, st->time_base,
2001 st2->time_base);
2002 }
2cab6b48
MS
2003 }
2004 }
b20359f5
JA
2005 if (ret == -RTCP_BYE) {
2006 rt->nb_byes++;
2007
2008 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
2009 rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
2010
2011 if (rt->nb_byes == rt->nb_rtsp_streams)
2012 return AVERROR_EOF;
2013 }
2cab6b48 2014 }
1243c722
MS
2015 } else if (rt->ts && CONFIG_RTPDEC) {
2016 ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf, len);
2017 if (ret >= 0) {
2018 if (ret < len) {
2019 rt->recvbuf_len = len;
2020 rt->recvbuf_pos = ret;
2021 rt->cur_transport_priv = rt->ts;
2022 return 1;
2023 } else {
2024 ret = 0;
2025 }
2026 }
df8cf076
MS
2027 } else {
2028 return AVERROR_INVALIDDATA;
2cab6b48 2029 }
321259c1 2030end:
0e59034e
RB
2031 if (ret < 0)
2032 goto redo;
c8965800 2033 if (ret == 1)
0e59034e
RB
2034 /* more packets may follow, so we save the RTP context */
2035 rt->cur_transport_priv = rtsp_st->transport_priv;
0e59034e
RB
2036
2037 return ret;
2038}
44b70ce5 2039#endif /* CONFIG_RTPDEC */
0e59034e 2040
44b70ce5 2041#if CONFIG_SDP_DEMUXER
cb1fdc61 2042static int sdp_probe(AVProbeData *p1)
93ced3e8 2043{
0e1ceacd 2044 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
cb1fdc61 2045
3fbd12d1 2046 /* we look for a line beginning "c=IN IP" */
0e1ceacd 2047 while (p < p_end && *p != '\0') {
3fbd12d1
MS
2048 if (p + sizeof("c=IN IP") - 1 < p_end &&
2049 av_strstart(p, "c=IN IP", NULL))
e0f8be64 2050 return AVPROBE_SCORE_EXTENSION;
0e1ceacd 2051
c8965800 2052 while (p < p_end - 1 && *p != '\n') p++;
0e1ceacd 2053 if (++p >= p_end)
cb1fdc61 2054 break;
cb1fdc61
FB
2055 if (*p == '\r')
2056 p++;
2057 }
93ced3e8
FB
2058 return 0;
2059}
2060
6e9651d1 2061static int sdp_read_header(AVFormatContext *s)
93ced3e8 2062{
8b1ab7bf 2063 RTSPState *rt = s->priv_data;
93ced3e8
FB
2064 RTSPStream *rtsp_st;
2065 int size, i, err;
2066 char *content;
2067 char url[1024];
2068
57b5555c
MS
2069 if (!ff_network_init())
2070 return AVERROR(EIO);
2071
4fa57d52 2072 if (s->max_delay < 0) /* Not set by the caller */
ccfa8aa2 2073 s->max_delay = DEFAULT_REORDERING_DELAY;
e96406ed
MS
2074 if (rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)
2075 rt->lower_transport = RTSP_LOWER_TRANSPORT_CUSTOM;
4fa57d52 2076
93ced3e8
FB
2077 /* read the whole sdp file */
2078 /* XXX: better loading */
2079 content = av_malloc(SDP_MAX_SIZE);
b7effd4e 2080 size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
93ced3e8
FB
2081 if (size <= 0) {
2082 av_free(content);
2083 return AVERROR_INVALIDDATA;
2084 }
2085 content[size] ='\0';
2086
f81c7ac7 2087 err = ff_sdp_parse(s, content);
93ced3e8 2088 av_free(content);
f81c7ac7 2089 if (err) goto fail;
93ced3e8
FB
2090
2091 /* open each RTP stream */
c8965800 2092 for (i = 0; i < rt->nb_rtsp_streams; i++) {
3fbd12d1 2093 char namebuf[50];
8b1ab7bf 2094 rtsp_st = rt->rtsp_streams[i];
115329f1 2095
e96406ed
MS
2096 if (!(rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)) {
2097 getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
2098 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
2099 ff_url_join(url, sizeof(url), "rtp", NULL,
2100 namebuf, rtsp_st->sdp_port,
2101 "?localport=%d&ttl=%d&connect=%d", rtsp_st->sdp_port,
2102 rtsp_st->sdp_ttl,
2103 rt->rtsp_flags & RTSP_FLAG_FILTER_SRC ? 1 : 0);
36fb0d02
ET
2104 if (rtsp_st->source_addr[0])
2105 av_strlcatf(url, sizeof(url), "&sources=%s", rtsp_st->source_addr);
e96406ed
MS
2106 if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
2107 &s->interrupt_callback, NULL) < 0) {
2108 err = AVERROR_INVALIDDATA;
2109 goto fail;
2110 }
93ced3e8 2111 }
6e71c120 2112 if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
8b1ab7bf 2113 goto fail;
93ced3e8
FB
2114 }
2115 return 0;
c8965800 2116fail:
3307e6ea 2117 ff_rtsp_close_streams(s);
57b5555c 2118 ff_network_close();
93ced3e8
FB
2119 return err;
2120}
2121
93ced3e8
FB
2122static int sdp_read_close(AVFormatContext *s)
2123{
3307e6ea 2124 ff_rtsp_close_streams(s);
57b5555c 2125 ff_network_close();
93ced3e8
FB
2126 return 0;
2127}
2128
51369f28
MS
2129static const AVClass sdp_demuxer_class = {
2130 .class_name = "SDP demuxer",
2131 .item_name = av_default_item_name,
2132 .option = sdp_options,
2133 .version = LIBAVUTIL_VERSION_INT,
2134};
2135
c6610a21 2136AVInputFormat ff_sdp_demuxer = {
dfc2c4d9
AK
2137 .name = "sdp",
2138 .long_name = NULL_IF_CONFIG_SMALL("SDP"),
2139 .priv_data_size = sizeof(RTSPState),
2140 .read_probe = sdp_probe,
2141 .read_header = sdp_read_header,
2142 .read_packet = ff_rtsp_fetch_packet,
2143 .read_close = sdp_read_close,
17934c18 2144 .priv_class = &sdp_demuxer_class,
93ced3e8 2145};
44b70ce5 2146#endif /* CONFIG_SDP_DEMUXER */
44594cc7 2147
44b70ce5 2148#if CONFIG_RTP_DEMUXER
44594cc7
MS
2149static int rtp_probe(AVProbeData *p)
2150{
2151 if (av_strstart(p->filename, "rtp:", NULL))
2152 return AVPROBE_SCORE_MAX;
2153 return 0;
2154}
2155
6e9651d1 2156static int rtp_read_header(AVFormatContext *s)
44594cc7 2157{
350ad50b 2158 uint8_t recvbuf[RTP_MAX_PACKET_LENGTH];
44594cc7
MS
2159 char host[500], sdp[500];
2160 int ret, port;
2161 URLContext* in = NULL;
2162 int payload_type;
a92be9b8 2163 AVCodecContext codec = { 0 };
44594cc7 2164 struct sockaddr_storage addr;
ae628ec1 2165 AVIOContext pb;
44594cc7 2166 socklen_t addrlen = sizeof(addr);
30266038 2167 RTSPState *rt = s->priv_data;
44594cc7
MS
2168
2169 if (!ff_network_init())
2170 return AVERROR(EIO);
2171
6f1b7b39 2172 ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ,
ddffc2fd 2173 &s->interrupt_callback, NULL);
44594cc7
MS
2174 if (ret)
2175 goto fail;
2176
2177 while (1) {
bc371aca 2178 ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
44594cc7
MS
2179 if (ret == AVERROR(EAGAIN))
2180 continue;
2181 if (ret < 0)
2182 goto fail;
2183 if (ret < 12) {
2184 av_log(s, AV_LOG_WARNING, "Received too short packet\n");
2185 continue;
2186 }
2187
2188 if ((recvbuf[0] & 0xc0) != 0x80) {
2189 av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
2190 "received\n");
2191 continue;
2192 }
2193
298a587f 2194 if (RTP_PT_IS_RTCP(recvbuf[1]))
f3a094f2
MS
2195 continue;
2196
44594cc7
MS
2197 payload_type = recvbuf[1] & 0x7f;
2198 break;
2199 }
1869ea03 2200 getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
e52a9145 2201 ffurl_close(in);
44594cc7
MS
2202 in = NULL;
2203
44594cc7
MS
2204 if (ff_rtp_get_codec_info(&codec, payload_type)) {
2205 av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
2206 "without an SDP file describing it\n",
2207 payload_type);
2208 goto fail;
2209 }
2210 if (codec.codec_type != AVMEDIA_TYPE_DATA) {
2211 av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
2212 "properly you need an SDP file "
2213 "describing it\n");
2214 }
2215
2216 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
2217 NULL, 0, s->filename);
2218
2219 snprintf(sdp, sizeof(sdp),
2220 "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
2221 addr.ss_family == AF_INET ? 4 : 6, host,
2222 codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
2223 codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
2224 port, payload_type);
2225 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
2226
e731b8d8 2227 ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
44594cc7
MS
2228 s->pb = &pb;
2229
2230 /* sdp_read_header initializes this again */
2231 ff_network_close();
2232
30266038
MS
2233 rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;
2234
6e9651d1 2235 ret = sdp_read_header(s);
44594cc7
MS
2236 s->pb = NULL;
2237 return ret;
2238
2239fail:
2240 if (in)
e52a9145 2241 ffurl_close(in);
44594cc7
MS
2242 ff_network_close();
2243 return ret;
2244}
2245
51369f28
MS
2246static const AVClass rtp_demuxer_class = {
2247 .class_name = "RTP demuxer",
2248 .item_name = av_default_item_name,
2249 .option = rtp_options,
2250 .version = LIBAVUTIL_VERSION_INT,
2251};
2252
c6610a21 2253AVInputFormat ff_rtp_demuxer = {
dfc2c4d9 2254 .name = "rtp",
6774247a 2255 .long_name = NULL_IF_CONFIG_SMALL("RTP input"),
dfc2c4d9
AK
2256 .priv_data_size = sizeof(RTSPState),
2257 .read_probe = rtp_probe,
2258 .read_header = rtp_read_header,
2259 .read_packet = ff_rtsp_fetch_packet,
2260 .read_close = sdp_read_close,
17934c18
MS
2261 .flags = AVFMT_NOFILE,
2262 .priv_class = &rtp_demuxer_class,
44594cc7 2263};
44b70ce5 2264#endif /* CONFIG_RTP_DEMUXER */