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