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