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