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