output-example: Set sample_fmt to SAMPLE_FMT_S16.
[libav.git] / libavformat / rtsp.c
CommitLineData
1617ad97 1/*
93ced3e8 2 * RTSP/SDP client
406792e7 3 * Copyright (c) 2002 Fabrice Bellard
1617ad97 4 *
b78e7197
DB
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg 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 *
b78e7197 12 * FFmpeg 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
b78e7197 18 * License along with FFmpeg; 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"
f5d33f52 25#include "libavutil/random_seed.h"
1617ad97
FB
26#include "avformat.h"
27
db0ed93e 28#include <sys/time.h>
b250f9c6 29#if HAVE_SYS_SELECT_H
933bd8e2 30#include <sys/select.h>
6ad1c9c9 31#endif
ea452b54 32#include <strings.h>
e4a9e3cc 33#include "internal.h"
42572ef5 34#include "network.h"
cbfa66d0 35#include "os_support.h"
f5d33f52 36#include "http.h"
c971ff19 37#include "rtsp.h"
1617ad97 38
302879cb 39#include "rtpdec.h"
e9dea59f 40#include "rdt.h"
f65919af 41#include "rtpdec_asf.h"
4934884a 42
1617ad97 43//#define DEBUG
b6892136 44//#define DEBUG_RTP_TCP
1617ad97 45
c482500f 46#if LIBAVFORMAT_VERSION_INT < (53 << 16)
90abbdba 47int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
c482500f 48#endif
85fb7b34 49
c2bfd816 50/* Timeout values for socket select, in ms,
9cba6f5f
SG
51 * and read_packet(), in seconds */
52#define SELECT_TIMEOUT_MS 100
53#define READ_PACKET_TIMEOUT_S 10
54#define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
55
1ef36a70 56#define SPACE_CHARS " \t\r\n"
da1e126e
RB
57/* we use memchr() instead of strchr() here because strchr() will return
58 * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */
59#define redir_isspace(c) memchr(SPACE_CHARS, c, 4)
1617ad97
FB
60static void skip_spaces(const char **pp)
61{
62 const char *p;
63 p = *pp;
64 while (redir_isspace(*p))
65 p++;
66 *pp = p;
67}
68
1ef36a70
RB
69static void get_word_until_chars(char *buf, int buf_size,
70 const char *sep, const char **pp)
1617ad97
FB
71{
72 const char *p;
73 char *q;
74
75 p = *pp;
76 skip_spaces(&p);
77 q = buf;
78 while (!strchr(sep, *p) && *p != '\0') {
79 if ((q - buf) < buf_size - 1)
80 *q++ = *p;
81 p++;
82 }
83 if (buf_size > 0)
84 *q = '\0';
85 *pp = p;
86}
87
1ef36a70
RB
88static void get_word_sep(char *buf, int buf_size, const char *sep,
89 const char **pp)
1617ad97 90{
1ef36a70
RB
91 if (**pp == '/') (*pp)++;
92 get_word_until_chars(buf, buf_size, sep, pp);
93}
1617ad97 94
1ef36a70
RB
95static void get_word(char *buf, int buf_size, const char **pp)
96{
97 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
1617ad97
FB
98}
99
c8965800 100/* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
8f3c87f3
RB
101static int sdp_parse_rtpmap(AVFormatContext *s,
102 AVCodecContext *codec, RTSPStream *rtsp_st,
c8965800 103 int payload_type, const char *p)
93ced3e8
FB
104{
105 char buf[256];
d1ccf0e0
RD
106 int i;
107 AVCodec *c;
7b49ce2e 108 const char *c_name;
93ced3e8 109
d1ccf0e0 110 /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
9d50d396
RB
111 * see if we can handle this kind of payload.
112 * The space should normally not be there but some Real streams or
113 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
114 * have a trailing space. */
115 get_word_sep(buf, sizeof(buf), "/ ", &p);
d1ccf0e0 116 if (payload_type >= RTP_PT_PRIVATE) {
c8965800
RB
117 RTPDynamicProtocolHandler *handler;
118 for (handler = RTPFirstDynamicPayloadHandler;
119 handler; handler = handler->next) {
120 if (!strcasecmp(buf, handler->enc_name) &&
121 codec->codec_type == handler->codec_type) {
122 codec->codec_id = handler->codec_id;
123 rtsp_st->dynamic_handler = handler;
124 if (handler->open)
125 rtsp_st->dynamic_protocol_context = handler->open();
d1ccf0e0
RD
126 break;
127 }
4934884a 128 }
93ced3e8 129 } else {
c8965800
RB
130 /* We are in a standard case
131 * (from http://www.iana.org/assignments/rtp-parameters). */
d1ccf0e0 132 /* search into AVRtpPayloadTypes[] */
7ed19d7f 133 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
d1ccf0e0
RD
134 }
135
136 c = avcodec_find_decoder(codec->codec_id);
137 if (c && c->name)
7b49ce2e 138 c_name = c->name;
d1ccf0e0 139 else
170870b7 140 c_name = "(null)";
d1ccf0e0 141
7515ed0c
RB
142 get_word_sep(buf, sizeof(buf), "/", &p);
143 i = atoi(buf);
144 switch (codec->codec_type) {
72415b2a 145 case AVMEDIA_TYPE_AUDIO:
7515ed0c
RB
146 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
147 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
148 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
149 if (i > 0) {
150 codec->sample_rate = i;
151 get_word_sep(buf, sizeof(buf), "/", &p);
152 i = atoi(buf);
153 if (i > 0)
154 codec->channels = i;
155 // TODO: there is a bug here; if it is a mono stream, and
156 // less than 22000Hz, faad upconverts to stereo and twice
157 // the frequency. No problem, but the sample rate is being
158 // set here by the sdp line. Patch on its way. (rdm)
d1ccf0e0 159 }
7515ed0c
RB
160 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
161 codec->sample_rate);
162 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
163 codec->channels);
164 break;
72415b2a 165 case AVMEDIA_TYPE_VIDEO:
7515ed0c
RB
166 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
167 break;
168 default:
169 break;
170 }
171 return 0;
93ced3e8
FB
172}
173
c8965800 174/* return the length and optionally the data */
93ced3e8
FB
175static int hex_to_data(uint8_t *data, const char *p)
176{
177 int c, len, v;
178
179 len = 0;
180 v = 1;
c8965800 181 for (;;) {
93ced3e8 182 skip_spaces(&p);
6a8c8b36 183 if (*p == '\0')
93ced3e8 184 break;
c8965800 185 c = toupper((unsigned char) *p++);
93ced3e8
FB
186 if (c >= '0' && c <= '9')
187 c = c - '0';
188 else if (c >= 'A' && c <= 'F')
189 c = c - 'A' + 10;
190 else
191 break;
192 v = (v << 4) | c;
193 if (v & 0x100) {
194 if (data)
195 data[len] = v;
196 len++;
197 v = 1;
198 }
199 }
200 return len;
201}
202
e6327fba
RB
203static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx,
204 char *attr, char *value)
d1ccf0e0
RD
205{
206 switch (codec->codec_id) {
c8965800
RB
207 case CODEC_ID_MPEG4:
208 case CODEC_ID_AAC:
209 if (!strcmp(attr, "config")) {
210 /* decode the hexa encoded parameter */
211 int len = hex_to_data(NULL, value);
212 if (codec->extradata)
213 av_free(codec->extradata);
214 codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
215 if (!codec->extradata)
216 return;
217 codec->extradata_size = len;
218 hex_to_data(codec->extradata, value);
219 }
220 break;
c8965800
RB
221 default:
222 break;
d1ccf0e0
RD
223 }
224 return;
225}
226
644e7acb 227typedef struct {
7b49ce2e 228 const char *str;
c8965800
RB
229 uint16_t type;
230 uint32_t offset;
644e7acb 231} AttrNameMap;
d1ccf0e0 232
c2bfd816 233/* All known fmtp parameters and the corresponding RTPAttrTypeEnum */
d1ccf0e0
RD
234#define ATTR_NAME_TYPE_INT 0
235#define ATTR_NAME_TYPE_STR 1
644e7acb 236static const AttrNameMap attr_names[]=
d1ccf0e0 237{
c8965800
RB
238 { "SizeLength", ATTR_NAME_TYPE_INT,
239 offsetof(RTPPayloadData, sizelength) },
240 { "IndexLength", ATTR_NAME_TYPE_INT,
241 offsetof(RTPPayloadData, indexlength) },
242 { "IndexDeltaLength", ATTR_NAME_TYPE_INT,
243 offsetof(RTPPayloadData, indexdeltalength) },
244 { "profile-level-id", ATTR_NAME_TYPE_INT,
245 offsetof(RTPPayloadData, profile_level_id) },
246 { "StreamType", ATTR_NAME_TYPE_INT,
247 offsetof(RTPPayloadData, streamtype) },
248 { "mode", ATTR_NAME_TYPE_STR,
249 offsetof(RTPPayloadData, mode) },
250 { NULL, -1, -1 },
d1ccf0e0
RD
251};
252
c2bfd816 253/* parse the attribute line from the fmtp a line of an sdp response. This
c8965800
RB
254 * is broken out as a function because it is used in rtp_h264.c, which is
255 * forthcoming. */
3307e6ea 256int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
93993933 257 char *value, int value_size)
d0deedcb
RM
258{
259 skip_spaces(p);
c8965800 260 if (**p) {
d0deedcb
RM
261 get_word_sep(attr, attr_size, "=", p);
262 if (**p == '=')
263 (*p)++;
264 get_word_sep(value, value_size, ";", p);
265 if (**p == ';')
266 (*p)++;
267 return 1;
268 }
269 return 0;
270}
271
d1ccf0e0
RD
272/* parse a SDP line and save stream attributes */
273static void sdp_parse_fmtp(AVStream *st, const char *p)
93ced3e8
FB
274{
275 char attr[256];
373afbaf
RB
276 /* Vorbis setup headers can be up to 12KB and are sent base64
277 * encoded, giving a 12KB * (4/3) = 16KB FMTP line. */
278 char value[16384];
d1ccf0e0 279 int i;
d1ccf0e0 280 RTSPStream *rtsp_st = st->priv_data;
01f4895c 281 AVCodecContext *codec = st->codec;
be73a544 282 RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data;
93ced3e8
FB
283
284 /* loop on each attribute */
3307e6ea 285 while (ff_rtsp_next_attr_and_value(&p, attr, sizeof(attr),
93993933 286 value, sizeof(value))) {
c8965800
RB
287 /* grab the codec extra_data from the config parameter of the fmtp
288 * line */
e6327fba
RB
289 sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context,
290 attr, value);
d1ccf0e0
RD
291 /* Looking for a known attribute */
292 for (i = 0; attr_names[i].str; ++i) {
293 if (!strcasecmp(attr, attr_names[i].str)) {
c8965800
RB
294 if (attr_names[i].type == ATTR_NAME_TYPE_INT) {
295 *(int *)((char *)rtp_payload_data +
296 attr_names[i].offset) = atoi(value);
297 } else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
298 *(char **)((char *)rtp_payload_data +
299 attr_names[i].offset) = av_strdup(value);
bb270c08 300 }
93ced3e8 301 }
93ced3e8
FB
302 }
303}
304
debe86bf 305/** Parse a string p in the form of Range:npt=xx-xx, and determine the start
31693e00
RM
306 * and end time.
307 * Used for seeking in the rtp stream.
308 */
309static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
310{
311 char buf[256];
312
313 skip_spaces(&p);
f7d78f36 314 if (!av_stristart(p, "npt=", &p))
31693e00
RM
315 return;
316
317 *start = AV_NOPTS_VALUE;
318 *end = AV_NOPTS_VALUE;
319
320 get_word_sep(buf, sizeof(buf), "-", &p);
321 *start = parse_date(buf, 1);
322 if (*p == '-') {
323 p++;
324 get_word_sep(buf, sizeof(buf), "-", &p);
325 *end = parse_date(buf, 1);
326 }
327// av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
328// av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
329}
330
93ced3e8
FB
331typedef struct SDPParseState {
332 /* SDP only */
333 struct in_addr default_ip;
c8965800
RB
334 int default_ttl;
335 int skip_media; ///< set if an unknown m= line occurs
93ced3e8
FB
336} SDPParseState;
337
338static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
1617ad97
FB
339 int letter, const char *buf)
340{
8b1ab7bf 341 RTSPState *rt = s->priv_data;
1617ad97
FB
342 char buf1[64], st_type[64];
343 const char *p;
72415b2a 344 enum AVMediaType codec_type;
fb65d2ca 345 int payload_type, i;
1617ad97
FB
346 AVStream *st;
347 RTSPStream *rtsp_st;
93ced3e8
FB
348 struct in_addr sdp_ip;
349 int ttl;
350
67c9cd69 351 dprintf(s, "sdp: %c='%s'\n", letter, buf);
1617ad97
FB
352
353 p = buf;
cb760a47
RB
354 if (s1->skip_media && letter != 'm')
355 return;
c8965800 356 switch (letter) {
93ced3e8
FB
357 case 'c':
358 get_word(buf1, sizeof(buf1), &p);
359 if (strcmp(buf1, "IN") != 0)
360 return;
361 get_word(buf1, sizeof(buf1), &p);
362 if (strcmp(buf1, "IP4") != 0)
363 return;
364 get_word_sep(buf1, sizeof(buf1), "/", &p);
ac11d562 365 if (ff_inet_aton(buf1, &sdp_ip) == 0)
93ced3e8
FB
366 return;
367 ttl = 16;
368 if (*p == '/') {
369 p++;
370 get_word_sep(buf1, sizeof(buf1), "/", &p);
371 ttl = atoi(buf1);
372 }
373 if (s->nb_streams == 0) {
374 s1->default_ip = sdp_ip;
375 s1->default_ttl = ttl;
376 } else {
377 st = s->streams[s->nb_streams - 1];
378 rtsp_st = st->priv_data;
379 rtsp_st->sdp_ip = sdp_ip;
380 rtsp_st->sdp_ttl = ttl;
381 }
382 break;
1617ad97 383 case 's':
2ef6c124 384 av_metadata_set2(&s->metadata, "title", p, 0);
1617ad97
FB
385 break;
386 case 'i':
387 if (s->nb_streams == 0) {
2ef6c124 388 av_metadata_set2(&s->metadata, "comment", p, 0);
1617ad97
FB
389 break;
390 }
391 break;
392 case 'm':
393 /* new stream */
cb760a47 394 s1->skip_media = 0;
1617ad97
FB
395 get_word(st_type, sizeof(st_type), &p);
396 if (!strcmp(st_type, "audio")) {
72415b2a 397 codec_type = AVMEDIA_TYPE_AUDIO;
1617ad97 398 } else if (!strcmp(st_type, "video")) {
72415b2a 399 codec_type = AVMEDIA_TYPE_VIDEO;
090438cc 400 } else if (!strcmp(st_type, "application")) {
72415b2a 401 codec_type = AVMEDIA_TYPE_DATA;
1617ad97 402 } else {
cb760a47 403 s1->skip_media = 1;
1617ad97
FB
404 return;
405 }
1617ad97
FB
406 rtsp_st = av_mallocz(sizeof(RTSPStream));
407 if (!rtsp_st)
408 return;
8b1ab7bf
FB
409 rtsp_st->stream_index = -1;
410 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
93ced3e8
FB
411
412 rtsp_st->sdp_ip = s1->default_ip;
413 rtsp_st->sdp_ttl = s1->default_ttl;
414
93ced3e8
FB
415 get_word(buf1, sizeof(buf1), &p); /* port */
416 rtsp_st->sdp_port = atoi(buf1);
417
418 get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
115329f1 419
93ced3e8
FB
420 /* XXX: handle list of formats */
421 get_word(buf1, sizeof(buf1), &p); /* format list */
422 rtsp_st->sdp_payload_type = atoi(buf1);
93ced3e8 423
7ed19d7f 424 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
8b1ab7bf
FB
425 /* no corresponding stream */
426 } else {
427 st = av_new_stream(s, 0);
428 if (!st)
429 return;
430 st->priv_data = rtsp_st;
431 rtsp_st->stream_index = st->index;
01f4895c 432 st->codec->codec_type = codec_type;
d1ccf0e0 433 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
8b1ab7bf 434 /* if standard payload type, we can find the codec right now */
bf6d9818 435 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
8b1ab7bf
FB
436 }
437 }
1617ad97 438 /* put a default control url */
00eb13e0 439 av_strlcpy(rtsp_st->control_url, rt->control_uri,
c8965800 440 sizeof(rtsp_st->control_url));
1617ad97
FB
441 break;
442 case 'a':
00eb13e0
AS
443 if (av_strstart(p, "control:", &p)) {
444 if (s->nb_streams == 0) {
445 if (!strncmp(p, "rtsp://", 7))
446 av_strlcpy(rt->control_uri, p,
447 sizeof(rt->control_uri));
448 } else {
1617ad97
FB
449 char proto[32];
450 /* get the control url */
451 st = s->streams[s->nb_streams - 1];
452 rtsp_st = st->priv_data;
115329f1 453
1617ad97 454 /* XXX: may need to add full url resolution */
c5c6e67c 455 ff_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
f984dcf6 456 NULL, NULL, 0, p);
1617ad97
FB
457 if (proto[0] == '\0') {
458 /* relative control URL */
00eb13e0 459 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
c8965800
RB
460 av_strlcat(rtsp_st->control_url, "/",
461 sizeof(rtsp_st->control_url));
462 av_strlcat(rtsp_st->control_url, p,
463 sizeof(rtsp_st->control_url));
464 } else
465 av_strlcpy(rtsp_st->control_url, p,
466 sizeof(rtsp_st->control_url));
00eb13e0 467 }
83d14c85 468 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
93ced3e8 469 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
115329f1 470 get_word(buf1, sizeof(buf1), &p);
93ced3e8 471 payload_type = atoi(buf1);
83d14c85 472 st = s->streams[s->nb_streams - 1];
ff16f551 473 rtsp_st = st->priv_data;
8f3c87f3 474 sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
f7d78f36 475 } else if (av_strstart(p, "fmtp:", &p)) {
93ced3e8 476 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
115329f1 477 get_word(buf1, sizeof(buf1), &p);
93ced3e8 478 payload_type = atoi(buf1);
c8965800
RB
479 for (i = 0; i < s->nb_streams; i++) {
480 st = s->streams[i];
93ced3e8
FB
481 rtsp_st = st->priv_data;
482 if (rtsp_st->sdp_payload_type == payload_type) {
c8965800
RB
483 if (!(rtsp_st->dynamic_handler &&
484 rtsp_st->dynamic_handler->parse_sdp_a_line &&
485 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
486 i, rtsp_st->dynamic_protocol_context, buf)))
ed787542 487 sdp_parse_fmtp(st, p);
93ced3e8
FB
488 }
489 }
c8965800 490 } else if (av_strstart(p, "framesize:", &p)) {
d0deedcb
RM
491 // let dynamic protocol handlers have a stab at the line.
492 get_word(buf1, sizeof(buf1), &p);
493 payload_type = atoi(buf1);
c8965800
RB
494 for (i = 0; i < s->nb_streams; i++) {
495 st = s->streams[i];
d0deedcb 496 rtsp_st = st->priv_data;
c8965800
RB
497 if (rtsp_st->sdp_payload_type == payload_type &&
498 rtsp_st->dynamic_handler &&
499 rtsp_st->dynamic_handler->parse_sdp_a_line)
500 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
501 rtsp_st->dynamic_protocol_context, buf);
d0deedcb 502 }
c8965800 503 } else if (av_strstart(p, "range:", &p)) {
31693e00
RM
504 int64_t start, end;
505
506 // this is so that seeking on a streamed file can work.
507 rtsp_parse_range_npt(p, &start, &end);
c8965800
RB
508 s->start_time = start;
509 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
510 s->duration = (end == AV_NOPTS_VALUE) ?
511 AV_NOPTS_VALUE : end - start;
119b4668
RB
512 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
513 if (atoi(p) == 1)
514 rt->transport = RTSP_TRANSPORT_RDT;
1a30d541
RB
515 } else {
516 if (rt->server_type == RTSP_SERVER_WMS)
517 ff_wms_parse_sdp_a_line(s, p);
518 if (s->nb_streams > 0) {
c4a3d032
RB
519 if (rt->server_type == RTSP_SERVER_REAL)
520 ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
521
522 rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
523 if (rtsp_st->dynamic_handler &&
524 rtsp_st->dynamic_handler->parse_sdp_a_line)
c8965800
RB
525 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
526 s->nb_streams - 1,
c4a3d032 527 rtsp_st->dynamic_protocol_context, buf);
1a30d541 528 }
1617ad97
FB
529 }
530 break;
531 }
532}
533
5c91a675 534static int sdp_parse(AVFormatContext *s, const char *content)
1617ad97
FB
535{
536 const char *p;
537 int letter;
9211bcdd
RB
538 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
539 * contain long SDP lines containing complete ASF Headers (several
540 * kB) or arrays of MDPR (RM stream descriptor) headers plus
541 * "rulebooks" describing their properties. Therefore, the SDP line
373afbaf
RB
542 * buffer is large.
543 *
544 * The Vorbis FMTP line can be up to 16KB - see sdp_parse_fmtp. */
545 char buf[16384], *q;
93ced3e8 546 SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
115329f1 547
93ced3e8 548 memset(s1, 0, sizeof(SDPParseState));
1617ad97 549 p = content;
c8965800 550 for (;;) {
1617ad97
FB
551 skip_spaces(&p);
552 letter = *p;
553 if (letter == '\0')
554 break;
555 p++;
556 if (*p != '=')
557 goto next_line;
558 p++;
559 /* get the content */
560 q = buf;
b6892136 561 while (*p != '\n' && *p != '\r' && *p != '\0') {
1617ad97
FB
562 if ((q - buf) < sizeof(buf) - 1)
563 *q++ = *p;
564 p++;
565 }
566 *q = '\0';
93ced3e8 567 sdp_parse_line(s, s1, letter, buf);
1617ad97
FB
568 next_line:
569 while (*p != '\n' && *p != '\0')
570 p++;
571 if (*p == '\n')
572 p++;
573 }
574 return 0;
575}
576
1ced9da3 577/* close and free RTSP streams */
3307e6ea 578void ff_rtsp_close_streams(AVFormatContext *s)
1ced9da3 579{
52aa4338 580 RTSPState *rt = s->priv_data;
1ced9da3
LA
581 int i;
582 RTSPStream *rtsp_st;
583
c8965800 584 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1ced9da3
LA
585 rtsp_st = rt->rtsp_streams[i];
586 if (rtsp_st) {
587 if (rtsp_st->transport_priv) {
fd450a51
MS
588 if (s->oformat) {
589 AVFormatContext *rtpctx = rtsp_st->transport_priv;
590 av_write_trailer(rtpctx);
b7dc88fc
MS
591 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
592 uint8_t *ptr;
593 url_close_dyn_buf(rtpctx->pb, &ptr);
594 av_free(ptr);
595 } else {
685e76b5 596 url_fclose(rtpctx->pb);
b7dc88fc 597 }
f86f6656
MS
598 av_metadata_free(&rtpctx->streams[0]->metadata);
599 av_metadata_free(&rtpctx->metadata);
fd450a51
MS
600 av_free(rtpctx->streams[0]);
601 av_free(rtpctx);
602 } else if (rt->transport == RTSP_TRANSPORT_RDT)
1ced9da3
LA
603 ff_rdt_parse_close(rtsp_st->transport_priv);
604 else
605 rtp_parse_close(rtsp_st->transport_priv);
606 }
607 if (rtsp_st->rtp_handle)
608 url_close(rtsp_st->rtp_handle);
609 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
c8965800
RB
610 rtsp_st->dynamic_handler->close(
611 rtsp_st->dynamic_protocol_context);
1ced9da3
LA
612 }
613 }
614 av_free(rt->rtsp_streams);
615 if (rt->asf_ctx) {
616 av_close_input_stream (rt->asf_ctx);
617 rt->asf_ctx = NULL;
618 }
1ced9da3
LA
619}
620
5c7fd910
MS
621static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st,
622 URLContext *handle)
623{
c07c6f81 624 RTSPState *rt = s->priv_data;
fd450a51
MS
625 AVFormatContext *rtpctx;
626 int ret;
627 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
628
629 if (!rtp_format)
630 return NULL;
631
632 /* Allocate an AVFormatContext for each output stream */
633 rtpctx = avformat_alloc_context();
634 if (!rtpctx)
635 return NULL;
636
637 rtpctx->oformat = rtp_format;
638 if (!av_new_stream(rtpctx, 0)) {
639 av_free(rtpctx);
640 return NULL;
641 }
642 /* Copy the max delay setting; the rtp muxer reads this. */
643 rtpctx->max_delay = s->max_delay;
644 /* Copy other stream parameters. */
645 rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
646
c07c6f81
MS
647 /* Set the synchronized start time. */
648 rtpctx->start_time_realtime = rt->start_time;
649
fd450a51
MS
650 /* Remove the local codec, link to the original codec
651 * context instead, to give the rtp muxer access to
652 * codec parameters. */
653 av_free(rtpctx->streams[0]->codec);
654 rtpctx->streams[0]->codec = st->codec;
655
b7dc88fc 656 if (handle) {
685e76b5 657 url_fdopen(&rtpctx->pb, handle);
b7dc88fc
MS
658 } else
659 url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
fd450a51
MS
660 ret = av_write_header(rtpctx);
661
662 if (ret) {
b7dc88fc 663 if (handle) {
685e76b5 664 url_fclose(rtpctx->pb);
b7dc88fc
MS
665 } else {
666 uint8_t *ptr;
667 url_close_dyn_buf(rtpctx->pb, &ptr);
668 av_free(ptr);
669 }
fd450a51
MS
670 av_free(rtpctx->streams[0]);
671 av_free(rtpctx);
672 return NULL;
673 }
674
675 /* Copy the RTP AVStream timebase back to the original AVStream */
676 st->time_base = rtpctx->streams[0]->time_base;
677 return rtpctx;
678}
679
c8965800 680static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
1ced9da3
LA
681{
682 RTSPState *rt = s->priv_data;
683 AVStream *st = NULL;
684
685 /* open the RTP context */
686 if (rtsp_st->stream_index >= 0)
687 st = s->streams[rtsp_st->stream_index];
688 if (!st)
689 s->ctx_flags |= AVFMTCTX_NOHEADER;
690
fd450a51
MS
691 if (s->oformat) {
692 rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
c2bfd816 693 /* Ownership of rtp_handle is passed to the rtp mux context */
fd450a51
MS
694 rtsp_st->rtp_handle = NULL;
695 } else if (rt->transport == RTSP_TRANSPORT_RDT)
1ced9da3
LA
696 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
697 rtsp_st->dynamic_protocol_context,
698 rtsp_st->dynamic_handler);
699 else
700 rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
701 rtsp_st->sdp_payload_type,
702 &rtsp_st->rtp_payload_data);
703
704 if (!rtsp_st->transport_priv) {
705 return AVERROR(ENOMEM);
706 } else if (rt->transport != RTSP_TRANSPORT_RDT) {
c8965800 707 if (rtsp_st->dynamic_handler) {
1ced9da3
LA
708 rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
709 rtsp_st->dynamic_protocol_context,
710 rtsp_st->dynamic_handler);
711 }
712 }
713
714 return 0;
715}
716
6f5a3d0a 717#if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
1ced9da3
LA
718static int rtsp_probe(AVProbeData *p)
719{
720 if (av_strstart(p->filename, "rtsp:", NULL))
721 return AVPROBE_SCORE_MAX;
722 return 0;
723}
724
1617ad97
FB
725static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
726{
727 const char *p;
728 int v;
729
730 p = *pp;
731 skip_spaces(&p);
732 v = strtol(p, (char **)&p, 10);
733 if (*p == '-') {
734 p++;
735 *min_ptr = v;
736 v = strtol(p, (char **)&p, 10);
737 *max_ptr = v;
738 } else {
739 *min_ptr = v;
740 *max_ptr = v;
741 }
742 *pp = p;
743}
744
745/* XXX: only one transport specification is parsed */
a9e534d5 746static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
1617ad97
FB
747{
748 char transport_protocol[16];
749 char profile[16];
750 char lower_transport[16];
751 char parameter[16];
752 RTSPTransportField *th;
753 char buf[256];
115329f1 754
1617ad97 755 reply->nb_transports = 0;
115329f1 756
c8965800 757 for (;;) {
1617ad97
FB
758 skip_spaces(&p);
759 if (*p == '\0')
760 break;
761
762 th = &reply->transports[reply->nb_transports];
763
115329f1 764 get_word_sep(transport_protocol, sizeof(transport_protocol),
1617ad97 765 "/", &p);
e1502118 766 if (!strcasecmp (transport_protocol, "rtp")) {
7ecc634e
LB
767 get_word_sep(profile, sizeof(profile), "/;,", &p);
768 lower_transport[0] = '\0';
769 /* rtp/avp/<protocol> */
770 if (*p == '/') {
7ecc634e
LB
771 get_word_sep(lower_transport, sizeof(lower_transport),
772 ";,", &p);
119b4668
RB
773 }
774 th->transport = RTSP_TRANSPORT_RTP;
775 } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
776 !strcasecmp (transport_protocol, "x-real-rdt")) {
7ecc634e 777 /* x-pn-tng/<protocol> */
e1502118
LB
778 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
779 profile[0] = '\0';
119b4668 780 th->transport = RTSP_TRANSPORT_RDT;
1617ad97 781 }
b6892136 782 if (!strcasecmp(lower_transport, "TCP"))
90abbdba 783 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
1617ad97 784 else
90abbdba 785 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
115329f1 786
1617ad97
FB
787 if (*p == ';')
788 p++;
789 /* get each parameter */
790 while (*p != '\0' && *p != ',') {
791 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
792 if (!strcmp(parameter, "port")) {
793 if (*p == '=') {
794 p++;
795 rtsp_parse_range(&th->port_min, &th->port_max, &p);
796 }
797 } else if (!strcmp(parameter, "client_port")) {
798 if (*p == '=') {
799 p++;
115329f1 800 rtsp_parse_range(&th->client_port_min,
1617ad97
FB
801 &th->client_port_max, &p);
802 }
803 } else if (!strcmp(parameter, "server_port")) {
804 if (*p == '=') {
805 p++;
115329f1 806 rtsp_parse_range(&th->server_port_min,
1617ad97
FB
807 &th->server_port_max, &p);
808 }
809 } else if (!strcmp(parameter, "interleaved")) {
810 if (*p == '=') {
811 p++;
115329f1 812 rtsp_parse_range(&th->interleaved_min,
1617ad97
FB
813 &th->interleaved_max, &p);
814 }
815 } else if (!strcmp(parameter, "multicast")) {
90abbdba
RB
816 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
817 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
1617ad97
FB
818 } else if (!strcmp(parameter, "ttl")) {
819 if (*p == '=') {
820 p++;
821 th->ttl = strtol(p, (char **)&p, 10);
822 }
823 } else if (!strcmp(parameter, "destination")) {
824 struct in_addr ipaddr;
825
826 if (*p == '=') {
827 p++;
828 get_word_sep(buf, sizeof(buf), ";,", &p);
ac11d562 829 if (ff_inet_aton(buf, &ipaddr))
1617ad97
FB
830 th->destination = ntohl(ipaddr.s_addr);
831 }
832 }
833 while (*p != ';' && *p != '\0' && *p != ',')
834 p++;
835 if (*p == ';')
836 p++;
837 }
838 if (*p == ',')
839 p++;
840
841 reply->nb_transports++;
842 }
843}
844
2626308a
MS
845void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
846 HTTPAuthState *auth_state)
1617ad97
FB
847{
848 const char *p;
849
850 /* NOTE: we do case independent match for broken servers */
851 p = buf;
f7d78f36 852 if (av_stristart(p, "Session:", &p)) {
30e79845 853 int t;
1617ad97 854 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
30e79845
RB
855 if (av_stristart(p, ";timeout=", &p) &&
856 (t = strtol(p, NULL, 10)) > 0) {
857 reply->timeout = t;
858 }
f7d78f36 859 } else if (av_stristart(p, "Content-Length:", &p)) {
1617ad97 860 reply->content_length = strtol(p, NULL, 10);
f7d78f36 861 } else if (av_stristart(p, "Transport:", &p)) {
1617ad97 862 rtsp_parse_transport(reply, p);
f7d78f36 863 } else if (av_stristart(p, "CSeq:", &p)) {
1617ad97 864 reply->seq = strtol(p, NULL, 10);
f7d78f36 865 } else if (av_stristart(p, "Range:", &p)) {
31693e00 866 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
30aa6aed
RB
867 } else if (av_stristart(p, "RealChallenge1:", &p)) {
868 skip_spaces(&p);
869 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
7a86bafa
RB
870 } else if (av_stristart(p, "Server:", &p)) {
871 skip_spaces(&p);
872 av_strlcpy(reply->server, p, sizeof(reply->server));
fccb1770
RB
873 } else if (av_stristart(p, "Notice:", &p) ||
874 av_stristart(p, "X-Notice:", &p)) {
875 reply->notice = strtol(p, NULL, 10);
d243ba30
LB
876 } else if (av_stristart(p, "Location:", &p)) {
877 skip_spaces(&p);
878 av_strlcpy(reply->location, p , sizeof(reply->location));
2626308a
MS
879 } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
880 skip_spaces(&p);
881 ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
882 } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
883 skip_spaces(&p);
884 ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
1617ad97
FB
885 }
886}
887
b7b8fc34 888/* skip a RTP/TCP interleaved packet */
ec55edba 889void ff_rtsp_skip_packet(AVFormatContext *s)
b7b8fc34
FB
890{
891 RTSPState *rt = s->priv_data;
892 int ret, len, len1;
893 uint8_t buf[1024];
894
0e848977 895 ret = url_read_complete(rt->rtsp_hd, buf, 3);
b7b8fc34
FB
896 if (ret != 3)
897 return;
80fb8234 898 len = AV_RB16(buf + 1);
67c9cd69
BC
899
900 dprintf(s, "skipping RTP packet len=%d\n", len);
901
b7b8fc34
FB
902 /* skip payload */
903 while (len > 0) {
904 len1 = len;
905 if (len1 > sizeof(buf))
906 len1 = sizeof(buf);
0e848977 907 ret = url_read_complete(rt->rtsp_hd, buf, len1);
b7b8fc34
FB
908 if (ret != len1)
909 return;
910 len -= len1;
911 }
912}
1617ad97 913
3307e6ea 914int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
93993933
MS
915 unsigned char **content_ptr,
916 int return_on_interleaved_data)
1617ad97
FB
917{
918 RTSPState *rt = s->priv_data;
919 char buf[4096], buf1[1024], *q;
920 unsigned char ch;
921 const char *p;
7e726132 922 int ret, content_length, line_count = 0;
1617ad97
FB
923 unsigned char *content = NULL;
924
d541a7d2 925 memset(reply, 0, sizeof(*reply));
1617ad97 926
1617ad97 927 /* parse reply (XXX: use buffers) */
1617ad97 928 rt->last_reply[0] = '\0';
c8965800 929 for (;;) {
1617ad97 930 q = buf;
c8965800 931 for (;;) {
0e848977 932 ret = url_read_complete(rt->rtsp_hd, &ch, 1);
7e726132 933#ifdef DEBUG_RTP_TCP
67c9cd69 934 dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
7e726132
RB
935#endif
936 if (ret != 1)
937 return -1;
1617ad97
FB
938 if (ch == '\n')
939 break;
b7b8fc34
FB
940 if (ch == '$') {
941 /* XXX: only parse it if first char on line ? */
7e726132
RB
942 if (return_on_interleaved_data) {
943 return 1;
944 } else
ec55edba 945 ff_rtsp_skip_packet(s);
b7b8fc34 946 } else if (ch != '\r') {
1617ad97
FB
947 if ((q - buf) < sizeof(buf) - 1)
948 *q++ = ch;
949 }
950 }
951 *q = '\0';
67c9cd69
BC
952
953 dprintf(s, "line='%s'\n", buf);
954
1617ad97
FB
955 /* test if last line */
956 if (buf[0] == '\0')
957 break;
958 p = buf;
959 if (line_count == 0) {
960 /* get reply code */
961 get_word(buf1, sizeof(buf1), &p);
962 get_word(buf1, sizeof(buf1), &p);
963 reply->status_code = atoi(buf1);
964 } else {
2626308a 965 ff_rtsp_parse_line(reply, p, &rt->auth_state);
75e61b0e
MR
966 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
967 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
1617ad97
FB
968 }
969 line_count++;
970 }
115329f1 971
1617ad97 972 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
75e61b0e 973 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
115329f1 974
1617ad97
FB
975 content_length = reply->content_length;
976 if (content_length > 0) {
977 /* leave some room for a trailing '\0' (useful for simple parsing) */
978 content = av_malloc(content_length + 1);
0e848977 979 (void)url_read_complete(rt->rtsp_hd, content, content_length);
1617ad97
FB
980 content[content_length] = '\0';
981 }
982 if (content_ptr)
983 *content_ptr = content;
e2e2e7dd
AB
984 else
985 av_free(content);
7e726132 986
7ed8211b
LB
987 if (rt->seq != reply->seq) {
988 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
989 rt->seq, reply->seq);
990 }
991
fccb1770
RB
992 /* EOS */
993 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
994 reply->notice == 2104 /* Start-of-Stream Reached */ ||
c8965800 995 reply->notice == 2306 /* Continuous Feed Terminated */) {
fccb1770 996 rt->state = RTSP_STATE_IDLE;
c8965800 997 } else if (reply->notice >= 4400 && reply->notice < 5500) {
fccb1770 998 return AVERROR(EIO); /* data or server error */
c8965800 999 } else if (reply->notice == 2401 /* Ticket Expired */ ||
fccb1770
RB
1000 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
1001 return AVERROR(EPERM);
1002
7e726132 1003 return 0;
1617ad97
FB
1004}
1005
d0382374 1006int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
fc490fcf
MS
1007 const char *method, const char *url,
1008 const char *headers,
1009 const unsigned char *send_content,
1010 int send_content_length)
29b9f58b
RB
1011{
1012 RTSPState *rt = s->priv_data;
f5d33f52
JA
1013 char buf[4096], *out_buf;
1014 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
29b9f58b 1015
f5d33f52
JA
1016 /* Add in RTSP headers */
1017 out_buf = buf;
29b9f58b 1018 rt->seq++;
b17d11c6
MS
1019 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
1020 if (headers)
1021 av_strlcat(buf, headers, sizeof(buf));
7b4a3645 1022 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
b17d11c6
MS
1023 if (rt->session_id[0] != '\0' && (!headers ||
1024 !strstr(headers, "\nIf-Match:"))) {
7b4a3645 1025 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
29b9f58b 1026 }
aa8bf2fb
MS
1027 if (rt->auth[0]) {
1028 char *str = ff_http_auth_create_response(&rt->auth_state,
1029 rt->auth, url, method);
1030 if (str)
1031 av_strlcat(buf, str, sizeof(buf));
1032 av_free(str);
1033 }
dfd017bf
MS
1034 if (send_content_length > 0 && send_content)
1035 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
29b9f58b 1036 av_strlcat(buf, "\r\n", sizeof(buf));
67c9cd69 1037
f5d33f52
JA
1038 /* base64 encode rtsp if tunneling */
1039 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1040 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1041 out_buf = base64buf;
1042 }
1043
67c9cd69
BC
1044 dprintf(s, "Sending:\n%s--\n", buf);
1045
f5d33f52
JA
1046 url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
1047 if (send_content_length > 0 && send_content) {
1048 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1049 av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
1050 "with content data not supported\n");
1051 return AVERROR_PATCHWELCOME;
1052 }
b8c2c41d 1053 url_write(rt->rtsp_hd_out, send_content, send_content_length);
f5d33f52 1054 }
30e79845 1055 rt->last_cmd_time = av_gettime();
d0382374
JA
1056
1057 return 0;
30e79845
RB
1058}
1059
d0382374 1060int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
fc490fcf 1061 const char *url, const char *headers)
dfd017bf 1062{
d0382374 1063 return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
dfd017bf
MS
1064}
1065
d0382374 1066int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
fc490fcf
MS
1067 const char *headers, RTSPMessageHeader *reply,
1068 unsigned char **content_ptr)
30e79845 1069{
d0382374 1070 return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
fc490fcf 1071 content_ptr, NULL, 0);
29b9f58b
RB
1072}
1073
d0382374 1074int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
fc490fcf
MS
1075 const char *method, const char *url,
1076 const char *header,
1077 RTSPMessageHeader *reply,
1078 unsigned char **content_ptr,
1079 const unsigned char *send_content,
1080 int send_content_length)
dfd017bf 1081{
30af0779
MS
1082 RTSPState *rt = s->priv_data;
1083 HTTPAuthType cur_auth_type;
d0382374 1084 int ret;
30af0779
MS
1085
1086retry:
1087 cur_auth_type = rt->auth_state.auth_type;
d0382374 1088 if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
fc490fcf
MS
1089 send_content,
1090 send_content_length)))
d0382374 1091 return ret;
dfd017bf 1092
d0382374
JA
1093 if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
1094 return ret;
30af0779
MS
1095
1096 if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
1097 rt->auth_state.auth_type != HTTP_AUTH_NONE)
1098 goto retry;
d0382374
JA
1099
1100 return 0;
dfd017bf
MS
1101}
1102
53620bba 1103/**
32e543f8 1104 * @return 0 on success, <0 on error, 1 if protocol is unavailable.
53620bba 1105 */
c8965800
RB
1106static int make_setup_request(AVFormatContext *s, const char *host, int port,
1107 int lower_transport, const char *real_challenge)
1617ad97
FB
1108{
1109 RTSPState *rt = s->priv_data;
f830c9a4 1110 int rtx, j, i, err, interleave = 0;
1617ad97 1111 RTSPStream *rtsp_st;
a9e534d5 1112 RTSPMessageHeader reply1, *reply = &reply1;
53620bba 1113 char cmd[2048];
e9dea59f
RB
1114 const char *trans_pref;
1115
119b4668 1116 if (rt->transport == RTSP_TRANSPORT_RDT)
e9dea59f
RB
1117 trans_pref = "x-pn-tng";
1118 else
1119 trans_pref = "RTP/AVP";
115329f1 1120
30e79845
RB
1121 /* default timeout: 1 minute */
1122 rt->timeout = 60;
1123
1617ad97
FB
1124 /* for each stream, make the setup request */
1125 /* XXX: we assume the same server is used for the control of each
c8965800 1126 * RTSP stream */
d1ccf0e0 1127
c8965800 1128 for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
1617ad97
FB
1129 char transport[2048];
1130
f830c9a4
RB
1131 /**
1132 * WMS serves all UDP data over a single connection, the RTX, which
1133 * isn't necessarily the first in the SDP but has to be the first
1134 * to be set up, else the second/third SETUP will fail with a 461.
1135 */
1136 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1137 rt->server_type == RTSP_SERVER_WMS) {
1138 if (i == 0) {
1139 /* rtx first */
1140 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1141 int len = strlen(rt->rtsp_streams[rtx]->control_url);
1142 if (len >= 4 &&
c8965800
RB
1143 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1144 "/rtx"))
f830c9a4
RB
1145 break;
1146 }
1147 if (rtx == rt->nb_rtsp_streams)
1148 return -1; /* no RTX found */
1149 rtsp_st = rt->rtsp_streams[rtx];
1150 } else
1151 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1152 } else
2fea9650 1153 rtsp_st = rt->rtsp_streams[i];
1617ad97 1154
1617ad97 1155 /* RTP/UDP */
90abbdba 1156 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
85fb7b34 1157 char buf[256];
85fb7b34 1158
f830c9a4
RB
1159 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1160 port = reply->transports[0].client_port_min;
1161 goto have_port;
1162 }
1163
85fb7b34 1164 /* first try in specified port range */
d1ccf0e0 1165 if (RTSP_RTP_PORT_MIN != 0) {
c8965800 1166 while (j <= RTSP_RTP_PORT_MAX) {
57b5555c
MS
1167 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1168 "?localport=%d", j);
c8965800
RB
1169 /* we will use two ports per rtp stream (rtp and rtcp) */
1170 j += 2;
1171 if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
85fb7b34
FB
1172 goto rtp_opened;
1173 }
1617ad97 1174 }
85fb7b34 1175
c8965800
RB
1176#if 0
1177 /* then try on any port */
1178 if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
1179 err = AVERROR_INVALIDDATA;
1180 goto fail;
1181 }
1182#endif
85fb7b34
FB
1183
1184 rtp_opened:
8b1ab7bf 1185 port = rtp_get_local_port(rtsp_st->rtp_handle);
f830c9a4 1186 have_port:
0ad306bc 1187 snprintf(transport, sizeof(transport) - 1,
eee2cbff
RB
1188 "%s/UDP;", trans_pref);
1189 if (rt->server_type != RTSP_SERVER_REAL)
1190 av_strlcat(transport, "unicast;", sizeof(transport));
1191 av_strlcatf(transport, sizeof(transport),
1192 "client_port=%d", port);
f830c9a4
RB
1193 if (rt->transport == RTSP_TRANSPORT_RTP &&
1194 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
e9dea59f 1195 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1617ad97
FB
1196 }
1197
1198 /* RTP/TCP */
90abbdba 1199 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
090438cc
RB
1200 /** For WMS streams, the application streams are only used for
1201 * UDP. When trying to set it up for TCP streams, the server
1202 * will return an error. Therefore, we skip those streams. */
1203 if (rt->server_type == RTSP_SERVER_WMS &&
c8965800 1204 s->streams[rtsp_st->stream_index]->codec->codec_type ==
72415b2a 1205 AVMEDIA_TYPE_DATA)
090438cc 1206 continue;
0ad306bc 1207 snprintf(transport, sizeof(transport) - 1,
d1c6e47c
RB
1208 "%s/TCP;", trans_pref);
1209 if (rt->server_type == RTSP_SERVER_WMS)
1210 av_strlcat(transport, "unicast;", sizeof(transport));
1211 av_strlcatf(transport, sizeof(transport),
1212 "interleaved=%d-%d",
1213 interleave, interleave + 1);
1214 interleave += 2;
1617ad97
FB
1215 }
1216
90abbdba 1217 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
0ad306bc 1218 snprintf(transport, sizeof(transport) - 1,
e9dea59f 1219 "%s/UDP;multicast", trans_pref);
1617ad97 1220 }
69adcc4f
MS
1221 if (s->oformat) {
1222 av_strlcat(transport, ";mode=receive", sizeof(transport));
1223 } else if (rt->server_type == RTSP_SERVER_REAL ||
2efc97c2 1224 rt->server_type == RTSP_SERVER_WMS)
e9dea59f 1225 av_strlcat(transport, ";mode=play", sizeof(transport));
115329f1 1226 snprintf(cmd, sizeof(cmd),
b6892136 1227 "Transport: %s\r\n",
b17d11c6 1228 transport);
2e889ae4 1229 if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
e9dea59f
RB
1230 char real_res[41], real_csum[9];
1231 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1232 real_challenge);
1233 av_strlcatf(cmd, sizeof(cmd),
1234 "If-Match: %s\r\n"
1235 "RealChallenge2: %s, sd=%s\r\n",
1236 rt->session_id, real_res, real_csum);
1237 }
b17d11c6 1238 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
8a8754d8
RB
1239 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1240 err = 1;
1241 goto fail;
7e6ca34f
RB
1242 } else if (reply->status_code != RTSP_STATUS_OK ||
1243 reply->nb_transports != 1) {
1617ad97
FB
1244 err = AVERROR_INVALIDDATA;
1245 goto fail;
1246 }
1247
1248 /* XXX: same protocol for all streams is required */
1249 if (i > 0) {
119b4668
RB
1250 if (reply->transports[0].lower_transport != rt->lower_transport ||
1251 reply->transports[0].transport != rt->transport) {
1617ad97
FB
1252 err = AVERROR_INVALIDDATA;
1253 goto fail;
1254 }
1255 } else {
90abbdba 1256 rt->lower_transport = reply->transports[0].lower_transport;
119b4668 1257 rt->transport = reply->transports[0].transport;
1617ad97
FB
1258 }
1259
1260 /* close RTP connection if not choosen */
90abbdba
RB
1261 if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
1262 (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
8b1ab7bf
FB
1263 url_close(rtsp_st->rtp_handle);
1264 rtsp_st->rtp_handle = NULL;
1617ad97
FB
1265 }
1266
90abbdba
RB
1267 switch(reply->transports[0].lower_transport) {
1268 case RTSP_LOWER_TRANSPORT_TCP:
1617ad97
FB
1269 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1270 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1271 break;
115329f1 1272
c8965800
RB
1273 case RTSP_LOWER_TRANSPORT_UDP: {
1274 char url[1024];
1275
1276 /* XXX: also use address if specified */
57b5555c
MS
1277 ff_url_join(url, sizeof(url), "rtp", NULL, host,
1278 reply->transports[0].server_port_min, NULL);
c8965800
RB
1279 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1280 rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1281 err = AVERROR_INVALIDDATA;
1282 goto fail;
1617ad97 1283 }
9c8fa20d
MS
1284 /* Try to initialize the connection state in a
1285 * potential NAT router by sending dummy packets.
1286 * RTP/RTCP dummy packets are used for RDT, too.
1287 */
30ff7c5c 1288 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
9c8fa20d 1289 rtp_send_punch_packets(rtsp_st->rtp_handle);
1617ad97 1290 break;
c8965800
RB
1291 }
1292 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1293 char url[1024];
1294 struct in_addr in;
1295 int port, ttl;
1296
1297 if (reply->transports[0].destination) {
1298 in.s_addr = htonl(reply->transports[0].destination);
1299 port = reply->transports[0].port_min;
1300 ttl = reply->transports[0].ttl;
1301 } else {
1302 in = rtsp_st->sdp_ip;
1303 port = rtsp_st->sdp_port;
1304 ttl = rtsp_st->sdp_ttl;
1305 }
57b5555c
MS
1306 ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in),
1307 port, "?ttl=%d", ttl);
c8965800
RB
1308 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1309 err = AVERROR_INVALIDDATA;
1310 goto fail;
1617ad97
FB
1311 }
1312 break;
1313 }
c8965800 1314 }
d1ccf0e0 1315
ee0cb67f 1316 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
8b1ab7bf 1317 goto fail;
1617ad97
FB
1318 }
1319
30e79845
RB
1320 if (reply->timeout > 0)
1321 rt->timeout = reply->timeout;
1322
2e889ae4 1323 if (rt->server_type == RTSP_SERVER_REAL)
1256d16b
RB
1324 rt->need_subscription = 1;
1325
53620bba
RB
1326 return 0;
1327
1328fail:
c8965800 1329 for (i = 0; i < rt->nb_rtsp_streams; i++) {
8a8754d8
RB
1330 if (rt->rtsp_streams[i]->rtp_handle) {
1331 url_close(rt->rtsp_streams[i]->rtp_handle);
1332 rt->rtsp_streams[i]->rtp_handle = NULL;
1333 }
1334 }
53620bba
RB
1335 return err;
1336}
1337
1ced9da3
LA
1338static int rtsp_read_play(AVFormatContext *s)
1339{
1340 RTSPState *rt = s->priv_data;
1341 RTSPMessageHeader reply1, *reply = &reply1;
5948f822 1342 int i;
1ced9da3
LA
1343 char cmd[1024];
1344
1345 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1346
1347 if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1348 if (rt->state == RTSP_STATE_PAUSED) {
b17d11c6 1349 cmd[0] = 0;
1ced9da3
LA
1350 } else {
1351 snprintf(cmd, sizeof(cmd),
1ced9da3 1352 "Range: npt=%0.3f-\r\n",
1ced9da3
LA
1353 (double)rt->seek_timestamp / AV_TIME_BASE);
1354 }
b17d11c6 1355 ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
1ced9da3
LA
1356 if (reply->status_code != RTSP_STATUS_OK) {
1357 return -1;
1358 }
5948f822
MS
1359 if (reply->range_start != AV_NOPTS_VALUE &&
1360 rt->transport == RTSP_TRANSPORT_RTP) {
1361 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1362 RTSPStream *rtsp_st = rt->rtsp_streams[i];
1363 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1364 AVStream *st = NULL;
8d168a92
MS
1365 if (!rtpctx)
1366 continue;
5948f822
MS
1367 if (rtsp_st->stream_index >= 0)
1368 st = s->streams[rtsp_st->stream_index];
1369 rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
1370 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
1371 if (st)
1372 rtpctx->range_start_offset = av_rescale_q(reply->range_start,
1373 AV_TIME_BASE_Q,
1374 st->time_base);
1375 }
1376 }
1ced9da3 1377 }
c02fd3d2 1378 rt->state = RTSP_STATE_STREAMING;
1ced9da3
LA
1379 return 0;
1380}
1381
6e69f6c4 1382static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
e23d195d
MS
1383{
1384 RTSPState *rt = s->priv_data;
e23d195d
MS
1385 char cmd[1024];
1386 unsigned char *content = NULL;
1387 int ret;
1388
1389 /* describe the stream */
1390 snprintf(cmd, sizeof(cmd),
b17d11c6 1391 "Accept: application/sdp\r\n");
e23d195d
MS
1392 if (rt->server_type == RTSP_SERVER_REAL) {
1393 /**
1394 * The Require: attribute is needed for proper streaming from
1395 * Realmedia servers.
1396 */
1397 av_strlcat(cmd,
1398 "Require: com.real.retain-entity-for-setup\r\n",
1399 sizeof(cmd));
1400 }
b17d11c6 1401 ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
e23d195d
MS
1402 if (!content)
1403 return AVERROR_INVALIDDATA;
1404 if (reply->status_code != RTSP_STATUS_OK) {
1405 av_freep(&content);
1406 return AVERROR_INVALIDDATA;
1407 }
1408
1409 /* now we got the SDP description, we parse it */
1410 ret = sdp_parse(s, (const char *)content);
1411 av_freep(&content);
1412 if (ret < 0)
1413 return AVERROR_INVALIDDATA;
1414
1415 return 0;
1416}
1417
26cb700c 1418static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
3e24c770
MS
1419{
1420 RTSPState *rt = s->priv_data;
1421 RTSPMessageHeader reply1, *reply = &reply1;
3e24c770
MS
1422 int i;
1423 char *sdp;
26cb700c 1424 AVFormatContext sdp_ctx, *ctx_array[1];
c07c6f81
MS
1425
1426 rt->start_time = av_gettime();
3e24c770
MS
1427
1428 /* Announce the stream */
3e24c770
MS
1429 sdp = av_mallocz(8192);
1430 if (sdp == NULL)
1431 return AVERROR(ENOMEM);
26cb700c
MS
1432 /* We create the SDP based on the RTSP AVFormatContext where we
1433 * aren't allowed to change the filename field. (We create the SDP
1434 * based on the RTSP context since the contexts for the RTP streams
1435 * don't exist yet.) In order to specify a custom URL with the actual
1436 * peer IP instead of the originally specified hostname, we create
1437 * a temporary copy of the AVFormatContext, where the custom URL is set.
1438 *
1439 * FIXME: Create the SDP without copying the AVFormatContext.
1440 * This either requires setting up the RTP stream AVFormatContexts
1441 * already here (complicating things immensely) or getting a more
1442 * flexible SDP creation interface.
1443 */
1444 sdp_ctx = *s;
1445 ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
1446 "rtsp", NULL, addr, -1, NULL);
1447 ctx_array[0] = &sdp_ctx;
1448 if (avf_sdp_create(ctx_array, 1, sdp, 8192)) {
3e24c770
MS
1449 av_free(sdp);
1450 return AVERROR_INVALIDDATA;
1451 }
1452 av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
b17d11c6
MS
1453 ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
1454 "Content-Type: application/sdp\r\n",
1455 reply, NULL, sdp, strlen(sdp));
3e24c770
MS
1456 av_free(sdp);
1457 if (reply->status_code != RTSP_STATUS_OK)
1458 return AVERROR_INVALIDDATA;
1459
1460 /* Set up the RTSPStreams for each AVStream */
1461 for (i = 0; i < s->nb_streams; i++) {
1462 RTSPStream *rtsp_st;
1463 AVStream *st = s->streams[i];
1464
1465 rtsp_st = av_mallocz(sizeof(RTSPStream));
1466 if (!rtsp_st)
1467 return AVERROR(ENOMEM);
1468 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
1469
1470 st->priv_data = rtsp_st;
1471 rtsp_st->stream_index = i;
1472
db76ca7f 1473 av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
3e24c770
MS
1474 /* Note, this must match the relative uri set in the sdp content */
1475 av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
1476 "/streamid=%d", i);
1477 }
1478
1479 return 0;
1480}
1481
b8c2c41d
JA
1482void ff_rtsp_close_connections(AVFormatContext *s)
1483{
1484 RTSPState *rt = s->priv_data;
1485 if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
1486 url_close(rt->rtsp_hd);
1487}
1488
3307e6ea 1489int ff_rtsp_connect(AVFormatContext *s)
53620bba
RB
1490{
1491 RTSPState *rt = s->priv_data;
921da217
LB
1492 char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1493 char *option_list, *option, *filename;
b8c2c41d 1494 URLContext *rtsp_hd, *rtsp_hd_out;
03f8fc08 1495 int port, err, tcp_fd;
3370289a 1496 RTSPMessageHeader reply1 = {}, *reply = &reply1;
90abbdba 1497 int lower_transport_mask = 0;
1cf151e9 1498 char real_challenge[64];
03f8fc08
MS
1499 struct sockaddr_storage peer;
1500 socklen_t peer_len = sizeof(peer);
57b5555c
MS
1501
1502 if (!ff_network_init())
1503 return AVERROR(EIO);
c8965800 1504redirect:
f5d33f52 1505 rt->control_transport = RTSP_MODE_PLAIN;
53620bba 1506 /* extract hostname and port */
c5c6e67c 1507 ff_url_split(NULL, 0, auth, sizeof(auth),
f984dcf6 1508 host, sizeof(host), &port, path, sizeof(path), s->filename);
f9337897 1509 if (*auth) {
aa8bf2fb 1510 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
f9337897 1511 }
53620bba
RB
1512 if (port < 0)
1513 port = RTSP_DEFAULT_PORT;
1514
1515 /* search for options */
602eb779 1516 option_list = strrchr(path, '?');
53620bba 1517 if (option_list) {
2a21adf9
MS
1518 /* Strip out the RTSP specific options, write out the rest of
1519 * the options back into the same string. */
1520 filename = option_list;
c8965800 1521 while (option_list) {
53620bba 1522 /* move the option pointer */
921da217 1523 option = ++option_list;
53620bba
RB
1524 option_list = strchr(option_list, '&');
1525 if (option_list)
921da217
LB
1526 *option_list = 0;
1527
53620bba 1528 /* handle the options */
c8965800 1529 if (!strcmp(option, "udp")) {
7a033e08 1530 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
c8965800 1531 } else if (!strcmp(option, "multicast")) {
7a033e08 1532 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
c8965800 1533 } else if (!strcmp(option, "tcp")) {
7a033e08 1534 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
f5d33f52
JA
1535 } else if(!strcmp(option, "http")) {
1536 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1537 rt->control_transport = RTSP_MODE_TUNNEL;
c8965800 1538 } else {
2a21adf9
MS
1539 /* Write options back into the buffer, using memmove instead
1540 * of strcpy since the strings may overlap. */
1541 int len = strlen(option);
1542 memmove(++filename, option, len);
1543 filename += len;
921da217
LB
1544 if (option_list) *filename = '&';
1545 }
53620bba 1546 }
921da217 1547 *filename = 0;
53620bba
RB
1548 }
1549
90abbdba 1550 if (!lower_transport_mask)
2a1d51c5 1551 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
53620bba 1552
3e24c770 1553 if (s->oformat) {
b7dc88fc
MS
1554 /* Only UDP or TCP - UDP multicast isn't supported. */
1555 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1556 (1 << RTSP_LOWER_TRANSPORT_TCP);
f5d33f52 1557 if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
3e24c770 1558 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
b7dc88fc 1559 "only UDP and TCP are supported for output.\n");
3e24c770
MS
1560 err = AVERROR(EINVAL);
1561 goto fail;
1562 }
1563 }
1564
4bc5cc23
MS
1565 /* Construct the URI used in request; this is similar to s->filename,
1566 * but with authentication credentials removed and RTSP specific options
1567 * stripped out. */
1568 ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1569 host, port, "%s", path);
1570
f5d33f52
JA
1571 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1572 /* set up initial handshake for tunneling */
1573 char httpname[1024];
1574 char sessioncookie[17];
1575 char headers[1024];
1576
1577 ff_url_join(httpname, sizeof(httpname), "http", NULL, host, port, "%s", path);
1578 snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1579 av_get_random_seed(), av_get_random_seed());
1580
1581 /* GET requests */
1582 if (url_open(&rtsp_hd, httpname, URL_RDONLY) < 0) {
1583 err = AVERROR(EIO);
1584 goto fail;
1585 }
1586
1587 /* generate GET headers */
1588 snprintf(headers, sizeof(headers),
1589 "x-sessioncookie: %s\r\n"
1590 "Accept: application/x-rtsp-tunnelled\r\n"
1591 "Pragma: no-cache\r\n"
1592 "Cache-Control: no-cache\r\n",
1593 sessioncookie);
1594 ff_http_set_headers(rtsp_hd, headers);
1595
1596 /* complete the connection */
1597 if (url_read(rtsp_hd, NULL, 0)) {
1598 err = AVERROR(EIO);
1599 goto fail;
1600 }
1601
1602 /* POST requests */
1603 if (url_open(&rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
1604 err = AVERROR(EIO);
1605 goto fail;
1606 }
1607
1608 /* generate POST headers */
1609 snprintf(headers, sizeof(headers),
1610 "x-sessioncookie: %s\r\n"
1611 "Content-Type: application/x-rtsp-tunnelled\r\n"
1612 "Pragma: no-cache\r\n"
1613 "Cache-Control: no-cache\r\n"
1614 "Content-Length: 32767\r\n"
1615 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1616 sessioncookie);
1617 ff_http_set_headers(rtsp_hd_out, headers);
1618 ff_http_set_chunked_transfer_encoding(rtsp_hd_out, 0);
1619
1620 } else {
53620bba 1621 /* open the tcp connexion */
57b5555c 1622 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
f9337897
RB
1623 if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0) {
1624 err = AVERROR(EIO);
1625 goto fail;
1626 }
b8c2c41d 1627 rtsp_hd_out = rtsp_hd;
f5d33f52 1628 }
53620bba 1629 rt->rtsp_hd = rtsp_hd;
b8c2c41d 1630 rt->rtsp_hd_out = rtsp_hd_out;
53620bba
RB
1631 rt->seq = 0;
1632
03f8fc08
MS
1633 tcp_fd = url_get_file_handle(rtsp_hd);
1634 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1635 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1636 NULL, 0, NI_NUMERICHOST);
1637 }
1638
c8965800
RB
1639 /* request options supported by the server; this also detects server
1640 * type */
1cf151e9 1641 for (rt->server_type = RTSP_SERVER_RTP;;) {
b17d11c6 1642 cmd[0] = 0;
2e889ae4 1643 if (rt->server_type == RTSP_SERVER_REAL)
1cf151e9
RB
1644 av_strlcat(cmd,
1645 /**
1646 * The following entries are required for proper
1647 * streaming from a Realmedia server. They are
1648 * interdependent in some way although we currently
1649 * don't quite understand how. Values were copied
1650 * from mplayer SVN r23589.
1651 * @param CompanyID is a 16-byte ID in base64
1652 * @param ClientChallenge is a 16-byte ID in hex
1653 */
1654 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1655 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1656 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1657 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1658 sizeof(cmd));
b17d11c6 1659 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1cf151e9
RB
1660 if (reply->status_code != RTSP_STATUS_OK) {
1661 err = AVERROR_INVALIDDATA;
1662 goto fail;
1663 }
1664
1665 /* detect server type if not standard-compliant RTP */
2e889ae4
RB
1666 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1667 rt->server_type = RTSP_SERVER_REAL;
1cf151e9 1668 continue;
7a86bafa
RB
1669 } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1670 rt->server_type = RTSP_SERVER_WMS;
c8965800 1671 } else if (rt->server_type == RTSP_SERVER_REAL)
1cf151e9 1672 strcpy(real_challenge, reply->real_challenge);
1cf151e9
RB
1673 break;
1674 }
1675
3e24c770 1676 if (s->iformat)
6e69f6c4 1677 err = rtsp_setup_input_streams(s, reply);
3e24c770 1678 else
26cb700c 1679 err = rtsp_setup_output_streams(s, host);
e23d195d 1680 if (err)
53620bba 1681 goto fail;
53620bba 1682
8a8754d8 1683 do {
c8965800
RB
1684 int lower_transport = ff_log2_tab[lower_transport_mask &
1685 ~(lower_transport_mask - 1)];
8a8754d8 1686
90abbdba 1687 err = make_setup_request(s, host, port, lower_transport,
2e889ae4 1688 rt->server_type == RTSP_SERVER_REAL ?
e9dea59f 1689 real_challenge : NULL);
8a8754d8 1690 if (err < 0)
7e6ca34f 1691 goto fail;
90abbdba
RB
1692 lower_transport_mask &= ~(1 << lower_transport);
1693 if (lower_transport_mask == 0 && err == 1) {
adef229e 1694 err = FF_NETERROR(EPROTONOSUPPORT);
8a8754d8
RB
1695 goto fail;
1696 }
1697 } while (err);
53620bba 1698
ff762d6e 1699 rt->state = RTSP_STATE_IDLE;
c8965800 1700 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1617ad97
FB
1701 return 0;
1702 fail:
3307e6ea 1703 ff_rtsp_close_streams(s);
b8c2c41d 1704 ff_rtsp_close_connections(s);
35cfd646 1705 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
d243ba30
LB
1706 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1707 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1708 reply->status_code,
1709 s->filename);
1710 goto redirect;
1711 }
57b5555c 1712 ff_network_close();
1617ad97
FB
1713 return err;
1714}
6f5a3d0a 1715#endif
1617ad97 1716
6f5a3d0a 1717#if CONFIG_RTSP_DEMUXER
4280f9bb
MS
1718static int rtsp_read_header(AVFormatContext *s,
1719 AVFormatParameters *ap)
1720{
4280f9bb
MS
1721 int ret;
1722
3307e6ea 1723 ret = ff_rtsp_connect(s);
4280f9bb
MS
1724 if (ret)
1725 return ret;
1726
1727 if (ap->initial_pause) {
1728 /* do not start immediately */
1729 } else {
1730 if (rtsp_read_play(s) < 0) {
3307e6ea 1731 ff_rtsp_close_streams(s);
b8c2c41d 1732 ff_rtsp_close_connections(s);
4280f9bb
MS
1733 return AVERROR_INVALIDDATA;
1734 }
1735 }
1736
1737 return 0;
1738}
1739
0e59034e
RB
1740static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1741 uint8_t *buf, int buf_size)
1742{
1743 RTSPState *rt = s->priv_data;
1744 RTSPStream *rtsp_st;
1745 fd_set rfds;
9cba6f5f 1746 int fd, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
0e59034e
RB
1747 struct timeval tv;
1748
c8965800 1749 for (;;) {
0e59034e
RB
1750 if (url_interrupt_cb())
1751 return AVERROR(EINTR);
1752 FD_ZERO(&rfds);
1753 if (rt->rtsp_hd) {
1754 tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
1755 FD_SET(tcp_fd, &rfds);
1756 } else {
1757 fd_max = 0;
1758 tcp_fd = -1;
1759 }
c8965800 1760 for (i = 0; i < rt->nb_rtsp_streams; i++) {
0e59034e
RB
1761 rtsp_st = rt->rtsp_streams[i];
1762 if (rtsp_st->rtp_handle) {
1763 /* currently, we cannot probe RTCP handle because of
1764 * blocking restrictions */
1765 fd = url_get_file_handle(rtsp_st->rtp_handle);
1766 if (fd > fd_max)
1767 fd_max = fd;
1768 FD_SET(fd, &rfds);
1769 }
1770 }
1771 tv.tv_sec = 0;
9cba6f5f 1772 tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
0e59034e
RB
1773 n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1774 if (n > 0) {
9cba6f5f 1775 timeout_cnt = 0;
c8965800 1776 for (i = 0; i < rt->nb_rtsp_streams; i++) {
0e59034e
RB
1777 rtsp_st = rt->rtsp_streams[i];
1778 if (rtsp_st->rtp_handle) {
1779 fd = url_get_file_handle(rtsp_st->rtp_handle);
1780 if (FD_ISSET(fd, &rfds)) {
1781 ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1782 if (ret > 0) {
1783 *prtsp_st = rtsp_st;
1784 return ret;
1785 }
1786 }
1787 }
1788 }
1789#if CONFIG_RTSP_DEMUXER
27000636 1790 if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
0e59034e
RB
1791 RTSPMessageHeader reply;
1792
3032276b
MS
1793 ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
1794 if (ret < 0)
1795 return ret;
0e59034e 1796 /* XXX: parse message */
c02fd3d2 1797 if (rt->state != RTSP_STATE_STREAMING)
0e59034e
RB
1798 return 0;
1799 }
1800#endif
9cba6f5f 1801 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
4aecee7f 1802 return FF_NETERROR(ETIMEDOUT);
9cba6f5f
SG
1803 } else if (n < 0 && errno != EINTR)
1804 return AVERROR(errno);
0e59034e
RB
1805 }
1806}
1807
8b1ab7bf
FB
1808static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1809 uint8_t *buf, int buf_size)
1617ad97
FB
1810{
1811 RTSPState *rt = s->priv_data;
b6892136 1812 int id, len, i, ret;
1617ad97 1813 RTSPStream *rtsp_st;
1617ad97 1814
b6892136 1815#ifdef DEBUG_RTP_TCP
67c9cd69 1816 dprintf(s, "tcp_read_packet:\n");
b6892136 1817#endif
c8965800
RB
1818redo:
1819 for (;;) {
7e726132
RB
1820 RTSPMessageHeader reply;
1821
3307e6ea 1822 ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
7e726132 1823 if (ret == -1)
8b1ab7bf 1824 return -1;
7e726132 1825 if (ret == 1) /* received '$' */
1617ad97 1826 break;
7e726132 1827 /* XXX: parse message */
c02fd3d2 1828 if (rt->state != RTSP_STATE_STREAMING)
fccb1770 1829 return 0;
1617ad97 1830 }
0e848977 1831 ret = url_read_complete(rt->rtsp_hd, buf, 3);
b6892136 1832 if (ret != 3)
8b1ab7bf 1833 return -1;
c8965800 1834 id = buf[0];
80fb8234 1835 len = AV_RB16(buf + 1);
b6892136 1836#ifdef DEBUG_RTP_TCP
67c9cd69 1837 dprintf(s, "id=%d len=%d\n", id, len);
b6892136 1838#endif
8b1ab7bf 1839 if (len > buf_size || len < 12)
1617ad97
FB
1840 goto redo;
1841 /* get the data */
0e848977 1842 ret = url_read_complete(rt->rtsp_hd, buf, len);
b6892136 1843 if (ret != len)
8b1ab7bf 1844 return -1;
985b05d3 1845 if (rt->transport == RTSP_TRANSPORT_RDT &&
114732f4 1846 ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
985b05d3 1847 return -1;
115329f1 1848
1617ad97 1849 /* find the matching stream */
c8965800 1850 for (i = 0; i < rt->nb_rtsp_streams; i++) {
8b1ab7bf 1851 rtsp_st = rt->rtsp_streams[i];
115329f1
DB
1852 if (id >= rtsp_st->interleaved_min &&
1853 id <= rtsp_st->interleaved_max)
1617ad97
FB
1854 goto found;
1855 }
1856 goto redo;
c8965800 1857found:
8b1ab7bf
FB
1858 *prtsp_st = rtsp_st;
1859 return len;
1617ad97
FB
1860}
1861
0e59034e
RB
1862static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1863{
1864 RTSPState *rt = s->priv_data;
1865 int ret, len;
1866 uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
1867 RTSPStream *rtsp_st;
1868
1869 /* get next frames from the same RTP packet */
1870 if (rt->cur_transport_priv) {
c8965800 1871 if (rt->transport == RTSP_TRANSPORT_RDT) {
0e59034e 1872 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
c8965800 1873 } else
0e59034e
RB
1874 ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1875 if (ret == 0) {
1876 rt->cur_transport_priv = NULL;
1877 return 0;
1878 } else if (ret == 1) {
1879 return 0;
c8965800 1880 } else
0e59034e 1881 rt->cur_transport_priv = NULL;
0e59034e
RB
1882 }
1883
1884 /* read next RTP packet */
1885 redo:
1886 switch(rt->lower_transport) {
1887 default:
1888#if CONFIG_RTSP_DEMUXER
1889 case RTSP_LOWER_TRANSPORT_TCP:
1890 len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1891 break;
1892#endif
1893 case RTSP_LOWER_TRANSPORT_UDP:
1894 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1895 len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1896 if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1897 rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1898 break;
1899 }
1900 if (len < 0)
1901 return len;
1902 if (len == 0)
1903 return AVERROR_EOF;
c8965800 1904 if (rt->transport == RTSP_TRANSPORT_RDT) {
0e59034e 1905 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
2cab6b48 1906 } else {
0e59034e 1907 ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
2cab6b48
MS
1908 if (ret < 0) {
1909 /* Either bad packet, or a RTCP packet. Check if the
1910 * first_rtcp_ntp_time field was initialized. */
1911 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1912 if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
1913 /* first_rtcp_ntp_time has been initialized for this stream,
1914 * copy the same value to all other uninitialized streams,
1915 * in order to map their timestamp origin to the same ntp time
1916 * as this one. */
1917 int i;
1918 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1919 RTPDemuxContext *rtpctx2 = rtsp_st->transport_priv;
1920 if (rtpctx2 &&
1921 rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
1922 rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
1923 }
1924 }
1925 }
1926 }
0e59034e
RB
1927 if (ret < 0)
1928 goto redo;
c8965800 1929 if (ret == 1)
0e59034e
RB
1930 /* more packets may follow, so we save the RTP context */
1931 rt->cur_transport_priv = rtsp_st->transport_priv;
0e59034e
RB
1932
1933 return ret;
1934}
1935
c8965800 1936static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
1617ad97
FB
1937{
1938 RTSPState *rt = s->priv_data;
98713182 1939 int ret;
30e79845
RB
1940 RTSPMessageHeader reply1, *reply = &reply1;
1941 char cmd[1024];
8b1ab7bf 1942
572c6a38 1943 if (rt->server_type == RTSP_SERVER_REAL) {
1256d16b 1944 int i;
572c6a38 1945 enum AVDiscard cache[MAX_STREAMS];
1256d16b 1946
572c6a38
RB
1947 for (i = 0; i < s->nb_streams; i++)
1948 cache[i] = s->streams[i]->discard;
1949
1950 if (!rt->need_subscription) {
1951 if (memcmp (cache, rt->real_setup_cache,
1952 sizeof(enum AVDiscard) * s->nb_streams)) {
8b9457de 1953 snprintf(cmd, sizeof(cmd),
7eaa646f 1954 "Unsubscribe: %s\r\n",
b17d11c6
MS
1955 rt->last_subscription);
1956 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1957 cmd, reply, NULL);
572c6a38
RB
1958 if (reply->status_code != RTSP_STATUS_OK)
1959 return AVERROR_INVALIDDATA;
1960 rt->need_subscription = 1;
1961 }
1256d16b 1962 }
1256d16b 1963
572c6a38
RB
1964 if (rt->need_subscription) {
1965 int r, rule_nr, first = 1;
1966
1967 memcpy(rt->real_setup_cache, cache,
1968 sizeof(enum AVDiscard) * s->nb_streams);
1969 rt->last_subscription[0] = 0;
1970
1971 snprintf(cmd, sizeof(cmd),
b17d11c6 1972 "Subscribe: ");
572c6a38
RB
1973 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1974 rule_nr = 0;
1975 for (r = 0; r < s->nb_streams; r++) {
1976 if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
1977 if (s->streams[r]->discard != AVDISCARD_ALL) {
1978 if (!first)
1979 av_strlcat(rt->last_subscription, ",",
1980 sizeof(rt->last_subscription));
1981 ff_rdt_subscribe_rule(
1982 rt->last_subscription,
1983 sizeof(rt->last_subscription), i, rule_nr);
1984 first = 0;
1985 }
1986 rule_nr++;
1987 }
1988 }
1989 }
1990 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
b17d11c6
MS
1991 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1992 cmd, reply, NULL);
572c6a38
RB
1993 if (reply->status_code != RTSP_STATUS_OK)
1994 return AVERROR_INVALIDDATA;
1995 rt->need_subscription = 0;
1996
c02fd3d2 1997 if (rt->state == RTSP_STATE_STREAMING)
572c6a38
RB
1998 rtsp_read_play (s);
1999 }
1256d16b
RB
2000 }
2001
d7250724 2002 ret = rtsp_fetch_packet(s, pkt);
c8965800 2003 if (ret < 0)
98713182 2004 return ret;
30e79845
RB
2005
2006 /* send dummy request to keep TCP connection alive */
2007 if ((rt->server_type == RTSP_SERVER_WMS ||
2008 rt->server_type == RTSP_SERVER_REAL) &&
2009 (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
2010 if (rt->server_type == RTSP_SERVER_WMS) {
b17d11c6 2011 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
30e79845 2012 } else {
b17d11c6 2013 ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
30e79845
RB
2014 }
2015 }
2016
8b1ab7bf 2017 return 0;
1617ad97
FB
2018}
2019
ff762d6e
FB
2020/* pause the stream */
2021static int rtsp_read_pause(AVFormatContext *s)
b7b8fc34 2022{
ff762d6e 2023 RTSPState *rt = s->priv_data;
a9e534d5 2024 RTSPMessageHeader reply1, *reply = &reply1;
b7b8fc34 2025
c02fd3d2 2026 if (rt->state != RTSP_STATE_STREAMING)
ff762d6e 2027 return 0;
2e889ae4 2028 else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
b17d11c6 2029 ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
99b2ac07
RB
2030 if (reply->status_code != RTSP_STATUS_OK) {
2031 return -1;
2032 }
1256d16b 2033 }
5f86057f
RB
2034 rt->state = RTSP_STATE_PAUSED;
2035 return 0;
b7b8fc34
FB
2036}
2037
115329f1 2038static int rtsp_read_seek(AVFormatContext *s, int stream_index,
7b3c1382 2039 int64_t timestamp, int flags)
ff762d6e
FB
2040{
2041 RTSPState *rt = s->priv_data;
115329f1 2042
c8965800
RB
2043 rt->seek_timestamp = av_rescale_q(timestamp,
2044 s->streams[stream_index]->time_base,
2045 AV_TIME_BASE_Q);
ff762d6e
FB
2046 switch(rt->state) {
2047 default:
2048 case RTSP_STATE_IDLE:
2049 break;
c02fd3d2 2050 case RTSP_STATE_STREAMING:
ec606b36
LB
2051 if (rtsp_read_pause(s) != 0)
2052 return -1;
2053 rt->state = RTSP_STATE_SEEKING;
ff762d6e
FB
2054 if (rtsp_read_play(s) != 0)
2055 return -1;
2056 break;
2057 case RTSP_STATE_PAUSED:
2058 rt->state = RTSP_STATE_IDLE;
2059 break;
2060 }
2061 return 0;
2062}
2063
1617ad97
FB
2064static int rtsp_read_close(AVFormatContext *s)
2065{
2066 RTSPState *rt = s->priv_data;
1617ad97 2067
b6892136 2068#if 0
1617ad97 2069 /* NOTE: it is valid to flush the buffer here */
90abbdba 2070 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1617ad97
FB
2071 url_fclose(&rt->rtsp_gb);
2072 }
b6892136 2073#endif
b17d11c6 2074 ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
1617ad97 2075
3307e6ea 2076 ff_rtsp_close_streams(s);
b8c2c41d 2077 ff_rtsp_close_connections(s);
57b5555c 2078 ff_network_close();
1617ad97
FB
2079 return 0;
2080}
2081
d2a067d1 2082AVInputFormat rtsp_demuxer = {
1617ad97 2083 "rtsp",
bde15e74 2084 NULL_IF_CONFIG_SMALL("RTSP input format"),
1617ad97
FB
2085 sizeof(RTSPState),
2086 rtsp_probe,
2087 rtsp_read_header,
2088 rtsp_read_packet,
2089 rtsp_read_close,
ff762d6e 2090 rtsp_read_seek,
bb76a117 2091 .flags = AVFMT_NOFILE,
ff762d6e
FB
2092 .read_play = rtsp_read_play,
2093 .read_pause = rtsp_read_pause,
1617ad97 2094};
96862926 2095#endif
1617ad97 2096
cb1fdc61 2097static int sdp_probe(AVProbeData *p1)
93ced3e8 2098{
0e1ceacd 2099 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
cb1fdc61
FB
2100
2101 /* we look for a line beginning "c=IN IP4" */
0e1ceacd 2102 while (p < p_end && *p != '\0') {
c8965800
RB
2103 if (p + sizeof("c=IN IP4") - 1 < p_end &&
2104 av_strstart(p, "c=IN IP4", NULL))
cb1fdc61 2105 return AVPROBE_SCORE_MAX / 2;
0e1ceacd 2106
c8965800 2107 while (p < p_end - 1 && *p != '\n') p++;
0e1ceacd 2108 if (++p >= p_end)
cb1fdc61 2109 break;
cb1fdc61
FB
2110 if (*p == '\r')
2111 p++;
2112 }
93ced3e8
FB
2113 return 0;
2114}
2115
2116#define SDP_MAX_SIZE 8192
2117
c8965800 2118static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
93ced3e8 2119{
8b1ab7bf 2120 RTSPState *rt = s->priv_data;
93ced3e8
FB
2121 RTSPStream *rtsp_st;
2122 int size, i, err;
2123 char *content;
2124 char url[1024];
2125
57b5555c
MS
2126 if (!ff_network_init())
2127 return AVERROR(EIO);
2128
93ced3e8
FB
2129 /* read the whole sdp file */
2130 /* XXX: better loading */
2131 content = av_malloc(SDP_MAX_SIZE);
899681cd 2132 size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
93ced3e8
FB
2133 if (size <= 0) {
2134 av_free(content);
2135 return AVERROR_INVALIDDATA;
2136 }
2137 content[size] ='\0';
2138
2139 sdp_parse(s, content);
2140 av_free(content);
2141
2142 /* open each RTP stream */
c8965800 2143 for (i = 0; i < rt->nb_rtsp_streams; i++) {
8b1ab7bf 2144 rtsp_st = rt->rtsp_streams[i];
115329f1 2145
57b5555c
MS
2146 ff_url_join(url, sizeof(url), "rtp", NULL,
2147 inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
2148 "?localport=%d&ttl=%d", rtsp_st->sdp_port,
2149 rtsp_st->sdp_ttl);
dbf30963 2150 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
93ced3e8
FB
2151 err = AVERROR_INVALIDDATA;
2152 goto fail;
2153 }
ee0cb67f 2154 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
8b1ab7bf 2155 goto fail;
93ced3e8
FB
2156 }
2157 return 0;
c8965800 2158fail:
3307e6ea 2159 ff_rtsp_close_streams(s);
57b5555c 2160 ff_network_close();
93ced3e8
FB
2161 return err;
2162}
2163
93ced3e8
FB
2164static int sdp_read_close(AVFormatContext *s)
2165{
3307e6ea 2166 ff_rtsp_close_streams(s);
57b5555c 2167 ff_network_close();
93ced3e8
FB
2168 return 0;
2169}
2170
ff70e601 2171AVInputFormat sdp_demuxer = {
93ced3e8 2172 "sdp",
bde15e74 2173 NULL_IF_CONFIG_SMALL("SDP"),
93ced3e8
FB
2174 sizeof(RTSPState),
2175 sdp_probe,
2176 sdp_read_header,
d7250724 2177 rtsp_fetch_packet,
93ced3e8
FB
2178 sdp_read_close,
2179};