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