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>
34 #include "os_support.h"
39 #include "rtpdec_asf.h"
40 #include "rtpdec_vorbis.h"
43 //#define DEBUG_RTP_TCP
45 #if LIBAVFORMAT_VERSION_INT < (53 << 16)
46 int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
49 /* Timeout values for socket select, in ms,
50 * and read_packet(), in seconds */
51 #define SELECT_TIMEOUT_MS 100
52 #define READ_PACKET_TIMEOUT_S 10
53 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
55 #define SPACE_CHARS " \t\r\n"
56 /* we use memchr() instead of strchr() here because strchr() will return
57 * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */
58 #define redir_isspace(c) memchr(SPACE_CHARS, c, 4)
59 static void skip_spaces(const char **pp)
63 while (redir_isspace(*p))
68 static void get_word_until_chars(char *buf, int buf_size,
69 const char *sep, const char **pp)
77 while (!strchr(sep, *p) && *p != '\0') {
78 if ((q - buf) < buf_size - 1)
87 static void get_word_sep(char *buf, int buf_size, const char *sep,
90 if (**pp == '/') (*pp)++;
91 get_word_until_chars(buf, buf_size, sep, pp);
94 static void get_word(char *buf, int buf_size, const char **pp)
96 get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
99 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
100 static int sdp_parse_rtpmap(AVFormatContext *s,
101 AVCodecContext *codec, RTSPStream *rtsp_st,
102 int payload_type, const char *p)
109 /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
110 * see if we can handle this kind of payload.
111 * The space should normally not be there but some Real streams or
112 * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
113 * have a trailing space. */
114 get_word_sep(buf, sizeof(buf), "/ ", &p);
115 if (payload_type >= RTP_PT_PRIVATE) {
116 RTPDynamicProtocolHandler *handler;
117 for (handler = RTPFirstDynamicPayloadHandler;
118 handler; handler = handler->next) {
119 if (!strcasecmp(buf, handler->enc_name) &&
120 codec->codec_type == handler->codec_type) {
121 codec->codec_id = handler->codec_id;
122 rtsp_st->dynamic_handler = handler;
124 rtsp_st->dynamic_protocol_context = handler->open();
129 /* We are in a standard case
130 * (from http://www.iana.org/assignments/rtp-parameters). */
131 /* search into AVRtpPayloadTypes[] */
132 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
135 c = avcodec_find_decoder(codec->codec_id);
141 get_word_sep(buf, sizeof(buf), "/", &p);
143 switch (codec->codec_type) {
144 case CODEC_TYPE_AUDIO:
145 av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
146 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
147 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
149 codec->sample_rate = i;
150 get_word_sep(buf, sizeof(buf), "/", &p);
154 // TODO: there is a bug here; if it is a mono stream, and
155 // less than 22000Hz, faad upconverts to stereo and twice
156 // the frequency. No problem, but the sample rate is being
157 // set here by the sdp line. Patch on its way. (rdm)
159 av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
161 av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
164 case CODEC_TYPE_VIDEO:
165 av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
173 /* return the length and optionally the data */
174 static int hex_to_data(uint8_t *data, const char *p)
184 c = toupper((unsigned char) *p++);
185 if (c >= '0' && c <= '9')
187 else if (c >= 'A' && c <= 'F')
202 static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx,
203 char *attr, char *value)
205 switch (codec->codec_id) {
208 if (!strcmp(attr, "config")) {
209 /* decode the hexa encoded parameter */
210 int len = hex_to_data(NULL, value);
211 if (codec->extradata)
212 av_free(codec->extradata);
213 codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
214 if (!codec->extradata)
216 codec->extradata_size = len;
217 hex_to_data(codec->extradata, value);
220 case CODEC_ID_VORBIS:
221 ff_vorbis_parse_fmtp_config(codec, ctx, attr, value);
235 /* All known fmtp parameters and the corresponding RTPAttrTypeEnum */
236 #define ATTR_NAME_TYPE_INT 0
237 #define ATTR_NAME_TYPE_STR 1
238 static const AttrNameMap attr_names[]=
240 { "SizeLength", ATTR_NAME_TYPE_INT,
241 offsetof(RTPPayloadData, sizelength) },
242 { "IndexLength", ATTR_NAME_TYPE_INT,
243 offsetof(RTPPayloadData, indexlength) },
244 { "IndexDeltaLength", ATTR_NAME_TYPE_INT,
245 offsetof(RTPPayloadData, indexdeltalength) },
246 { "profile-level-id", ATTR_NAME_TYPE_INT,
247 offsetof(RTPPayloadData, profile_level_id) },
248 { "StreamType", ATTR_NAME_TYPE_INT,
249 offsetof(RTPPayloadData, streamtype) },
250 { "mode", ATTR_NAME_TYPE_STR,
251 offsetof(RTPPayloadData, mode) },
255 /* parse the attribute line from the fmtp a line of an sdp response. This
256 * is broken out as a function because it is used in rtp_h264.c, which is
258 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
259 char *value, int value_size)
263 get_word_sep(attr, attr_size, "=", p);
266 get_word_sep(value, value_size, ";", p);
274 /* parse a SDP line and save stream attributes */
275 static void sdp_parse_fmtp(AVStream *st, const char *p)
278 /* Vorbis setup headers can be up to 12KB and are sent base64
279 * encoded, giving a 12KB * (4/3) = 16KB FMTP line. */
282 RTSPStream *rtsp_st = st->priv_data;
283 AVCodecContext *codec = st->codec;
284 RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data;
286 /* loop on each attribute */
287 while (ff_rtsp_next_attr_and_value(&p, attr, sizeof(attr),
288 value, sizeof(value))) {
289 /* grab the codec extra_data from the config parameter of the fmtp
291 sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context,
293 /* Looking for a known attribute */
294 for (i = 0; attr_names[i].str; ++i) {
295 if (!strcasecmp(attr, attr_names[i].str)) {
296 if (attr_names[i].type == ATTR_NAME_TYPE_INT) {
297 *(int *)((char *)rtp_payload_data +
298 attr_names[i].offset) = atoi(value);
299 } else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
300 *(char **)((char *)rtp_payload_data +
301 attr_names[i].offset) = av_strdup(value);
307 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
309 * Used for seeking in the rtp stream.
311 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
316 if (!av_stristart(p, "npt=", &p))
319 *start = AV_NOPTS_VALUE;
320 *end = AV_NOPTS_VALUE;
322 get_word_sep(buf, sizeof(buf), "-", &p);
323 *start = parse_date(buf, 1);
326 get_word_sep(buf, sizeof(buf), "-", &p);
327 *end = parse_date(buf, 1);
329 // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
330 // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
333 typedef struct SDPParseState {
335 struct in_addr default_ip;
337 int skip_media; ///< set if an unknown m= line occurs
340 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
341 int letter, const char *buf)
343 RTSPState *rt = s->priv_data;
344 char buf1[64], st_type[64];
346 enum CodecType codec_type;
350 struct in_addr sdp_ip;
353 dprintf(s, "sdp: %c='%s'\n", letter, buf);
356 if (s1->skip_media && letter != 'm')
360 get_word(buf1, sizeof(buf1), &p);
361 if (strcmp(buf1, "IN") != 0)
363 get_word(buf1, sizeof(buf1), &p);
364 if (strcmp(buf1, "IP4") != 0)
366 get_word_sep(buf1, sizeof(buf1), "/", &p);
367 if (ff_inet_aton(buf1, &sdp_ip) == 0)
372 get_word_sep(buf1, sizeof(buf1), "/", &p);
375 if (s->nb_streams == 0) {
376 s1->default_ip = sdp_ip;
377 s1->default_ttl = ttl;
379 st = s->streams[s->nb_streams - 1];
380 rtsp_st = st->priv_data;
381 rtsp_st->sdp_ip = sdp_ip;
382 rtsp_st->sdp_ttl = ttl;
386 av_metadata_set(&s->metadata, "title", p);
389 if (s->nb_streams == 0) {
390 av_metadata_set(&s->metadata, "comment", p);
397 get_word(st_type, sizeof(st_type), &p);
398 if (!strcmp(st_type, "audio")) {
399 codec_type = CODEC_TYPE_AUDIO;
400 } else if (!strcmp(st_type, "video")) {
401 codec_type = CODEC_TYPE_VIDEO;
402 } else if (!strcmp(st_type, "application")) {
403 codec_type = CODEC_TYPE_DATA;
408 rtsp_st = av_mallocz(sizeof(RTSPStream));
411 rtsp_st->stream_index = -1;
412 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
414 rtsp_st->sdp_ip = s1->default_ip;
415 rtsp_st->sdp_ttl = s1->default_ttl;
417 get_word(buf1, sizeof(buf1), &p); /* port */
418 rtsp_st->sdp_port = atoi(buf1);
420 get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
422 /* XXX: handle list of formats */
423 get_word(buf1, sizeof(buf1), &p); /* format list */
424 rtsp_st->sdp_payload_type = atoi(buf1);
426 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
427 /* no corresponding stream */
429 st = av_new_stream(s, 0);
432 st->priv_data = rtsp_st;
433 rtsp_st->stream_index = st->index;
434 st->codec->codec_type = codec_type;
435 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
436 /* if standard payload type, we can find the codec right now */
437 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
440 /* put a default control url */
441 av_strlcpy(rtsp_st->control_url, rt->control_uri,
442 sizeof(rtsp_st->control_url));
445 if (av_strstart(p, "control:", &p)) {
446 if (s->nb_streams == 0) {
447 if (!strncmp(p, "rtsp://", 7))
448 av_strlcpy(rt->control_uri, p,
449 sizeof(rt->control_uri));
452 /* get the control url */
453 st = s->streams[s->nb_streams - 1];
454 rtsp_st = st->priv_data;
456 /* XXX: may need to add full url resolution */
457 ff_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
459 if (proto[0] == '\0') {
460 /* relative control URL */
461 if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
462 av_strlcat(rtsp_st->control_url, "/",
463 sizeof(rtsp_st->control_url));
464 av_strlcat(rtsp_st->control_url, p,
465 sizeof(rtsp_st->control_url));
467 av_strlcpy(rtsp_st->control_url, p,
468 sizeof(rtsp_st->control_url));
470 } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
471 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
472 get_word(buf1, sizeof(buf1), &p);
473 payload_type = atoi(buf1);
474 st = s->streams[s->nb_streams - 1];
475 rtsp_st = st->priv_data;
476 sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
477 } else if (av_strstart(p, "fmtp:", &p)) {
478 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
479 get_word(buf1, sizeof(buf1), &p);
480 payload_type = atoi(buf1);
481 for (i = 0; i < s->nb_streams; i++) {
483 rtsp_st = st->priv_data;
484 if (rtsp_st->sdp_payload_type == payload_type) {
485 if (!(rtsp_st->dynamic_handler &&
486 rtsp_st->dynamic_handler->parse_sdp_a_line &&
487 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
488 i, rtsp_st->dynamic_protocol_context, buf)))
489 sdp_parse_fmtp(st, p);
492 } else if (av_strstart(p, "framesize:", &p)) {
493 // let dynamic protocol handlers have a stab at the line.
494 get_word(buf1, sizeof(buf1), &p);
495 payload_type = atoi(buf1);
496 for (i = 0; i < s->nb_streams; i++) {
498 rtsp_st = st->priv_data;
499 if (rtsp_st->sdp_payload_type == payload_type &&
500 rtsp_st->dynamic_handler &&
501 rtsp_st->dynamic_handler->parse_sdp_a_line)
502 rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
503 rtsp_st->dynamic_protocol_context, buf);
505 } else if (av_strstart(p, "range:", &p)) {
508 // this is so that seeking on a streamed file can work.
509 rtsp_parse_range_npt(p, &start, &end);
510 s->start_time = start;
511 /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
512 s->duration = (end == AV_NOPTS_VALUE) ?
513 AV_NOPTS_VALUE : end - start;
514 } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
516 rt->transport = RTSP_TRANSPORT_RDT;
518 if (rt->server_type == RTSP_SERVER_WMS)
519 ff_wms_parse_sdp_a_line(s, p);
520 if (s->nb_streams > 0) {
521 if (rt->server_type == RTSP_SERVER_REAL)
522 ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
524 rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
525 if (rtsp_st->dynamic_handler &&
526 rtsp_st->dynamic_handler->parse_sdp_a_line)
527 rtsp_st->dynamic_handler->parse_sdp_a_line(s,
529 rtsp_st->dynamic_protocol_context, buf);
536 static int sdp_parse(AVFormatContext *s, const char *content)
540 /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
541 * contain long SDP lines containing complete ASF Headers (several
542 * kB) or arrays of MDPR (RM stream descriptor) headers plus
543 * "rulebooks" describing their properties. Therefore, the SDP line
546 * The Vorbis FMTP line can be up to 16KB - see sdp_parse_fmtp. */
548 SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
550 memset(s1, 0, sizeof(SDPParseState));
561 /* get the content */
563 while (*p != '\n' && *p != '\r' && *p != '\0') {
564 if ((q - buf) < sizeof(buf) - 1)
569 sdp_parse_line(s, s1, letter, buf);
571 while (*p != '\n' && *p != '\0')
579 /* close and free RTSP streams */
580 void ff_rtsp_close_streams(AVFormatContext *s)
582 RTSPState *rt = s->priv_data;
586 for (i = 0; i < rt->nb_rtsp_streams; i++) {
587 rtsp_st = rt->rtsp_streams[i];
589 if (rtsp_st->transport_priv) {
591 AVFormatContext *rtpctx = rtsp_st->transport_priv;
592 av_write_trailer(rtpctx);
593 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
595 url_close_dyn_buf(rtpctx->pb, &ptr);
598 url_fclose(rtpctx->pb);
600 av_metadata_free(&rtpctx->streams[0]->metadata);
601 av_metadata_free(&rtpctx->metadata);
602 av_free(rtpctx->streams[0]);
604 } else if (rt->transport == RTSP_TRANSPORT_RDT)
605 ff_rdt_parse_close(rtsp_st->transport_priv);
607 rtp_parse_close(rtsp_st->transport_priv);
609 if (rtsp_st->rtp_handle)
610 url_close(rtsp_st->rtp_handle);
611 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
612 rtsp_st->dynamic_handler->close(
613 rtsp_st->dynamic_protocol_context);
616 av_free(rt->rtsp_streams);
618 av_close_input_stream (rt->asf_ctx);
623 static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st,
626 RTSPState *rt = s->priv_data;
627 AVFormatContext *rtpctx;
629 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
634 /* Allocate an AVFormatContext for each output stream */
635 rtpctx = avformat_alloc_context();
639 rtpctx->oformat = rtp_format;
640 if (!av_new_stream(rtpctx, 0)) {
644 /* Copy the max delay setting; the rtp muxer reads this. */
645 rtpctx->max_delay = s->max_delay;
646 /* Copy other stream parameters. */
647 rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
649 /* Set the synchronized start time. */
650 rtpctx->start_time_realtime = rt->start_time;
652 /* Remove the local codec, link to the original codec
653 * context instead, to give the rtp muxer access to
654 * codec parameters. */
655 av_free(rtpctx->streams[0]->codec);
656 rtpctx->streams[0]->codec = st->codec;
659 url_fdopen(&rtpctx->pb, handle);
661 url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
662 ret = av_write_header(rtpctx);
666 url_fclose(rtpctx->pb);
669 url_close_dyn_buf(rtpctx->pb, &ptr);
672 av_free(rtpctx->streams[0]);
677 /* Copy the RTP AVStream timebase back to the original AVStream */
678 st->time_base = rtpctx->streams[0]->time_base;
682 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
684 RTSPState *rt = s->priv_data;
687 /* open the RTP context */
688 if (rtsp_st->stream_index >= 0)
689 st = s->streams[rtsp_st->stream_index];
691 s->ctx_flags |= AVFMTCTX_NOHEADER;
694 rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
695 /* Ownership of rtp_handle is passed to the rtp mux context */
696 rtsp_st->rtp_handle = NULL;
697 } else if (rt->transport == RTSP_TRANSPORT_RDT)
698 rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
699 rtsp_st->dynamic_protocol_context,
700 rtsp_st->dynamic_handler);
702 rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
703 rtsp_st->sdp_payload_type,
704 &rtsp_st->rtp_payload_data);
706 if (!rtsp_st->transport_priv) {
707 return AVERROR(ENOMEM);
708 } else if (rt->transport != RTSP_TRANSPORT_RDT) {
709 if (rtsp_st->dynamic_handler) {
710 rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
711 rtsp_st->dynamic_protocol_context,
712 rtsp_st->dynamic_handler);
719 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
720 static int rtsp_probe(AVProbeData *p)
722 if (av_strstart(p->filename, "rtsp:", NULL))
723 return AVPROBE_SCORE_MAX;
727 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
734 v = strtol(p, (char **)&p, 10);
738 v = strtol(p, (char **)&p, 10);
747 /* XXX: only one transport specification is parsed */
748 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
750 char transport_protocol[16];
752 char lower_transport[16];
754 RTSPTransportField *th;
757 reply->nb_transports = 0;
764 th = &reply->transports[reply->nb_transports];
766 get_word_sep(transport_protocol, sizeof(transport_protocol),
768 if (!strcasecmp (transport_protocol, "rtp")) {
769 get_word_sep(profile, sizeof(profile), "/;,", &p);
770 lower_transport[0] = '\0';
771 /* rtp/avp/<protocol> */
773 get_word_sep(lower_transport, sizeof(lower_transport),
776 th->transport = RTSP_TRANSPORT_RTP;
777 } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
778 !strcasecmp (transport_protocol, "x-real-rdt")) {
779 /* x-pn-tng/<protocol> */
780 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
782 th->transport = RTSP_TRANSPORT_RDT;
784 if (!strcasecmp(lower_transport, "TCP"))
785 th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
787 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
791 /* get each parameter */
792 while (*p != '\0' && *p != ',') {
793 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
794 if (!strcmp(parameter, "port")) {
797 rtsp_parse_range(&th->port_min, &th->port_max, &p);
799 } else if (!strcmp(parameter, "client_port")) {
802 rtsp_parse_range(&th->client_port_min,
803 &th->client_port_max, &p);
805 } else if (!strcmp(parameter, "server_port")) {
808 rtsp_parse_range(&th->server_port_min,
809 &th->server_port_max, &p);
811 } else if (!strcmp(parameter, "interleaved")) {
814 rtsp_parse_range(&th->interleaved_min,
815 &th->interleaved_max, &p);
817 } else if (!strcmp(parameter, "multicast")) {
818 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
819 th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
820 } else if (!strcmp(parameter, "ttl")) {
823 th->ttl = strtol(p, (char **)&p, 10);
825 } else if (!strcmp(parameter, "destination")) {
826 struct in_addr ipaddr;
830 get_word_sep(buf, sizeof(buf), ";,", &p);
831 if (ff_inet_aton(buf, &ipaddr))
832 th->destination = ntohl(ipaddr.s_addr);
835 while (*p != ';' && *p != '\0' && *p != ',')
843 reply->nb_transports++;
847 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
848 HTTPAuthState *auth_state)
852 /* NOTE: we do case independent match for broken servers */
854 if (av_stristart(p, "Session:", &p)) {
856 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
857 if (av_stristart(p, ";timeout=", &p) &&
858 (t = strtol(p, NULL, 10)) > 0) {
861 } else if (av_stristart(p, "Content-Length:", &p)) {
862 reply->content_length = strtol(p, NULL, 10);
863 } else if (av_stristart(p, "Transport:", &p)) {
864 rtsp_parse_transport(reply, p);
865 } else if (av_stristart(p, "CSeq:", &p)) {
866 reply->seq = strtol(p, NULL, 10);
867 } else if (av_stristart(p, "Range:", &p)) {
868 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
869 } else if (av_stristart(p, "RealChallenge1:", &p)) {
871 av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
872 } else if (av_stristart(p, "Server:", &p)) {
874 av_strlcpy(reply->server, p, sizeof(reply->server));
875 } else if (av_stristart(p, "Notice:", &p) ||
876 av_stristart(p, "X-Notice:", &p)) {
877 reply->notice = strtol(p, NULL, 10);
878 } else if (av_stristart(p, "Location:", &p)) {
880 av_strlcpy(reply->location, p , sizeof(reply->location));
881 } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
883 ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
884 } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
886 ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
890 /* skip a RTP/TCP interleaved packet */
891 void ff_rtsp_skip_packet(AVFormatContext *s)
893 RTSPState *rt = s->priv_data;
897 ret = url_read_complete(rt->rtsp_hd, buf, 3);
900 len = AV_RB16(buf + 1);
902 dprintf(s, "skipping RTP packet len=%d\n", len);
907 if (len1 > sizeof(buf))
909 ret = url_read_complete(rt->rtsp_hd, buf, len1);
916 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
917 unsigned char **content_ptr,
918 int return_on_interleaved_data)
920 RTSPState *rt = s->priv_data;
921 char buf[4096], buf1[1024], *q;
924 int ret, content_length, line_count = 0;
925 unsigned char *content = NULL;
927 memset(reply, 0, sizeof(*reply));
929 /* parse reply (XXX: use buffers) */
930 rt->last_reply[0] = '\0';
934 ret = url_read_complete(rt->rtsp_hd, &ch, 1);
936 dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
943 /* XXX: only parse it if first char on line ? */
944 if (return_on_interleaved_data) {
947 ff_rtsp_skip_packet(s);
948 } else if (ch != '\r') {
949 if ((q - buf) < sizeof(buf) - 1)
955 dprintf(s, "line='%s'\n", buf);
957 /* test if last line */
961 if (line_count == 0) {
963 get_word(buf1, sizeof(buf1), &p);
964 get_word(buf1, sizeof(buf1), &p);
965 reply->status_code = atoi(buf1);
967 ff_rtsp_parse_line(reply, p, &rt->auth_state);
968 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
969 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
974 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
975 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
977 content_length = reply->content_length;
978 if (content_length > 0) {
979 /* leave some room for a trailing '\0' (useful for simple parsing) */
980 content = av_malloc(content_length + 1);
981 (void)url_read_complete(rt->rtsp_hd, content, content_length);
982 content[content_length] = '\0';
985 *content_ptr = content;
989 if (rt->seq != reply->seq) {
990 av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
991 rt->seq, reply->seq);
995 if (reply->notice == 2101 /* End-of-Stream Reached */ ||
996 reply->notice == 2104 /* Start-of-Stream Reached */ ||
997 reply->notice == 2306 /* Continuous Feed Terminated */) {
998 rt->state = RTSP_STATE_IDLE;
999 } else if (reply->notice >= 4400 && reply->notice < 5500) {
1000 return AVERROR(EIO); /* data or server error */
1001 } else if (reply->notice == 2401 /* Ticket Expired */ ||
1002 (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
1003 return AVERROR(EPERM);
1008 void ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
1009 const char *method, const char *url,
1010 const char *headers,
1011 const unsigned char *send_content,
1012 int send_content_length)
1014 RTSPState *rt = s->priv_data;
1018 snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
1020 av_strlcat(buf, headers, sizeof(buf));
1021 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
1022 if (rt->session_id[0] != '\0' && (!headers ||
1023 !strstr(headers, "\nIf-Match:"))) {
1024 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
1027 char *str = ff_http_auth_create_response(&rt->auth_state,
1028 rt->auth, url, method);
1030 av_strlcat(buf, str, sizeof(buf));
1033 if (send_content_length > 0 && send_content)
1034 av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
1035 av_strlcat(buf, "\r\n", sizeof(buf));
1037 dprintf(s, "Sending:\n%s--\n", buf);
1039 url_write(rt->rtsp_hd, buf, strlen(buf));
1040 if (send_content_length > 0 && send_content)
1041 url_write(rt->rtsp_hd, send_content, send_content_length);
1042 rt->last_cmd_time = av_gettime();
1045 void ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
1046 const char *url, const char *headers)
1048 ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
1051 void ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
1052 const char *headers, RTSPMessageHeader *reply,
1053 unsigned char **content_ptr)
1055 ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
1056 content_ptr, NULL, 0);
1059 void ff_rtsp_send_cmd_with_content(AVFormatContext *s,
1060 const char *method, const char *url,
1062 RTSPMessageHeader *reply,
1063 unsigned char **content_ptr,
1064 const unsigned char *send_content,
1065 int send_content_length)
1067 RTSPState *rt = s->priv_data;
1068 HTTPAuthType cur_auth_type;
1071 cur_auth_type = rt->auth_state.auth_type;
1072 ff_rtsp_send_cmd_with_content_async(s, method, url, header,
1073 send_content, send_content_length);
1075 ff_rtsp_read_reply(s, reply, content_ptr, 0);
1077 if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
1078 rt->auth_state.auth_type != HTTP_AUTH_NONE)
1083 * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
1085 static int make_setup_request(AVFormatContext *s, const char *host, int port,
1086 int lower_transport, const char *real_challenge)
1088 RTSPState *rt = s->priv_data;
1089 int rtx, j, i, err, interleave = 0;
1090 RTSPStream *rtsp_st;
1091 RTSPMessageHeader reply1, *reply = &reply1;
1093 const char *trans_pref;
1095 if (rt->transport == RTSP_TRANSPORT_RDT)
1096 trans_pref = "x-pn-tng";
1098 trans_pref = "RTP/AVP";
1100 /* default timeout: 1 minute */
1103 /* for each stream, make the setup request */
1104 /* XXX: we assume the same server is used for the control of each
1107 for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
1108 char transport[2048];
1111 * WMS serves all UDP data over a single connection, the RTX, which
1112 * isn't necessarily the first in the SDP but has to be the first
1113 * to be set up, else the second/third SETUP will fail with a 461.
1115 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1116 rt->server_type == RTSP_SERVER_WMS) {
1119 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1120 int len = strlen(rt->rtsp_streams[rtx]->control_url);
1122 !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1126 if (rtx == rt->nb_rtsp_streams)
1127 return -1; /* no RTX found */
1128 rtsp_st = rt->rtsp_streams[rtx];
1130 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1132 rtsp_st = rt->rtsp_streams[i];
1135 if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1138 if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1139 port = reply->transports[0].client_port_min;
1143 /* first try in specified port range */
1144 if (RTSP_RTP_PORT_MIN != 0) {
1145 while (j <= RTSP_RTP_PORT_MAX) {
1146 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1147 "?localport=%d", j);
1148 /* we will use two ports per rtp stream (rtp and rtcp) */
1150 if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
1156 /* then try on any port */
1157 if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
1158 err = AVERROR_INVALIDDATA;
1164 port = rtp_get_local_port(rtsp_st->rtp_handle);
1166 snprintf(transport, sizeof(transport) - 1,
1167 "%s/UDP;", trans_pref);
1168 if (rt->server_type != RTSP_SERVER_REAL)
1169 av_strlcat(transport, "unicast;", sizeof(transport));
1170 av_strlcatf(transport, sizeof(transport),
1171 "client_port=%d", port);
1172 if (rt->transport == RTSP_TRANSPORT_RTP &&
1173 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1174 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1178 else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1179 /** For WMS streams, the application streams are only used for
1180 * UDP. When trying to set it up for TCP streams, the server
1181 * will return an error. Therefore, we skip those streams. */
1182 if (rt->server_type == RTSP_SERVER_WMS &&
1183 s->streams[rtsp_st->stream_index]->codec->codec_type ==
1186 snprintf(transport, sizeof(transport) - 1,
1187 "%s/TCP;", trans_pref);
1188 if (rt->server_type == RTSP_SERVER_WMS)
1189 av_strlcat(transport, "unicast;", sizeof(transport));
1190 av_strlcatf(transport, sizeof(transport),
1191 "interleaved=%d-%d",
1192 interleave, interleave + 1);
1196 else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1197 snprintf(transport, sizeof(transport) - 1,
1198 "%s/UDP;multicast", trans_pref);
1201 av_strlcat(transport, ";mode=receive", sizeof(transport));
1202 } else if (rt->server_type == RTSP_SERVER_REAL ||
1203 rt->server_type == RTSP_SERVER_WMS)
1204 av_strlcat(transport, ";mode=play", sizeof(transport));
1205 snprintf(cmd, sizeof(cmd),
1206 "Transport: %s\r\n",
1208 if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
1209 char real_res[41], real_csum[9];
1210 ff_rdt_calc_response_and_checksum(real_res, real_csum,
1212 av_strlcatf(cmd, sizeof(cmd),
1214 "RealChallenge2: %s, sd=%s\r\n",
1215 rt->session_id, real_res, real_csum);
1217 ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1218 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1221 } else if (reply->status_code != RTSP_STATUS_OK ||
1222 reply->nb_transports != 1) {
1223 err = AVERROR_INVALIDDATA;
1227 /* XXX: same protocol for all streams is required */
1229 if (reply->transports[0].lower_transport != rt->lower_transport ||
1230 reply->transports[0].transport != rt->transport) {
1231 err = AVERROR_INVALIDDATA;
1235 rt->lower_transport = reply->transports[0].lower_transport;
1236 rt->transport = reply->transports[0].transport;
1239 /* close RTP connection if not choosen */
1240 if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
1241 (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
1242 url_close(rtsp_st->rtp_handle);
1243 rtsp_st->rtp_handle = NULL;
1246 switch(reply->transports[0].lower_transport) {
1247 case RTSP_LOWER_TRANSPORT_TCP:
1248 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1249 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1252 case RTSP_LOWER_TRANSPORT_UDP: {
1255 /* XXX: also use address if specified */
1256 ff_url_join(url, sizeof(url), "rtp", NULL, host,
1257 reply->transports[0].server_port_min, NULL);
1258 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1259 rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1260 err = AVERROR_INVALIDDATA;
1263 /* Try to initialize the connection state in a
1264 * potential NAT router by sending dummy packets.
1265 * RTP/RTCP dummy packets are used for RDT, too.
1267 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
1268 rtp_send_punch_packets(rtsp_st->rtp_handle);
1271 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1276 if (reply->transports[0].destination) {
1277 in.s_addr = htonl(reply->transports[0].destination);
1278 port = reply->transports[0].port_min;
1279 ttl = reply->transports[0].ttl;
1281 in = rtsp_st->sdp_ip;
1282 port = rtsp_st->sdp_port;
1283 ttl = rtsp_st->sdp_ttl;
1285 ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in),
1286 port, "?ttl=%d", ttl);
1287 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1288 err = AVERROR_INVALIDDATA;
1295 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1299 if (reply->timeout > 0)
1300 rt->timeout = reply->timeout;
1302 if (rt->server_type == RTSP_SERVER_REAL)
1303 rt->need_subscription = 1;
1308 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1309 if (rt->rtsp_streams[i]->rtp_handle) {
1310 url_close(rt->rtsp_streams[i]->rtp_handle);
1311 rt->rtsp_streams[i]->rtp_handle = NULL;
1317 static int rtsp_read_play(AVFormatContext *s)
1319 RTSPState *rt = s->priv_data;
1320 RTSPMessageHeader reply1, *reply = &reply1;
1323 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1325 if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1326 if (rt->state == RTSP_STATE_PAUSED) {
1329 snprintf(cmd, sizeof(cmd),
1330 "Range: npt=%0.3f-\r\n",
1331 (double)rt->seek_timestamp / AV_TIME_BASE);
1333 ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
1334 if (reply->status_code != RTSP_STATUS_OK) {
1338 rt->state = RTSP_STATE_STREAMING;
1342 static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
1344 RTSPState *rt = s->priv_data;
1346 unsigned char *content = NULL;
1349 /* describe the stream */
1350 snprintf(cmd, sizeof(cmd),
1351 "Accept: application/sdp\r\n");
1352 if (rt->server_type == RTSP_SERVER_REAL) {
1354 * The Require: attribute is needed for proper streaming from
1355 * Realmedia servers.
1358 "Require: com.real.retain-entity-for-setup\r\n",
1361 ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
1363 return AVERROR_INVALIDDATA;
1364 if (reply->status_code != RTSP_STATUS_OK) {
1366 return AVERROR_INVALIDDATA;
1369 /* now we got the SDP description, we parse it */
1370 ret = sdp_parse(s, (const char *)content);
1373 return AVERROR_INVALIDDATA;
1378 static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
1380 RTSPState *rt = s->priv_data;
1381 RTSPMessageHeader reply1, *reply = &reply1;
1384 AVFormatContext sdp_ctx, *ctx_array[1];
1386 rt->start_time = av_gettime();
1388 /* Announce the stream */
1389 sdp = av_mallocz(8192);
1391 return AVERROR(ENOMEM);
1392 /* We create the SDP based on the RTSP AVFormatContext where we
1393 * aren't allowed to change the filename field. (We create the SDP
1394 * based on the RTSP context since the contexts for the RTP streams
1395 * don't exist yet.) In order to specify a custom URL with the actual
1396 * peer IP instead of the originally specified hostname, we create
1397 * a temporary copy of the AVFormatContext, where the custom URL is set.
1399 * FIXME: Create the SDP without copying the AVFormatContext.
1400 * This either requires setting up the RTP stream AVFormatContexts
1401 * already here (complicating things immensely) or getting a more
1402 * flexible SDP creation interface.
1405 ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
1406 "rtsp", NULL, addr, -1, NULL);
1407 ctx_array[0] = &sdp_ctx;
1408 if (avf_sdp_create(ctx_array, 1, sdp, 8192)) {
1410 return AVERROR_INVALIDDATA;
1412 av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
1413 ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
1414 "Content-Type: application/sdp\r\n",
1415 reply, NULL, sdp, strlen(sdp));
1417 if (reply->status_code != RTSP_STATUS_OK)
1418 return AVERROR_INVALIDDATA;
1420 /* Set up the RTSPStreams for each AVStream */
1421 for (i = 0; i < s->nb_streams; i++) {
1422 RTSPStream *rtsp_st;
1423 AVStream *st = s->streams[i];
1425 rtsp_st = av_mallocz(sizeof(RTSPStream));
1427 return AVERROR(ENOMEM);
1428 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
1430 st->priv_data = rtsp_st;
1431 rtsp_st->stream_index = i;
1433 av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
1434 /* Note, this must match the relative uri set in the sdp content */
1435 av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
1442 int ff_rtsp_connect(AVFormatContext *s)
1444 RTSPState *rt = s->priv_data;
1445 char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1446 char *option_list, *option, *filename;
1447 URLContext *rtsp_hd;
1448 int port, err, tcp_fd;
1449 RTSPMessageHeader reply1, *reply = &reply1;
1450 int lower_transport_mask = 0;
1451 char real_challenge[64];
1452 struct sockaddr_storage peer;
1453 socklen_t peer_len = sizeof(peer);
1455 if (!ff_network_init())
1456 return AVERROR(EIO);
1458 /* extract hostname and port */
1459 ff_url_split(NULL, 0, auth, sizeof(auth),
1460 host, sizeof(host), &port, path, sizeof(path), s->filename);
1462 av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1465 port = RTSP_DEFAULT_PORT;
1467 /* search for options */
1468 option_list = strrchr(path, '?');
1470 /* Strip out the RTSP specific options, write out the rest of
1471 * the options back into the same string. */
1472 filename = option_list;
1473 while (option_list) {
1474 /* move the option pointer */
1475 option = ++option_list;
1476 option_list = strchr(option_list, '&');
1480 /* handle the options */
1481 if (!strcmp(option, "udp")) {
1482 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
1483 } else if (!strcmp(option, "multicast")) {
1484 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
1485 } else if (!strcmp(option, "tcp")) {
1486 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1488 /* Write options back into the buffer, using memmove instead
1489 * of strcpy since the strings may overlap. */
1490 int len = strlen(option);
1491 memmove(++filename, option, len);
1493 if (option_list) *filename = '&';
1499 if (!lower_transport_mask)
1500 lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1503 /* Only UDP or TCP - UDP multicast isn't supported. */
1504 lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1505 (1 << RTSP_LOWER_TRANSPORT_TCP);
1506 if (!lower_transport_mask) {
1507 av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1508 "only UDP and TCP are supported for output.\n");
1509 err = AVERROR(EINVAL);
1514 /* Construct the URI used in request; this is similar to s->filename,
1515 * but with authentication credentials removed and RTSP specific options
1517 ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1518 host, port, "%s", path);
1520 /* open the tcp connexion */
1521 ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
1522 if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0) {
1526 rt->rtsp_hd = rtsp_hd;
1529 tcp_fd = url_get_file_handle(rtsp_hd);
1530 if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1531 getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1532 NULL, 0, NI_NUMERICHOST);
1535 /* request options supported by the server; this also detects server
1537 for (rt->server_type = RTSP_SERVER_RTP;;) {
1539 if (rt->server_type == RTSP_SERVER_REAL)
1542 * The following entries are required for proper
1543 * streaming from a Realmedia server. They are
1544 * interdependent in some way although we currently
1545 * don't quite understand how. Values were copied
1546 * from mplayer SVN r23589.
1547 * @param CompanyID is a 16-byte ID in base64
1548 * @param ClientChallenge is a 16-byte ID in hex
1550 "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1551 "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1552 "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1553 "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1555 ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1556 if (reply->status_code != RTSP_STATUS_OK) {
1557 err = AVERROR_INVALIDDATA;
1561 /* detect server type if not standard-compliant RTP */
1562 if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1563 rt->server_type = RTSP_SERVER_REAL;
1565 } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1566 rt->server_type = RTSP_SERVER_WMS;
1567 } else if (rt->server_type == RTSP_SERVER_REAL)
1568 strcpy(real_challenge, reply->real_challenge);
1573 err = rtsp_setup_input_streams(s, reply);
1575 err = rtsp_setup_output_streams(s, host);
1580 int lower_transport = ff_log2_tab[lower_transport_mask &
1581 ~(lower_transport_mask - 1)];
1583 err = make_setup_request(s, host, port, lower_transport,
1584 rt->server_type == RTSP_SERVER_REAL ?
1585 real_challenge : NULL);
1588 lower_transport_mask &= ~(1 << lower_transport);
1589 if (lower_transport_mask == 0 && err == 1) {
1590 err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
1595 rt->state = RTSP_STATE_IDLE;
1596 rt->seek_timestamp = 0; /* default is to start stream at position zero */
1599 ff_rtsp_close_streams(s);
1600 url_close(rt->rtsp_hd);
1601 if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1602 av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1603 av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1613 #if CONFIG_RTSP_DEMUXER
1614 static int rtsp_read_header(AVFormatContext *s,
1615 AVFormatParameters *ap)
1617 RTSPState *rt = s->priv_data;
1620 ret = ff_rtsp_connect(s);
1624 if (ap->initial_pause) {
1625 /* do not start immediately */
1627 if (rtsp_read_play(s) < 0) {
1628 ff_rtsp_close_streams(s);
1629 url_close(rt->rtsp_hd);
1630 return AVERROR_INVALIDDATA;
1637 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1638 uint8_t *buf, int buf_size)
1640 RTSPState *rt = s->priv_data;
1641 RTSPStream *rtsp_st;
1643 int fd, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
1647 if (url_interrupt_cb())
1648 return AVERROR(EINTR);
1651 tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
1652 FD_SET(tcp_fd, &rfds);
1657 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1658 rtsp_st = rt->rtsp_streams[i];
1659 if (rtsp_st->rtp_handle) {
1660 /* currently, we cannot probe RTCP handle because of
1661 * blocking restrictions */
1662 fd = url_get_file_handle(rtsp_st->rtp_handle);
1669 tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
1670 n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1673 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1674 rtsp_st = rt->rtsp_streams[i];
1675 if (rtsp_st->rtp_handle) {
1676 fd = url_get_file_handle(rtsp_st->rtp_handle);
1677 if (FD_ISSET(fd, &rfds)) {
1678 ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1680 *prtsp_st = rtsp_st;
1686 #if CONFIG_RTSP_DEMUXER
1687 if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
1688 RTSPMessageHeader reply;
1690 ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
1693 /* XXX: parse message */
1694 if (rt->state != RTSP_STATE_STREAMING)
1698 } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1699 return AVERROR(ETIME);
1700 } else if (n < 0 && errno != EINTR)
1701 return AVERROR(errno);
1705 static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1706 uint8_t *buf, int buf_size)
1708 RTSPState *rt = s->priv_data;
1709 int id, len, i, ret;
1710 RTSPStream *rtsp_st;
1712 #ifdef DEBUG_RTP_TCP
1713 dprintf(s, "tcp_read_packet:\n");
1717 RTSPMessageHeader reply;
1719 ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
1722 if (ret == 1) /* received '$' */
1724 /* XXX: parse message */
1725 if (rt->state != RTSP_STATE_STREAMING)
1728 ret = url_read_complete(rt->rtsp_hd, buf, 3);
1732 len = AV_RB16(buf + 1);
1733 #ifdef DEBUG_RTP_TCP
1734 dprintf(s, "id=%d len=%d\n", id, len);
1736 if (len > buf_size || len < 12)
1739 ret = url_read_complete(rt->rtsp_hd, buf, len);
1742 if (rt->transport == RTSP_TRANSPORT_RDT &&
1743 ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
1746 /* find the matching stream */
1747 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1748 rtsp_st = rt->rtsp_streams[i];
1749 if (id >= rtsp_st->interleaved_min &&
1750 id <= rtsp_st->interleaved_max)
1755 *prtsp_st = rtsp_st;
1759 static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1761 RTSPState *rt = s->priv_data;
1763 uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
1764 RTSPStream *rtsp_st;
1766 /* get next frames from the same RTP packet */
1767 if (rt->cur_transport_priv) {
1768 if (rt->transport == RTSP_TRANSPORT_RDT) {
1769 ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1771 ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1773 rt->cur_transport_priv = NULL;
1775 } else if (ret == 1) {
1778 rt->cur_transport_priv = NULL;
1781 /* read next RTP packet */
1783 switch(rt->lower_transport) {
1785 #if CONFIG_RTSP_DEMUXER
1786 case RTSP_LOWER_TRANSPORT_TCP:
1787 len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1790 case RTSP_LOWER_TRANSPORT_UDP:
1791 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1792 len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1793 if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1794 rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1801 if (rt->transport == RTSP_TRANSPORT_RDT) {
1802 ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
1804 ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
1808 /* more packets may follow, so we save the RTP context */
1809 rt->cur_transport_priv = rtsp_st->transport_priv;
1814 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
1816 RTSPState *rt = s->priv_data;
1818 RTSPMessageHeader reply1, *reply = &reply1;
1821 if (rt->server_type == RTSP_SERVER_REAL) {
1823 enum AVDiscard cache[MAX_STREAMS];
1825 for (i = 0; i < s->nb_streams; i++)
1826 cache[i] = s->streams[i]->discard;
1828 if (!rt->need_subscription) {
1829 if (memcmp (cache, rt->real_setup_cache,
1830 sizeof(enum AVDiscard) * s->nb_streams)) {
1831 snprintf(cmd, sizeof(cmd),
1832 "Unsubscribe: %s\r\n",
1833 rt->last_subscription);
1834 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1836 if (reply->status_code != RTSP_STATUS_OK)
1837 return AVERROR_INVALIDDATA;
1838 rt->need_subscription = 1;
1842 if (rt->need_subscription) {
1843 int r, rule_nr, first = 1;
1845 memcpy(rt->real_setup_cache, cache,
1846 sizeof(enum AVDiscard) * s->nb_streams);
1847 rt->last_subscription[0] = 0;
1849 snprintf(cmd, sizeof(cmd),
1851 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1853 for (r = 0; r < s->nb_streams; r++) {
1854 if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
1855 if (s->streams[r]->discard != AVDISCARD_ALL) {
1857 av_strlcat(rt->last_subscription, ",",
1858 sizeof(rt->last_subscription));
1859 ff_rdt_subscribe_rule(
1860 rt->last_subscription,
1861 sizeof(rt->last_subscription), i, rule_nr);
1868 av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
1869 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1871 if (reply->status_code != RTSP_STATUS_OK)
1872 return AVERROR_INVALIDDATA;
1873 rt->need_subscription = 0;
1875 if (rt->state == RTSP_STATE_STREAMING)
1880 ret = rtsp_fetch_packet(s, pkt);
1884 /* send dummy request to keep TCP connection alive */
1885 if ((rt->server_type == RTSP_SERVER_WMS ||
1886 rt->server_type == RTSP_SERVER_REAL) &&
1887 (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
1888 if (rt->server_type == RTSP_SERVER_WMS) {
1889 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
1891 ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
1898 /* pause the stream */
1899 static int rtsp_read_pause(AVFormatContext *s)
1901 RTSPState *rt = s->priv_data;
1902 RTSPMessageHeader reply1, *reply = &reply1;
1906 if (rt->state != RTSP_STATE_STREAMING)
1908 else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1909 ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
1910 if (reply->status_code != RTSP_STATUS_OK) {
1914 rt->state = RTSP_STATE_PAUSED;
1918 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1919 int64_t timestamp, int flags)
1921 RTSPState *rt = s->priv_data;
1923 rt->seek_timestamp = av_rescale_q(timestamp,
1924 s->streams[stream_index]->time_base,
1928 case RTSP_STATE_IDLE:
1930 case RTSP_STATE_STREAMING:
1931 if (rtsp_read_pause(s) != 0)
1933 rt->state = RTSP_STATE_SEEKING;
1934 if (rtsp_read_play(s) != 0)
1937 case RTSP_STATE_PAUSED:
1938 rt->state = RTSP_STATE_IDLE;
1944 static int rtsp_read_close(AVFormatContext *s)
1946 RTSPState *rt = s->priv_data;
1949 /* NOTE: it is valid to flush the buffer here */
1950 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1951 url_fclose(&rt->rtsp_gb);
1954 ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
1956 ff_rtsp_close_streams(s);
1957 url_close(rt->rtsp_hd);
1962 AVInputFormat rtsp_demuxer = {
1964 NULL_IF_CONFIG_SMALL("RTSP input format"),
1971 .flags = AVFMT_NOFILE,
1972 .read_play = rtsp_read_play,
1973 .read_pause = rtsp_read_pause,
1977 static int sdp_probe(AVProbeData *p1)
1979 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
1981 /* we look for a line beginning "c=IN IP4" */
1982 while (p < p_end && *p != '\0') {
1983 if (p + sizeof("c=IN IP4") - 1 < p_end &&
1984 av_strstart(p, "c=IN IP4", NULL))
1985 return AVPROBE_SCORE_MAX / 2;
1987 while (p < p_end - 1 && *p != '\n') p++;
1996 #define SDP_MAX_SIZE 8192
1998 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
2000 RTSPState *rt = s->priv_data;
2001 RTSPStream *rtsp_st;
2006 if (!ff_network_init())
2007 return AVERROR(EIO);
2009 /* read the whole sdp file */
2010 /* XXX: better loading */
2011 content = av_malloc(SDP_MAX_SIZE);
2012 size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
2015 return AVERROR_INVALIDDATA;
2017 content[size] ='\0';
2019 sdp_parse(s, content);
2022 /* open each RTP stream */
2023 for (i = 0; i < rt->nb_rtsp_streams; i++) {
2024 rtsp_st = rt->rtsp_streams[i];
2026 ff_url_join(url, sizeof(url), "rtp", NULL,
2027 inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
2028 "?localport=%d&ttl=%d", rtsp_st->sdp_port,
2030 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
2031 err = AVERROR_INVALIDDATA;
2034 if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
2039 ff_rtsp_close_streams(s);
2044 static int sdp_read_close(AVFormatContext *s)
2046 ff_rtsp_close_streams(s);
2051 AVInputFormat sdp_demuxer = {
2053 NULL_IF_CONFIG_SMALL("SDP"),