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