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