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