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