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