rtpproto: Check the source IP if one single source has been specified
[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);
1a30d541
RB
498 } else {
499 if (rt->server_type == RTSP_SERVER_WMS)
500 ff_wms_parse_sdp_a_line(s, p);
501 if (s->nb_streams > 0) {
45600148
MS
502 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
503
c4a3d032 504 if (rt->server_type == RTSP_SERVER_REAL)
45600148 505 ff_real_parse_sdp_a_line(s, rtsp_st->stream_index, p);
c4a3d032 506
c4a3d032
RB
507 if (rtsp_st->dynamic_handler &&
508 rtsp_st->dynamic_handler->parse_sdp_a_line)
c8965800 509 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
45600148 510 rtsp_st->stream_index,
c4a3d032 511 rtsp_st->dynamic_protocol_context, buf);
1a30d541 512 }
1617ad97
FB
513 }
514 break;
515 }
516}
517
0526c6f7 518int ff_sdp_parse(AVFormatContext *s, const char *content)
1617ad97 519{
a8475bbd 520 RTSPState *rt = s->priv_data;
1617ad97
FB
521 const char *p;
522 int letter;
9211bcdd
RB
523 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
524 * contain long SDP lines containing complete ASF Headers (several
525 * kB) or arrays of MDPR (RM stream descriptor) headers plus
526 * "rulebooks" describing their properties. Therefore, the SDP line
373afbaf
RB
527 * buffer is large.
528 *
afcea58c
JA
529 * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
530 * in rtpdec_xiph.c. */
373afbaf 531 char buf[16384], *q;
a92be9b8 532 SDPParseState sdp_parse_state = { { 0 } }, *s1 = &sdp_parse_state;
115329f1 533
1617ad97 534 p = content;
c8965800 535 for (;;) {
30619e6e 536 p += strspn(p, SPACE_CHARS);
1617ad97
FB
537 letter = *p;
538 if (letter == '\0')
539 break;
540 p++;
541 if (*p != '=')
542 goto next_line;
543 p++;
544 /* get the content */
545 q = buf;
b6892136 546 while (*p != '\n' && *p != '\r' && *p != '\0') {
1617ad97
FB
547 if ((q - buf) < sizeof(buf) - 1)
548 *q++ = *p;
549 p++;
550 }
551 *q = '\0';
93ced3e8 552 sdp_parse_line(s, s1, letter, buf);
1617ad97
FB
553 next_line:
554 while (*p != '\n' && *p != '\0')
555 p++;
556 if (*p == '\n')
557 p++;
558 }
a8475bbd
LB
559 rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
560 if (!rt->p) return AVERROR(ENOMEM);
1617ad97
FB
561 return 0;
562}
44b70ce5 563#endif /* CONFIG_RTPDEC */
1617ad97 564
93e7490e
MS
565void ff_rtsp_undo_setup(AVFormatContext *s)
566{
567 RTSPState *rt = s->priv_data;
568 int i;
569
570 for (i = 0; i < rt->nb_rtsp_streams; i++) {
571 RTSPStream *rtsp_st = rt->rtsp_streams[i];
572 if (!rtsp_st)
573 continue;
574 if (rtsp_st->transport_priv) {
575 if (s->oformat) {
576 AVFormatContext *rtpctx = rtsp_st->transport_priv;
577 av_write_trailer(rtpctx);
578 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
579 uint8_t *ptr;
6dc7d80d 580 avio_close_dyn_buf(rtpctx->pb, &ptr);
93e7490e
MS
581 av_free(ptr);
582 } else {
22a3212e 583 avio_close(rtpctx->pb);
93e7490e 584 }
b22dbb29 585 avformat_free_context(rtpctx);
93e7490e
MS
586 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
587 ff_rdt_parse_close(rtsp_st->transport_priv);
125c6c07 588 else if (rt->transport == RTSP_TRANSPORT_RTP && CONFIG_RTPDEC)
bfc6db44 589 ff_rtp_parse_close(rtsp_st->transport_priv);
93e7490e
MS
590 }
591 rtsp_st->transport_priv = NULL;
592 if (rtsp_st->rtp_handle)
e52a9145 593 ffurl_close(rtsp_st->rtp_handle);
93e7490e
MS
594 rtsp_st->rtp_handle = NULL;
595 }
596}
597
1ced9da3 598/* close and free RTSP streams */
3307e6ea 599void ff_rtsp_close_streams(AVFormatContext *s)
1ced9da3 600{
52aa4338 601 RTSPState *rt = s->priv_data;
1ced9da3
LA
602 int i;
603 RTSPStream *rtsp_st;
604
93e7490e 605 ff_rtsp_undo_setup(s);
c8965800 606 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1ced9da3
LA
607 rtsp_st = rt->rtsp_streams[i];
608 if (rtsp_st) {
1ced9da3 609 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
9261e6cf 610 rtsp_st->dynamic_handler->free(
c8965800 611 rtsp_st->dynamic_protocol_context);
ea7f0807 612 av_free(rtsp_st);
1ced9da3
LA
613 }
614 }
615 av_free(rt->rtsp_streams);
616 if (rt->asf_ctx) {
cd3716b9 617 avformat_close_input(&rt->asf_ctx);
1ced9da3 618 }
1243c722
MS
619 if (rt->ts && CONFIG_RTPDEC)
620 ff_mpegts_parse_close(rt->ts);
a8475bbd 621 av_free(rt->p);
96a7c975 622 av_free(rt->recvbuf);
1ced9da3
LA
623}
624
6e71c120 625int ff_rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
1ced9da3
LA
626{
627 RTSPState *rt = s->priv_data;
628 AVStream *st = NULL;
3f055f8f
MS
629 int reordering_queue_size = rt->reordering_queue_size;
630 if (reordering_queue_size < 0) {
631 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
632 reordering_queue_size = 0;
633 else
634 reordering_queue_size = RTP_REORDER_QUEUE_DEFAULT_SIZE;
635 }
1ced9da3
LA
636
637 /* open the RTP context */
638 if (rtsp_st->stream_index >= 0)
639 st = s->streams[rtsp_st->stream_index];
640 if (!st)
641 s->ctx_flags |= AVFMTCTX_NOHEADER;
642
44b70ce5 643 if (s->oformat && CONFIG_RTSP_MUXER) {
68c81308
MS
644 int ret = ff_rtp_chain_mux_open(&rtsp_st->transport_priv, s, st,
645 rtsp_st->rtp_handle,
8034130e
LB
646 RTSP_TCP_MAX_PACKET_SIZE,
647 rtsp_st->stream_index);
c2bfd816 648 /* Ownership of rtp_handle is passed to the rtp mux context */
fd450a51 649 rtsp_st->rtp_handle = NULL;
68c81308
MS
650 if (ret < 0)
651 return ret;
df8cf076
MS
652 } else if (rt->transport == RTSP_TRANSPORT_RAW) {
653 return 0; // Don't need to open any parser here
44b70ce5 654 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
1ced9da3
LA
655 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
656 rtsp_st->dynamic_protocol_context,
657 rtsp_st->dynamic_handler);
44b70ce5 658 else if (CONFIG_RTPDEC)
3f95f0dd 659 rtsp_st->transport_priv = ff_rtp_parse_open(s, st,
58ee0991 660 rtsp_st->sdp_payload_type,
3f055f8f 661 reordering_queue_size);
1ced9da3
LA
662
663 if (!rtsp_st->transport_priv) {
664 return AVERROR(ENOMEM);
df8cf076 665 } else if (rt->transport == RTSP_TRANSPORT_RTP && CONFIG_RTPDEC) {
c8965800 666 if (rtsp_st->dynamic_handler) {
bfc6db44
MS
667 ff_rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
668 rtsp_st->dynamic_protocol_context,
669 rtsp_st->dynamic_handler);
1ced9da3 670 }
424da308
MS
671 if (rtsp_st->crypto_suite[0])
672 ff_rtp_parse_set_crypto(rtsp_st->transport_priv,
673 rtsp_st->crypto_suite,
674 rtsp_st->crypto_params);
1ced9da3
LA
675 }
676
677 return 0;
678}
679
6f5a3d0a 680#if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
1617ad97
FB
681static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
682{
ddce7dab
MR
683 const char *q;
684 char *p;
1617ad97
FB
685 int v;
686
ddce7dab
MR
687 q = *pp;
688 q += strspn(q, SPACE_CHARS);
689 v = strtol(q, &p, 10);
1617ad97
FB
690 if (*p == '-') {
691 p++;
692 *min_ptr = v;
ddce7dab 693 v = strtol(p, &p, 10);
1617ad97
FB
694 *max_ptr = v;
695 } else {
696 *min_ptr = v;
697 *max_ptr = v;
698 }
699 *pp = p;
700}
701
702/* XXX: only one transport specification is parsed */
a9e534d5 703static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
1617ad97
FB
704{
705 char transport_protocol[16];
706 char profile[16];
707 char lower_transport[16];
708 char parameter[16];
709 RTSPTransportField *th;
710 char buf[256];
115329f1 711
1617ad97 712 reply->nb_transports = 0;
115329f1 713
c8965800 714 for (;;) {
30619e6e 715 p += strspn(p, SPACE_CHARS);
1617ad97
FB
716 if (*p == '\0')
717 break;
718
719 th = &reply->transports[reply->nb_transports];
720
115329f1 721 get_word_sep(transport_protocol, sizeof(transport_protocol),
1617ad97 722 "/", &p);
bb3244de 723 if (!av_strcasecmp (transport_protocol, "rtp")) {
7ecc634e
LB
724 get_word_sep(profile, sizeof(profile), "/;,", &p);
725 lower_transport[0] = '\0';
726 /* rtp/avp/<protocol> */
727 if (*p == '/') {
7ecc634e
LB
728 get_word_sep(lower_transport, sizeof(lower_transport),
729 ";,", &p);
119b4668
RB
730 }
731 th->transport = RTSP_TRANSPORT_RTP;
bb3244de
RD
732 } else if (!av_strcasecmp (transport_protocol, "x-pn-tng") ||
733 !av_strcasecmp (transport_protocol, "x-real-rdt")) {
7ecc634e 734 /* x-pn-tng/<protocol> */
e1502118
LB
735 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
736 profile[0] = '\0';
119b4668 737 th->transport = RTSP_TRANSPORT_RDT;
df8cf076
MS
738 } else if (!av_strcasecmp(transport_protocol, "raw")) {
739 get_word_sep(profile, sizeof(profile), "/;,", &p);
740 lower_transport[0] = '\0';
741 /* raw/raw/<protocol> */
742 if (*p == '/') {
743 get_word_sep(lower_transport, sizeof(lower_transport),
744 ";,", &p);
745 }
746 th->transport = RTSP_TRANSPORT_RAW;
1617ad97 747 }
bb3244de 748 if (!av_strcasecmp(lower_transport, "TCP"))
90abbdba 749 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
1617ad97 750 else
90abbdba 751 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
115329f1 752
1617ad97
FB
753 if (*p == ';')
754 p++;
755 /* get each parameter */
756 while (*p != '\0' && *p != ',') {
757 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
758 if (!strcmp(parameter, "port")) {
759 if (*p == '=') {
760 p++;
761 rtsp_parse_range(&th->port_min, &th->port_max, &p);
762 }
763 } else if (!strcmp(parameter, "client_port")) {
764 if (*p == '=') {
765 p++;
115329f1 766 rtsp_parse_range(&th->client_port_min,
1617ad97
FB
767 &th->client_port_max, &p);
768 }
769 } else if (!strcmp(parameter, "server_port")) {
770 if (*p == '=') {
771 p++;
115329f1 772 rtsp_parse_range(&th->server_port_min,
1617ad97
FB
773 &th->server_port_max, &p);
774 }
775 } else if (!strcmp(parameter, "interleaved")) {
776 if (*p == '=') {
777 p++;
115329f1 778 rtsp_parse_range(&th->interleaved_min,
1617ad97
FB
779 &th->interleaved_max, &p);
780 }
781 } else if (!strcmp(parameter, "multicast")) {
90abbdba
RB
782 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
783 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
1617ad97
FB
784 } else if (!strcmp(parameter, "ttl")) {
785 if (*p == '=') {
f21d5c90 786 char *end;
1617ad97 787 p++;
f21d5c90
MS
788 th->ttl = strtol(p, &end, 10);
789 p = end;
1617ad97
FB
790 }
791 } else if (!strcmp(parameter, "destination")) {
1617ad97
FB
792 if (*p == '=') {
793 p++;
794 get_word_sep(buf, sizeof(buf), ";,", &p);
7934b15d 795 get_sockaddr(buf, &th->destination);
1617ad97 796 }
619298a8
JW
797 } else if (!strcmp(parameter, "source")) {
798 if (*p == '=') {
799 p++;
800 get_word_sep(buf, sizeof(buf), ";,", &p);
801 av_strlcpy(th->source, buf, sizeof(th->source));
802 }
45b06858
JO
803 } else if (!strcmp(parameter, "mode")) {
804 if (*p == '=') {
805 p++;
806 get_word_sep(buf, sizeof(buf), ";, ", &p);
807 if (!strcmp(buf, "record") ||
808 !strcmp(buf, "receive"))
809 th->mode_record = 1;
810 }
1617ad97 811 }
619298a8 812
1617ad97
FB
813 while (*p != ';' && *p != '\0' && *p != ',')
814 p++;
815 if (*p == ';')
816 p++;
817 }
818 if (*p == ',')
819 p++;
820
821 reply->nb_transports++;
822 }
823}
824
29db7c3a
MS
825static void handle_rtp_info(RTSPState *rt, const char *url,
826 uint32_t seq, uint32_t rtptime)
827{
828 int i;
829 if (!rtptime || !url[0])
830 return;
831 if (rt->transport != RTSP_TRANSPORT_RTP)
832 return;
833 for (i = 0; i < rt->nb_rtsp_streams; i++) {
834 RTSPStream *rtsp_st = rt->rtsp_streams[i];
835 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
836 if (!rtpctx)
837 continue;
838 if (!strcmp(rtsp_st->control_url, url)) {
839 rtpctx->base_timestamp = rtptime;
840 break;
841 }
842 }
843}
844
845static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
846{
847 int read = 0;
848 char key[20], value[1024], url[1024] = "";
849 uint32_t seq = 0, rtptime = 0;
850
851 for (;;) {
852 p += strspn(p, SPACE_CHARS);
853 if (!*p)
854 break;
855 get_word_sep(key, sizeof(key), "=", &p);
856 if (*p != '=')
857 break;
858 p++;
859 get_word_sep(value, sizeof(value), ";, ", &p);
860 read++;
861 if (!strcmp(key, "url"))
862 av_strlcpy(url, value, sizeof(url));
863 else if (!strcmp(key, "seq"))
4515f9b5 864 seq = strtoul(value, NULL, 10);
29db7c3a 865 else if (!strcmp(key, "rtptime"))
4515f9b5 866 rtptime = strtoul(value, NULL, 10);
29db7c3a
MS
867 if (*p == ',') {
868 handle_rtp_info(rt, url, seq, rtptime);
869 url[0] = '\0';
870 seq = rtptime = 0;
871 read = 0;
872 }
873 if (*p)
874 p++;
875 }
876 if (read > 0)
877 handle_rtp_info(rt, url, seq, rtptime);
878}
879
2626308a 880void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
77223c53 881 RTSPState *rt, const char *method)
1617ad97
FB
882{
883 const char *p;
884
885 /* NOTE: we do case independent match for broken servers */
886 p = buf;
f7d78f36 887 if (av_stristart(p, "Session:", &p)) {
30e79845 888 int t;
1617ad97 889 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
30e79845
RB
890 if (av_stristart(p, ";timeout=", &p) &&
891 (t = strtol(p, NULL, 10)) > 0) {
892 reply->timeout = t;
893 }
f7d78f36 894 } else if (av_stristart(p, "Content-Length:", &p)) {
1617ad97 895 reply->content_length = strtol(p, NULL, 10);
f7d78f36 896 } else if (av_stristart(p, "Transport:", &p)) {
1617ad97 897 rtsp_parse_transport(reply, p);
f7d78f36 898 } else if (av_stristart(p, "CSeq:", &p)) {
1617ad97 899 reply->seq = strtol(p, NULL, 10);
f7d78f36 900 } else if (av_stristart(p, "Range:", &p)) {
31693e00 901 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
30aa6aed 902 } else if (av_stristart(p, "RealChallenge1:", &p)) {
30619e6e 903 p += strspn(p, SPACE_CHARS);
30aa6aed 904 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
7a86bafa 905 } else if (av_stristart(p, "Server:", &p)) {
30619e6e 906 p += strspn(p, SPACE_CHARS);
7a86bafa 907 av_strlcpy(reply->server, p, sizeof(reply->server));
fccb1770
RB
908 } else if (av_stristart(p, "Notice:", &p) ||
909 av_stristart(p, "X-Notice:", &p)) {
910 reply->notice = strtol(p, NULL, 10);
d243ba30 911 } else if (av_stristart(p, "Location:", &p)) {
30619e6e 912 p += strspn(p, SPACE_CHARS);
d243ba30 913 av_strlcpy(reply->location, p , sizeof(reply->location));
acc9ed14 914 } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
30619e6e 915 p += strspn(p, SPACE_CHARS);
acc9ed14
MS
916 ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
917 } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
30619e6e 918 p += strspn(p, SPACE_CHARS);
acc9ed14 919 ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
d2995eb9 920 } else if (av_stristart(p, "Content-Base:", &p) && rt) {
dd22cfb1 921 p += strspn(p, SPACE_CHARS);
d2995eb9
MS
922 if (method && !strcmp(method, "DESCRIBE"))
923 av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
29db7c3a
MS
924 } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
925 p += strspn(p, SPACE_CHARS);
926 if (method && !strcmp(method, "PLAY"))
927 rtsp_parse_rtp_info(rt, p);
0b4949b5
MS
928 } else if (av_stristart(p, "Public:", &p) && rt) {
929 if (strstr(p, "GET_PARAMETER") &&
930 method && !strcmp(method, "OPTIONS"))
931 rt->get_parameter_supported = 1;
30eae325
MS
932 } else if (av_stristart(p, "x-Accept-Dynamic-Rate:", &p) && rt) {
933 p += strspn(p, SPACE_CHARS);
934 rt->accept_dynamic_rate = atoi(p);
fcd0298c
JO
935 } else if (av_stristart(p, "Content-Type:", &p)) {
936 p += strspn(p, SPACE_CHARS);
937 av_strlcpy(reply->content_type, p, sizeof(reply->content_type));
1617ad97
FB
938 }
939}
940
b7b8fc34 941/* skip a RTP/TCP interleaved packet */
ec55edba 942void ff_rtsp_skip_packet(AVFormatContext *s)
b7b8fc34
FB
943{
944 RTSPState *rt = s->priv_data;
945 int ret, len, len1;
946 uint8_t buf[1024];
947
dce37564 948 ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
b7b8fc34
FB
949 if (ret != 3)
950 return;
80fb8234 951 len = AV_RB16(buf + 1);
67c9cd69 952
dfd2a005 953 av_dlog(s, "skipping RTP packet len=%d\n", len);
67c9cd69 954
b7b8fc34
FB
955 /* skip payload */
956 while (len > 0) {
957 len1 = len;
958 if (len1 > sizeof(buf))
959 len1 = sizeof(buf);
dce37564 960 ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
b7b8fc34
FB
961 if (ret != len1)
962 return;
963 len -= len1;
964 }
965}
1617ad97 966
3307e6ea 967int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
93993933 968 unsigned char **content_ptr,
3df54c6b 969 int return_on_interleaved_data, const char *method)
1617ad97
FB
970{
971 RTSPState *rt = s->priv_data;
972 char buf[4096], buf1[1024], *q;
973 unsigned char ch;
974 const char *p;
1a6b9a98 975 int ret, content_length, line_count = 0, request = 0;
1617ad97
FB
976 unsigned char *content = NULL;
977
1a6b9a98
TW
978start:
979 line_count = 0;
980 request = 0;
981 content = NULL;
d541a7d2 982 memset(reply, 0, sizeof(*reply));
1617ad97 983
1617ad97 984 /* parse reply (XXX: use buffers) */
1617ad97 985 rt->last_reply[0] = '\0';
c8965800 986 for (;;) {
1617ad97 987 q = buf;
c8965800 988 for (;;) {
dce37564 989 ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
dfd2a005 990 av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
7e726132 991 if (ret != 1)
2401660d 992 return AVERROR_EOF;
1617ad97
FB
993 if (ch == '\n')
994 break;
b7b8fc34
FB
995 if (ch == '$') {
996 /* XXX: only parse it if first char on line ? */
7e726132
RB
997 if (return_on_interleaved_data) {
998 return 1;
999 } else
ec55edba 1000 ff_rtsp_skip_packet(s);
b7b8fc34 1001 } else if (ch != '\r') {
1617ad97
FB
1002 if ((q - buf) < sizeof(buf) - 1)
1003 *q++ = ch;
1004 }
1005 }
1006 *q = '\0';
67c9cd69 1007
dfd2a005 1008 av_dlog(s, "line='%s'\n", buf);
67c9cd69 1009
1617ad97
FB
1010 /* test if last line */
1011 if (buf[0] == '\0')
1012 break;
1013 p = buf;
1014 if (line_count == 0) {
1015 /* get reply code */
1016 get_word(buf1, sizeof(buf1), &p);
1a6b9a98
TW
1017 if (!strncmp(buf1, "RTSP/", 5)) {
1018 get_word(buf1, sizeof(buf1), &p);
1019 reply->status_code = atoi(buf1);
1020 av_strlcpy(reply->reason, p, sizeof(reply->reason));
1021 } else {
1022 av_strlcpy(reply->reason, buf1, sizeof(reply->reason)); // method
1023 get_word(buf1, sizeof(buf1), &p); // object
1024 request = 1;
1025 }
1617ad97 1026 } else {
77223c53 1027 ff_rtsp_parse_line(reply, p, rt, method);
75e61b0e
MR
1028 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
1029 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
1617ad97
FB
1030 }
1031 line_count++;
1032 }
115329f1 1033
1a6b9a98 1034 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0' && !request)
75e61b0e 1035 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
115329f1 1036
1617ad97
FB
1037 content_length = reply->content_length;
1038 if (content_length > 0) {
1039 /* leave some room for a trailing '\0' (useful for simple parsing) */
1040 content = av_malloc(content_length + 1);
dce37564 1041 ffurl_read_complete(rt->rtsp_hd, content, content_length);
1617ad97
FB
1042 content[content_length] = '\0';
1043 }
1044 if (content_ptr)
1045 *content_ptr = content;
e2e2e7dd
AB
1046 else
1047 av_free(content);
7e726132 1048
1a6b9a98
TW
1049 if (request) {
1050 char buf[1024];
1051 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
1052 const char* ptr = buf;
1053
1054 if (!strcmp(reply->reason, "OPTIONS")) {
1055 snprintf(buf, sizeof(buf), "RTSP/1.0 200 OK\r\n");
1056 if (reply->seq)
1057 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", reply->seq);
1058 if (reply->session_id[0])
1059 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n",
1060 reply->session_id);
1061 } else {
1062 snprintf(buf, sizeof(buf), "RTSP/1.0 501 Not Implemented\r\n");
1063 }
1064 av_strlcat(buf, "\r\n", sizeof(buf));
1065
1066 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1067 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1068 ptr = base64buf;
1069 }
1070 ffurl_write(rt->rtsp_hd_out, ptr, strlen(ptr));
1071
1072 rt->last_cmd_time = av_gettime();
1073 /* Even if the request from the server had data, it is not the data
1074 * that the caller wants or expects. The memory could also be leaked
1075 * if the actual following reply has content data. */
1076 if (content_ptr)
1077 av_freep(content_ptr);
1078 /* If method is set, this is called from ff_rtsp_send_cmd,
1079 * where a reply to exactly this request is awaited. For
705eeb5e 1080 * callers from within packet receiving, we just want to
1a6b9a98
TW
1081 * return to the caller and go back to receiving packets. */
1082 if (method)
1083 goto start;
1084 return 0;
1085 }
1086
7ed8211b
LB
1087 if (rt->seq != reply->seq) {
1088 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
1089 rt->seq, reply->seq);
1090 }
1091
fccb1770
RB
1092 /* EOS */
1093 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
1094 reply->notice == 2104 /* Start-of-Stream Reached */ ||
c8965800 1095 reply->notice == 2306 /* Continuous Feed Terminated */) {
fccb1770 1096 rt->state = RTSP_STATE_IDLE;
c8965800 1097 } else if (reply->notice >= 4400 && reply->notice < 5500) {
fccb1770 1098 return AVERROR(EIO); /* data or server error */
c8965800 1099 } else if (reply->notice == 2401 /* Ticket Expired */ ||
fccb1770
RB
1100 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
1101 return AVERROR(EPERM);
1102
7e726132 1103 return 0;
1617ad97
FB
1104}
1105
57c4d01e
DEP
1106/**
1107 * Send a command to the RTSP server without waiting for the reply.
1108 *
1109 * @param s RTSP (de)muxer context
1110 * @param method the method for the request
1111 * @param url the target url for the request
1112 * @param headers extra header lines to include in the request
1113 * @param send_content if non-null, the data to send as request body content
1114 * @param send_content_length the length of the send_content data, or 0 if
1115 * send_content is null
1116 *
1117 * @return zero if success, nonzero otherwise
1118 */
e926b5ce
DB
1119static int rtsp_send_cmd_with_content_async(AVFormatContext *s,
1120 const char *method, const char *url,
1121 const char *headers,
1122 const unsigned char *send_content,
1123 int send_content_length)
29b9f58b
RB
1124{
1125 RTSPState *rt = s->priv_data;
f5d33f52
JA
1126 char buf[4096], *out_buf;
1127 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
29b9f58b 1128
f5d33f52
JA
1129 /* Add in RTSP headers */
1130 out_buf = buf;
29b9f58b 1131 rt->seq++;
b17d11c6
MS
1132 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
1133 if (headers)
1134 av_strlcat(buf, headers, sizeof(buf));
7b4a3645 1135 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
1dd1b233 1136 av_strlcatf(buf, sizeof(buf), "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
b17d11c6
MS
1137 if (rt->session_id[0] != '\0' && (!headers ||
1138 !strstr(headers, "\nIf-Match:"))) {
7b4a3645 1139 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
29b9f58b 1140 }
aa8bf2fb
MS
1141 if (rt->auth[0]) {
1142 char *str = ff_http_auth_create_response(&rt->auth_state,
1143 rt->auth, url, method);
1144 if (str)
1145 av_strlcat(buf, str, sizeof(buf));
1146 av_free(str);
1147 }
dfd017bf
MS
1148 if (send_content_length > 0 && send_content)
1149 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
29b9f58b 1150 av_strlcat(buf, "\r\n", sizeof(buf));
67c9cd69 1151
f5d33f52
JA
1152 /* base64 encode rtsp if tunneling */
1153 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1154 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1155 out_buf = base64buf;
1156 }
1157
dfd2a005 1158 av_dlog(s, "Sending:\n%s--\n", buf);
67c9cd69 1159
925e908b 1160 ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
f5d33f52
JA
1161 if (send_content_length > 0 && send_content) {
1162 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1163 av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
1164 "with content data not supported\n");
1165 return AVERROR_PATCHWELCOME;
1166 }
925e908b 1167 ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
f5d33f52 1168 }
30e79845 1169 rt->last_cmd_time = av_gettime();
d0382374
JA
1170
1171 return 0;
30e79845
RB
1172}
1173
d0382374 1174int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
fc490fcf 1175 const char *url, const char *headers)
dfd017bf 1176{
e926b5ce 1177 return rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
dfd017bf
MS
1178}
1179
d0382374 1180int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
fc490fcf
MS
1181 const char *headers, RTSPMessageHeader *reply,
1182 unsigned char **content_ptr)
30e79845 1183{
d0382374 1184 return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
fc490fcf 1185 content_ptr, NULL, 0);
29b9f58b
RB
1186}
1187
d0382374 1188int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
fc490fcf
MS
1189 const char *method, const char *url,
1190 const char *header,
1191 RTSPMessageHeader *reply,
1192 unsigned char **content_ptr,
1193 const unsigned char *send_content,
1194 int send_content_length)
dfd017bf 1195{
30af0779
MS
1196 RTSPState *rt = s->priv_data;
1197 HTTPAuthType cur_auth_type;
2f96cc1f 1198 int ret, attempts = 0;
30af0779
MS
1199
1200retry:
1201 cur_auth_type = rt->auth_state.auth_type;
e926b5ce
DB
1202 if ((ret = rtsp_send_cmd_with_content_async(s, method, url, header,
1203 send_content,
1204 send_content_length)))
d0382374 1205 return ret;
dfd017bf 1206
3df54c6b 1207 if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
d0382374 1208 return ret;
2f96cc1f 1209 attempts++;
30af0779 1210
2f96cc1f
MS
1211 if (reply->status_code == 401 &&
1212 (cur_auth_type == HTTP_AUTH_NONE || rt->auth_state.stale) &&
1213 rt->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2)
30af0779 1214 goto retry;
d0382374 1215
bf55cf19 1216 if (reply->status_code > 400){
d93fdcbf 1217 av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
bf55cf19 1218 method,
d93fdcbf
LB
1219 reply->status_code,
1220 reply->reason);
bf55cf19
LB
1221 av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
1222 }
1223
d0382374 1224 return 0;
dfd017bf
MS
1225}
1226
fef5649a 1227int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
c8965800 1228 int lower_transport, const char *real_challenge)
1617ad97
FB
1229{
1230 RTSPState *rt = s->priv_data;
58f09785 1231 int rtx = 0, j, i, err, interleave = 0, port_off;
1617ad97 1232 RTSPStream *rtsp_st;
a9e534d5 1233 RTSPMessageHeader reply1, *reply = &reply1;
53620bba 1234 char cmd[2048];
e9dea59f
RB
1235 const char *trans_pref;
1236
119b4668 1237 if (rt->transport == RTSP_TRANSPORT_RDT)
e9dea59f 1238 trans_pref = "x-pn-tng";
df8cf076
MS
1239 else if (rt->transport == RTSP_TRANSPORT_RAW)
1240 trans_pref = "RAW/RAW";
e9dea59f
RB
1241 else
1242 trans_pref = "RTP/AVP";
115329f1 1243
30e79845
RB
1244 /* default timeout: 1 minute */
1245 rt->timeout = 60;
1246
1617ad97
FB
1247 /* for each stream, make the setup request */
1248 /* XXX: we assume the same server is used for the control of each
c8965800 1249 * RTSP stream */
d1ccf0e0 1250
58f09785
DV
1251 /* Choose a random starting offset within the first half of the
1252 * port range, to allow for a number of ports to try even if the offset
1253 * happens to be at the end of the random range. */
1254 port_off = av_get_random_seed() % ((rt->rtp_port_max - rt->rtp_port_min)/2);
1255 /* even random offset */
1256 port_off -= port_off & 0x01;
1257
1258 for (j = rt->rtp_port_min + port_off, i = 0; i < rt->nb_rtsp_streams; ++i) {
1617ad97
FB
1259 char transport[2048];
1260
f75e3da5 1261 /*
f830c9a4
RB
1262 * WMS serves all UDP data over a single connection, the RTX, which
1263 * isn't necessarily the first in the SDP but has to be the first
1264 * to be set up, else the second/third SETUP will fail with a 461.
1265 */
1266 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1267 rt->server_type == RTSP_SERVER_WMS) {
1268 if (i == 0) {
1269 /* rtx first */
1270 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1271 int len = strlen(rt->rtsp_streams[rtx]->control_url);
1272 if (len >= 4 &&
c8965800
RB
1273 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1274 "/rtx"))
f830c9a4
RB
1275 break;
1276 }
1277 if (rtx == rt->nb_rtsp_streams)
1278 return -1; /* no RTX found */
1279 rtsp_st = rt->rtsp_streams[rtx];
1280 } else
1281 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1282 } else
2fea9650 1283 rtsp_st = rt->rtsp_streams[i];
1617ad97 1284
1617ad97 1285 /* RTP/UDP */
90abbdba 1286 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
85fb7b34 1287 char buf[256];
85fb7b34 1288
f830c9a4
RB
1289 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1290 port = reply->transports[0].client_port_min;
1291 goto have_port;
1292 }
1293
85fb7b34 1294 /* first try in specified port range */
dbb06b8c 1295 while (j <= rt->rtp_port_max) {
bc495bad
DV
1296 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1297 "?localport=%d", j);
1298 /* we will use two ports per rtp stream (rtp and rtcp) */
1299 j += 2;
1300 if (!ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE,
1301 &s->interrupt_callback, NULL))
1302 goto rtp_opened;
1617ad97 1303 }
85fb7b34 1304
a3b058b7
MS
1305 av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
1306 err = AVERROR(EIO);
1307 goto fail;
85fb7b34
FB
1308
1309 rtp_opened:
bfc6db44 1310 port = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
f830c9a4 1311 have_port:
0ad306bc 1312 snprintf(transport, sizeof(transport) - 1,
eee2cbff
RB
1313 "%s/UDP;", trans_pref);
1314 if (rt->server_type != RTSP_SERVER_REAL)
1315 av_strlcat(transport, "unicast;", sizeof(transport));
1316 av_strlcatf(transport, sizeof(transport),
1317 "client_port=%d", port);
f830c9a4
RB
1318 if (rt->transport == RTSP_TRANSPORT_RTP &&
1319 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
e9dea59f 1320 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1617ad97
FB
1321 }
1322
1323 /* RTP/TCP */
90abbdba 1324 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
f75e3da5 1325 /* For WMS streams, the application streams are only used for
090438cc
RB
1326 * UDP. When trying to set it up for TCP streams, the server
1327 * will return an error. Therefore, we skip those streams. */
1328 if (rt->server_type == RTSP_SERVER_WMS &&
45600148
MS
1329 (rtsp_st->stream_index < 0 ||
1330 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1331 AVMEDIA_TYPE_DATA))
090438cc 1332 continue;
0ad306bc 1333 snprintf(transport, sizeof(transport) - 1,
d1c6e47c 1334 "%s/TCP;", trans_pref);
895678f8 1335 if (rt->transport != RTSP_TRANSPORT_RDT)
d1c6e47c
RB
1336 av_strlcat(transport, "unicast;", sizeof(transport));
1337 av_strlcatf(transport, sizeof(transport),
1338 "interleaved=%d-%d",
1339 interleave, interleave + 1);
1340 interleave += 2;
1617ad97
FB
1341 }
1342
90abbdba 1343 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
0ad306bc 1344 snprintf(transport, sizeof(transport) - 1,
e9dea59f 1345 "%s/UDP;multicast", trans_pref);
1617ad97 1346 }
69adcc4f 1347 if (s->oformat) {
bbc80386 1348 av_strlcat(transport, ";mode=record", sizeof(transport));
69adcc4f 1349 } else if (rt->server_type == RTSP_SERVER_REAL ||
2efc97c2 1350 rt->server_type == RTSP_SERVER_WMS)
e9dea59f 1351 av_strlcat(transport, ";mode=play", sizeof(transport));
115329f1 1352 snprintf(cmd, sizeof(cmd),
b6892136 1353 "Transport: %s\r\n",
b17d11c6 1354 transport);
76b0d03d
MS
1355 if (rt->accept_dynamic_rate)
1356 av_strlcat(cmd, "x-Dynamic-Rate: 0\r\n", sizeof(cmd));
44b70ce5 1357 if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
e9dea59f
RB
1358 char real_res[41], real_csum[9];
1359 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1360 real_challenge);
1361 av_strlcatf(cmd, sizeof(cmd),
1362 "If-Match: %s\r\n"
1363 "RealChallenge2: %s, sd=%s\r\n",
1364 rt->session_id, real_res, real_csum);
1365 }
b17d11c6 1366 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
8a8754d8
RB
1367 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1368 err = 1;
1369 goto fail;
7e6ca34f
RB
1370 } else if (reply->status_code != RTSP_STATUS_OK ||
1371 reply->nb_transports != 1) {
1617ad97
FB
1372 err = AVERROR_INVALIDDATA;
1373 goto fail;
1374 }
1375
1376 /* XXX: same protocol for all streams is required */
1377 if (i > 0) {
119b4668
RB
1378 if (reply->transports[0].lower_transport != rt->lower_transport ||
1379 reply->transports[0].transport != rt->transport) {
1617ad97
FB
1380 err = AVERROR_INVALIDDATA;
1381 goto fail;
1382 }
1383 } else {
90abbdba 1384 rt->lower_transport = reply->transports[0].lower_transport;
119b4668 1385 rt->transport = reply->transports[0].transport;
1617ad97
FB
1386 }
1387
8c579c1c
MS
1388 /* Fail if the server responded with another lower transport mode
1389 * than what we requested. */
1390 if (reply->transports[0].lower_transport != lower_transport) {
1391 av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
1392 err = AVERROR_INVALIDDATA;
1393 goto fail;
1617ad97
FB
1394 }
1395
90abbdba
RB
1396 switch(reply->transports[0].lower_transport) {
1397 case RTSP_LOWER_TRANSPORT_TCP:
1617ad97
FB
1398 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1399 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1400 break;
115329f1 1401
c8965800 1402 case RTSP_LOWER_TRANSPORT_UDP: {
a92c30d7 1403 char url[1024], options[30] = "";
c8965800 1404
9867aea5 1405 if (rt->rtsp_flags & RTSP_FLAG_FILTER_SRC)
a92c30d7 1406 av_strlcpy(options, "?connect=1", sizeof(options));
619298a8
JW
1407 /* Use source address if specified */
1408 if (reply->transports[0].source[0]) {
1409 ff_url_join(url, sizeof(url), "rtp", NULL,
1410 reply->transports[0].source,
d8407339 1411 reply->transports[0].server_port_min, "%s", options);
619298a8 1412 } else {
7bac991f 1413 ff_url_join(url, sizeof(url), "rtp", NULL, host,
d8407339 1414 reply->transports[0].server_port_min, "%s", options);
619298a8 1415 }
c8965800 1416 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
bfc6db44 1417 ff_rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
c8965800
RB
1418 err = AVERROR_INVALIDDATA;
1419 goto fail;
1617ad97 1420 }
9c8fa20d
MS
1421 /* Try to initialize the connection state in a
1422 * potential NAT router by sending dummy packets.
1423 * RTP/RTCP dummy packets are used for RDT, too.
1424 */
44b70ce5
MS
1425 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
1426 CONFIG_RTPDEC)
bfc6db44 1427 ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
1617ad97 1428 break;
c8965800
RB
1429 }
1430 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
6294d708 1431 char url[1024], namebuf[50], optbuf[20] = "";
7934b15d 1432 struct sockaddr_storage addr;
c8965800
RB
1433 int port, ttl;
1434
7934b15d
MS
1435 if (reply->transports[0].destination.ss_family) {
1436 addr = reply->transports[0].destination;
c8965800
RB
1437 port = reply->transports[0].port_min;
1438 ttl = reply->transports[0].ttl;
1439 } else {
7934b15d 1440 addr = rtsp_st->sdp_ip;
c8965800
RB
1441 port = rtsp_st->sdp_port;
1442 ttl = rtsp_st->sdp_ttl;
1443 }
6294d708
MS
1444 if (ttl > 0)
1445 snprintf(optbuf, sizeof(optbuf), "?ttl=%d", ttl);
7934b15d
MS
1446 getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1447 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1448 ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
6294d708 1449 port, "%s", optbuf);
6f1b7b39 1450 if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
ddffc2fd 1451 &s->interrupt_callback, NULL) < 0) {
c8965800
RB
1452 err = AVERROR_INVALIDDATA;
1453 goto fail;
1617ad97
FB
1454 }
1455 break;
1456 }
c8965800 1457 }
d1ccf0e0 1458
6e71c120 1459 if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
8b1ab7bf 1460 goto fail;
1617ad97
FB
1461 }
1462
62c3c8ca 1463 if (rt->nb_rtsp_streams && reply->timeout > 0)
30e79845
RB
1464 rt->timeout = reply->timeout;
1465
2e889ae4 1466 if (rt->server_type == RTSP_SERVER_REAL)
1256d16b
RB
1467 rt->need_subscription = 1;
1468
53620bba
RB
1469 return 0;
1470
1471fail:
aeb2de1c 1472 ff_rtsp_undo_setup(s);
53620bba
RB
1473 return err;
1474}
1475
b8c2c41d
JA
1476void ff_rtsp_close_connections(AVFormatContext *s)
1477{
1478 RTSPState *rt = s->priv_data;
e52a9145
AK
1479 if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
1480 ffurl_close(rt->rtsp_hd);
6217b645 1481 rt->rtsp_hd = rt->rtsp_hd_out = NULL;
b8c2c41d
JA
1482}
1483
3307e6ea 1484int ff_rtsp_connect(AVFormatContext *s)
53620bba
RB
1485{
1486 RTSPState *rt = s->priv_data;
921da217 1487 char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
03f8fc08 1488 int port, err, tcp_fd;
354b7573 1489 RTSPMessageHeader reply1 = {0}, *reply = &reply1;
90abbdba 1490 int lower_transport_mask = 0;
2762a7a2 1491 char real_challenge[64] = "";
03f8fc08
MS
1492 struct sockaddr_storage peer;
1493 socklen_t peer_len = sizeof(peer);
57b5555c 1494
dbb06b8c
MS
1495 if (rt->rtp_port_max < rt->rtp_port_min) {
1496 av_log(s, AV_LOG_ERROR, "Invalid UDP port range, max port %d less "
1497 "than min port %d\n", rt->rtp_port_max,
1498 rt->rtp_port_min);
1499 return AVERROR(EINVAL);
1500 }
1501
57b5555c
MS
1502 if (!ff_network_init())
1503 return AVERROR(EIO);
eca4850c 1504
4fa57d52 1505 if (s->max_delay < 0) /* Not set by the caller */
ccfa8aa2 1506 s->max_delay = s->iformat ? DEFAULT_REORDERING_DELAY : 0;
4fa57d52 1507
f5d33f52 1508 rt->control_transport = RTSP_MODE_PLAIN;
eca4850c
MS
1509 if (rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_HTTP)) {
1510 rt->lower_transport_mask = 1 << RTSP_LOWER_TRANSPORT_TCP;
1511 rt->control_transport = RTSP_MODE_TUNNEL;
1512 }
1513 /* Only pass through valid flags from here */
1514 rt->lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
eca4850c
MS
1515
1516redirect:
1517 lower_transport_mask = rt->lower_transport_mask;
53620bba 1518 /* extract hostname and port */
f3bfe388 1519 av_url_split(NULL, 0, auth, sizeof(auth),
f984dcf6 1520 host, sizeof(host), &port, path, sizeof(path), s->filename);
f9337897 1521 if (*auth) {
aa8bf2fb 1522 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
f9337897 1523 }
53620bba
RB
1524 if (port < 0)
1525 port = RTSP_DEFAULT_PORT;
1526
90abbdba 1527 if (!lower_transport_mask)
2a1d51c5 1528 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
53620bba 1529
3e24c770 1530 if (s->oformat) {
b7dc88fc
MS
1531 /* Only UDP or TCP - UDP multicast isn't supported. */
1532 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1533 (1 << RTSP_LOWER_TRANSPORT_TCP);
f5d33f52 1534 if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
3e24c770 1535 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
b7dc88fc 1536 "only UDP and TCP are supported for output.\n");
3e24c770
MS
1537 err = AVERROR(EINVAL);
1538 goto fail;
1539 }
1540 }
1541
4bc5cc23
MS
1542 /* Construct the URI used in request; this is similar to s->filename,
1543 * but with authentication credentials removed and RTSP specific options
1544 * stripped out. */
1545 ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1546 host, port, "%s", path);
1547
f5d33f52
JA
1548 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1549 /* set up initial handshake for tunneling */
1550 char httpname[1024];
1551 char sessioncookie[17];
1552 char headers[1024];
1553
10ed37b5 1554 ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
f5d33f52
JA
1555 snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1556 av_get_random_seed(), av_get_random_seed());
1557
1558 /* GET requests */
6f1b7b39
MS
1559 if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_FLAG_READ,
1560 &s->interrupt_callback) < 0) {
f5d33f52
JA
1561 err = AVERROR(EIO);
1562 goto fail;
1563 }
1564
1565 /* generate GET headers */
1566 snprintf(headers, sizeof(headers),
1567 "x-sessioncookie: %s\r\n"
1568 "Accept: application/x-rtsp-tunnelled\r\n"
1569 "Pragma: no-cache\r\n"
1570 "Cache-Control: no-cache\r\n",
1571 sessioncookie);
196bf28c 1572 av_opt_set(rt->rtsp_hd->priv_data, "headers", headers, 0);
f5d33f52
JA
1573
1574 /* complete the connection */
ddffc2fd 1575 if (ffurl_connect(rt->rtsp_hd, NULL)) {
f5d33f52
JA
1576 err = AVERROR(EIO);
1577 goto fail;
1578 }
1579
1580 /* POST requests */
6f1b7b39
MS
1581 if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_FLAG_WRITE,
1582 &s->interrupt_callback) < 0 ) {
f5d33f52
JA
1583 err = AVERROR(EIO);
1584 goto fail;
1585 }
1586
1587 /* generate POST headers */
1588 snprintf(headers, sizeof(headers),
1589 "x-sessioncookie: %s\r\n"
1590 "Content-Type: application/x-rtsp-tunnelled\r\n"
1591 "Pragma: no-cache\r\n"
1592 "Cache-Control: no-cache\r\n"
1593 "Content-Length: 32767\r\n"
1594 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1595 sessioncookie);
196bf28c 1596 av_opt_set(rt->rtsp_hd_out->priv_data, "headers", headers, 0);
6149485f 1597 av_opt_set(rt->rtsp_hd_out->priv_data, "chunked_post", "0", 0);
f5d33f52 1598
a8ead332
MS
1599 /* Initialize the authentication state for the POST session. The HTTP
1600 * protocol implementation doesn't properly handle multi-pass
1601 * authentication for POST requests, since it would require one of
1602 * the following:
1603 * - implementing Expect: 100-continue, which many HTTP servers
1604 * don't support anyway, even less the RTSP servers that do HTTP
1605 * tunneling
1606 * - sending the whole POST data until getting a 401 reply specifying
1607 * what authentication method to use, then resending all that data
1608 * - waiting for potential 401 replies directly after sending the
1609 * POST header (waiting for some unspecified time)
1610 * Therefore, we copy the full auth state, which works for both basic
1611 * and digest. (For digest, we would have to synchronize the nonce
1612 * count variable between the two sessions, if we'd do more requests
1613 * with the original session, though.)
1614 */
1615 ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1616
9290f15d 1617 /* complete the connection */
ddffc2fd 1618 if (ffurl_connect(rt->rtsp_hd_out, NULL)) {
9290f15d
MS
1619 err = AVERROR(EIO);
1620 goto fail;
1621 }
f5d33f52 1622 } else {
48e77473 1623 /* open the tcp connection */
41874d0a 1624 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
6f1b7b39 1625 if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
ddffc2fd 1626 &s->interrupt_callback, NULL) < 0) {
41874d0a
JA
1627 err = AVERROR(EIO);
1628 goto fail;
1629 }
00e4a1f4 1630 rt->rtsp_hd_out = rt->rtsp_hd;
f5d33f52 1631 }
53620bba
RB
1632 rt->seq = 0;
1633
1869ea03 1634 tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
03f8fc08
MS
1635 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1636 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1637 NULL, 0, NI_NUMERICHOST);
1638 }
1639
c8965800
RB
1640 /* request options supported by the server; this also detects server
1641 * type */
1cf151e9 1642 for (rt->server_type = RTSP_SERVER_RTP;;) {
b17d11c6 1643 cmd[0] = 0;
2e889ae4 1644 if (rt->server_type == RTSP_SERVER_REAL)
1cf151e9 1645 av_strlcat(cmd,
f75e3da5 1646 /*
1cf151e9
RB
1647 * The following entries are required for proper
1648 * streaming from a Realmedia server. They are
1649 * interdependent in some way although we currently
1650 * don't quite understand how. Values were copied
1651 * from mplayer SVN r23589.
f75e3da5
DB
1652 * ClientChallenge is a 16-byte ID in hex
1653 * CompanyID is a 16-byte ID in base64
1cf151e9
RB
1654 */
1655 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1656 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1657 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1658 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1659 sizeof(cmd));
b17d11c6 1660 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1cf151e9
RB
1661 if (reply->status_code != RTSP_STATUS_OK) {
1662 err = AVERROR_INVALIDDATA;
1663 goto fail;
1664 }
1665
1666 /* detect server type if not standard-compliant RTP */
2e889ae4
RB
1667 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1668 rt->server_type = RTSP_SERVER_REAL;
1cf151e9 1669 continue;
bb3244de 1670 } else if (!av_strncasecmp(reply->server, "WMServer/", 9)) {
7a86bafa 1671 rt->server_type = RTSP_SERVER_WMS;
c8965800 1672 } else if (rt->server_type == RTSP_SERVER_REAL)
1cf151e9 1673 strcpy(real_challenge, reply->real_challenge);
1cf151e9
RB
1674 break;
1675 }
1676
44b70ce5 1677 if (s->iformat && CONFIG_RTSP_DEMUXER)
0526c6f7 1678 err = ff_rtsp_setup_input_streams(s, reply);
44b70ce5 1679 else if (CONFIG_RTSP_MUXER)
c2688f3a 1680 err = ff_rtsp_setup_output_streams(s, host);
e23d195d 1681 if (err)
53620bba 1682 goto fail;
53620bba 1683
8a8754d8 1684 do {
c8965800
RB
1685 int lower_transport = ff_log2_tab[lower_transport_mask &
1686 ~(lower_transport_mask - 1)];
8a8754d8 1687
fef5649a 1688 err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
2e889ae4 1689 rt->server_type == RTSP_SERVER_REAL ?
e9dea59f 1690 real_challenge : NULL);
8a8754d8 1691 if (err < 0)
7e6ca34f 1692 goto fail;
90abbdba
RB
1693 lower_transport_mask &= ~(1 << lower_transport);
1694 if (lower_transport_mask == 0 && err == 1) {
28c4741a 1695 err = AVERROR(EPROTONOSUPPORT);
8a8754d8
RB
1696 goto fail;
1697 }
1698 } while (err);
53620bba 1699
2762a7a2
MS
1700 rt->lower_transport_mask = lower_transport_mask;
1701 av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
ff762d6e 1702 rt->state = RTSP_STATE_IDLE;
c8965800 1703 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1617ad97
FB
1704 return 0;
1705 fail:
3307e6ea 1706 ff_rtsp_close_streams(s);
b8c2c41d 1707 ff_rtsp_close_connections(s);
35cfd646 1708 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
d243ba30
LB
1709 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1710 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1711 reply->status_code,
1712 s->filename);
1713 goto redirect;
1714 }
57b5555c 1715 ff_network_close();
1617ad97
FB
1716 return err;
1717}
2e802e38 1718#endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1617ad97 1719
44b70ce5 1720#if CONFIG_RTPDEC
0e59034e 1721static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
321259c1 1722 uint8_t *buf, int buf_size, int64_t wait_end)
0e59034e
RB
1723{
1724 RTSPState *rt = s->priv_data;
1725 RTSPStream *rtsp_st;
a8475bbd
LB
1726 int n, i, ret, tcp_fd, timeout_cnt = 0;
1727 int max_p = 0;
1728 struct pollfd *p = rt->p;
e7993ece 1729 int *fds = NULL, fdsnum, fdsidx;
0e59034e 1730
c8965800 1731 for (;;) {
9957cdbf 1732 if (ff_check_interrupt(&s->interrupt_callback))
c76374c6 1733 return AVERROR_EXIT;
321259c1
MS
1734 if (wait_end && wait_end - av_gettime() < 0)
1735 return AVERROR(EAGAIN);
a8475bbd 1736 max_p = 0;
0e59034e 1737 if (rt->rtsp_hd) {
1869ea03 1738 tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
a8475bbd
LB
1739 p[max_p].fd = tcp_fd;
1740 p[max_p++].events = POLLIN;
0e59034e 1741 } else {
0e59034e
RB
1742 tcp_fd = -1;
1743 }
c8965800 1744 for (i = 0; i < rt->nb_rtsp_streams; i++) {
0e59034e
RB
1745 rtsp_st = rt->rtsp_streams[i];
1746 if (rtsp_st->rtp_handle) {
e7993ece
JO
1747 if (ret = ffurl_get_multi_file_handle(rtsp_st->rtp_handle,
1748 &fds, &fdsnum)) {
1749 av_log(s, AV_LOG_ERROR, "Unable to recover rtp ports\n");
1750 return ret;
1751 }
1752 if (fdsnum != 2) {
1753 av_log(s, AV_LOG_ERROR,
1754 "Number of fds %d not supported\n", fdsnum);
1755 return AVERROR_INVALIDDATA;
1756 }
1757 for (fdsidx = 0; fdsidx < fdsnum; fdsidx++) {
1758 p[max_p].fd = fds[fdsidx];
1759 p[max_p++].events = POLLIN;
1760 }
1761 av_free(fds);
0e59034e
RB
1762 }
1763 }
a8475bbd 1764 n = poll(p, max_p, POLL_TIMEOUT_MS);
0e59034e 1765 if (n > 0) {
a8475bbd 1766 int j = 1 - (tcp_fd == -1);
9cba6f5f 1767 timeout_cnt = 0;
c8965800 1768 for (i = 0; i < rt->nb_rtsp_streams; i++) {
0e59034e
RB
1769 rtsp_st = rt->rtsp_streams[i];
1770 if (rtsp_st->rtp_handle) {
a8475bbd 1771 if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
bc371aca 1772 ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
0e59034e
RB
1773 if (ret > 0) {
1774 *prtsp_st = rtsp_st;
1775 return ret;
1776 }
1777 }
a8475bbd 1778 j+=2;
0e59034e
RB
1779 }
1780 }
5fe8021a 1781#if CONFIG_RTSP_DEMUXER
a8475bbd 1782 if (tcp_fd != -1 && p[0].revents & POLLIN) {
a8ad6ffa
JO
1783 if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
1784 if (rt->state == RTSP_STATE_STREAMING) {
1785 if (!ff_rtsp_parse_streaming_commands(s))
1786 return AVERROR_EOF;
1787 else
1788 av_log(s, AV_LOG_WARNING,
1789 "Unable to answer to TEARDOWN\n");
1790 } else
1791 return 0;
1792 } else {
1793 RTSPMessageHeader reply;
1794 ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
1795 if (ret < 0)
1796 return ret;
1797 /* XXX: parse message */
1798 if (rt->state != RTSP_STATE_STREAMING)
1799 return 0;
1800 }
0e59034e 1801 }
5fe8021a 1802#endif
9cba6f5f 1803 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
28c4741a 1804 return AVERROR(ETIMEDOUT);
9cba6f5f
SG
1805 } else if (n < 0 && errno != EINTR)
1806 return AVERROR(errno);
0e59034e
RB
1807 }
1808}
1809
e96406ed
MS
1810static int pick_stream(AVFormatContext *s, RTSPStream **rtsp_st,
1811 const uint8_t *buf, int len)
1812{
1813 RTSPState *rt = s->priv_data;
1814 int i;
1815 if (len < 0)
1816 return len;
1817 if (rt->nb_rtsp_streams == 1) {
1818 *rtsp_st = rt->rtsp_streams[0];
1819 return len;
1820 }
1821 if (len >= 8 && rt->transport == RTSP_TRANSPORT_RTP) {
1822 if (RTP_PT_IS_RTCP(rt->recvbuf[1])) {
1823 int no_ssrc = 0;
1824 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1825 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
1826 if (!rtpctx)
1827 continue;
1828 if (rtpctx->ssrc == AV_RB32(&buf[4])) {
1829 *rtsp_st = rt->rtsp_streams[i];
1830 return len;
1831 }
1832 if (!rtpctx->ssrc)
1833 no_ssrc = 1;
1834 }
1835 if (no_ssrc) {
1836 av_log(s, AV_LOG_WARNING,
1837 "Unable to pick stream for packet - SSRC not known for "
1838 "all streams\n");
1839 return AVERROR(EAGAIN);
1840 }
1841 } else {
1842 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1843 if ((buf[1] & 0x7f) == rt->rtsp_streams[i]->sdp_payload_type) {
1844 *rtsp_st = rt->rtsp_streams[i];
1845 return len;
1846 }
1847 }
1848 }
1849 }
1850 av_log(s, AV_LOG_WARNING, "Unable to pick stream for packet\n");
1851 return AVERROR(EAGAIN);
1852}
1853
0526c6f7 1854int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
0e59034e
RB
1855{
1856 RTSPState *rt = s->priv_data;
1857 int ret, len;
321259c1
MS
1858 RTSPStream *rtsp_st, *first_queue_st = NULL;
1859 int64_t wait_end = 0;
0e59034e 1860
b20359f5
JA
1861 if (rt->nb_byes == rt->nb_rtsp_streams)
1862 return AVERROR_EOF;
1863
0e59034e
RB
1864 /* get next frames from the same RTP packet */
1865 if (rt->cur_transport_priv) {
c8965800 1866 if (rt->transport == RTSP_TRANSPORT_RDT) {
0e59034e 1867 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1243c722 1868 } else if (rt->transport == RTSP_TRANSPORT_RTP) {
bfc6db44 1869 ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1243c722
MS
1870 } else if (rt->ts && CONFIG_RTPDEC) {
1871 ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf + rt->recvbuf_pos, rt->recvbuf_len - rt->recvbuf_pos);
1872 if (ret >= 0) {
1873 rt->recvbuf_pos += ret;
1874 ret = rt->recvbuf_pos < rt->recvbuf_len;
1875 }
2f41eaa9
MS
1876 } else
1877 ret = -1;
0e59034e
RB
1878 if (ret == 0) {
1879 rt->cur_transport_priv = NULL;
1880 return 0;
1881 } else if (ret == 1) {
1882 return 0;
c8965800 1883 } else
0e59034e 1884 rt->cur_transport_priv = NULL;
0e59034e
RB
1885 }
1886
8729698d 1887redo:
321259c1
MS
1888 if (rt->transport == RTSP_TRANSPORT_RTP) {
1889 int i;
1890 int64_t first_queue_time = 0;
1891 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1892 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
9e99f84f
MS
1893 int64_t queue_time;
1894 if (!rtpctx)
1895 continue;
1896 queue_time = ff_rtp_queued_packet_time(rtpctx);
321259c1
MS
1897 if (queue_time && (queue_time - first_queue_time < 0 ||
1898 !first_queue_time)) {
1899 first_queue_time = queue_time;
1900 first_queue_st = rt->rtsp_streams[i];
1901 }
1902 }
8729698d 1903 if (first_queue_time) {
321259c1 1904 wait_end = first_queue_time + s->max_delay;
8729698d
MS
1905 } else {
1906 wait_end = 0;
1907 first_queue_st = NULL;
1908 }
321259c1
MS
1909 }
1910
0e59034e 1911 /* read next RTP packet */
96a7c975
MS
1912 if (!rt->recvbuf) {
1913 rt->recvbuf = av_malloc(RECVBUF_SIZE);
1914 if (!rt->recvbuf)
1915 return AVERROR(ENOMEM);
1916 }
1917
0e59034e
RB
1918 switch(rt->lower_transport) {
1919 default:
5fe8021a 1920#if CONFIG_RTSP_DEMUXER
0e59034e 1921 case RTSP_LOWER_TRANSPORT_TCP:
0526c6f7 1922 len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
0e59034e 1923 break;
5fe8021a 1924#endif
0e59034e
RB
1925 case RTSP_LOWER_TRANSPORT_UDP:
1926 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
321259c1 1927 len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
2c35a6bd 1928 if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
e96406ed
MS
1929 ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, rtsp_st->rtp_handle, NULL, len);
1930 break;
1931 case RTSP_LOWER_TRANSPORT_CUSTOM:
f811cd2d
MS
1932 if (first_queue_st && rt->transport == RTSP_TRANSPORT_RTP &&
1933 wait_end && wait_end < av_gettime())
1934 len = AVERROR(EAGAIN);
1935 else
1936 len = ffio_read_partial(s->pb, rt->recvbuf, RECVBUF_SIZE);
e96406ed
MS
1937 len = pick_stream(s, &rtsp_st, rt->recvbuf, len);
1938 if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1939 ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, NULL, s->pb, len);
0e59034e
RB
1940 break;
1941 }
321259c1
MS
1942 if (len == AVERROR(EAGAIN) && first_queue_st &&
1943 rt->transport == RTSP_TRANSPORT_RTP) {
1944 rtsp_st = first_queue_st;
bfc6db44 1945 ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
321259c1
MS
1946 goto end;
1947 }
0e59034e
RB
1948 if (len < 0)
1949 return len;
1950 if (len == 0)
1951 return AVERROR_EOF;
c8965800 1952 if (rt->transport == RTSP_TRANSPORT_RDT) {
ad4ad27f 1953 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
df8cf076 1954 } else if (rt->transport == RTSP_TRANSPORT_RTP) {
bfc6db44 1955 ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
86d9181c
MS
1956 if (rtsp_st->feedback) {
1957 AVIOContext *pb = NULL;
1958 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_CUSTOM)
1959 pb = s->pb;
1960 ff_rtp_send_rtcp_feedback(rtsp_st->transport_priv, rtsp_st->rtp_handle, pb);
1961 }
2cab6b48
MS
1962 if (ret < 0) {
1963 /* Either bad packet, or a RTCP packet. Check if the
1964 * first_rtcp_ntp_time field was initialized. */
1965 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1966 if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
1967 /* first_rtcp_ntp_time has been initialized for this stream,
1968 * copy the same value to all other uninitialized streams,
1969 * in order to map their timestamp origin to the same ntp time
1970 * as this one. */
1971 int i;
3a1cdcc7
MS
1972 AVStream *st = NULL;
1973 if (rtsp_st->stream_index >= 0)
1974 st = s->streams[rtsp_st->stream_index];
2cab6b48 1975 for (i = 0; i < rt->nb_rtsp_streams; i++) {
744a882f 1976 RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
3a1cdcc7
MS
1977 AVStream *st2 = NULL;
1978 if (rt->rtsp_streams[i]->stream_index >= 0)
1979 st2 = s->streams[rt->rtsp_streams[i]->stream_index];
1980 if (rtpctx2 && st && st2 &&
1981 rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
2cab6b48 1982 rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
3a1cdcc7
MS
1983 rtpctx2->rtcp_ts_offset = av_rescale_q(
1984 rtpctx->rtcp_ts_offset, st->time_base,
1985 st2->time_base);
1986 }
2cab6b48
MS
1987 }
1988 }
b20359f5
JA
1989 if (ret == -RTCP_BYE) {
1990 rt->nb_byes++;
1991
1992 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
1993 rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
1994
1995 if (rt->nb_byes == rt->nb_rtsp_streams)
1996 return AVERROR_EOF;
1997 }
2cab6b48 1998 }
1243c722
MS
1999 } else if (rt->ts && CONFIG_RTPDEC) {
2000 ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf, len);
2001 if (ret >= 0) {
2002 if (ret < len) {
2003 rt->recvbuf_len = len;
2004 rt->recvbuf_pos = ret;
2005 rt->cur_transport_priv = rt->ts;
2006 return 1;
2007 } else {
2008 ret = 0;
2009 }
2010 }
df8cf076
MS
2011 } else {
2012 return AVERROR_INVALIDDATA;
2cab6b48 2013 }
321259c1 2014end:
0e59034e
RB
2015 if (ret < 0)
2016 goto redo;
c8965800 2017 if (ret == 1)
0e59034e
RB
2018 /* more packets may follow, so we save the RTP context */
2019 rt->cur_transport_priv = rtsp_st->transport_priv;
0e59034e
RB
2020
2021 return ret;
2022}
44b70ce5 2023#endif /* CONFIG_RTPDEC */
0e59034e 2024
44b70ce5 2025#if CONFIG_SDP_DEMUXER
cb1fdc61 2026static int sdp_probe(AVProbeData *p1)
93ced3e8 2027{
0e1ceacd 2028 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
cb1fdc61 2029
3fbd12d1 2030 /* we look for a line beginning "c=IN IP" */
0e1ceacd 2031 while (p < p_end && *p != '\0') {
3fbd12d1
MS
2032 if (p + sizeof("c=IN IP") - 1 < p_end &&
2033 av_strstart(p, "c=IN IP", NULL))
e0f8be64 2034 return AVPROBE_SCORE_EXTENSION;
0e1ceacd 2035
c8965800 2036 while (p < p_end - 1 && *p != '\n') p++;
0e1ceacd 2037 if (++p >= p_end)
cb1fdc61 2038 break;
cb1fdc61
FB
2039 if (*p == '\r')
2040 p++;
2041 }
93ced3e8
FB
2042 return 0;
2043}
2044
6e9651d1 2045static int sdp_read_header(AVFormatContext *s)
93ced3e8 2046{
8b1ab7bf 2047 RTSPState *rt = s->priv_data;
93ced3e8
FB
2048 RTSPStream *rtsp_st;
2049 int size, i, err;
2050 char *content;
2051 char url[1024];
2052
57b5555c
MS
2053 if (!ff_network_init())
2054 return AVERROR(EIO);
2055
4fa57d52 2056 if (s->max_delay < 0) /* Not set by the caller */
ccfa8aa2 2057 s->max_delay = DEFAULT_REORDERING_DELAY;
e96406ed
MS
2058 if (rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)
2059 rt->lower_transport = RTSP_LOWER_TRANSPORT_CUSTOM;
4fa57d52 2060
93ced3e8
FB
2061 /* read the whole sdp file */
2062 /* XXX: better loading */
2063 content = av_malloc(SDP_MAX_SIZE);
b7effd4e 2064 size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
93ced3e8
FB
2065 if (size <= 0) {
2066 av_free(content);
2067 return AVERROR_INVALIDDATA;
2068 }
2069 content[size] ='\0';
2070
f81c7ac7 2071 err = ff_sdp_parse(s, content);
93ced3e8 2072 av_free(content);
f81c7ac7 2073 if (err) goto fail;
93ced3e8
FB
2074
2075 /* open each RTP stream */
c8965800 2076 for (i = 0; i < rt->nb_rtsp_streams; i++) {
3fbd12d1 2077 char namebuf[50];
8b1ab7bf 2078 rtsp_st = rt->rtsp_streams[i];
115329f1 2079
e96406ed
MS
2080 if (!(rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)) {
2081 getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
2082 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
2083 ff_url_join(url, sizeof(url), "rtp", NULL,
2084 namebuf, rtsp_st->sdp_port,
2085 "?localport=%d&ttl=%d&connect=%d", rtsp_st->sdp_port,
2086 rtsp_st->sdp_ttl,
2087 rt->rtsp_flags & RTSP_FLAG_FILTER_SRC ? 1 : 0);
2088 if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
2089 &s->interrupt_callback, NULL) < 0) {
2090 err = AVERROR_INVALIDDATA;
2091 goto fail;
2092 }
93ced3e8 2093 }
6e71c120 2094 if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
8b1ab7bf 2095 goto fail;
93ced3e8
FB
2096 }
2097 return 0;
c8965800 2098fail:
3307e6ea 2099 ff_rtsp_close_streams(s);
57b5555c 2100 ff_network_close();
93ced3e8
FB
2101 return err;
2102}
2103
93ced3e8
FB
2104static int sdp_read_close(AVFormatContext *s)
2105{
3307e6ea 2106 ff_rtsp_close_streams(s);
57b5555c 2107 ff_network_close();
93ced3e8
FB
2108 return 0;
2109}
2110
51369f28
MS
2111static const AVClass sdp_demuxer_class = {
2112 .class_name = "SDP demuxer",
2113 .item_name = av_default_item_name,
2114 .option = sdp_options,
2115 .version = LIBAVUTIL_VERSION_INT,
2116};
2117
c6610a21 2118AVInputFormat ff_sdp_demuxer = {
dfc2c4d9
AK
2119 .name = "sdp",
2120 .long_name = NULL_IF_CONFIG_SMALL("SDP"),
2121 .priv_data_size = sizeof(RTSPState),
2122 .read_probe = sdp_probe,
2123 .read_header = sdp_read_header,
2124 .read_packet = ff_rtsp_fetch_packet,
2125 .read_close = sdp_read_close,
17934c18 2126 .priv_class = &sdp_demuxer_class,
93ced3e8 2127};
44b70ce5 2128#endif /* CONFIG_SDP_DEMUXER */
44594cc7 2129
44b70ce5 2130#if CONFIG_RTP_DEMUXER
44594cc7
MS
2131static int rtp_probe(AVProbeData *p)
2132{
2133 if (av_strstart(p->filename, "rtp:", NULL))
2134 return AVPROBE_SCORE_MAX;
2135 return 0;
2136}
2137
6e9651d1 2138static int rtp_read_header(AVFormatContext *s)
44594cc7 2139{
350ad50b 2140 uint8_t recvbuf[RTP_MAX_PACKET_LENGTH];
44594cc7
MS
2141 char host[500], sdp[500];
2142 int ret, port;
2143 URLContext* in = NULL;
2144 int payload_type;
a92be9b8 2145 AVCodecContext codec = { 0 };
44594cc7 2146 struct sockaddr_storage addr;
ae628ec1 2147 AVIOContext pb;
44594cc7 2148 socklen_t addrlen = sizeof(addr);
30266038 2149 RTSPState *rt = s->priv_data;
44594cc7
MS
2150
2151 if (!ff_network_init())
2152 return AVERROR(EIO);
2153
6f1b7b39 2154 ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ,
ddffc2fd 2155 &s->interrupt_callback, NULL);
44594cc7
MS
2156 if (ret)
2157 goto fail;
2158
2159 while (1) {
bc371aca 2160 ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
44594cc7
MS
2161 if (ret == AVERROR(EAGAIN))
2162 continue;
2163 if (ret < 0)
2164 goto fail;
2165 if (ret < 12) {
2166 av_log(s, AV_LOG_WARNING, "Received too short packet\n");
2167 continue;
2168 }
2169
2170 if ((recvbuf[0] & 0xc0) != 0x80) {
2171 av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
2172 "received\n");
2173 continue;
2174 }
2175
298a587f 2176 if (RTP_PT_IS_RTCP(recvbuf[1]))
f3a094f2
MS
2177 continue;
2178
44594cc7
MS
2179 payload_type = recvbuf[1] & 0x7f;
2180 break;
2181 }
1869ea03 2182 getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
e52a9145 2183 ffurl_close(in);
44594cc7
MS
2184 in = NULL;
2185
44594cc7
MS
2186 if (ff_rtp_get_codec_info(&codec, payload_type)) {
2187 av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
2188 "without an SDP file describing it\n",
2189 payload_type);
2190 goto fail;
2191 }
2192 if (codec.codec_type != AVMEDIA_TYPE_DATA) {
2193 av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
2194 "properly you need an SDP file "
2195 "describing it\n");
2196 }
2197
2198 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
2199 NULL, 0, s->filename);
2200
2201 snprintf(sdp, sizeof(sdp),
2202 "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
2203 addr.ss_family == AF_INET ? 4 : 6, host,
2204 codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
2205 codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
2206 port, payload_type);
2207 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
2208
e731b8d8 2209 ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
44594cc7
MS
2210 s->pb = &pb;
2211
2212 /* sdp_read_header initializes this again */
2213 ff_network_close();
2214
30266038
MS
2215 rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;
2216
6e9651d1 2217 ret = sdp_read_header(s);
44594cc7
MS
2218 s->pb = NULL;
2219 return ret;
2220
2221fail:
2222 if (in)
e52a9145 2223 ffurl_close(in);
44594cc7
MS
2224 ff_network_close();
2225 return ret;
2226}
2227
51369f28
MS
2228static const AVClass rtp_demuxer_class = {
2229 .class_name = "RTP demuxer",
2230 .item_name = av_default_item_name,
2231 .option = rtp_options,
2232 .version = LIBAVUTIL_VERSION_INT,
2233};
2234
c6610a21 2235AVInputFormat ff_rtp_demuxer = {
dfc2c4d9 2236 .name = "rtp",
6774247a 2237 .long_name = NULL_IF_CONFIG_SMALL("RTP input"),
dfc2c4d9
AK
2238 .priv_data_size = sizeof(RTSPState),
2239 .read_probe = rtp_probe,
2240 .read_header = rtp_read_header,
2241 .read_packet = ff_rtsp_fetch_packet,
2242 .read_close = sdp_read_close,
17934c18
MS
2243 .flags = AVFMT_NOFILE,
2244 .priv_class = &rtp_demuxer_class,
44594cc7 2245};
44b70ce5 2246#endif /* CONFIG_RTP_DEMUXER */