3 * Copyright (c) 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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"
29 #include <sys/select.h>
37 #include "rtpdec_asf.h"
38 #include "rtpdec_vorbis.h"
41 //#define DEBUG_RTP_TCP
43 #if LIBAVFORMAT_VERSION_INT < (53 << 16)
44 int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
47 #define SPACE_CHARS " \t\r\n"
48 /* we use memchr() instead of strchr() here because strchr() will return
49 * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */
50 #define redir_isspace(c) memchr(SPACE_CHARS, c, 4)
51 static void skip_spaces(const char **pp)
55 while (redir_isspace(*p))
60 static void get_word_until_chars(char *buf, int buf_size,
61 const char *sep, const char **pp)
69 while (!strchr(sep, *p) && *p != '\0') {
70 if ((q - buf) < buf_size - 1)
79 static void get_word_sep(char *buf, int buf_size, const char *sep,
82 if (**pp == '/') (*pp)++;
83 get_word_until_chars(buf, buf_size, sep, pp);
86 static void get_word(char *buf, int buf_size, const char **pp)
88 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
91 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
92 static int sdp_parse_rtpmap(AVFormatContext *s,
93 AVCodecContext *codec, RTSPStream *rtsp_st,
94 int payload_type, const char *p)
101 /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
102 * see if we can handle this kind of payload.
103 * The space should normally not be there but some Real streams or
104 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
105 * have a trailing space. */
106 get_word_sep(buf, sizeof(buf), "/ ", &p);
107 if (payload_type >= RTP_PT_PRIVATE) {
108 RTPDynamicProtocolHandler *handler;
109 for (handler = RTPFirstDynamicPayloadHandler;
110 handler; handler = handler->next) {
111 if (!strcasecmp(buf, handler->enc_name) &&
112 codec->codec_type == handler->codec_type) {
113 codec->codec_id = handler->codec_id;
114 rtsp_st->dynamic_handler = handler;
116 rtsp_st->dynamic_protocol_context = handler->open();
121 /* We are in a standard case
122 * (from http://www.iana.org/assignments/rtp-parameters). */
123 /* search into AVRtpPayloadTypes[] */
124 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
127 c = avcodec_find_decoder(codec->codec_id);
133 get_word_sep(buf, sizeof(buf), "/", &p);
135 switch (codec->codec_type) {
136 case CODEC_TYPE_AUDIO:
137 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
138 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
139 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
141 codec->sample_rate = i;
142 get_word_sep(buf, sizeof(buf), "/", &p);
146 // TODO: there is a bug here; if it is a mono stream, and
147 // less than 22000Hz, faad upconverts to stereo and twice
148 // the frequency. No problem, but the sample rate is being
149 // set here by the sdp line. Patch on its way. (rdm)
151 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
153 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
156 case CODEC_TYPE_VIDEO:
157 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
165 /* return the length and optionally the data */
166 static int hex_to_data(uint8_t *data, const char *p)
176 c = toupper((unsigned char) *p++);
177 if (c >= '0' && c <= '9')
179 else if (c >= 'A' && c <= 'F')
194 static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx,
195 char *attr, char *value)
197 switch (codec->codec_id) {
200 if (!strcmp(attr, "config")) {
201 /* decode the hexa encoded parameter */
202 int len = hex_to_data(NULL, value);
203 if (codec->extradata)
204 av_free(codec->extradata);
205 codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
206 if (!codec->extradata)
208 codec->extradata_size = len;
209 hex_to_data(codec->extradata, value);
212 case CODEC_ID_VORBIS:
213 ff_vorbis_parse_fmtp_config(codec, ctx, attr, value);
227 /* All known fmtp parmeters and the corresping RTPAttrTypeEnum */
228 #define ATTR_NAME_TYPE_INT 0
229 #define ATTR_NAME_TYPE_STR 1
230 static const AttrNameMap attr_names[]=
232 { "SizeLength", ATTR_NAME_TYPE_INT,
233 offsetof(RTPPayloadData, sizelength) },
234 { "IndexLength", ATTR_NAME_TYPE_INT,
235 offsetof(RTPPayloadData, indexlength) },
236 { "IndexDeltaLength", ATTR_NAME_TYPE_INT,
237 offsetof(RTPPayloadData, indexdeltalength) },
238 { "profile-level-id", ATTR_NAME_TYPE_INT,
239 offsetof(RTPPayloadData, profile_level_id) },
240 { "StreamType", ATTR_NAME_TYPE_INT,
241 offsetof(RTPPayloadData, streamtype) },
242 { "mode", ATTR_NAME_TYPE_STR,
243 offsetof(RTPPayloadData, mode) },
247 /* parse the attribute line from the fmtp a line of an sdp resonse. This
248 * is broken out as a function because it is used in rtp_h264.c, which is
250 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
251 char *value, int value_size)
255 get_word_sep(attr, attr_size, "=", p);
258 get_word_sep(value, value_size, ";", p);
266 /* parse a SDP line and save stream attributes */
267 static void sdp_parse_fmtp(AVStream *st, const char *p)
270 /* Vorbis setup headers can be up to 12KB and are sent base64
271 * encoded, giving a 12KB * (4/3) = 16KB FMTP line. */
274 RTSPStream *rtsp_st = st->priv_data;
275 AVCodecContext *codec = st->codec;
276 RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data;
278 /* loop on each attribute */
279 while (ff_rtsp_next_attr_and_value(&p, attr, sizeof(attr),
280 value, sizeof(value))) {
281 /* grab the codec extra_data from the config parameter of the fmtp
283 sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context,
285 /* Looking for a known attribute */
286 for (i = 0; attr_names[i].str; ++i) {
287 if (!strcasecmp(attr, attr_names[i].str)) {
288 if (attr_names[i].type == ATTR_NAME_TYPE_INT) {
289 *(int *)((char *)rtp_payload_data +
290 attr_names[i].offset) = atoi(value);
291 } else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
292 *(char **)((char *)rtp_payload_data +
293 attr_names[i].offset) = av_strdup(value);
299 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
301 * Used for seeking in the rtp stream.
303 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
308 if (!av_stristart(p, "npt=", &p))
311 *start = AV_NOPTS_VALUE;
312 *end = AV_NOPTS_VALUE;
314 get_word_sep(buf, sizeof(buf), "-", &p);
315 *start = parse_date(buf, 1);
318 get_word_sep(buf, sizeof(buf), "-", &p);
319 *end = parse_date(buf, 1);
321 // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
322 // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
325 typedef struct SDPParseState {
327 struct in_addr default_ip;
329 int skip_media; ///< set if an unknown m= line occurs
332 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
333 int letter, const char *buf)
335 RTSPState *rt = s->priv_data;
336 char buf1[64], st_type[64];
338 enum CodecType codec_type;
342 struct in_addr sdp_ip;
345 dprintf(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") != 0)
358 get_word_sep(buf1, sizeof(buf1), "/", &p);
359 if (ff_inet_aton(buf1, &sdp_ip) == 0)
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 st = s->streams[s->nb_streams - 1];
372 rtsp_st = st->priv_data;
373 rtsp_st->sdp_ip = sdp_ip;
374 rtsp_st->sdp_ttl = ttl;
378 av_metadata_set(&s->metadata, "title", p);
381 if (s->nb_streams == 0) {
382 av_metadata_set(&s->metadata, "comment", p);
389 get_word(st_type, sizeof(st_type), &p);
390 if (!strcmp(st_type, "audio")) {
391 codec_type = CODEC_TYPE_AUDIO;
392 } else if (!strcmp(st_type, "video")) {
393 codec_type = CODEC_TYPE_VIDEO;
394 } else if (!strcmp(st_type, "application")) {
395 codec_type = CODEC_TYPE_DATA;
400 rtsp_st = av_mallocz(sizeof(RTSPStream));
403 rtsp_st->stream_index = -1;
404 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
406 rtsp_st->sdp_ip = s1->default_ip;
407 rtsp_st->sdp_ttl = s1->default_ttl;
409 get_word(buf1, sizeof(buf1), &p); /* port */
410 rtsp_st->sdp_port = atoi(buf1);
412 get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
414 /* XXX: handle list of formats */
415 get_word(buf1, sizeof(buf1), &p); /* format list */
416 rtsp_st->sdp_payload_type = atoi(buf1);
418 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
419 /* no corresponding stream */
421 st = av_new_stream(s, 0);
424 st->priv_data = rtsp_st;
425 rtsp_st->stream_index = st->index;
426 st->codec->codec_type = codec_type;
427 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
428 /* if standard payload type, we can find the codec right now */
429 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
432 /* put a default control url */
433 av_strlcpy(rtsp_st->control_url, rt->control_uri,
434 sizeof(rtsp_st->control_url));
437 if (av_strstart(p, "control:", &p)) {
438 if (s->nb_streams == 0) {
439 if (!strncmp(p, "rtsp://", 7))
440 av_strlcpy(rt->control_uri, p,
441 sizeof(rt->control_uri));
444 /* get the control url */
445 st = s->streams[s->nb_streams - 1];
446 rtsp_st = st->priv_data;
448 /* XXX: may need to add full url resolution */
449 url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
451 if (proto[0] == '\0') {
452 /* relative control URL */
453 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
454 av_strlcat(rtsp_st->control_url, "/",
455 sizeof(rtsp_st->control_url));
456 av_strlcat(rtsp_st->control_url, p,
457 sizeof(rtsp_st->control_url));
459 av_strlcpy(rtsp_st->control_url, p,
460 sizeof(rtsp_st->control_url));
462 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
463 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
464 get_word(buf1, sizeof(buf1), &p);
465 payload_type = atoi(buf1);
466 st = s->streams[s->nb_streams - 1];
467 rtsp_st = st->priv_data;
468 sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
469 } else if (av_strstart(p, "fmtp:", &p)) {
470 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
471 get_word(buf1, sizeof(buf1), &p);
472 payload_type = atoi(buf1);
473 for (i = 0; i < s->nb_streams; i++) {
475 rtsp_st = st->priv_data;
476 if (rtsp_st->sdp_payload_type == payload_type) {
477 if (!(rtsp_st->dynamic_handler &&
478 rtsp_st->dynamic_handler->parse_sdp_a_line &&
479 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
480 i, rtsp_st->dynamic_protocol_context, buf)))
481 sdp_parse_fmtp(st, p);
484 } else if (av_strstart(p, "framesize:", &p)) {
485 // let dynamic protocol handlers have a stab at the line.
486 get_word(buf1, sizeof(buf1), &p);
487 payload_type = atoi(buf1);
488 for (i = 0; i < s->nb_streams; i++) {
490 rtsp_st = st->priv_data;
491 if (rtsp_st->sdp_payload_type == payload_type &&
492 rtsp_st->dynamic_handler &&
493 rtsp_st->dynamic_handler->parse_sdp_a_line)
494 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
495 rtsp_st->dynamic_protocol_context, buf);
497 } else if (av_strstart(p, "range:", &p)) {
500 // this is so that seeking on a streamed file can work.
501 rtsp_parse_range_npt(p, &start, &end);
502 s->start_time = start;
503 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
504 s->duration = (end == AV_NOPTS_VALUE) ?
505 AV_NOPTS_VALUE : end - start;
506 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
508 rt->transport = RTSP_TRANSPORT_RDT;
510 if (rt->server_type == RTSP_SERVER_WMS)
511 ff_wms_parse_sdp_a_line(s, p);
512 if (s->nb_streams > 0) {
513 if (rt->server_type == RTSP_SERVER_REAL)
514 ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
516 rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
517 if (rtsp_st->dynamic_handler &&
518 rtsp_st->dynamic_handler->parse_sdp_a_line)
519 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
521 rtsp_st->dynamic_protocol_context, buf);
528 static int sdp_parse(AVFormatContext *s, const char *content)
532 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
533 * contain long SDP lines containing complete ASF Headers (several
534 * kB) or arrays of MDPR (RM stream descriptor) headers plus
535 * "rulebooks" describing their properties. Therefore, the SDP line
538 * The Vorbis FMTP line can be up to 16KB - see sdp_parse_fmtp. */
540 SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
542 memset(s1, 0, sizeof(SDPParseState));
553 /* get the content */
555 while (*p != '\n' && *p != '\r' && *p != '\0') {
556 if ((q - buf) < sizeof(buf) - 1)
561 sdp_parse_line(s, s1, letter, buf);
563 while (*p != '\n' && *p != '\0')
571 /* close and free RTSP streams */
572 void ff_rtsp_close_streams(AVFormatContext *s)
574 RTSPState *rt = s->priv_data;
578 for (i = 0; i < rt->nb_rtsp_streams; i++) {
579 rtsp_st = rt->rtsp_streams[i];
581 if (rtsp_st->transport_priv) {
583 AVFormatContext *rtpctx = rtsp_st->transport_priv;
584 av_write_trailer(rtpctx);
585 url_fclose(rtpctx->pb);
586 av_metadata_free(&rtpctx->streams[0]->metadata);
587 av_metadata_free(&rtpctx->metadata);
588 av_free(rtpctx->streams[0]);
590 } else if (rt->transport == RTSP_TRANSPORT_RDT)
591 ff_rdt_parse_close(rtsp_st->transport_priv);
593 rtp_parse_close(rtsp_st->transport_priv);
595 if (rtsp_st->rtp_handle)
596 url_close(rtsp_st->rtp_handle);
597 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
598 rtsp_st->dynamic_handler->close(
599 rtsp_st->dynamic_protocol_context);
602 av_free(rt->rtsp_streams);
604 av_close_input_stream (rt->asf_ctx);
607 av_freep(&rt->auth_b64);
610 static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st, URLContext *handle) {
611 AVFormatContext *rtpctx;
613 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
618 /* Allocate an AVFormatContext for each output stream */
619 rtpctx = avformat_alloc_context();
623 rtpctx->oformat = rtp_format;
624 if (!av_new_stream(rtpctx, 0)) {
628 /* Copy the max delay setting; the rtp muxer reads this. */
629 rtpctx->max_delay = s->max_delay;
630 /* Copy other stream parameters. */
631 rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
633 /* Remove the local codec, link to the original codec
634 * context instead, to give the rtp muxer access to
635 * codec parameters. */
636 av_free(rtpctx->streams[0]->codec);
637 rtpctx->streams[0]->codec = st->codec;
639 url_fdopen(&rtpctx->pb, handle);
640 ret = av_write_header(rtpctx);
643 url_fclose(rtpctx->pb);
644 av_free(rtpctx->streams[0]);
649 /* Copy the RTP AVStream timebase back to the original AVStream */
650 st->time_base = rtpctx->streams[0]->time_base;
654 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
656 RTSPState *rt = s->priv_data;
659 /* open the RTP context */
660 if (rtsp_st->stream_index >= 0)
661 st = s->streams[rtsp_st->stream_index];
663 s->ctx_flags |= AVFMTCTX_NOHEADER;
666 rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
667 /* Ownage of rtp_handle is passed to the rtp mux context */
668 rtsp_st->rtp_handle = NULL;
669 } else if (rt->transport == RTSP_TRANSPORT_RDT)
670 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
671 rtsp_st->dynamic_protocol_context,
672 rtsp_st->dynamic_handler);
674 rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
675 rtsp_st->sdp_payload_type,
676 &rtsp_st->rtp_payload_data);
678 if (!rtsp_st->transport_priv) {
679 return AVERROR(ENOMEM);
680 } else if (rt->transport != RTSP_TRANSPORT_RDT) {
681 if (rtsp_st->dynamic_handler) {
682 rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
683 rtsp_st->dynamic_protocol_context,
684 rtsp_st->dynamic_handler);
691 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
692 static int rtsp_probe(AVProbeData *p)
694 if (av_strstart(p->filename, "rtsp:", NULL))
695 return AVPROBE_SCORE_MAX;
699 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
706 v = strtol(p, (char **)&p, 10);
710 v = strtol(p, (char **)&p, 10);
719 /* XXX: only one transport specification is parsed */
720 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
722 char transport_protocol[16];
724 char lower_transport[16];
726 RTSPTransportField *th;
729 reply->nb_transports = 0;
736 th = &reply->transports[reply->nb_transports];
738 get_word_sep(transport_protocol, sizeof(transport_protocol),
740 if (!strcasecmp (transport_protocol, "rtp")) {
741 get_word_sep(profile, sizeof(profile), "/;,", &p);
742 lower_transport[0] = '\0';
743 /* rtp/avp/<protocol> */
745 get_word_sep(lower_transport, sizeof(lower_transport),
748 th->transport = RTSP_TRANSPORT_RTP;
749 } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
750 !strcasecmp (transport_protocol, "x-real-rdt")) {
751 /* x-pn-tng/<protocol> */
752 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
754 th->transport = RTSP_TRANSPORT_RDT;
756 if (!strcasecmp(lower_transport, "TCP"))
757 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
759 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
763 /* get each parameter */
764 while (*p != '\0' && *p != ',') {
765 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
766 if (!strcmp(parameter, "port")) {
769 rtsp_parse_range(&th->port_min, &th->port_max, &p);
771 } else if (!strcmp(parameter, "client_port")) {
774 rtsp_parse_range(&th->client_port_min,
775 &th->client_port_max, &p);
777 } else if (!strcmp(parameter, "server_port")) {
780 rtsp_parse_range(&th->server_port_min,
781 &th->server_port_max, &p);
783 } else if (!strcmp(parameter, "interleaved")) {
786 rtsp_parse_range(&th->interleaved_min,
787 &th->interleaved_max, &p);
789 } else if (!strcmp(parameter, "multicast")) {
790 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
791 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
792 } else if (!strcmp(parameter, "ttl")) {
795 th->ttl = strtol(p, (char **)&p, 10);
797 } else if (!strcmp(parameter, "destination")) {
798 struct in_addr ipaddr;
802 get_word_sep(buf, sizeof(buf), ";,", &p);
803 if (ff_inet_aton(buf, &ipaddr))
804 th->destination = ntohl(ipaddr.s_addr);
807 while (*p != ';' && *p != '\0' && *p != ',')
815 reply->nb_transports++;
819 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf)
823 /* NOTE: we do case independent match for broken servers */
825 if (av_stristart(p, "Session:", &p)) {
827 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
828 if (av_stristart(p, ";timeout=", &p) &&
829 (t = strtol(p, NULL, 10)) > 0) {
832 } else if (av_stristart(p, "Content-Length:", &p)) {
833 reply->content_length = strtol(p, NULL, 10);
834 } else if (av_stristart(p, "Transport:", &p)) {
835 rtsp_parse_transport(reply, p);
836 } else if (av_stristart(p, "CSeq:", &p)) {
837 reply->seq = strtol(p, NULL, 10);
838 } else if (av_stristart(p, "Range:", &p)) {
839 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
840 } else if (av_stristart(p, "RealChallenge1:", &p)) {
842 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
843 } else if (av_stristart(p, "Server:", &p)) {
845 av_strlcpy(reply->server, p, sizeof(reply->server));
846 } else if (av_stristart(p, "Notice:", &p) ||
847 av_stristart(p, "X-Notice:", &p)) {
848 reply->notice = strtol(p, NULL, 10);
849 } else if (av_stristart(p, "Location:", &p)) {
851 av_strlcpy(reply->location, p , sizeof(reply->location));
855 /* skip a RTP/TCP interleaved packet */
856 static void rtsp_skip_packet(AVFormatContext *s)
858 RTSPState *rt = s->priv_data;
862 ret = url_read_complete(rt->rtsp_hd, buf, 3);
865 len = AV_RB16(buf + 1);
867 dprintf(s, "skipping RTP packet len=%d\n", len);
872 if (len1 > sizeof(buf))
874 ret = url_read_complete(rt->rtsp_hd, buf, len1);
881 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
882 unsigned char **content_ptr,
883 int return_on_interleaved_data)
885 RTSPState *rt = s->priv_data;
886 char buf[4096], buf1[1024], *q;
889 int ret, content_length, line_count = 0;
890 unsigned char *content = NULL;
892 memset(reply, 0, sizeof(*reply));
894 /* parse reply (XXX: use buffers) */
895 rt->last_reply[0] = '\0';
899 ret = url_read_complete(rt->rtsp_hd, &ch, 1);
901 dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
908 /* XXX: only parse it if first char on line ? */
909 if (return_on_interleaved_data) {
913 } else if (ch != '\r') {
914 if ((q - buf) < sizeof(buf) - 1)
920 dprintf(s, "line='%s'\n", buf);
922 /* test if last line */
926 if (line_count == 0) {
928 get_word(buf1, sizeof(buf1), &p);
929 get_word(buf1, sizeof(buf1), &p);
930 reply->status_code = atoi(buf1);
932 ff_rtsp_parse_line(reply, p);
933 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
934 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
939 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
940 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
942 content_length = reply->content_length;
943 if (content_length > 0) {
944 /* leave some room for a trailing '\0' (useful for simple parsing) */
945 content = av_malloc(content_length + 1);
946 (void)url_read_complete(rt->rtsp_hd, content, content_length);
947 content[content_length] = '\0';
950 *content_ptr = content;
955 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
956 reply->notice == 2104 /* Start-of-Stream Reached */ ||
957 reply->notice == 2306 /* Continuous Feed Terminated */) {
958 rt->state = RTSP_STATE_IDLE;
959 } else if (reply->notice >= 4400 && reply->notice < 5500) {
960 return AVERROR(EIO); /* data or server error */
961 } else if (reply->notice == 2401 /* Ticket Expired */ ||
962 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
963 return AVERROR(EPERM);
968 void ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
970 const unsigned char *send_content,
971 int send_content_length)
973 RTSPState *rt = s->priv_data;
974 char buf[4096], buf1[1024];
977 av_strlcpy(buf, cmd, sizeof(buf));
978 snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
979 av_strlcat(buf, buf1, sizeof(buf));
980 if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
981 snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
982 av_strlcat(buf, buf1, sizeof(buf));
985 av_strlcatf(buf, sizeof(buf),
986 "Authorization: Basic %s\r\n",
988 if (send_content_length > 0 && send_content)
989 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
990 av_strlcat(buf, "\r\n", sizeof(buf));
992 dprintf(s, "Sending:\n%s--\n", buf);
994 url_write(rt->rtsp_hd, buf, strlen(buf));
995 if (send_content_length > 0 && send_content)
996 url_write(rt->rtsp_hd, send_content, send_content_length);
997 rt->last_cmd_time = av_gettime();
1000 void ff_rtsp_send_cmd_async(AVFormatContext *s, const char *cmd)
1002 ff_rtsp_send_cmd_with_content_async(s, cmd, NULL, 0);
1005 void ff_rtsp_send_cmd(AVFormatContext *s,
1006 const char *cmd, RTSPMessageHeader *reply,
1007 unsigned char **content_ptr)
1009 ff_rtsp_send_cmd_async(s, cmd);
1011 ff_rtsp_read_reply(s, reply, content_ptr, 0);
1014 void ff_rtsp_send_cmd_with_content(AVFormatContext *s,
1016 RTSPMessageHeader *reply,
1017 unsigned char **content_ptr,
1018 const unsigned char *send_content,
1019 int send_content_length)
1021 ff_rtsp_send_cmd_with_content_async(s, cmd, send_content, send_content_length);
1023 ff_rtsp_read_reply(s, reply, content_ptr, 0);
1027 * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
1029 static int make_setup_request(AVFormatContext *s, const char *host, int port,
1030 int lower_transport, const char *real_challenge)
1032 RTSPState *rt = s->priv_data;
1033 int rtx, j, i, err, interleave = 0;
1034 RTSPStream *rtsp_st;
1035 RTSPMessageHeader reply1, *reply = &reply1;
1037 const char *trans_pref;
1039 if (rt->transport == RTSP_TRANSPORT_RDT)
1040 trans_pref = "x-pn-tng";
1042 trans_pref = "RTP/AVP";
1044 /* default timeout: 1 minute */
1047 /* for each stream, make the setup request */
1048 /* XXX: we assume the same server is used for the control of each
1051 for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
1052 char transport[2048];
1055 * WMS serves all UDP data over a single connection, the RTX, which
1056 * isn't necessarily the first in the SDP but has to be the first
1057 * to be set up, else the second/third SETUP will fail with a 461.
1059 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1060 rt->server_type == RTSP_SERVER_WMS) {
1063 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1064 int len = strlen(rt->rtsp_streams[rtx]->control_url);
1066 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1070 if (rtx == rt->nb_rtsp_streams)
1071 return -1; /* no RTX found */
1072 rtsp_st = rt->rtsp_streams[rtx];
1074 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1076 rtsp_st = rt->rtsp_streams[i];
1079 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1082 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1083 port = reply->transports[0].client_port_min;
1087 /* first try in specified port range */
1088 if (RTSP_RTP_PORT_MIN != 0) {
1089 while (j <= RTSP_RTP_PORT_MAX) {
1090 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1091 "?localport=%d", j);
1092 /* we will use two ports per rtp stream (rtp and rtcp) */
1094 if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
1100 /* then try on any port */
1101 if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
1102 err = AVERROR_INVALIDDATA;
1108 port = rtp_get_local_port(rtsp_st->rtp_handle);
1110 snprintf(transport, sizeof(transport) - 1,
1111 "%s/UDP;", trans_pref);
1112 if (rt->server_type != RTSP_SERVER_REAL)
1113 av_strlcat(transport, "unicast;", sizeof(transport));
1114 av_strlcatf(transport, sizeof(transport),
1115 "client_port=%d", port);
1116 if (rt->transport == RTSP_TRANSPORT_RTP &&
1117 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1118 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1122 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1123 /** For WMS streams, the application streams are only used for
1124 * UDP. When trying to set it up for TCP streams, the server
1125 * will return an error. Therefore, we skip those streams. */
1126 if (rt->server_type == RTSP_SERVER_WMS &&
1127 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1130 snprintf(transport, sizeof(transport) - 1,
1131 "%s/TCP;", trans_pref);
1132 if (rt->server_type == RTSP_SERVER_WMS)
1133 av_strlcat(transport, "unicast;", sizeof(transport));
1134 av_strlcatf(transport, sizeof(transport),
1135 "interleaved=%d-%d",
1136 interleave, interleave + 1);
1140 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1141 snprintf(transport, sizeof(transport) - 1,
1142 "%s/UDP;multicast", trans_pref);
1145 av_strlcat(transport, ";mode=receive", sizeof(transport));
1146 } else if (rt->server_type == RTSP_SERVER_REAL ||
1147 rt->server_type == RTSP_SERVER_WMS)
1148 av_strlcat(transport, ";mode=play", sizeof(transport));
1149 snprintf(cmd, sizeof(cmd),
1150 "SETUP %s RTSP/1.0\r\n"
1151 "Transport: %s\r\n",
1152 rtsp_st->control_url, transport);
1153 if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
1154 char real_res[41], real_csum[9];
1155 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1157 av_strlcatf(cmd, sizeof(cmd),
1159 "RealChallenge2: %s, sd=%s\r\n",
1160 rt->session_id, real_res, real_csum);
1162 ff_rtsp_send_cmd(s, cmd, reply, NULL);
1163 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1166 } else if (reply->status_code != RTSP_STATUS_OK ||
1167 reply->nb_transports != 1) {
1168 err = AVERROR_INVALIDDATA;
1172 /* XXX: same protocol for all streams is required */
1174 if (reply->transports[0].lower_transport != rt->lower_transport ||
1175 reply->transports[0].transport != rt->transport) {
1176 err = AVERROR_INVALIDDATA;
1180 rt->lower_transport = reply->transports[0].lower_transport;
1181 rt->transport = reply->transports[0].transport;
1184 /* close RTP connection if not choosen */
1185 if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
1186 (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
1187 url_close(rtsp_st->rtp_handle);
1188 rtsp_st->rtp_handle = NULL;
1191 switch(reply->transports[0].lower_transport) {
1192 case RTSP_LOWER_TRANSPORT_TCP:
1193 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1194 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1197 case RTSP_LOWER_TRANSPORT_UDP: {
1200 /* XXX: also use address if specified */
1201 ff_url_join(url, sizeof(url), "rtp", NULL, host,
1202 reply->transports[0].server_port_min, NULL);
1203 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1204 rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1205 err = AVERROR_INVALIDDATA;
1208 /* Try to initialize the connection state in a
1209 * potential NAT router by sending dummy packets.
1210 * RTP/RTCP dummy packets are used for RDT, too.
1212 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
1213 rtp_send_punch_packets(rtsp_st->rtp_handle);
1216 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1221 if (reply->transports[0].destination) {
1222 in.s_addr = htonl(reply->transports[0].destination);
1223 port = reply->transports[0].port_min;
1224 ttl = reply->transports[0].ttl;
1226 in = rtsp_st->sdp_ip;
1227 port = rtsp_st->sdp_port;
1228 ttl = rtsp_st->sdp_ttl;
1230 ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in),
1231 port, "?ttl=%d", ttl);
1232 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1233 err = AVERROR_INVALIDDATA;
1240 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1244 if (reply->timeout > 0)
1245 rt->timeout = reply->timeout;
1247 if (rt->server_type == RTSP_SERVER_REAL)
1248 rt->need_subscription = 1;
1253 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1254 if (rt->rtsp_streams[i]->rtp_handle) {
1255 url_close(rt->rtsp_streams[i]->rtp_handle);
1256 rt->rtsp_streams[i]->rtp_handle = NULL;
1262 static int rtsp_read_play(AVFormatContext *s)
1264 RTSPState *rt = s->priv_data;
1265 RTSPMessageHeader reply1, *reply = &reply1;
1268 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1270 if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1271 if (rt->state == RTSP_STATE_PAUSED) {
1272 snprintf(cmd, sizeof(cmd),
1273 "PLAY %s RTSP/1.0\r\n",
1276 snprintf(cmd, sizeof(cmd),
1277 "PLAY %s RTSP/1.0\r\n"
1278 "Range: npt=%0.3f-\r\n",
1280 (double)rt->seek_timestamp / AV_TIME_BASE);
1282 ff_rtsp_send_cmd(s, cmd, reply, NULL);
1283 if (reply->status_code != RTSP_STATUS_OK) {
1287 rt->state = RTSP_STATE_STREAMING;
1291 static int rtsp_setup_input_streams(AVFormatContext *s)
1293 RTSPState *rt = s->priv_data;
1294 RTSPMessageHeader reply1, *reply = &reply1;
1296 unsigned char *content = NULL;
1299 /* describe the stream */
1300 snprintf(cmd, sizeof(cmd),
1301 "DESCRIBE %s RTSP/1.0\r\n"
1302 "Accept: application/sdp\r\n",
1304 if (rt->server_type == RTSP_SERVER_REAL) {
1306 * The Require: attribute is needed for proper streaming from
1307 * Realmedia servers.
1310 "Require: com.real.retain-entity-for-setup\r\n",
1313 ff_rtsp_send_cmd(s, cmd, reply, &content);
1315 return AVERROR_INVALIDDATA;
1316 if (reply->status_code != RTSP_STATUS_OK) {
1318 return AVERROR_INVALIDDATA;
1321 /* now we got the SDP description, we parse it */
1322 ret = sdp_parse(s, (const char *)content);
1325 return AVERROR_INVALIDDATA;
1330 static int rtsp_setup_output_streams(AVFormatContext *s)
1332 RTSPState *rt = s->priv_data;
1333 RTSPMessageHeader reply1, *reply = &reply1;
1338 /* Announce the stream */
1339 snprintf(cmd, sizeof(cmd),
1340 "ANNOUNCE %s RTSP/1.0\r\n"
1341 "Content-Type: application/sdp\r\n",
1343 sdp = av_mallocz(8192);
1345 return AVERROR(ENOMEM);
1346 if (avf_sdp_create(&s, 1, sdp, 8192)) {
1348 return AVERROR_INVALIDDATA;
1350 av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
1351 ff_rtsp_send_cmd_with_content(s, cmd, reply, NULL, sdp, strlen(sdp));
1353 if (reply->status_code != RTSP_STATUS_OK)
1354 return AVERROR_INVALIDDATA;
1356 /* Set up the RTSPStreams for each AVStream */
1357 for (i = 0; i < s->nb_streams; i++) {
1358 RTSPStream *rtsp_st;
1359 AVStream *st = s->streams[i];
1361 rtsp_st = av_mallocz(sizeof(RTSPStream));
1363 return AVERROR(ENOMEM);
1364 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
1366 st->priv_data = rtsp_st;
1367 rtsp_st->stream_index = i;
1369 av_strlcpy(rtsp_st->control_url, s->filename, sizeof(rtsp_st->control_url));
1370 /* Note, this must match the relative uri set in the sdp content */
1371 av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
1378 int ff_rtsp_connect(AVFormatContext *s)
1380 RTSPState *rt = s->priv_data;
1381 char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1382 char *option_list, *option, *filename;
1383 URLContext *rtsp_hd;
1385 RTSPMessageHeader reply1, *reply = &reply1;
1386 int lower_transport_mask = 0;
1387 char real_challenge[64];
1389 if (!ff_network_init())
1390 return AVERROR(EIO);
1392 /* extract hostname and port */
1393 url_split(NULL, 0, auth, sizeof(auth),
1394 host, sizeof(host), &port, path, sizeof(path), s->filename);
1396 int auth_len = strlen(auth), b64_len = ((auth_len + 2) / 3) * 4 + 1;
1398 if (!(rt->auth_b64 = av_malloc(b64_len)))
1399 return AVERROR(ENOMEM);
1400 if (!av_base64_encode(rt->auth_b64, b64_len, auth, auth_len)) {
1401 err = AVERROR(EINVAL);
1406 port = RTSP_DEFAULT_PORT;
1408 /* search for options */
1409 option_list = strchr(path, '?');
1411 filename = strchr(s->filename, '?');
1412 while (option_list) {
1413 /* move the option pointer */
1414 option = ++option_list;
1415 option_list = strchr(option_list, '&');
1419 /* handle the options */
1420 if (!strcmp(option, "udp")) {
1421 lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP);
1422 } else if (!strcmp(option, "multicast")) {
1423 lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
1424 } else if (!strcmp(option, "tcp")) {
1425 lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_TCP);
1427 strcpy(++filename, option);
1428 filename += strlen(option);
1429 if (option_list) *filename = '&';
1435 if (!lower_transport_mask)
1436 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1439 /* Only UDP output is supported at the moment. */
1440 lower_transport_mask &= 1 << RTSP_LOWER_TRANSPORT_UDP;
1441 if (!lower_transport_mask) {
1442 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1443 "only UDP is supported for output.\n");
1444 err = AVERROR(EINVAL);
1449 /* open the tcp connexion */
1450 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
1451 if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0) {
1455 rt->rtsp_hd = rtsp_hd;
1458 /* request options supported by the server; this also detects server
1460 av_strlcpy(rt->control_uri, s->filename,
1461 sizeof(rt->control_uri));
1462 for (rt->server_type = RTSP_SERVER_RTP;;) {
1463 snprintf(cmd, sizeof(cmd),
1464 "OPTIONS %s RTSP/1.0\r\n", s->filename);
1465 if (rt->server_type == RTSP_SERVER_REAL)
1468 * The following entries are required for proper
1469 * streaming from a Realmedia server. They are
1470 * interdependent in some way although we currently
1471 * don't quite understand how. Values were copied
1472 * from mplayer SVN r23589.
1473 * @param CompanyID is a 16-byte ID in base64
1474 * @param ClientChallenge is a 16-byte ID in hex
1476 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1477 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1478 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1479 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1481 ff_rtsp_send_cmd(s, cmd, reply, NULL);
1482 if (reply->status_code != RTSP_STATUS_OK) {
1483 err = AVERROR_INVALIDDATA;
1487 /* detect server type if not standard-compliant RTP */
1488 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1489 rt->server_type = RTSP_SERVER_REAL;
1491 } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1492 rt->server_type = RTSP_SERVER_WMS;
1493 } else if (rt->server_type == RTSP_SERVER_REAL)
1494 strcpy(real_challenge, reply->real_challenge);
1499 err = rtsp_setup_input_streams(s);
1501 err = rtsp_setup_output_streams(s);
1506 int lower_transport = ff_log2_tab[lower_transport_mask &
1507 ~(lower_transport_mask - 1)];
1509 err = make_setup_request(s, host, port, lower_transport,
1510 rt->server_type == RTSP_SERVER_REAL ?
1511 real_challenge : NULL);
1514 lower_transport_mask &= ~(1 << lower_transport);
1515 if (lower_transport_mask == 0 && err == 1) {
1516 err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
1521 rt->state = RTSP_STATE_IDLE;
1522 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1525 ff_rtsp_close_streams(s);
1526 url_close(rt->rtsp_hd);
1527 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1528 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1529 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1539 #if CONFIG_RTSP_DEMUXER
1540 static int rtsp_read_header(AVFormatContext *s,
1541 AVFormatParameters *ap)
1543 RTSPState *rt = s->priv_data;
1546 ret = ff_rtsp_connect(s);
1550 if (ap->initial_pause) {
1551 /* do not start immediately */
1553 if (rtsp_read_play(s) < 0) {
1554 ff_rtsp_close_streams(s);
1555 url_close(rt->rtsp_hd);
1556 return AVERROR_INVALIDDATA;
1563 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1564 uint8_t *buf, int buf_size)
1566 RTSPState *rt = s->priv_data;
1567 RTSPStream *rtsp_st;
1569 int fd, fd_max, n, i, ret, tcp_fd;
1573 if (url_interrupt_cb())
1574 return AVERROR(EINTR);
1577 tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
1578 FD_SET(tcp_fd, &rfds);
1583 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1584 rtsp_st = rt->rtsp_streams[i];
1585 if (rtsp_st->rtp_handle) {
1586 /* currently, we cannot probe RTCP handle because of
1587 * blocking restrictions */
1588 fd = url_get_file_handle(rtsp_st->rtp_handle);
1595 tv.tv_usec = 100 * 1000;
1596 n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1598 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1599 rtsp_st = rt->rtsp_streams[i];
1600 if (rtsp_st->rtp_handle) {
1601 fd = url_get_file_handle(rtsp_st->rtp_handle);
1602 if (FD_ISSET(fd, &rfds)) {
1603 ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1605 *prtsp_st = rtsp_st;
1611 #if CONFIG_RTSP_DEMUXER
1612 if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
1613 RTSPMessageHeader reply;
1615 ff_rtsp_read_reply(s, &reply, NULL, 0);
1616 /* XXX: parse message */
1617 if (rt->state != RTSP_STATE_STREAMING)
1625 static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1626 uint8_t *buf, int buf_size)
1628 RTSPState *rt = s->priv_data;
1629 int id, len, i, ret;
1630 RTSPStream *rtsp_st;
1632 #ifdef DEBUG_RTP_TCP
1633 dprintf(s, "tcp_read_packet:\n");
1637 RTSPMessageHeader reply;
1639 ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
1642 if (ret == 1) /* received '$' */
1644 /* XXX: parse message */
1645 if (rt->state != RTSP_STATE_STREAMING)
1648 ret = url_read_complete(rt->rtsp_hd, buf, 3);
1652 len = AV_RB16(buf + 1);
1653 #ifdef DEBUG_RTP_TCP
1654 dprintf(s, "id=%d len=%d\n", id, len);
1656 if (len > buf_size || len < 12)
1659 ret = url_read_complete(rt->rtsp_hd, buf, len);
1662 if (rt->transport == RTSP_TRANSPORT_RDT &&
1663 ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
1666 /* find the matching stream */
1667 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1668 rtsp_st = rt->rtsp_streams[i];
1669 if (id >= rtsp_st->interleaved_min &&
1670 id <= rtsp_st->interleaved_max)
1675 *prtsp_st = rtsp_st;
1679 static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1681 RTSPState *rt = s->priv_data;
1683 uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
1684 RTSPStream *rtsp_st;
1686 /* get next frames from the same RTP packet */
1687 if (rt->cur_transport_priv) {
1688 if (rt->transport == RTSP_TRANSPORT_RDT) {
1689 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1691 ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1693 rt->cur_transport_priv = NULL;
1695 } else if (ret == 1) {
1698 rt->cur_transport_priv = NULL;
1701 /* read next RTP packet */
1703 switch(rt->lower_transport) {
1705 #if CONFIG_RTSP_DEMUXER
1706 case RTSP_LOWER_TRANSPORT_TCP:
1707 len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1710 case RTSP_LOWER_TRANSPORT_UDP:
1711 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1712 len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1713 if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1714 rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1721 if (rt->transport == RTSP_TRANSPORT_RDT) {
1722 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
1724 ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
1728 /* more packets may follow, so we save the RTP context */
1729 rt->cur_transport_priv = rtsp_st->transport_priv;
1734 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
1736 RTSPState *rt = s->priv_data;
1738 RTSPMessageHeader reply1, *reply = &reply1;
1741 if (rt->server_type == RTSP_SERVER_REAL) {
1743 enum AVDiscard cache[MAX_STREAMS];
1745 for (i = 0; i < s->nb_streams; i++)
1746 cache[i] = s->streams[i]->discard;
1748 if (!rt->need_subscription) {
1749 if (memcmp (cache, rt->real_setup_cache,
1750 sizeof(enum AVDiscard) * s->nb_streams)) {
1751 snprintf(cmd, sizeof(cmd),
1752 "SET_PARAMETER %s RTSP/1.0\r\n"
1753 "Unsubscribe: %s\r\n",
1754 rt->control_uri, rt->last_subscription);
1755 ff_rtsp_send_cmd(s, cmd, reply, NULL);
1756 if (reply->status_code != RTSP_STATUS_OK)
1757 return AVERROR_INVALIDDATA;
1758 rt->need_subscription = 1;
1762 if (rt->need_subscription) {
1763 int r, rule_nr, first = 1;
1765 memcpy(rt->real_setup_cache, cache,
1766 sizeof(enum AVDiscard) * s->nb_streams);
1767 rt->last_subscription[0] = 0;
1769 snprintf(cmd, sizeof(cmd),
1770 "SET_PARAMETER %s RTSP/1.0\r\n"
1773 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1775 for (r = 0; r < s->nb_streams; r++) {
1776 if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
1777 if (s->streams[r]->discard != AVDISCARD_ALL) {
1779 av_strlcat(rt->last_subscription, ",",
1780 sizeof(rt->last_subscription));
1781 ff_rdt_subscribe_rule(
1782 rt->last_subscription,
1783 sizeof(rt->last_subscription), i, rule_nr);
1790 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
1791 ff_rtsp_send_cmd(s, cmd, reply, NULL);
1792 if (reply->status_code != RTSP_STATUS_OK)
1793 return AVERROR_INVALIDDATA;
1794 rt->need_subscription = 0;
1796 if (rt->state == RTSP_STATE_STREAMING)
1801 ret = rtsp_fetch_packet(s, pkt);
1805 /* send dummy request to keep TCP connection alive */
1806 if ((rt->server_type == RTSP_SERVER_WMS ||
1807 rt->server_type == RTSP_SERVER_REAL) &&
1808 (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
1809 if (rt->server_type == RTSP_SERVER_WMS) {
1810 snprintf(cmd, sizeof(cmd) - 1,
1811 "GET_PARAMETER %s RTSP/1.0\r\n",
1813 ff_rtsp_send_cmd_async(s, cmd);
1815 ff_rtsp_send_cmd_async(s, "OPTIONS * RTSP/1.0\r\n");
1822 /* pause the stream */
1823 static int rtsp_read_pause(AVFormatContext *s)
1825 RTSPState *rt = s->priv_data;
1826 RTSPMessageHeader reply1, *reply = &reply1;
1831 if (rt->state != RTSP_STATE_STREAMING)
1833 else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1834 snprintf(cmd, sizeof(cmd),
1835 "PAUSE %s RTSP/1.0\r\n",
1837 ff_rtsp_send_cmd(s, cmd, reply, NULL);
1838 if (reply->status_code != RTSP_STATUS_OK) {
1842 rt->state = RTSP_STATE_PAUSED;
1846 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1847 int64_t timestamp, int flags)
1849 RTSPState *rt = s->priv_data;
1851 rt->seek_timestamp = av_rescale_q(timestamp,
1852 s->streams[stream_index]->time_base,
1856 case RTSP_STATE_IDLE:
1858 case RTSP_STATE_STREAMING:
1859 if (rtsp_read_pause(s) != 0)
1861 rt->state = RTSP_STATE_SEEKING;
1862 if (rtsp_read_play(s) != 0)
1865 case RTSP_STATE_PAUSED:
1866 rt->state = RTSP_STATE_IDLE;
1872 static int rtsp_read_close(AVFormatContext *s)
1874 RTSPState *rt = s->priv_data;
1878 /* NOTE: it is valid to flush the buffer here */
1879 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1880 url_fclose(&rt->rtsp_gb);
1883 snprintf(cmd, sizeof(cmd),
1884 "TEARDOWN %s RTSP/1.0\r\n",
1886 ff_rtsp_send_cmd_async(s, cmd);
1888 ff_rtsp_close_streams(s);
1889 url_close(rt->rtsp_hd);
1894 AVInputFormat rtsp_demuxer = {
1896 NULL_IF_CONFIG_SMALL("RTSP input format"),
1903 .flags = AVFMT_NOFILE,
1904 .read_play = rtsp_read_play,
1905 .read_pause = rtsp_read_pause,
1909 static int sdp_probe(AVProbeData *p1)
1911 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
1913 /* we look for a line beginning "c=IN IP4" */
1914 while (p < p_end && *p != '\0') {
1915 if (p + sizeof("c=IN IP4") - 1 < p_end &&
1916 av_strstart(p, "c=IN IP4", NULL))
1917 return AVPROBE_SCORE_MAX / 2;
1919 while (p < p_end - 1 && *p != '\n') p++;
1928 #define SDP_MAX_SIZE 8192
1930 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
1932 RTSPState *rt = s->priv_data;
1933 RTSPStream *rtsp_st;
1938 if (!ff_network_init())
1939 return AVERROR(EIO);
1941 /* read the whole sdp file */
1942 /* XXX: better loading */
1943 content = av_malloc(SDP_MAX_SIZE);
1944 size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
1947 return AVERROR_INVALIDDATA;
1949 content[size] ='\0';
1951 sdp_parse(s, content);
1954 /* open each RTP stream */
1955 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1956 rtsp_st = rt->rtsp_streams[i];
1958 ff_url_join(url, sizeof(url), "rtp", NULL,
1959 inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
1960 "?localport=%d&ttl=%d", rtsp_st->sdp_port,
1962 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1963 err = AVERROR_INVALIDDATA;
1966 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1971 ff_rtsp_close_streams(s);
1976 static int sdp_read_close(AVFormatContext *s)
1978 ff_rtsp_close_streams(s);
1983 AVInputFormat sdp_demuxer = {
1985 NULL_IF_CONFIG_SMALL("SDP"),