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