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