3 * Copyright (c) 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/base64.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/parseutils.h"
27 #include "libavutil/random_seed.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/time.h"
32 #include "avio_internal.h"
39 #include "os_support.h"
46 #include "rtpdec_formats.h"
47 #include "rtpenc_chain.h"
52 /* Timeout values for socket poll, in ms,
53 * and read_packet(), in seconds */
54 #define POLL_TIMEOUT_MS 100
55 #define READ_PACKET_TIMEOUT_S 10
56 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / POLL_TIMEOUT_MS
57 #define SDP_MAX_SIZE 16384
58 #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
59 #define DEFAULT_REORDERING_DELAY 100000
61 #define OFFSET(x) offsetof(RTSPState, x)
62 #define DEC AV_OPT_FLAG_DECODING_PARAM
63 #define ENC AV_OPT_FLAG_ENCODING_PARAM
65 #define RTSP_FLAG_OPTS(name, longname) \
66 { name, longname, OFFSET(rtsp_flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtsp_flags" }, \
67 { "filter_src", "Only receive packets from the negotiated peer IP", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_FILTER_SRC}, 0, 0, DEC, "rtsp_flags" }
69 #define RTSP_MEDIATYPE_OPTS(name, longname) \
70 { name, longname, OFFSET(media_type_mask), AV_OPT_TYPE_FLAGS, { .i64 = (1 << (AVMEDIA_TYPE_DATA+1)) - 1 }, INT_MIN, INT_MAX, DEC, "allowed_media_types" }, \
71 { "video", "Video", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_VIDEO}, 0, 0, DEC, "allowed_media_types" }, \
72 { "audio", "Audio", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_AUDIO}, 0, 0, DEC, "allowed_media_types" }, \
73 { "data", "Data", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_DATA}, 0, 0, DEC, "allowed_media_types" }
75 #define RTSP_REORDERING_OPTS() \
76 { "reorder_queue_size", "Number of packets to buffer for handling of reordered packets", OFFSET(reordering_queue_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, DEC }
78 const AVOption ff_rtsp_options[] = {
79 { "initial_pause", "Don't start playing the stream immediately", OFFSET(initial_pause), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
80 FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags),
81 { "rtsp_transport", "RTSP transport protocols", OFFSET(lower_transport_mask), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, DEC|ENC, "rtsp_transport" }, \
82 { "udp", "UDP", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_UDP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
83 { "tcp", "TCP", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_TCP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
84 { "udp_multicast", "UDP multicast", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_UDP_MULTICAST}, 0, 0, DEC, "rtsp_transport" },
85 { "http", "HTTP tunneling", 0, AV_OPT_TYPE_CONST, {.i64 = (1 << RTSP_LOWER_TRANSPORT_HTTP)}, 0, 0, DEC, "rtsp_transport" },
86 RTSP_FLAG_OPTS("rtsp_flags", "RTSP flags"),
87 { "listen", "Wait for incoming connections", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_LISTEN}, 0, 0, DEC, "rtsp_flags" },
88 RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
89 { "min_port", "Minimum local UDP port", OFFSET(rtp_port_min), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MIN}, 0, 65535, DEC|ENC },
90 { "max_port", "Maximum local UDP port", OFFSET(rtp_port_max), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MAX}, 0, 65535, DEC|ENC },
91 { "timeout", "Maximum timeout (in seconds) to wait for incoming connections. -1 is infinite. Implies flag listen", OFFSET(initial_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, DEC },
92 RTSP_REORDERING_OPTS(),
96 static const AVOption sdp_options[] = {
97 RTSP_FLAG_OPTS("sdp_flags", "SDP flags"),
98 { "custom_io", "Use custom IO", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_CUSTOM_IO}, 0, 0, DEC, "rtsp_flags" },
99 { "rtcp_to_source", "Send RTCP packets to the source address of received packets", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_RTCP_TO_SOURCE}, 0, 0, DEC, "rtsp_flags" },
100 RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
101 RTSP_REORDERING_OPTS(),
105 static const AVOption rtp_options[] = {
106 RTSP_FLAG_OPTS("rtp_flags", "RTP flags"),
107 RTSP_REORDERING_OPTS(),
111 static void get_word_until_chars(char *buf, int buf_size,
112 const char *sep, const char **pp)
118 p += strspn(p, SPACE_CHARS);
120 while (!strchr(sep, *p) && *p != '\0') {
121 if ((q - buf) < buf_size - 1)
130 static void get_word_sep(char *buf, int buf_size, const char *sep,
133 if (**pp == '/') (*pp)++;
134 get_word_until_chars(buf, buf_size, sep, pp);
137 static void get_word(char *buf, int buf_size, const char **pp)
139 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
142 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
144 * Used for seeking in the rtp stream.
146 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
150 p += strspn(p, SPACE_CHARS);
151 if (!av_stristart(p, "npt=", &p))
154 *start = AV_NOPTS_VALUE;
155 *end = AV_NOPTS_VALUE;
157 get_word_sep(buf, sizeof(buf), "-", &p);
158 av_parse_time(start, buf, 1);
161 get_word_sep(buf, sizeof(buf), "-", &p);
162 av_parse_time(end, buf, 1);
166 static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
168 struct addrinfo hints = { 0 }, *ai = NULL;
169 hints.ai_flags = AI_NUMERICHOST;
170 if (getaddrinfo(buf, NULL, &hints, &ai))
172 memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
178 static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
179 RTSPStream *rtsp_st, AVCodecContext *codec)
184 codec->codec_id = handler->codec_id;
185 rtsp_st->dynamic_handler = handler;
186 if (handler->alloc) {
187 rtsp_st->dynamic_protocol_context = handler->alloc();
188 if (!rtsp_st->dynamic_protocol_context)
189 rtsp_st->dynamic_handler = NULL;
193 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
194 static int sdp_parse_rtpmap(AVFormatContext *s,
195 AVStream *st, RTSPStream *rtsp_st,
196 int payload_type, const char *p)
198 AVCodecContext *codec = st->codec;
204 /* See if we can handle this kind of payload.
205 * The space should normally not be there but some Real streams or
206 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
207 * have a trailing space. */
208 get_word_sep(buf, sizeof(buf), "/ ", &p);
209 if (payload_type < RTP_PT_PRIVATE) {
210 /* We are in a standard case
211 * (from http://www.iana.org/assignments/rtp-parameters). */
212 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
215 if (codec->codec_id == AV_CODEC_ID_NONE) {
216 RTPDynamicProtocolHandler *handler =
217 ff_rtp_handler_find_by_name(buf, codec->codec_type);
218 init_rtp_handler(handler, rtsp_st, codec);
219 /* If no dynamic handler was found, check with the list of standard
220 * allocated types, if such a stream for some reason happens to
221 * use a private payload type. This isn't handled in rtpdec.c, since
222 * the format name from the rtpmap line never is passed into rtpdec. */
223 if (!rtsp_st->dynamic_handler)
224 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
227 c = avcodec_find_decoder(codec->codec_id);
233 get_word_sep(buf, sizeof(buf), "/", &p);
235 switch (codec->codec_type) {
236 case AVMEDIA_TYPE_AUDIO:
237 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
238 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
239 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
241 codec->sample_rate = i;
242 avpriv_set_pts_info(st, 32, 1, codec->sample_rate);
243 get_word_sep(buf, sizeof(buf), "/", &p);
248 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
250 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
253 case AVMEDIA_TYPE_VIDEO:
254 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
256 avpriv_set_pts_info(st, 32, 1, i);
261 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->init)
262 rtsp_st->dynamic_handler->init(s, st->index,
263 rtsp_st->dynamic_protocol_context);
267 /* parse the attribute line from the fmtp a line of an sdp response. This
268 * is broken out as a function because it is used in rtp_h264.c, which is
270 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
271 char *value, int value_size)
273 *p += strspn(*p, SPACE_CHARS);
275 get_word_sep(attr, attr_size, "=", p);
278 get_word_sep(value, value_size, ";", p);
286 typedef struct SDPParseState {
288 struct sockaddr_storage default_ip;
290 int skip_media; ///< set if an unknown m= line occurs
291 int nb_default_include_source_addrs; /**< Number of source-specific multicast include source IP address (from SDP content) */
292 struct RTSPSource **default_include_source_addrs; /**< Source-specific multicast include source IP address (from SDP content) */
293 int nb_default_exclude_source_addrs; /**< Number of source-specific multicast exclude source IP address (from SDP content) */
294 struct RTSPSource **default_exclude_source_addrs; /**< Source-specific multicast exclude source IP address (from SDP content) */
297 char delayed_fmtp[2048];
300 static void copy_default_source_addrs(struct RTSPSource **addrs, int count,
301 struct RTSPSource ***dest, int *dest_count)
303 RTSPSource *rtsp_src, *rtsp_src2;
305 for (i = 0; i < count; i++) {
307 rtsp_src2 = av_malloc(sizeof(*rtsp_src2));
310 memcpy(rtsp_src2, rtsp_src, sizeof(*rtsp_src));
311 dynarray_add(dest, dest_count, rtsp_src2);
315 static void parse_fmtp(AVFormatContext *s, RTSPState *rt,
316 int payload_type, const char *line)
320 for (i = 0; i < rt->nb_rtsp_streams; i++) {
321 RTSPStream *rtsp_st = rt->rtsp_streams[i];
322 if (rtsp_st->sdp_payload_type == payload_type &&
323 rtsp_st->dynamic_handler &&
324 rtsp_st->dynamic_handler->parse_sdp_a_line) {
325 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
326 rtsp_st->dynamic_protocol_context, line);
331 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
332 int letter, const char *buf)
334 RTSPState *rt = s->priv_data;
335 char buf1[64], st_type[64];
337 enum AVMediaType codec_type;
341 RTSPSource *rtsp_src;
342 struct sockaddr_storage sdp_ip;
345 av_dlog(s, "sdp: %c='%s'\n", letter, buf);
348 if (s1->skip_media && letter != 'm')
352 get_word(buf1, sizeof(buf1), &p);
353 if (strcmp(buf1, "IN") != 0)
355 get_word(buf1, sizeof(buf1), &p);
356 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
358 get_word_sep(buf1, sizeof(buf1), "/", &p);
359 if (get_sockaddr(buf1, &sdp_ip))
364 get_word_sep(buf1, sizeof(buf1), "/", &p);
367 if (s->nb_streams == 0) {
368 s1->default_ip = sdp_ip;
369 s1->default_ttl = ttl;
371 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
372 rtsp_st->sdp_ip = sdp_ip;
373 rtsp_st->sdp_ttl = ttl;
377 av_dict_set(&s->metadata, "title", p, 0);
380 if (s->nb_streams == 0) {
381 av_dict_set(&s->metadata, "comment", p, 0);
390 codec_type = AVMEDIA_TYPE_UNKNOWN;
391 get_word(st_type, sizeof(st_type), &p);
392 if (!strcmp(st_type, "audio")) {
393 codec_type = AVMEDIA_TYPE_AUDIO;
394 } else if (!strcmp(st_type, "video")) {
395 codec_type = AVMEDIA_TYPE_VIDEO;
396 } else if (!strcmp(st_type, "application")) {
397 codec_type = AVMEDIA_TYPE_DATA;
399 if (codec_type == AVMEDIA_TYPE_UNKNOWN || !(rt->media_type_mask & (1 << codec_type))) {
403 rtsp_st = av_mallocz(sizeof(RTSPStream));
406 rtsp_st->stream_index = -1;
407 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
409 rtsp_st->sdp_ip = s1->default_ip;
410 rtsp_st->sdp_ttl = s1->default_ttl;
412 copy_default_source_addrs(s1->default_include_source_addrs,
413 s1->nb_default_include_source_addrs,
414 &rtsp_st->include_source_addrs,
415 &rtsp_st->nb_include_source_addrs);
416 copy_default_source_addrs(s1->default_exclude_source_addrs,
417 s1->nb_default_exclude_source_addrs,
418 &rtsp_st->exclude_source_addrs,
419 &rtsp_st->nb_exclude_source_addrs);
421 get_word(buf1, sizeof(buf1), &p); /* port */
422 rtsp_st->sdp_port = atoi(buf1);
424 get_word(buf1, sizeof(buf1), &p); /* protocol */
425 if (!strcmp(buf1, "udp"))
426 rt->transport = RTSP_TRANSPORT_RAW;
427 else if (strstr(buf1, "/AVPF") || strstr(buf1, "/SAVPF"))
428 rtsp_st->feedback = 1;
430 /* XXX: handle list of formats */
431 get_word(buf1, sizeof(buf1), &p); /* format list */
432 rtsp_st->sdp_payload_type = atoi(buf1);
434 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
435 /* no corresponding stream */
436 if (rt->transport == RTSP_TRANSPORT_RAW) {
437 if (!rt->ts && CONFIG_RTPDEC)
438 rt->ts = ff_mpegts_parse_open(s);
440 RTPDynamicProtocolHandler *handler;
441 handler = ff_rtp_handler_find_by_id(
442 rtsp_st->sdp_payload_type, AVMEDIA_TYPE_DATA);
443 init_rtp_handler(handler, rtsp_st, NULL);
444 if (handler && handler->init)
445 handler->init(s, -1, rtsp_st->dynamic_protocol_context);
447 } else if (rt->server_type == RTSP_SERVER_WMS &&
448 codec_type == AVMEDIA_TYPE_DATA) {
449 /* RTX stream, a stream that carries all the other actual
450 * audio/video streams. Don't expose this to the callers. */
452 st = avformat_new_stream(s, NULL);
455 st->id = rt->nb_rtsp_streams - 1;
456 rtsp_st->stream_index = st->index;
457 st->codec->codec_type = codec_type;
458 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
459 RTPDynamicProtocolHandler *handler;
460 /* if standard payload type, we can find the codec right now */
461 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
462 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
463 st->codec->sample_rate > 0)
464 avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);
465 /* Even static payload types may need a custom depacketizer */
466 handler = ff_rtp_handler_find_by_id(
467 rtsp_st->sdp_payload_type, st->codec->codec_type);
468 init_rtp_handler(handler, rtsp_st, st->codec);
469 if (handler && handler->init)
470 handler->init(s, st->index,
471 rtsp_st->dynamic_protocol_context);
474 /* put a default control url */
475 av_strlcpy(rtsp_st->control_url, rt->control_uri,
476 sizeof(rtsp_st->control_url));
479 if (av_strstart(p, "control:", &p)) {
480 if (s->nb_streams == 0) {
481 if (!strncmp(p, "rtsp://", 7))
482 av_strlcpy(rt->control_uri, p,
483 sizeof(rt->control_uri));
486 /* get the control url */
487 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
489 /* XXX: may need to add full url resolution */
490 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
492 if (proto[0] == '\0') {
493 /* relative control URL */
494 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
495 av_strlcat(rtsp_st->control_url, "/",
496 sizeof(rtsp_st->control_url));
497 av_strlcat(rtsp_st->control_url, p,
498 sizeof(rtsp_st->control_url));
500 av_strlcpy(rtsp_st->control_url, p,
501 sizeof(rtsp_st->control_url));
503 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
504 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
505 get_word(buf1, sizeof(buf1), &p);
506 payload_type = atoi(buf1);
507 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
508 if (rtsp_st->stream_index >= 0) {
509 st = s->streams[rtsp_st->stream_index];
510 sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
514 parse_fmtp(s, rt, payload_type, s1->delayed_fmtp);
516 } else if (av_strstart(p, "fmtp:", &p) ||
517 av_strstart(p, "framesize:", &p)) {
518 // let dynamic protocol handlers have a stab at the line.
519 get_word(buf1, sizeof(buf1), &p);
520 payload_type = atoi(buf1);
521 if (s1->seen_rtpmap) {
522 parse_fmtp(s, rt, payload_type, buf);
525 av_strlcpy(s1->delayed_fmtp, buf, sizeof(s1->delayed_fmtp));
527 } else if (av_strstart(p, "range:", &p)) {
530 // this is so that seeking on a streamed file can work.
531 rtsp_parse_range_npt(p, &start, &end);
532 s->start_time = start;
533 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
534 s->duration = (end == AV_NOPTS_VALUE) ?
535 AV_NOPTS_VALUE : end - start;
536 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
538 rt->transport = RTSP_TRANSPORT_RDT;
539 } else if (av_strstart(p, "SampleRate:integer;", &p) &&
541 st = s->streams[s->nb_streams - 1];
542 st->codec->sample_rate = atoi(p);
543 } else if (av_strstart(p, "crypto:", &p) && s->nb_streams > 0) {
545 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
546 get_word(buf1, sizeof(buf1), &p); // ignore tag
547 get_word(rtsp_st->crypto_suite, sizeof(rtsp_st->crypto_suite), &p);
548 p += strspn(p, SPACE_CHARS);
549 if (av_strstart(p, "inline:", &p))
550 get_word(rtsp_st->crypto_params, sizeof(rtsp_st->crypto_params), &p);
551 } else if (av_strstart(p, "source-filter:", &p)) {
553 get_word(buf1, sizeof(buf1), &p);
554 if (strcmp(buf1, "incl") && strcmp(buf1, "excl"))
556 exclude = !strcmp(buf1, "excl");
558 get_word(buf1, sizeof(buf1), &p);
559 if (strcmp(buf1, "IN") != 0)
561 get_word(buf1, sizeof(buf1), &p);
562 if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6") && strcmp(buf1, "*"))
564 // not checking that the destination address actually matches or is wildcard
565 get_word(buf1, sizeof(buf1), &p);
568 rtsp_src = av_mallocz(sizeof(*rtsp_src));
571 get_word(rtsp_src->addr, sizeof(rtsp_src->addr), &p);
573 if (s->nb_streams == 0) {
574 dynarray_add(&s1->default_exclude_source_addrs, &s1->nb_default_exclude_source_addrs, rtsp_src);
576 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
577 dynarray_add(&rtsp_st->exclude_source_addrs, &rtsp_st->nb_exclude_source_addrs, rtsp_src);
580 if (s->nb_streams == 0) {
581 dynarray_add(&s1->default_include_source_addrs, &s1->nb_default_include_source_addrs, rtsp_src);
583 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
584 dynarray_add(&rtsp_st->include_source_addrs, &rtsp_st->nb_include_source_addrs, rtsp_src);
589 if (rt->server_type == RTSP_SERVER_WMS)
590 ff_wms_parse_sdp_a_line(s, p);
591 if (s->nb_streams > 0) {
592 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
594 if (rt->server_type == RTSP_SERVER_REAL)
595 ff_real_parse_sdp_a_line(s, rtsp_st->stream_index, p);
597 if (rtsp_st->dynamic_handler &&
598 rtsp_st->dynamic_handler->parse_sdp_a_line)
599 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
600 rtsp_st->stream_index,
601 rtsp_st->dynamic_protocol_context, buf);
608 int ff_sdp_parse(AVFormatContext *s, const char *content)
610 RTSPState *rt = s->priv_data;
613 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
614 * contain long SDP lines containing complete ASF Headers (several
615 * kB) or arrays of MDPR (RM stream descriptor) headers plus
616 * "rulebooks" describing their properties. Therefore, the SDP line
619 * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
620 * in rtpdec_xiph.c. */
622 SDPParseState sdp_parse_state = { { 0 } }, *s1 = &sdp_parse_state;
626 p += strspn(p, SPACE_CHARS);
634 /* get the content */
636 while (*p != '\n' && *p != '\r' && *p != '\0') {
637 if ((q - buf) < sizeof(buf) - 1)
642 sdp_parse_line(s, s1, letter, buf);
644 while (*p != '\n' && *p != '\0')
650 for (i = 0; i < s1->nb_default_include_source_addrs; i++)
651 av_free(s1->default_include_source_addrs[i]);
652 av_freep(&s1->default_include_source_addrs);
653 for (i = 0; i < s1->nb_default_exclude_source_addrs; i++)
654 av_free(s1->default_exclude_source_addrs[i]);
655 av_freep(&s1->default_exclude_source_addrs);
657 rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
658 if (!rt->p) return AVERROR(ENOMEM);
661 #endif /* CONFIG_RTPDEC */
663 void ff_rtsp_undo_setup(AVFormatContext *s, int send_packets)
665 RTSPState *rt = s->priv_data;
668 for (i = 0; i < rt->nb_rtsp_streams; i++) {
669 RTSPStream *rtsp_st = rt->rtsp_streams[i];
672 if (rtsp_st->transport_priv) {
674 AVFormatContext *rtpctx = rtsp_st->transport_priv;
675 av_write_trailer(rtpctx);
676 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
678 if (CONFIG_RTSP_MUXER && rtpctx->pb && send_packets)
679 ff_rtsp_tcp_write_packet(s, rtsp_st);
680 avio_close_dyn_buf(rtpctx->pb, &ptr);
683 avio_close(rtpctx->pb);
685 avformat_free_context(rtpctx);
686 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
687 ff_rdt_parse_close(rtsp_st->transport_priv);
688 else if (rt->transport == RTSP_TRANSPORT_RTP && CONFIG_RTPDEC)
689 ff_rtp_parse_close(rtsp_st->transport_priv);
691 rtsp_st->transport_priv = NULL;
692 if (rtsp_st->rtp_handle)
693 ffurl_close(rtsp_st->rtp_handle);
694 rtsp_st->rtp_handle = NULL;
698 /* close and free RTSP streams */
699 void ff_rtsp_close_streams(AVFormatContext *s)
701 RTSPState *rt = s->priv_data;
705 ff_rtsp_undo_setup(s, 0);
706 for (i = 0; i < rt->nb_rtsp_streams; i++) {
707 rtsp_st = rt->rtsp_streams[i];
709 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
710 rtsp_st->dynamic_handler->free(
711 rtsp_st->dynamic_protocol_context);
712 for (j = 0; j < rtsp_st->nb_include_source_addrs; j++)
713 av_free(rtsp_st->include_source_addrs[j]);
714 av_freep(&rtsp_st->include_source_addrs);
715 for (j = 0; j < rtsp_st->nb_exclude_source_addrs; j++)
716 av_free(rtsp_st->exclude_source_addrs[j]);
717 av_freep(&rtsp_st->exclude_source_addrs);
722 av_free(rt->rtsp_streams);
724 avformat_close_input(&rt->asf_ctx);
726 if (rt->ts && CONFIG_RTPDEC)
727 ff_mpegts_parse_close(rt->ts);
729 av_free(rt->recvbuf);
732 int ff_rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
734 RTSPState *rt = s->priv_data;
736 int reordering_queue_size = rt->reordering_queue_size;
737 if (reordering_queue_size < 0) {
738 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
739 reordering_queue_size = 0;
741 reordering_queue_size = RTP_REORDER_QUEUE_DEFAULT_SIZE;
744 /* open the RTP context */
745 if (rtsp_st->stream_index >= 0)
746 st = s->streams[rtsp_st->stream_index];
748 s->ctx_flags |= AVFMTCTX_NOHEADER;
750 if (s->oformat && CONFIG_RTSP_MUXER) {
751 int ret = ff_rtp_chain_mux_open((AVFormatContext **)&rtsp_st->transport_priv,
752 s, st, rtsp_st->rtp_handle,
753 RTSP_TCP_MAX_PACKET_SIZE,
754 rtsp_st->stream_index);
755 /* Ownership of rtp_handle is passed to the rtp mux context */
756 rtsp_st->rtp_handle = NULL;
759 st->time_base = ((AVFormatContext*)rtsp_st->transport_priv)->streams[0]->time_base;
760 } else if (rt->transport == RTSP_TRANSPORT_RAW) {
761 return 0; // Don't need to open any parser here
762 } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
763 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
764 rtsp_st->dynamic_protocol_context,
765 rtsp_st->dynamic_handler);
766 else if (CONFIG_RTPDEC)
767 rtsp_st->transport_priv = ff_rtp_parse_open(s, st,
768 rtsp_st->sdp_payload_type,
769 reordering_queue_size);
771 if (!rtsp_st->transport_priv) {
772 return AVERROR(ENOMEM);
773 } else if (rt->transport == RTSP_TRANSPORT_RTP && CONFIG_RTPDEC) {
774 if (rtsp_st->dynamic_handler) {
775 ff_rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
776 rtsp_st->dynamic_protocol_context,
777 rtsp_st->dynamic_handler);
779 if (rtsp_st->crypto_suite[0])
780 ff_rtp_parse_set_crypto(rtsp_st->transport_priv,
781 rtsp_st->crypto_suite,
782 rtsp_st->crypto_params);
788 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
789 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
796 q += strspn(q, SPACE_CHARS);
797 v = strtol(q, &p, 10);
801 v = strtol(p, &p, 10);
810 /* XXX: only one transport specification is parsed */
811 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
813 char transport_protocol[16];
815 char lower_transport[16];
817 RTSPTransportField *th;
820 reply->nb_transports = 0;
823 p += strspn(p, SPACE_CHARS);
827 th = &reply->transports[reply->nb_transports];
829 get_word_sep(transport_protocol, sizeof(transport_protocol),
831 if (!av_strcasecmp (transport_protocol, "rtp")) {
832 get_word_sep(profile, sizeof(profile), "/;,", &p);
833 lower_transport[0] = '\0';
834 /* rtp/avp/<protocol> */
836 get_word_sep(lower_transport, sizeof(lower_transport),
839 th->transport = RTSP_TRANSPORT_RTP;
840 } else if (!av_strcasecmp (transport_protocol, "x-pn-tng") ||
841 !av_strcasecmp (transport_protocol, "x-real-rdt")) {
842 /* x-pn-tng/<protocol> */
843 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
845 th->transport = RTSP_TRANSPORT_RDT;
846 } else if (!av_strcasecmp(transport_protocol, "raw")) {
847 get_word_sep(profile, sizeof(profile), "/;,", &p);
848 lower_transport[0] = '\0';
849 /* raw/raw/<protocol> */
851 get_word_sep(lower_transport, sizeof(lower_transport),
854 th->transport = RTSP_TRANSPORT_RAW;
856 if (!av_strcasecmp(lower_transport, "TCP"))
857 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
859 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
863 /* get each parameter */
864 while (*p != '\0' && *p != ',') {
865 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
866 if (!strcmp(parameter, "port")) {
869 rtsp_parse_range(&th->port_min, &th->port_max, &p);
871 } else if (!strcmp(parameter, "client_port")) {
874 rtsp_parse_range(&th->client_port_min,
875 &th->client_port_max, &p);
877 } else if (!strcmp(parameter, "server_port")) {
880 rtsp_parse_range(&th->server_port_min,
881 &th->server_port_max, &p);
883 } else if (!strcmp(parameter, "interleaved")) {
886 rtsp_parse_range(&th->interleaved_min,
887 &th->interleaved_max, &p);
889 } else if (!strcmp(parameter, "multicast")) {
890 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
891 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
892 } else if (!strcmp(parameter, "ttl")) {
896 th->ttl = strtol(p, &end, 10);
899 } else if (!strcmp(parameter, "destination")) {
902 get_word_sep(buf, sizeof(buf), ";,", &p);
903 get_sockaddr(buf, &th->destination);
905 } else if (!strcmp(parameter, "source")) {
908 get_word_sep(buf, sizeof(buf), ";,", &p);
909 av_strlcpy(th->source, buf, sizeof(th->source));
911 } else if (!strcmp(parameter, "mode")) {
914 get_word_sep(buf, sizeof(buf), ";, ", &p);
915 if (!strcmp(buf, "record") ||
916 !strcmp(buf, "receive"))
921 while (*p != ';' && *p != '\0' && *p != ',')
929 reply->nb_transports++;
933 static void handle_rtp_info(RTSPState *rt, const char *url,
934 uint32_t seq, uint32_t rtptime)
937 if (!rtptime || !url[0])
939 if (rt->transport != RTSP_TRANSPORT_RTP)
941 for (i = 0; i < rt->nb_rtsp_streams; i++) {
942 RTSPStream *rtsp_st = rt->rtsp_streams[i];
943 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
946 if (!strcmp(rtsp_st->control_url, url)) {
947 rtpctx->base_timestamp = rtptime;
953 static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
956 char key[20], value[1024], url[1024] = "";
957 uint32_t seq = 0, rtptime = 0;
960 p += strspn(p, SPACE_CHARS);
963 get_word_sep(key, sizeof(key), "=", &p);
967 get_word_sep(value, sizeof(value), ";, ", &p);
969 if (!strcmp(key, "url"))
970 av_strlcpy(url, value, sizeof(url));
971 else if (!strcmp(key, "seq"))
972 seq = strtoul(value, NULL, 10);
973 else if (!strcmp(key, "rtptime"))
974 rtptime = strtoul(value, NULL, 10);
976 handle_rtp_info(rt, url, seq, rtptime);
985 handle_rtp_info(rt, url, seq, rtptime);
988 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
989 RTSPState *rt, const char *method)
993 /* NOTE: we do case independent match for broken servers */
995 if (av_stristart(p, "Session:", &p)) {
997 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
998 if (av_stristart(p, ";timeout=", &p) &&
999 (t = strtol(p, NULL, 10)) > 0) {
1002 } else if (av_stristart(p, "Content-Length:", &p)) {
1003 reply->content_length = strtol(p, NULL, 10);
1004 } else if (av_stristart(p, "Transport:", &p)) {
1005 rtsp_parse_transport(reply, p);
1006 } else if (av_stristart(p, "CSeq:", &p)) {
1007 reply->seq = strtol(p, NULL, 10);
1008 } else if (av_stristart(p, "Range:", &p)) {
1009 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
1010 } else if (av_stristart(p, "RealChallenge1:", &p)) {
1011 p += strspn(p, SPACE_CHARS);
1012 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
1013 } else if (av_stristart(p, "Server:", &p)) {
1014 p += strspn(p, SPACE_CHARS);
1015 av_strlcpy(reply->server, p, sizeof(reply->server));
1016 } else if (av_stristart(p, "Notice:", &p) ||
1017 av_stristart(p, "X-Notice:", &p)) {
1018 reply->notice = strtol(p, NULL, 10);
1019 } else if (av_stristart(p, "Location:", &p)) {
1020 p += strspn(p, SPACE_CHARS);
1021 av_strlcpy(reply->location, p , sizeof(reply->location));
1022 } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
1023 p += strspn(p, SPACE_CHARS);
1024 ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
1025 } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
1026 p += strspn(p, SPACE_CHARS);
1027 ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
1028 } else if (av_stristart(p, "Content-Base:", &p) && rt) {
1029 p += strspn(p, SPACE_CHARS);
1030 if (method && !strcmp(method, "DESCRIBE"))
1031 av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
1032 } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
1033 p += strspn(p, SPACE_CHARS);
1034 if (method && !strcmp(method, "PLAY"))
1035 rtsp_parse_rtp_info(rt, p);
1036 } else if (av_stristart(p, "Public:", &p) && rt) {
1037 if (strstr(p, "GET_PARAMETER") &&
1038 method && !strcmp(method, "OPTIONS"))
1039 rt->get_parameter_supported = 1;
1040 } else if (av_stristart(p, "x-Accept-Dynamic-Rate:", &p) && rt) {
1041 p += strspn(p, SPACE_CHARS);
1042 rt->accept_dynamic_rate = atoi(p);
1043 } else if (av_stristart(p, "Content-Type:", &p)) {
1044 p += strspn(p, SPACE_CHARS);
1045 av_strlcpy(reply->content_type, p, sizeof(reply->content_type));
1049 /* skip a RTP/TCP interleaved packet */
1050 void ff_rtsp_skip_packet(AVFormatContext *s)
1052 RTSPState *rt = s->priv_data;
1056 ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
1059 len = AV_RB16(buf + 1);
1061 av_dlog(s, "skipping RTP packet len=%d\n", len);
1066 if (len1 > sizeof(buf))
1068 ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
1075 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
1076 unsigned char **content_ptr,
1077 int return_on_interleaved_data, const char *method)
1079 RTSPState *rt = s->priv_data;
1080 char buf[4096], buf1[1024], *q;
1083 int ret, content_length, line_count = 0, request = 0;
1084 unsigned char *content = NULL;
1090 memset(reply, 0, sizeof(*reply));
1092 /* parse reply (XXX: use buffers) */
1093 rt->last_reply[0] = '\0';
1097 ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
1098 av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
1104 /* XXX: only parse it if first char on line ? */
1105 if (return_on_interleaved_data) {
1108 ff_rtsp_skip_packet(s);
1109 } else if (ch != '\r') {
1110 if ((q - buf) < sizeof(buf) - 1)
1116 av_dlog(s, "line='%s'\n", buf);
1118 /* test if last line */
1122 if (line_count == 0) {
1123 /* get reply code */
1124 get_word(buf1, sizeof(buf1), &p);
1125 if (!strncmp(buf1, "RTSP/", 5)) {
1126 get_word(buf1, sizeof(buf1), &p);
1127 reply->status_code = atoi(buf1);
1128 av_strlcpy(reply->reason, p, sizeof(reply->reason));
1130 av_strlcpy(reply->reason, buf1, sizeof(reply->reason)); // method
1131 get_word(buf1, sizeof(buf1), &p); // object
1135 ff_rtsp_parse_line(reply, p, rt, method);
1136 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
1137 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
1142 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0' && !request)
1143 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
1145 content_length = reply->content_length;
1146 if (content_length > 0) {
1147 /* leave some room for a trailing '\0' (useful for simple parsing) */
1148 content = av_malloc(content_length + 1);
1150 return AVERROR(ENOMEM);
1151 ffurl_read_complete(rt->rtsp_hd, content, content_length);
1152 content[content_length] = '\0';
1155 *content_ptr = content;
1161 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
1162 const char* ptr = buf;
1164 if (!strcmp(reply->reason, "OPTIONS")) {
1165 snprintf(buf, sizeof(buf), "RTSP/1.0 200 OK\r\n");
1167 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", reply->seq);
1168 if (reply->session_id[0])
1169 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n",
1172 snprintf(buf, sizeof(buf), "RTSP/1.0 501 Not Implemented\r\n");
1174 av_strlcat(buf, "\r\n", sizeof(buf));
1176 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1177 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1180 ffurl_write(rt->rtsp_hd_out, ptr, strlen(ptr));
1182 rt->last_cmd_time = av_gettime();
1183 /* Even if the request from the server had data, it is not the data
1184 * that the caller wants or expects. The memory could also be leaked
1185 * if the actual following reply has content data. */
1187 av_freep(content_ptr);
1188 /* If method is set, this is called from ff_rtsp_send_cmd,
1189 * where a reply to exactly this request is awaited. For
1190 * callers from within packet receiving, we just want to
1191 * return to the caller and go back to receiving packets. */
1197 if (rt->seq != reply->seq) {
1198 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
1199 rt->seq, reply->seq);
1203 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
1204 reply->notice == 2104 /* Start-of-Stream Reached */ ||
1205 reply->notice == 2306 /* Continuous Feed Terminated */) {
1206 rt->state = RTSP_STATE_IDLE;
1207 } else if (reply->notice >= 4400 && reply->notice < 5500) {
1208 return AVERROR(EIO); /* data or server error */
1209 } else if (reply->notice == 2401 /* Ticket Expired */ ||
1210 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
1211 return AVERROR(EPERM);
1217 * Send a command to the RTSP server without waiting for the reply.
1219 * @param s RTSP (de)muxer context
1220 * @param method the method for the request
1221 * @param url the target url for the request
1222 * @param headers extra header lines to include in the request
1223 * @param send_content if non-null, the data to send as request body content
1224 * @param send_content_length the length of the send_content data, or 0 if
1225 * send_content is null
1227 * @return zero if success, nonzero otherwise
1229 static int rtsp_send_cmd_with_content_async(AVFormatContext *s,
1230 const char *method, const char *url,
1231 const char *headers,
1232 const unsigned char *send_content,
1233 int send_content_length)
1235 RTSPState *rt = s->priv_data;
1236 char buf[4096], *out_buf;
1237 char base64buf[AV_BASE64_SIZE(sizeof(buf))];
1239 /* Add in RTSP headers */
1242 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
1244 av_strlcat(buf, headers, sizeof(buf));
1245 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
1246 av_strlcatf(buf, sizeof(buf), "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
1247 if (rt->session_id[0] != '\0' && (!headers ||
1248 !strstr(headers, "\nIf-Match:"))) {
1249 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
1252 char *str = ff_http_auth_create_response(&rt->auth_state,
1253 rt->auth, url, method);
1255 av_strlcat(buf, str, sizeof(buf));
1258 if (send_content_length > 0 && send_content)
1259 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
1260 av_strlcat(buf, "\r\n", sizeof(buf));
1262 /* base64 encode rtsp if tunneling */
1263 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1264 av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1265 out_buf = base64buf;
1268 av_dlog(s, "Sending:\n%s--\n", buf);
1270 ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
1271 if (send_content_length > 0 && send_content) {
1272 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1273 av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
1274 "with content data not supported\n");
1275 return AVERROR_PATCHWELCOME;
1277 ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
1279 rt->last_cmd_time = av_gettime();
1284 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
1285 const char *url, const char *headers)
1287 return rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
1290 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
1291 const char *headers, RTSPMessageHeader *reply,
1292 unsigned char **content_ptr)
1294 return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
1295 content_ptr, NULL, 0);
1298 int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
1299 const char *method, const char *url,
1301 RTSPMessageHeader *reply,
1302 unsigned char **content_ptr,
1303 const unsigned char *send_content,
1304 int send_content_length)
1306 RTSPState *rt = s->priv_data;
1307 HTTPAuthType cur_auth_type;
1308 int ret, attempts = 0;
1311 cur_auth_type = rt->auth_state.auth_type;
1312 if ((ret = rtsp_send_cmd_with_content_async(s, method, url, header,
1314 send_content_length)))
1317 if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
1321 if (reply->status_code == 401 &&
1322 (cur_auth_type == HTTP_AUTH_NONE || rt->auth_state.stale) &&
1323 rt->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2)
1326 if (reply->status_code > 400){
1327 av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
1331 av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
1337 int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
1338 int lower_transport, const char *real_challenge)
1340 RTSPState *rt = s->priv_data;
1341 int rtx = 0, j, i, err, interleave = 0, port_off;
1342 RTSPStream *rtsp_st;
1343 RTSPMessageHeader reply1, *reply = &reply1;
1345 const char *trans_pref;
1347 if (rt->transport == RTSP_TRANSPORT_RDT)
1348 trans_pref = "x-pn-tng";
1349 else if (rt->transport == RTSP_TRANSPORT_RAW)
1350 trans_pref = "RAW/RAW";
1352 trans_pref = "RTP/AVP";
1354 /* default timeout: 1 minute */
1357 /* for each stream, make the setup request */
1358 /* XXX: we assume the same server is used for the control of each
1361 /* Choose a random starting offset within the first half of the
1362 * port range, to allow for a number of ports to try even if the offset
1363 * happens to be at the end of the random range. */
1364 port_off = av_get_random_seed() % ((rt->rtp_port_max - rt->rtp_port_min)/2);
1365 /* even random offset */
1366 port_off -= port_off & 0x01;
1368 for (j = rt->rtp_port_min + port_off, i = 0; i < rt->nb_rtsp_streams; ++i) {
1369 char transport[2048];
1372 * WMS serves all UDP data over a single connection, the RTX, which
1373 * isn't necessarily the first in the SDP but has to be the first
1374 * to be set up, else the second/third SETUP will fail with a 461.
1376 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1377 rt->server_type == RTSP_SERVER_WMS) {
1380 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1381 int len = strlen(rt->rtsp_streams[rtx]->control_url);
1383 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1387 if (rtx == rt->nb_rtsp_streams)
1388 return -1; /* no RTX found */
1389 rtsp_st = rt->rtsp_streams[rtx];
1391 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1393 rtsp_st = rt->rtsp_streams[i];
1396 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1399 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1400 port = reply->transports[0].client_port_min;
1404 /* first try in specified port range */
1405 while (j <= rt->rtp_port_max) {
1406 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1407 "?localport=%d", j);
1408 /* we will use two ports per rtp stream (rtp and rtcp) */
1410 if (!ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE,
1411 &s->interrupt_callback, NULL))
1415 av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
1420 port = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
1422 snprintf(transport, sizeof(transport) - 1,
1423 "%s/UDP;", trans_pref);
1424 if (rt->server_type != RTSP_SERVER_REAL)
1425 av_strlcat(transport, "unicast;", sizeof(transport));
1426 av_strlcatf(transport, sizeof(transport),
1427 "client_port=%d", port);
1428 if (rt->transport == RTSP_TRANSPORT_RTP &&
1429 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1430 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1434 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1435 /* For WMS streams, the application streams are only used for
1436 * UDP. When trying to set it up for TCP streams, the server
1437 * will return an error. Therefore, we skip those streams. */
1438 if (rt->server_type == RTSP_SERVER_WMS &&
1439 (rtsp_st->stream_index < 0 ||
1440 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1443 snprintf(transport, sizeof(transport) - 1,
1444 "%s/TCP;", trans_pref);
1445 if (rt->transport != RTSP_TRANSPORT_RDT)
1446 av_strlcat(transport, "unicast;", sizeof(transport));
1447 av_strlcatf(transport, sizeof(transport),
1448 "interleaved=%d-%d",
1449 interleave, interleave + 1);
1453 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1454 snprintf(transport, sizeof(transport) - 1,
1455 "%s/UDP;multicast", trans_pref);
1458 av_strlcat(transport, ";mode=record", sizeof(transport));
1459 } else if (rt->server_type == RTSP_SERVER_REAL ||
1460 rt->server_type == RTSP_SERVER_WMS)
1461 av_strlcat(transport, ";mode=play", sizeof(transport));
1462 snprintf(cmd, sizeof(cmd),
1463 "Transport: %s\r\n",
1465 if (rt->accept_dynamic_rate)
1466 av_strlcat(cmd, "x-Dynamic-Rate: 0\r\n", sizeof(cmd));
1467 if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
1468 char real_res[41], real_csum[9];
1469 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1471 av_strlcatf(cmd, sizeof(cmd),
1473 "RealChallenge2: %s, sd=%s\r\n",
1474 rt->session_id, real_res, real_csum);
1476 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1477 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1480 } else if (reply->status_code != RTSP_STATUS_OK ||
1481 reply->nb_transports != 1) {
1482 err = AVERROR_INVALIDDATA;
1486 /* XXX: same protocol for all streams is required */
1488 if (reply->transports[0].lower_transport != rt->lower_transport ||
1489 reply->transports[0].transport != rt->transport) {
1490 err = AVERROR_INVALIDDATA;
1494 rt->lower_transport = reply->transports[0].lower_transport;
1495 rt->transport = reply->transports[0].transport;
1498 /* Fail if the server responded with another lower transport mode
1499 * than what we requested. */
1500 if (reply->transports[0].lower_transport != lower_transport) {
1501 av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
1502 err = AVERROR_INVALIDDATA;
1506 switch(reply->transports[0].lower_transport) {
1507 case RTSP_LOWER_TRANSPORT_TCP:
1508 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1509 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1512 case RTSP_LOWER_TRANSPORT_UDP: {
1513 char url[1024], options[30] = "";
1514 const char *peer = host;
1516 if (rt->rtsp_flags & RTSP_FLAG_FILTER_SRC)
1517 av_strlcpy(options, "?connect=1", sizeof(options));
1518 /* Use source address if specified */
1519 if (reply->transports[0].source[0])
1520 peer = reply->transports[0].source;
1521 ff_url_join(url, sizeof(url), "rtp", NULL, peer,
1522 reply->transports[0].server_port_min, "%s", options);
1523 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1524 ff_rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1525 err = AVERROR_INVALIDDATA;
1528 /* Try to initialize the connection state in a
1529 * potential NAT router by sending dummy packets.
1530 * RTP/RTCP dummy packets are used for RDT, too.
1532 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
1534 ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
1537 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1538 char url[1024], namebuf[50], optbuf[20] = "";
1539 struct sockaddr_storage addr;
1542 if (reply->transports[0].destination.ss_family) {
1543 addr = reply->transports[0].destination;
1544 port = reply->transports[0].port_min;
1545 ttl = reply->transports[0].ttl;
1547 addr = rtsp_st->sdp_ip;
1548 port = rtsp_st->sdp_port;
1549 ttl = rtsp_st->sdp_ttl;
1552 snprintf(optbuf, sizeof(optbuf), "?ttl=%d", ttl);
1553 getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1554 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1555 ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
1556 port, "%s", optbuf);
1557 if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
1558 &s->interrupt_callback, NULL) < 0) {
1559 err = AVERROR_INVALIDDATA;
1566 if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
1570 if (rt->nb_rtsp_streams && reply->timeout > 0)
1571 rt->timeout = reply->timeout;
1573 if (rt->server_type == RTSP_SERVER_REAL)
1574 rt->need_subscription = 1;
1579 ff_rtsp_undo_setup(s, 0);
1583 void ff_rtsp_close_connections(AVFormatContext *s)
1585 RTSPState *rt = s->priv_data;
1586 if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
1587 ffurl_close(rt->rtsp_hd);
1588 rt->rtsp_hd = rt->rtsp_hd_out = NULL;
1591 int ff_rtsp_connect(AVFormatContext *s)
1593 RTSPState *rt = s->priv_data;
1594 char proto[128], host[1024], path[1024];
1595 char tcpname[1024], cmd[2048], auth[128];
1596 const char *lower_rtsp_proto = "tcp";
1597 int port, err, tcp_fd;
1598 RTSPMessageHeader reply1 = {0}, *reply = &reply1;
1599 int lower_transport_mask = 0;
1600 int default_port = RTSP_DEFAULT_PORT;
1601 char real_challenge[64] = "";
1602 struct sockaddr_storage peer;
1603 socklen_t peer_len = sizeof(peer);
1605 if (rt->rtp_port_max < rt->rtp_port_min) {
1606 av_log(s, AV_LOG_ERROR, "Invalid UDP port range, max port %d less "
1607 "than min port %d\n", rt->rtp_port_max,
1609 return AVERROR(EINVAL);
1612 if (!ff_network_init())
1613 return AVERROR(EIO);
1615 if (s->max_delay < 0) /* Not set by the caller */
1616 s->max_delay = s->iformat ? DEFAULT_REORDERING_DELAY : 0;
1618 rt->control_transport = RTSP_MODE_PLAIN;
1619 if (rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_HTTP)) {
1620 rt->lower_transport_mask = 1 << RTSP_LOWER_TRANSPORT_TCP;
1621 rt->control_transport = RTSP_MODE_TUNNEL;
1623 /* Only pass through valid flags from here */
1624 rt->lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1627 /* extract hostname and port */
1628 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
1629 host, sizeof(host), &port, path, sizeof(path), s->filename);
1631 if (!strcmp(proto, "rtsps")) {
1632 lower_rtsp_proto = "tls";
1633 default_port = RTSPS_DEFAULT_PORT;
1634 rt->lower_transport_mask = 1 << RTSP_LOWER_TRANSPORT_TCP;
1638 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1641 port = default_port;
1643 lower_transport_mask = rt->lower_transport_mask;
1645 if (!lower_transport_mask)
1646 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1649 /* Only UDP or TCP - UDP multicast isn't supported. */
1650 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1651 (1 << RTSP_LOWER_TRANSPORT_TCP);
1652 if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
1653 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1654 "only UDP and TCP are supported for output.\n");
1655 err = AVERROR(EINVAL);
1660 /* Construct the URI used in request; this is similar to s->filename,
1661 * but with authentication credentials removed and RTSP specific options
1663 ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL,
1664 host, port, "%s", path);
1666 if (rt->control_transport == RTSP_MODE_TUNNEL) {
1667 /* set up initial handshake for tunneling */
1668 char httpname[1024];
1669 char sessioncookie[17];
1672 ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
1673 snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1674 av_get_random_seed(), av_get_random_seed());
1677 if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_FLAG_READ,
1678 &s->interrupt_callback) < 0) {
1683 /* generate GET headers */
1684 snprintf(headers, sizeof(headers),
1685 "x-sessioncookie: %s\r\n"
1686 "Accept: application/x-rtsp-tunnelled\r\n"
1687 "Pragma: no-cache\r\n"
1688 "Cache-Control: no-cache\r\n",
1690 av_opt_set(rt->rtsp_hd->priv_data, "headers", headers, 0);
1692 /* complete the connection */
1693 if (ffurl_connect(rt->rtsp_hd, NULL)) {
1699 if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_FLAG_WRITE,
1700 &s->interrupt_callback) < 0 ) {
1705 /* generate POST headers */
1706 snprintf(headers, sizeof(headers),
1707 "x-sessioncookie: %s\r\n"
1708 "Content-Type: application/x-rtsp-tunnelled\r\n"
1709 "Pragma: no-cache\r\n"
1710 "Cache-Control: no-cache\r\n"
1711 "Content-Length: 32767\r\n"
1712 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1714 av_opt_set(rt->rtsp_hd_out->priv_data, "headers", headers, 0);
1715 av_opt_set(rt->rtsp_hd_out->priv_data, "chunked_post", "0", 0);
1717 /* Initialize the authentication state for the POST session. The HTTP
1718 * protocol implementation doesn't properly handle multi-pass
1719 * authentication for POST requests, since it would require one of
1721 * - implementing Expect: 100-continue, which many HTTP servers
1722 * don't support anyway, even less the RTSP servers that do HTTP
1724 * - sending the whole POST data until getting a 401 reply specifying
1725 * what authentication method to use, then resending all that data
1726 * - waiting for potential 401 replies directly after sending the
1727 * POST header (waiting for some unspecified time)
1728 * Therefore, we copy the full auth state, which works for both basic
1729 * and digest. (For digest, we would have to synchronize the nonce
1730 * count variable between the two sessions, if we'd do more requests
1731 * with the original session, though.)
1733 ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1735 /* complete the connection */
1736 if (ffurl_connect(rt->rtsp_hd_out, NULL)) {
1741 /* open the tcp connection */
1742 ff_url_join(tcpname, sizeof(tcpname), lower_rtsp_proto, NULL,
1744 if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
1745 &s->interrupt_callback, NULL) < 0) {
1749 rt->rtsp_hd_out = rt->rtsp_hd;
1753 tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
1754 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1755 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1756 NULL, 0, NI_NUMERICHOST);
1759 /* request options supported by the server; this also detects server
1761 for (rt->server_type = RTSP_SERVER_RTP;;) {
1763 if (rt->server_type == RTSP_SERVER_REAL)
1766 * The following entries are required for proper
1767 * streaming from a Realmedia server. They are
1768 * interdependent in some way although we currently
1769 * don't quite understand how. Values were copied
1770 * from mplayer SVN r23589.
1771 * ClientChallenge is a 16-byte ID in hex
1772 * CompanyID is a 16-byte ID in base64
1774 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1775 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1776 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1777 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1779 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1780 if (reply->status_code != RTSP_STATUS_OK) {
1781 err = AVERROR_INVALIDDATA;
1785 /* detect server type if not standard-compliant RTP */
1786 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1787 rt->server_type = RTSP_SERVER_REAL;
1789 } else if (!av_strncasecmp(reply->server, "WMServer/", 9)) {
1790 rt->server_type = RTSP_SERVER_WMS;
1791 } else if (rt->server_type == RTSP_SERVER_REAL)
1792 strcpy(real_challenge, reply->real_challenge);
1796 if (s->iformat && CONFIG_RTSP_DEMUXER)
1797 err = ff_rtsp_setup_input_streams(s, reply);
1798 else if (CONFIG_RTSP_MUXER)
1799 err = ff_rtsp_setup_output_streams(s, host);
1804 int lower_transport = ff_log2_tab[lower_transport_mask &
1805 ~(lower_transport_mask - 1)];
1807 err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
1808 rt->server_type == RTSP_SERVER_REAL ?
1809 real_challenge : NULL);
1812 lower_transport_mask &= ~(1 << lower_transport);
1813 if (lower_transport_mask == 0 && err == 1) {
1814 err = AVERROR(EPROTONOSUPPORT);
1819 rt->lower_transport_mask = lower_transport_mask;
1820 av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
1821 rt->state = RTSP_STATE_IDLE;
1822 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1825 ff_rtsp_close_streams(s);
1826 ff_rtsp_close_connections(s);
1827 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1828 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1829 rt->session_id[0] = '\0';
1830 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1838 #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1841 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1842 uint8_t *buf, int buf_size, int64_t wait_end)
1844 RTSPState *rt = s->priv_data;
1845 RTSPStream *rtsp_st;
1846 int n, i, ret, tcp_fd, timeout_cnt = 0;
1848 struct pollfd *p = rt->p;
1849 int *fds = NULL, fdsnum, fdsidx;
1852 if (ff_check_interrupt(&s->interrupt_callback))
1853 return AVERROR_EXIT;
1854 if (wait_end && wait_end - av_gettime() < 0)
1855 return AVERROR(EAGAIN);
1858 tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
1859 p[max_p].fd = tcp_fd;
1860 p[max_p++].events = POLLIN;
1864 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1865 rtsp_st = rt->rtsp_streams[i];
1866 if (rtsp_st->rtp_handle) {
1867 if (ret = ffurl_get_multi_file_handle(rtsp_st->rtp_handle,
1869 av_log(s, AV_LOG_ERROR, "Unable to recover rtp ports\n");
1873 av_log(s, AV_LOG_ERROR,
1874 "Number of fds %d not supported\n", fdsnum);
1875 return AVERROR_INVALIDDATA;
1877 for (fdsidx = 0; fdsidx < fdsnum; fdsidx++) {
1878 p[max_p].fd = fds[fdsidx];
1879 p[max_p++].events = POLLIN;
1884 n = poll(p, max_p, POLL_TIMEOUT_MS);
1886 int j = 1 - (tcp_fd == -1);
1888 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1889 rtsp_st = rt->rtsp_streams[i];
1890 if (rtsp_st->rtp_handle) {
1891 if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
1892 ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
1894 *prtsp_st = rtsp_st;
1901 #if CONFIG_RTSP_DEMUXER
1902 if (tcp_fd != -1 && p[0].revents & POLLIN) {
1903 if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
1904 if (rt->state == RTSP_STATE_STREAMING) {
1905 if (!ff_rtsp_parse_streaming_commands(s))
1908 av_log(s, AV_LOG_WARNING,
1909 "Unable to answer to TEARDOWN\n");
1913 RTSPMessageHeader reply;
1914 ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
1917 /* XXX: parse message */
1918 if (rt->state != RTSP_STATE_STREAMING)
1923 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1924 return AVERROR(ETIMEDOUT);
1925 } else if (n < 0 && errno != EINTR)
1926 return AVERROR(errno);
1930 static int pick_stream(AVFormatContext *s, RTSPStream **rtsp_st,
1931 const uint8_t *buf, int len)
1933 RTSPState *rt = s->priv_data;
1937 if (rt->nb_rtsp_streams == 1) {
1938 *rtsp_st = rt->rtsp_streams[0];
1941 if (len >= 8 && rt->transport == RTSP_TRANSPORT_RTP) {
1942 if (RTP_PT_IS_RTCP(rt->recvbuf[1])) {
1944 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1945 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
1948 if (rtpctx->ssrc == AV_RB32(&buf[4])) {
1949 *rtsp_st = rt->rtsp_streams[i];
1956 av_log(s, AV_LOG_WARNING,
1957 "Unable to pick stream for packet - SSRC not known for "
1959 return AVERROR(EAGAIN);
1962 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1963 if ((buf[1] & 0x7f) == rt->rtsp_streams[i]->sdp_payload_type) {
1964 *rtsp_st = rt->rtsp_streams[i];
1970 av_log(s, AV_LOG_WARNING, "Unable to pick stream for packet\n");
1971 return AVERROR(EAGAIN);
1974 int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1976 RTSPState *rt = s->priv_data;
1978 RTSPStream *rtsp_st, *first_queue_st = NULL;
1979 int64_t wait_end = 0;
1981 if (rt->nb_byes == rt->nb_rtsp_streams)
1984 /* get next frames from the same RTP packet */
1985 if (rt->cur_transport_priv) {
1986 if (rt->transport == RTSP_TRANSPORT_RDT) {
1987 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1988 } else if (rt->transport == RTSP_TRANSPORT_RTP) {
1989 ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1990 } else if (rt->ts && CONFIG_RTPDEC) {
1991 ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf + rt->recvbuf_pos, rt->recvbuf_len - rt->recvbuf_pos);
1993 rt->recvbuf_pos += ret;
1994 ret = rt->recvbuf_pos < rt->recvbuf_len;
1999 rt->cur_transport_priv = NULL;
2001 } else if (ret == 1) {
2004 rt->cur_transport_priv = NULL;
2008 if (rt->transport == RTSP_TRANSPORT_RTP) {
2010 int64_t first_queue_time = 0;
2011 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2012 RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
2016 queue_time = ff_rtp_queued_packet_time(rtpctx);
2017 if (queue_time && (queue_time - first_queue_time < 0 ||
2018 !first_queue_time)) {
2019 first_queue_time = queue_time;
2020 first_queue_st = rt->rtsp_streams[i];
2023 if (first_queue_time) {
2024 wait_end = first_queue_time + s->max_delay;
2027 first_queue_st = NULL;
2031 /* read next RTP packet */
2033 rt->recvbuf = av_malloc(RECVBUF_SIZE);
2035 return AVERROR(ENOMEM);
2038 switch(rt->lower_transport) {
2040 #if CONFIG_RTSP_DEMUXER
2041 case RTSP_LOWER_TRANSPORT_TCP:
2042 len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
2045 case RTSP_LOWER_TRANSPORT_UDP:
2046 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
2047 len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
2048 if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
2049 ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, rtsp_st->rtp_handle, NULL, len);
2051 case RTSP_LOWER_TRANSPORT_CUSTOM:
2052 if (first_queue_st && rt->transport == RTSP_TRANSPORT_RTP &&
2053 wait_end && wait_end < av_gettime())
2054 len = AVERROR(EAGAIN);
2056 len = ffio_read_partial(s->pb, rt->recvbuf, RECVBUF_SIZE);
2057 len = pick_stream(s, &rtsp_st, rt->recvbuf, len);
2058 if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
2059 ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, NULL, s->pb, len);
2062 if (len == AVERROR(EAGAIN) && first_queue_st &&
2063 rt->transport == RTSP_TRANSPORT_RTP) {
2064 rtsp_st = first_queue_st;
2065 ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
2072 if (rt->transport == RTSP_TRANSPORT_RDT) {
2073 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
2074 } else if (rt->transport == RTSP_TRANSPORT_RTP) {
2075 ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
2076 if (rtsp_st->feedback) {
2077 AVIOContext *pb = NULL;
2078 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_CUSTOM)
2080 ff_rtp_send_rtcp_feedback(rtsp_st->transport_priv, rtsp_st->rtp_handle, pb);
2083 /* Either bad packet, or a RTCP packet. Check if the
2084 * first_rtcp_ntp_time field was initialized. */
2085 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
2086 if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
2087 /* first_rtcp_ntp_time has been initialized for this stream,
2088 * copy the same value to all other uninitialized streams,
2089 * in order to map their timestamp origin to the same ntp time
2092 AVStream *st = NULL;
2093 if (rtsp_st->stream_index >= 0)
2094 st = s->streams[rtsp_st->stream_index];
2095 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2096 RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
2097 AVStream *st2 = NULL;
2098 if (rt->rtsp_streams[i]->stream_index >= 0)
2099 st2 = s->streams[rt->rtsp_streams[i]->stream_index];
2100 if (rtpctx2 && st && st2 &&
2101 rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
2102 rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
2103 rtpctx2->rtcp_ts_offset = av_rescale_q(
2104 rtpctx->rtcp_ts_offset, st->time_base,
2109 if (ret == -RTCP_BYE) {
2112 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
2113 rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
2115 if (rt->nb_byes == rt->nb_rtsp_streams)
2119 } else if (rt->ts && CONFIG_RTPDEC) {
2120 ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf, len);
2123 rt->recvbuf_len = len;
2124 rt->recvbuf_pos = ret;
2125 rt->cur_transport_priv = rt->ts;
2132 return AVERROR_INVALIDDATA;
2138 /* more packets may follow, so we save the RTP context */
2139 rt->cur_transport_priv = rtsp_st->transport_priv;
2143 #endif /* CONFIG_RTPDEC */
2145 #if CONFIG_SDP_DEMUXER
2146 static int sdp_probe(AVProbeData *p1)
2148 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
2150 /* we look for a line beginning "c=IN IP" */
2151 while (p < p_end && *p != '\0') {
2152 if (p + sizeof("c=IN IP") - 1 < p_end &&
2153 av_strstart(p, "c=IN IP", NULL))
2154 return AVPROBE_SCORE_EXTENSION;
2156 while (p < p_end - 1 && *p != '\n') p++;
2165 static void append_source_addrs(char *buf, int size, const char *name,
2166 int count, struct RTSPSource **addrs)
2171 av_strlcatf(buf, size, "&%s=%s", name, addrs[0]->addr);
2172 for (i = 1; i < count; i++)
2173 av_strlcatf(buf, size, ",%s", addrs[i]->addr);
2176 static int sdp_read_header(AVFormatContext *s)
2178 RTSPState *rt = s->priv_data;
2179 RTSPStream *rtsp_st;
2184 if (!ff_network_init())
2185 return AVERROR(EIO);
2187 if (s->max_delay < 0) /* Not set by the caller */
2188 s->max_delay = DEFAULT_REORDERING_DELAY;
2189 if (rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)
2190 rt->lower_transport = RTSP_LOWER_TRANSPORT_CUSTOM;
2192 /* read the whole sdp file */
2193 /* XXX: better loading */
2194 content = av_malloc(SDP_MAX_SIZE);
2195 size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
2198 return AVERROR_INVALIDDATA;
2200 content[size] ='\0';
2202 err = ff_sdp_parse(s, content);
2206 /* open each RTP stream */
2207 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2209 rtsp_st = rt->rtsp_streams[i];
2211 if (!(rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)) {
2212 getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
2213 namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
2214 ff_url_join(url, sizeof(url), "rtp", NULL,
2215 namebuf, rtsp_st->sdp_port,
2216 "?localport=%d&ttl=%d&connect=%d&write_to_source=%d",
2217 rtsp_st->sdp_port, rtsp_st->sdp_ttl,
2218 rt->rtsp_flags & RTSP_FLAG_FILTER_SRC ? 1 : 0,
2219 rt->rtsp_flags & RTSP_FLAG_RTCP_TO_SOURCE ? 1 : 0);
2221 append_source_addrs(url, sizeof(url), "sources",
2222 rtsp_st->nb_include_source_addrs,
2223 rtsp_st->include_source_addrs);
2224 append_source_addrs(url, sizeof(url), "block",
2225 rtsp_st->nb_exclude_source_addrs,
2226 rtsp_st->exclude_source_addrs);
2227 if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
2228 &s->interrupt_callback, NULL) < 0) {
2229 err = AVERROR_INVALIDDATA;
2233 if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
2238 ff_rtsp_close_streams(s);
2243 static int sdp_read_close(AVFormatContext *s)
2245 ff_rtsp_close_streams(s);
2250 static const AVClass sdp_demuxer_class = {
2251 .class_name = "SDP demuxer",
2252 .item_name = av_default_item_name,
2253 .option = sdp_options,
2254 .version = LIBAVUTIL_VERSION_INT,
2257 AVInputFormat ff_sdp_demuxer = {
2259 .long_name = NULL_IF_CONFIG_SMALL("SDP"),
2260 .priv_data_size = sizeof(RTSPState),
2261 .read_probe = sdp_probe,
2262 .read_header = sdp_read_header,
2263 .read_packet = ff_rtsp_fetch_packet,
2264 .read_close = sdp_read_close,
2265 .priv_class = &sdp_demuxer_class,
2267 #endif /* CONFIG_SDP_DEMUXER */
2269 #if CONFIG_RTP_DEMUXER
2270 static int rtp_probe(AVProbeData *p)
2272 if (av_strstart(p->filename, "rtp:", NULL))
2273 return AVPROBE_SCORE_MAX;
2277 static int rtp_read_header(AVFormatContext *s)
2279 uint8_t recvbuf[RTP_MAX_PACKET_LENGTH];
2280 char host[500], sdp[500];
2282 URLContext* in = NULL;
2284 AVCodecContext codec = { 0 };
2285 struct sockaddr_storage addr;
2287 socklen_t addrlen = sizeof(addr);
2288 RTSPState *rt = s->priv_data;
2290 if (!ff_network_init())
2291 return AVERROR(EIO);
2293 ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ,
2294 &s->interrupt_callback, NULL);
2299 ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
2300 if (ret == AVERROR(EAGAIN))
2305 av_log(s, AV_LOG_WARNING, "Received too short packet\n");
2309 if ((recvbuf[0] & 0xc0) != 0x80) {
2310 av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
2315 if (RTP_PT_IS_RTCP(recvbuf[1]))
2318 payload_type = recvbuf[1] & 0x7f;
2321 getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
2325 if (ff_rtp_get_codec_info(&codec, payload_type)) {
2326 av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
2327 "without an SDP file describing it\n",
2331 if (codec.codec_type != AVMEDIA_TYPE_DATA) {
2332 av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
2333 "properly you need an SDP file "
2337 av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
2338 NULL, 0, s->filename);
2340 snprintf(sdp, sizeof(sdp),
2341 "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
2342 addr.ss_family == AF_INET ? 4 : 6, host,
2343 codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
2344 codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
2345 port, payload_type);
2346 av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
2348 ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
2351 /* sdp_read_header initializes this again */
2354 rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;
2356 ret = sdp_read_header(s);
2367 static const AVClass rtp_demuxer_class = {
2368 .class_name = "RTP demuxer",
2369 .item_name = av_default_item_name,
2370 .option = rtp_options,
2371 .version = LIBAVUTIL_VERSION_INT,
2374 AVInputFormat ff_rtp_demuxer = {
2376 .long_name = NULL_IF_CONFIG_SMALL("RTP input"),
2377 .priv_data_size = sizeof(RTSPState),
2378 .read_probe = rtp_probe,
2379 .read_header = rtp_read_header,
2380 .read_packet = ff_rtsp_fetch_packet,
2381 .read_close = sdp_read_close,
2382 .flags = AVFMT_NOFILE,
2383 .priv_class = &rtp_demuxer_class,
2385 #endif /* CONFIG_RTP_DEMUXER */