libavformat/rtsp.c
1617ad97
 /*
93ced3e8
  * RTSP/SDP client
406792e7
  * Copyright (c) 2002 Fabrice Bellard
1617ad97
  *
b78e7197
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
1617ad97
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
b78e7197
  * version 2.1 of the License, or (at your option) any later version.
1617ad97
  *
b78e7197
  * FFmpeg is distributed in the hope that it will be useful,
1617ad97
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
b78e7197
  * License along with FFmpeg; if not, write to the Free Software
5509bffa
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1617ad97
  */
245976da
 
f9337897
 #include "libavutil/base64.h"
245976da
 #include "libavutil/avstring.h"
6a5d31ac
 #include "libavutil/intreadwrite.h"
9fcae973
 #include "libavutil/parseutils.h"
f5d33f52
 #include "libavutil/random_seed.h"
d2d67e42
 #include "libavutil/dict.h"
1617ad97
 #include "avformat.h"
e731b8d8
 #include "avio_internal.h"
1617ad97
 
db0ed93e
 #include <sys/time.h>
a8475bbd
 #if HAVE_POLL_H
 #include <poll.h>
6ad1c9c9
 #endif
ea452b54
 #include <strings.h>
e4a9e3cc
 #include "internal.h"
42572ef5
 #include "network.h"
cbfa66d0
 #include "os_support.h"
f5d33f52
 #include "http.h"
c971ff19
 #include "rtsp.h"
1617ad97
 
302879cb
 #include "rtpdec.h"
e9dea59f
 #include "rdt.h"
965a3ddb
 #include "rtpdec_formats.h"
a493f80a
 #include "rtpenc_chain.h"
5652bb94
 #include "url.h"
4934884a
 
1617ad97
 //#define DEBUG
 
a8475bbd
 /* Timeout values for socket poll, in ms,
9cba6f5f
  * and read_packet(), in seconds  */
a8475bbd
 #define POLL_TIMEOUT_MS 100
9cba6f5f
 #define READ_PACKET_TIMEOUT_S 10
a8475bbd
 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / POLL_TIMEOUT_MS
91af5601
 #define SDP_MAX_SIZE 16384
96a7c975
 #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
9cba6f5f
 
1ef36a70
 static void get_word_until_chars(char *buf, int buf_size,
                                  const char *sep, const char **pp)
1617ad97
 {
     const char *p;
     char *q;
 
     p = *pp;
30619e6e
     p += strspn(p, SPACE_CHARS);
1617ad97
     q = buf;
     while (!strchr(sep, *p) && *p != '\0') {
         if ((q - buf) < buf_size - 1)
             *q++ = *p;
         p++;
     }
     if (buf_size > 0)
         *q = '\0';
     *pp = p;
 }
 
1ef36a70
 static void get_word_sep(char *buf, int buf_size, const char *sep,
                          const char **pp)
1617ad97
 {
1ef36a70
     if (**pp == '/') (*pp)++;
     get_word_until_chars(buf, buf_size, sep, pp);
 }
1617ad97
 
1ef36a70
 static void get_word(char *buf, int buf_size, const char **pp)
 {
     get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
1617ad97
 }
 
8bf0f969
 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
  *  and end time.
  *  Used for seeking in the rtp stream.
  */
 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
 {
     char buf[256];
 
     p += strspn(p, SPACE_CHARS);
     if (!av_stristart(p, "npt=", &p))
         return;
 
     *start = AV_NOPTS_VALUE;
     *end = AV_NOPTS_VALUE;
 
     get_word_sep(buf, sizeof(buf), "-", &p);
9fcae973
     av_parse_time(start, buf, 1);
8bf0f969
     if (*p == '-') {
         p++;
         get_word_sep(buf, sizeof(buf), "-", &p);
9fcae973
         av_parse_time(end, buf, 1);
8bf0f969
     }
 //    av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
 //    av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
 }
 
 static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
 {
     struct addrinfo hints, *ai = NULL;
     memset(&hints, 0, sizeof(hints));
     hints.ai_flags = AI_NUMERICHOST;
     if (getaddrinfo(buf, NULL, &hints, &ai))
         return -1;
     memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
     freeaddrinfo(ai);
     return 0;
 }
 
44b70ce5
 #if CONFIG_RTPDEC
003eb642
 static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
                              RTSPStream *rtsp_st, AVCodecContext *codec)
 {
     if (!handler)
         return;
     codec->codec_id          = handler->codec_id;
     rtsp_st->dynamic_handler = handler;
9261e6cf
     if (handler->alloc)
         rtsp_st->dynamic_protocol_context = handler->alloc();
003eb642
 }
 
c8965800
 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
8f3c87f3
 static int sdp_parse_rtpmap(AVFormatContext *s,
86b6e387
                             AVStream *st, RTSPStream *rtsp_st,
c8965800
                             int payload_type, const char *p)
93ced3e8
 {
86b6e387
     AVCodecContext *codec = st->codec;
93ced3e8
     char buf[256];
d1ccf0e0
     int i;
     AVCodec *c;
7b49ce2e
     const char *c_name;
93ced3e8
 
d1ccf0e0
     /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
9d50d396
      * see if we can handle this kind of payload.
      * The space should normally not be there but some Real streams or
      * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
      * have a trailing space. */
     get_word_sep(buf, sizeof(buf), "/ ", &p);
d1ccf0e0
     if (payload_type >= RTP_PT_PRIVATE) {
003eb642
         RTPDynamicProtocolHandler *handler =
             ff_rtp_handler_find_by_name(buf, codec->codec_type);
         init_rtp_handler(handler, rtsp_st, codec);
160918d5
         /* If no dynamic handler was found, check with the list of standard
          * allocated types, if such a stream for some reason happens to
          * use a private payload type. This isn't handled in rtpdec.c, since
          * the format name from the rtpmap line never is passed into rtpdec. */
         if (!rtsp_st->dynamic_handler)
             codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
93ced3e8
     } else {
c8965800
         /* We are in a standard case
          * (from http://www.iana.org/assignments/rtp-parameters). */
d1ccf0e0
         /* search into AVRtpPayloadTypes[] */
7ed19d7f
         codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
d1ccf0e0
     }
 
     c = avcodec_find_decoder(codec->codec_id);
     if (c && c->name)
7b49ce2e
         c_name = c->name;
d1ccf0e0
     else
170870b7
         c_name = "(null)";
d1ccf0e0
 
7515ed0c
     get_word_sep(buf, sizeof(buf), "/", &p);
     i = atoi(buf);
     switch (codec->codec_type) {
72415b2a
     case AVMEDIA_TYPE_AUDIO:
7515ed0c
         av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
         codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
         codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
         if (i > 0) {
             codec->sample_rate = i;
86b6e387
             av_set_pts_info(st, 32, 1, codec->sample_rate);
7515ed0c
             get_word_sep(buf, sizeof(buf), "/", &p);
             i = atoi(buf);
             if (i > 0)
                 codec->channels = i;
             // TODO: there is a bug here; if it is a mono stream, and
             // less than 22000Hz, faad upconverts to stereo and twice
             // the frequency.  No problem, but the sample rate is being
             // set here by the sdp line. Patch on its way. (rdm)
d1ccf0e0
         }
7515ed0c
         av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
                codec->sample_rate);
         av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
                codec->channels);
         break;
72415b2a
     case AVMEDIA_TYPE_VIDEO:
7515ed0c
         av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
86b6e387
         if (i > 0)
             av_set_pts_info(st, 32, 1, i);
7515ed0c
         break;
     default:
         break;
     }
     return 0;
93ced3e8
 }
 
c2bfd816
 /* parse the attribute line from the fmtp a line of an sdp response. This
c8965800
  * is broken out as a function because it is used in rtp_h264.c, which is
  * forthcoming. */
3307e6ea
 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
93993933
                                 char *value, int value_size)
d0deedcb
 {
30619e6e
     *p += strspn(*p, SPACE_CHARS);
c8965800
     if (**p) {
d0deedcb
         get_word_sep(attr, attr_size, "=", p);
         if (**p == '=')
             (*p)++;
         get_word_sep(value, value_size, ";", p);
         if (**p == ';')
             (*p)++;
         return 1;
     }
     return 0;
 }
 
93ced3e8
 typedef struct SDPParseState {
     /* SDP only */
3fbd12d1
     struct sockaddr_storage default_ip;
c8965800
     int            default_ttl;
     int            skip_media;  ///< set if an unknown m= line occurs
93ced3e8
 } SDPParseState;
 
 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
1617ad97
                            int letter, const char *buf)
 {
8b1ab7bf
     RTSPState *rt = s->priv_data;
1617ad97
     char buf1[64], st_type[64];
     const char *p;
72415b2a
     enum AVMediaType codec_type;
fb65d2ca
     int payload_type, i;
1617ad97
     AVStream *st;
     RTSPStream *rtsp_st;
3fbd12d1
     struct sockaddr_storage sdp_ip;
93ced3e8
     int ttl;
 
dfd2a005
     av_dlog(s, "sdp: %c='%s'\n", letter, buf);
1617ad97
 
     p = buf;
cb760a47
     if (s1->skip_media && letter != 'm')
         return;
c8965800
     switch (letter) {
93ced3e8
     case 'c':
         get_word(buf1, sizeof(buf1), &p);
         if (strcmp(buf1, "IN") != 0)
             return;
         get_word(buf1, sizeof(buf1), &p);
3fbd12d1
         if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
93ced3e8
             return;
         get_word_sep(buf1, sizeof(buf1), "/", &p);
3fbd12d1
         if (get_sockaddr(buf1, &sdp_ip))
93ced3e8
             return;
         ttl = 16;
         if (*p == '/') {
             p++;
             get_word_sep(buf1, sizeof(buf1), "/", &p);
             ttl = atoi(buf1);
         }
         if (s->nb_streams == 0) {
             s1->default_ip = sdp_ip;
             s1->default_ttl = ttl;
         } else {
d9c0510e
             rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
93ced3e8
             rtsp_st->sdp_ip = sdp_ip;
             rtsp_st->sdp_ttl = ttl;
         }
         break;
1617ad97
     case 's':
d2d67e42
         av_dict_set(&s->metadata, "title", p, 0);
1617ad97
         break;
     case 'i':
         if (s->nb_streams == 0) {
d2d67e42
             av_dict_set(&s->metadata, "comment", p, 0);
1617ad97
             break;
         }
         break;
     case 'm':
         /* new stream */
cb760a47
         s1->skip_media = 0;
1617ad97
         get_word(st_type, sizeof(st_type), &p);
         if (!strcmp(st_type, "audio")) {
72415b2a
             codec_type = AVMEDIA_TYPE_AUDIO;
1617ad97
         } else if (!strcmp(st_type, "video")) {
72415b2a
             codec_type = AVMEDIA_TYPE_VIDEO;
090438cc
         } else if (!strcmp(st_type, "application")) {
72415b2a
             codec_type = AVMEDIA_TYPE_DATA;
1617ad97
         } else {
cb760a47
             s1->skip_media = 1;
1617ad97
             return;
         }
         rtsp_st = av_mallocz(sizeof(RTSPStream));
         if (!rtsp_st)
             return;
8b1ab7bf
         rtsp_st->stream_index = -1;
         dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
93ced3e8
 
         rtsp_st->sdp_ip = s1->default_ip;
         rtsp_st->sdp_ttl = s1->default_ttl;
 
         get_word(buf1, sizeof(buf1), &p); /* port */
         rtsp_st->sdp_port = atoi(buf1);
 
         get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
115329f1
 
93ced3e8
         /* XXX: handle list of formats */
         get_word(buf1, sizeof(buf1), &p); /* format list */
         rtsp_st->sdp_payload_type = atoi(buf1);
 
7ed19d7f
         if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
8b1ab7bf
             /* no corresponding stream */
         } else {
b2dd842d
             st = av_new_stream(s, rt->nb_rtsp_streams - 1);
8b1ab7bf
             if (!st)
                 return;
             rtsp_st->stream_index = st->index;
01f4895c
             st->codec->codec_type = codec_type;
d1ccf0e0
             if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
6a7e31a9
                 RTPDynamicProtocolHandler *handler;
8b1ab7bf
                 /* if standard payload type, we can find the codec right now */
bf6d9818
                 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
bbd8f547
                 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
                     st->codec->sample_rate > 0)
86b6e387
                     av_set_pts_info(st, 32, 1, st->codec->sample_rate);
6a7e31a9
                 /* Even static payload types may need a custom depacketizer */
                 handler = ff_rtp_handler_find_by_id(
                               rtsp_st->sdp_payload_type, st->codec->codec_type);
                 init_rtp_handler(handler, rtsp_st, st->codec);
8b1ab7bf
             }
         }
1617ad97
         /* put a default control url */
00eb13e0
         av_strlcpy(rtsp_st->control_url, rt->control_uri,
c8965800
                    sizeof(rtsp_st->control_url));
1617ad97
         break;
     case 'a':
00eb13e0
         if (av_strstart(p, "control:", &p)) {
             if (s->nb_streams == 0) {
                 if (!strncmp(p, "rtsp://", 7))
                     av_strlcpy(rt->control_uri, p,
                                sizeof(rt->control_uri));
             } else {
0b6a7ff4
                 char proto[32];
                 /* get the control url */
d9c0510e
                 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
115329f1
 
0b6a7ff4
                 /* XXX: may need to add full url resolution */
                 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
                              NULL, NULL, 0, p);
                 if (proto[0] == '\0') {
                     /* relative control URL */
                     if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
                     av_strlcat(rtsp_st->control_url, "/",
                                sizeof(rtsp_st->control_url));
                     av_strlcat(rtsp_st->control_url, p,
                                sizeof(rtsp_st->control_url));
                 } else
                     av_strlcpy(rtsp_st->control_url, p,
                                sizeof(rtsp_st->control_url));
00eb13e0
             }
83d14c85
         } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
93ced3e8
             /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
115329f1
             get_word(buf1, sizeof(buf1), &p);
93ced3e8
             payload_type = atoi(buf1);
83d14c85
             st = s->streams[s->nb_streams - 1];
d9c0510e
             rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
86b6e387
             sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
7fc8ac7f
         } else if (av_strstart(p, "fmtp:", &p) ||
                    av_strstart(p, "framesize:", &p)) {
93ced3e8
             /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
d0deedcb
             // let dynamic protocol handlers have a stab at the line.
             get_word(buf1, sizeof(buf1), &p);
             payload_type = atoi(buf1);
d9c0510e
             for (i = 0; i < rt->nb_rtsp_streams; i++) {
                 rtsp_st = rt->rtsp_streams[i];
c8965800
                 if (rtsp_st->sdp_payload_type == payload_type &&
                     rtsp_st->dynamic_handler &&
                     rtsp_st->dynamic_handler->parse_sdp_a_line)
                     rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
                         rtsp_st->dynamic_protocol_context, buf);
d0deedcb
             }
c8965800
         } else if (av_strstart(p, "range:", &p)) {
31693e00
             int64_t start, end;
 
             // this is so that seeking on a streamed file can work.
             rtsp_parse_range_npt(p, &start, &end);
c8965800
             s->start_time = start;
             /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
             s->duration   = (end == AV_NOPTS_VALUE) ?
                             AV_NOPTS_VALUE : end - start;
119b4668
         } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
             if (atoi(p) == 1)
                 rt->transport = RTSP_TRANSPORT_RDT;
bb776f3b
         } else if (av_strstart(p, "SampleRate:integer;", &p) &&
                    s->nb_streams > 0) {
             st = s->streams[s->nb_streams - 1];
             st->codec->sample_rate = atoi(p);
1a30d541
         } else {
             if (rt->server_type == RTSP_SERVER_WMS)
                 ff_wms_parse_sdp_a_line(s, p);
             if (s->nb_streams > 0) {
c4a3d032
                 if (rt->server_type == RTSP_SERVER_REAL)
                     ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
 
d9c0510e
                 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
c4a3d032
                 if (rtsp_st->dynamic_handler &&
                     rtsp_st->dynamic_handler->parse_sdp_a_line)
c8965800
                     rtsp_st->dynamic_handler->parse_sdp_a_line(s,
                         s->nb_streams - 1,
c4a3d032
                         rtsp_st->dynamic_protocol_context, buf);
1a30d541
             }
1617ad97
         }
         break;
     }
 }
 
0526c6f7
 int ff_sdp_parse(AVFormatContext *s, const char *content)
1617ad97
 {
a8475bbd
     RTSPState *rt = s->priv_data;
1617ad97
     const char *p;
     int letter;
9211bcdd
     /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
      * contain long SDP lines containing complete ASF Headers (several
      * kB) or arrays of MDPR (RM stream descriptor) headers plus
      * "rulebooks" describing their properties. Therefore, the SDP line
373afbaf
      * buffer is large.
      *
afcea58c
      * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
      * in rtpdec_xiph.c. */
373afbaf
     char buf[16384], *q;
93ced3e8
     SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
115329f1
 
93ced3e8
     memset(s1, 0, sizeof(SDPParseState));
1617ad97
     p = content;
c8965800
     for (;;) {
30619e6e
         p += strspn(p, SPACE_CHARS);
1617ad97
         letter = *p;
         if (letter == '\0')
             break;
         p++;
         if (*p != '=')
             goto next_line;
         p++;
         /* get the content */
         q = buf;
b6892136
         while (*p != '\n' && *p != '\r' && *p != '\0') {
1617ad97
             if ((q - buf) < sizeof(buf) - 1)
                 *q++ = *p;
             p++;
         }
         *q = '\0';
93ced3e8
         sdp_parse_line(s, s1, letter, buf);
1617ad97
     next_line:
         while (*p != '\n' && *p != '\0')
             p++;
         if (*p == '\n')
             p++;
     }
a8475bbd
     rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
     if (!rt->p) return AVERROR(ENOMEM);
1617ad97
     return 0;
 }
44b70ce5
 #endif /* CONFIG_RTPDEC */
1617ad97
 
93e7490e
 void ff_rtsp_undo_setup(AVFormatContext *s)
 {
     RTSPState *rt = s->priv_data;
     int i;
 
     for (i = 0; i < rt->nb_rtsp_streams; i++) {
         RTSPStream *rtsp_st = rt->rtsp_streams[i];
         if (!rtsp_st)
             continue;
         if (rtsp_st->transport_priv) {
             if (s->oformat) {
                 AVFormatContext *rtpctx = rtsp_st->transport_priv;
                 av_write_trailer(rtpctx);
                 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
                     uint8_t *ptr;
6dc7d80d
                     avio_close_dyn_buf(rtpctx->pb, &ptr);
93e7490e
                     av_free(ptr);
                 } else {
22a3212e
                     avio_close(rtpctx->pb);
93e7490e
                 }
b22dbb29
                 avformat_free_context(rtpctx);
93e7490e
             } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
                 ff_rdt_parse_close(rtsp_st->transport_priv);
             else if (CONFIG_RTPDEC)
                 rtp_parse_close(rtsp_st->transport_priv);
         }
         rtsp_st->transport_priv = NULL;
         if (rtsp_st->rtp_handle)
e52a9145
             ffurl_close(rtsp_st->rtp_handle);
93e7490e
         rtsp_st->rtp_handle = NULL;
     }
 }
 
1ced9da3
 /* close and free RTSP streams */
3307e6ea
 void ff_rtsp_close_streams(AVFormatContext *s)
1ced9da3
 {
52aa4338
     RTSPState *rt = s->priv_data;
1ced9da3
     int i;
     RTSPStream *rtsp_st;
 
93e7490e
     ff_rtsp_undo_setup(s);
c8965800
     for (i = 0; i < rt->nb_rtsp_streams; i++) {
1ced9da3
         rtsp_st = rt->rtsp_streams[i];
         if (rtsp_st) {
             if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
9261e6cf
                 rtsp_st->dynamic_handler->free(
c8965800
                     rtsp_st->dynamic_protocol_context);
ea7f0807
             av_free(rtsp_st);
1ced9da3
         }
     }
     av_free(rt->rtsp_streams);
     if (rt->asf_ctx) {
         av_close_input_stream (rt->asf_ctx);
         rt->asf_ctx = NULL;
     }
a8475bbd
     av_free(rt->p);
96a7c975
     av_free(rt->recvbuf);
1ced9da3
 }
 
c8965800
 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
1ced9da3
 {
     RTSPState *rt = s->priv_data;
     AVStream *st = NULL;
 
     /* open the RTP context */
     if (rtsp_st->stream_index >= 0)
         st = s->streams[rtsp_st->stream_index];
     if (!st)
         s->ctx_flags |= AVFMTCTX_NOHEADER;
 
44b70ce5
     if (s->oformat && CONFIG_RTSP_MUXER) {
a493f80a
         rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
                                       rtsp_st->rtp_handle,
                                       RTSP_TCP_MAX_PACKET_SIZE);
c2bfd816
         /* Ownership of rtp_handle is passed to the rtp mux context */
fd450a51
         rtsp_st->rtp_handle = NULL;
44b70ce5
     } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
1ced9da3
         rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
                                             rtsp_st->dynamic_protocol_context,
                                             rtsp_st->dynamic_handler);
44b70ce5
     else if (CONFIG_RTPDEC)
1ced9da3
         rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
58ee0991
                                          rtsp_st->sdp_payload_type,
             (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
             ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
1ced9da3
 
     if (!rtsp_st->transport_priv) {
          return AVERROR(ENOMEM);
44b70ce5
     } else if (rt->transport != RTSP_TRANSPORT_RDT && CONFIG_RTPDEC) {
c8965800
         if (rtsp_st->dynamic_handler) {
1ced9da3
             rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
                                            rtsp_st->dynamic_protocol_context,
                                            rtsp_st->dynamic_handler);
         }
     }
 
     return 0;
 }
 
6f5a3d0a
 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
1617ad97
 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
 {
     const char *p;
     int v;
 
     p = *pp;
30619e6e
     p += strspn(p, SPACE_CHARS);
1617ad97
     v = strtol(p, (char **)&p, 10);
     if (*p == '-') {
         p++;
         *min_ptr = v;
         v = strtol(p, (char **)&p, 10);
         *max_ptr = v;
     } else {
         *min_ptr = v;
         *max_ptr = v;
     }
     *pp = p;
 }
 
 /* XXX: only one transport specification is parsed */
a9e534d5
 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
1617ad97
 {
     char transport_protocol[16];
     char profile[16];
     char lower_transport[16];
     char parameter[16];
     RTSPTransportField *th;
     char buf[256];
115329f1
 
1617ad97
     reply->nb_transports = 0;
115329f1
 
c8965800
     for (;;) {
30619e6e
         p += strspn(p, SPACE_CHARS);
1617ad97
         if (*p == '\0')
             break;
 
         th = &reply->transports[reply->nb_transports];
 
115329f1
         get_word_sep(transport_protocol, sizeof(transport_protocol),
1617ad97
                      "/", &p);
e1502118
         if (!strcasecmp (transport_protocol, "rtp")) {
7ecc634e
             get_word_sep(profile, sizeof(profile), "/;,", &p);
             lower_transport[0] = '\0';
             /* rtp/avp/<protocol> */
             if (*p == '/') {
                 get_word_sep(lower_transport, sizeof(lower_transport),
                              ";,", &p);
119b4668
             }
             th->transport = RTSP_TRANSPORT_RTP;
         } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
                    !strcasecmp (transport_protocol, "x-real-rdt")) {
7ecc634e
             /* x-pn-tng/<protocol> */
e1502118
             get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
             profile[0] = '\0';
119b4668
             th->transport = RTSP_TRANSPORT_RDT;
1617ad97
         }
b6892136
         if (!strcasecmp(lower_transport, "TCP"))
90abbdba
             th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
1617ad97
         else
90abbdba
             th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
115329f1
 
1617ad97
         if (*p == ';')
             p++;
         /* get each parameter */
         while (*p != '\0' && *p != ',') {
             get_word_sep(parameter, sizeof(parameter), "=;,", &p);
             if (!strcmp(parameter, "port")) {
                 if (*p == '=') {
                     p++;
                     rtsp_parse_range(&th->port_min, &th->port_max, &p);
                 }
             } else if (!strcmp(parameter, "client_port")) {
                 if (*p == '=') {
                     p++;
115329f1
                     rtsp_parse_range(&th->client_port_min,
1617ad97
                                      &th->client_port_max, &p);
                 }
             } else if (!strcmp(parameter, "server_port")) {
                 if (*p == '=') {
                     p++;
115329f1
                     rtsp_parse_range(&th->server_port_min,
1617ad97
                                      &th->server_port_max, &p);
                 }
             } else if (!strcmp(parameter, "interleaved")) {
                 if (*p == '=') {
                     p++;
115329f1
                     rtsp_parse_range(&th->interleaved_min,
1617ad97
                                      &th->interleaved_max, &p);
                 }
             } else if (!strcmp(parameter, "multicast")) {
90abbdba
                 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
                     th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
1617ad97
             } else if (!strcmp(parameter, "ttl")) {
                 if (*p == '=') {
                     p++;
                     th->ttl = strtol(p, (char **)&p, 10);
                 }
             } else if (!strcmp(parameter, "destination")) {
                 if (*p == '=') {
                     p++;
                     get_word_sep(buf, sizeof(buf), ";,", &p);
7934b15d
                     get_sockaddr(buf, &th->destination);
1617ad97
                 }
619298a8
             } else if (!strcmp(parameter, "source")) {
                 if (*p == '=') {
                     p++;
                     get_word_sep(buf, sizeof(buf), ";,", &p);
                     av_strlcpy(th->source, buf, sizeof(th->source));
                 }
1617ad97
             }
619298a8
 
1617ad97
             while (*p != ';' && *p != '\0' && *p != ',')
                 p++;
             if (*p == ';')
                 p++;
         }
         if (*p == ',')
             p++;
 
         reply->nb_transports++;
     }
 }
 
29db7c3a
 static void handle_rtp_info(RTSPState *rt, const char *url,
                             uint32_t seq, uint32_t rtptime)
 {
     int i;
     if (!rtptime || !url[0])
         return;
     if (rt->transport != RTSP_TRANSPORT_RTP)
         return;
     for (i = 0; i < rt->nb_rtsp_streams; i++) {
         RTSPStream *rtsp_st = rt->rtsp_streams[i];
         RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
         if (!rtpctx)
             continue;
         if (!strcmp(rtsp_st->control_url, url)) {
             rtpctx->base_timestamp = rtptime;
             break;
         }
     }
 }
 
 static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
 {
     int read = 0;
     char key[20], value[1024], url[1024] = "";
     uint32_t seq = 0, rtptime = 0;
 
     for (;;) {
         p += strspn(p, SPACE_CHARS);
         if (!*p)
             break;
         get_word_sep(key, sizeof(key), "=", &p);
         if (*p != '=')
             break;
         p++;
         get_word_sep(value, sizeof(value), ";, ", &p);
         read++;
         if (!strcmp(key, "url"))
             av_strlcpy(url, value, sizeof(url));
         else if (!strcmp(key, "seq"))
907783f2
             seq = strtoul(value, NULL, 10);
29db7c3a
         else if (!strcmp(key, "rtptime"))
907783f2
             rtptime = strtoul(value, NULL, 10);
29db7c3a
         if (*p == ',') {
             handle_rtp_info(rt, url, seq, rtptime);
             url[0] = '\0';
             seq = rtptime = 0;
             read = 0;
         }
         if (*p)
             p++;
     }
     if (read > 0)
         handle_rtp_info(rt, url, seq, rtptime);
 }
 
2626308a
 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
77223c53
                         RTSPState *rt, const char *method)
1617ad97
 {
     const char *p;
 
     /* NOTE: we do case independent match for broken servers */
     p = buf;
f7d78f36
     if (av_stristart(p, "Session:", &p)) {
30e79845
         int t;
1617ad97
         get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
30e79845
         if (av_stristart(p, ";timeout=", &p) &&
             (t = strtol(p, NULL, 10)) > 0) {
             reply->timeout = t;
         }
f7d78f36
     } else if (av_stristart(p, "Content-Length:", &p)) {
1617ad97
         reply->content_length = strtol(p, NULL, 10);
f7d78f36
     } else if (av_stristart(p, "Transport:", &p)) {
1617ad97
         rtsp_parse_transport(reply, p);
f7d78f36
     } else if (av_stristart(p, "CSeq:", &p)) {
1617ad97
         reply->seq = strtol(p, NULL, 10);
f7d78f36
     } else if (av_stristart(p, "Range:", &p)) {
31693e00
         rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
30aa6aed
     } else if (av_stristart(p, "RealChallenge1:", &p)) {
30619e6e
         p += strspn(p, SPACE_CHARS);
30aa6aed
         av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
7a86bafa
     } else if (av_stristart(p, "Server:", &p)) {
30619e6e
         p += strspn(p, SPACE_CHARS);
7a86bafa
         av_strlcpy(reply->server, p, sizeof(reply->server));
fccb1770
     } else if (av_stristart(p, "Notice:", &p) ||
                av_stristart(p, "X-Notice:", &p)) {
         reply->notice = strtol(p, NULL, 10);
d243ba30
     } else if (av_stristart(p, "Location:", &p)) {
30619e6e
         p += strspn(p, SPACE_CHARS);
d243ba30
         av_strlcpy(reply->location, p , sizeof(reply->location));
acc9ed14
     } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
30619e6e
         p += strspn(p, SPACE_CHARS);
acc9ed14
         ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
     } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
30619e6e
         p += strspn(p, SPACE_CHARS);
acc9ed14
         ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
d2995eb9
     } else if (av_stristart(p, "Content-Base:", &p) && rt) {
dd22cfb1
         p += strspn(p, SPACE_CHARS);
d2995eb9
         if (method && !strcmp(method, "DESCRIBE"))
             av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
29db7c3a
     } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
         p += strspn(p, SPACE_CHARS);
         if (method && !strcmp(method, "PLAY"))
             rtsp_parse_rtp_info(rt, p);
0b4949b5
     } else if (av_stristart(p, "Public:", &p) && rt) {
         if (strstr(p, "GET_PARAMETER") &&
             method && !strcmp(method, "OPTIONS"))
             rt->get_parameter_supported = 1;
1617ad97
     }
 }
 
b7b8fc34
 /* skip a RTP/TCP interleaved packet */
ec55edba
 void ff_rtsp_skip_packet(AVFormatContext *s)
b7b8fc34
 {
     RTSPState *rt = s->priv_data;
     int ret, len, len1;
     uint8_t buf[1024];
 
dce37564
     ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
b7b8fc34
     if (ret != 3)
         return;
80fb8234
     len = AV_RB16(buf + 1);
67c9cd69
 
dfd2a005
     av_dlog(s, "skipping RTP packet len=%d\n", len);
67c9cd69
 
b7b8fc34
     /* skip payload */
     while (len > 0) {
         len1 = len;
         if (len1 > sizeof(buf))
             len1 = sizeof(buf);
dce37564
         ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
b7b8fc34
         if (ret != len1)
             return;
         len -= len1;
     }
 }
1617ad97
 
3307e6ea
 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
93993933
                        unsigned char **content_ptr,
3df54c6b
                        int return_on_interleaved_data, const char *method)
1617ad97
 {
     RTSPState *rt = s->priv_data;
     char buf[4096], buf1[1024], *q;
     unsigned char ch;
     const char *p;
7e726132
     int ret, content_length, line_count = 0;
1617ad97
     unsigned char *content = NULL;
 
d541a7d2
     memset(reply, 0, sizeof(*reply));
1617ad97
 
     /* parse reply (XXX: use buffers) */
     rt->last_reply[0] = '\0';
c8965800
     for (;;) {
1617ad97
         q = buf;
c8965800
         for (;;) {
dce37564
             ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
dfd2a005
             av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
7e726132
             if (ret != 1)
2401660d
                 return AVERROR_EOF;
1617ad97
             if (ch == '\n')
                 break;
b7b8fc34
             if (ch == '$') {
                 /* XXX: only parse it if first char on line ? */
7e726132
                 if (return_on_interleaved_data) {
                     return 1;
                 } else
ec55edba
                     ff_rtsp_skip_packet(s);
b7b8fc34
             } else if (ch != '\r') {
1617ad97
                 if ((q - buf) < sizeof(buf) - 1)
                     *q++ = ch;
             }
         }
         *q = '\0';
67c9cd69
 
dfd2a005
         av_dlog(s, "line='%s'\n", buf);
67c9cd69
 
1617ad97
         /* test if last line */
         if (buf[0] == '\0')
             break;
         p = buf;
         if (line_count == 0) {
             /* get reply code */
             get_word(buf1, sizeof(buf1), &p);
             get_word(buf1, sizeof(buf1), &p);
             reply->status_code = atoi(buf1);
d93fdcbf
             av_strlcpy(reply->reason, p, sizeof(reply->reason));
1617ad97
         } else {
77223c53
             ff_rtsp_parse_line(reply, p, rt, method);
75e61b0e
             av_strlcat(rt->last_reply, p,    sizeof(rt->last_reply));
             av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
1617ad97
         }
         line_count++;
     }
115329f1
 
1617ad97
     if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
75e61b0e
         av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
115329f1
 
1617ad97
     content_length = reply->content_length;
     if (content_length > 0) {
         /* leave some room for a trailing '\0' (useful for simple parsing) */
         content = av_malloc(content_length + 1);
dce37564
         ffurl_read_complete(rt->rtsp_hd, content, content_length);
1617ad97
         content[content_length] = '\0';
     }
     if (content_ptr)
         *content_ptr = content;
e2e2e7dd
     else
         av_free(content);
7e726132
 
7ed8211b
     if (rt->seq != reply->seq) {
         av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
             rt->seq, reply->seq);
     }
 
fccb1770
     /* EOS */
     if (reply->notice == 2101 /* End-of-Stream Reached */      ||
         reply->notice == 2104 /* Start-of-Stream Reached */    ||
c8965800
         reply->notice == 2306 /* Continuous Feed Terminated */) {
fccb1770
         rt->state = RTSP_STATE_IDLE;
c8965800
     } else if (reply->notice >= 4400 && reply->notice < 5500) {
fccb1770
         return AVERROR(EIO); /* data or server error */
c8965800
     } else if (reply->notice == 2401 /* Ticket Expired */ ||
fccb1770
              (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
         return AVERROR(EPERM);
 
7e726132
     return 0;
1617ad97
 }
 
57c4d01e
 /**
  * Send a command to the RTSP server without waiting for the reply.
  *
  * @param s RTSP (de)muxer context
  * @param method the method for the request
  * @param url the target url for the request
  * @param headers extra header lines to include in the request
  * @param send_content if non-null, the data to send as request body content
  * @param send_content_length the length of the send_content data, or 0 if
  *                            send_content is null
  *
  * @return zero if success, nonzero otherwise
  */
 static int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
                                                const char *method, const char *url,
                                                const char *headers,
                                                const unsigned char *send_content,
                                                int send_content_length)
29b9f58b
 {
     RTSPState *rt = s->priv_data;
f5d33f52
     char buf[4096], *out_buf;
     char base64buf[AV_BASE64_SIZE(sizeof(buf))];
29b9f58b
 
f5d33f52
     /* Add in RTSP headers */
     out_buf = buf;
29b9f58b
     rt->seq++;
b17d11c6
     snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
     if (headers)
         av_strlcat(buf, headers, sizeof(buf));
7b4a3645
     av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
b17d11c6
     if (rt->session_id[0] != '\0' && (!headers ||
         !strstr(headers, "\nIf-Match:"))) {
7b4a3645
         av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
29b9f58b
     }
aa8bf2fb
     if (rt->auth[0]) {
         char *str = ff_http_auth_create_response(&rt->auth_state,
                                                  rt->auth, url, method);
         if (str)
             av_strlcat(buf, str, sizeof(buf));
         av_free(str);
     }
dfd017bf
     if (send_content_length > 0 && send_content)
         av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
29b9f58b
     av_strlcat(buf, "\r\n", sizeof(buf));
67c9cd69
 
f5d33f52
     /* base64 encode rtsp if tunneling */
     if (rt->control_transport == RTSP_MODE_TUNNEL) {
         av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
         out_buf = base64buf;
     }
 
dfd2a005
     av_dlog(s, "Sending:\n%s--\n", buf);
67c9cd69
 
925e908b
     ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
f5d33f52
     if (send_content_length > 0 && send_content) {
         if (rt->control_transport == RTSP_MODE_TUNNEL) {
             av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
                                     "with content data not supported\n");
             return AVERROR_PATCHWELCOME;
         }
925e908b
         ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
f5d33f52
     }
30e79845
     rt->last_cmd_time = av_gettime();
d0382374
 
     return 0;
30e79845
 }
 
d0382374
 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
fc490fcf
                            const char *url, const char *headers)
dfd017bf
 {
d0382374
     return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
dfd017bf
 }
 
d0382374
 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
fc490fcf
                      const char *headers, RTSPMessageHeader *reply,
                      unsigned char **content_ptr)
30e79845
 {
d0382374
     return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
fc490fcf
                                          content_ptr, NULL, 0);
29b9f58b
 }
 
d0382374
 int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
fc490fcf
                                   const char *method, const char *url,
                                   const char *header,
                                   RTSPMessageHeader *reply,
                                   unsigned char **content_ptr,
                                   const unsigned char *send_content,
                                   int send_content_length)
dfd017bf
 {
30af0779
     RTSPState *rt = s->priv_data;
     HTTPAuthType cur_auth_type;
d0382374
     int ret;
30af0779
 
 retry:
     cur_auth_type = rt->auth_state.auth_type;
d0382374
     if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
fc490fcf
                                                    send_content,
                                                    send_content_length)))
d0382374
         return ret;
dfd017bf
 
3df54c6b
     if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
d0382374
         return ret;
30af0779
 
     if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
         rt->auth_state.auth_type != HTTP_AUTH_NONE)
         goto retry;
d0382374
 
bf55cf19
     if (reply->status_code > 400){
d93fdcbf
         av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
bf55cf19
                method,
d93fdcbf
                reply->status_code,
                reply->reason);
bf55cf19
         av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
     }
 
d0382374
     return 0;
dfd017bf
 }
 
fef5649a
 int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
c8965800
                               int lower_transport, const char *real_challenge)
1617ad97
 {
     RTSPState *rt = s->priv_data;
f830c9a4
     int rtx, j, i, err, interleave = 0;
1617ad97
     RTSPStream *rtsp_st;
a9e534d5
     RTSPMessageHeader reply1, *reply = &reply1;
53620bba
     char cmd[2048];
e9dea59f
     const char *trans_pref;
 
119b4668
     if (rt->transport == RTSP_TRANSPORT_RDT)
e9dea59f
         trans_pref = "x-pn-tng";
     else
         trans_pref = "RTP/AVP";
115329f1
 
30e79845
     /* default timeout: 1 minute */
     rt->timeout = 60;
 
1617ad97
     /* for each stream, make the setup request */
     /* XXX: we assume the same server is used for the control of each
c8965800
      * RTSP stream */
d1ccf0e0
 
c8965800
     for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
1617ad97
         char transport[2048];
 
07dc4a79
         /*
f830c9a4
          * WMS serves all UDP data over a single connection, the RTX, which
          * isn't necessarily the first in the SDP but has to be the first
          * to be set up, else the second/third SETUP will fail with a 461.
          */
         if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
              rt->server_type == RTSP_SERVER_WMS) {
             if (i == 0) {
                 /* rtx first */
                 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
                     int len = strlen(rt->rtsp_streams[rtx]->control_url);
                     if (len >= 4 &&
c8965800
                         !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
                                 "/rtx"))
f830c9a4
                         break;
                 }
                 if (rtx == rt->nb_rtsp_streams)
                     return -1; /* no RTX found */
                 rtsp_st = rt->rtsp_streams[rtx];
             } else
                 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
         } else
2fea9650
             rtsp_st = rt->rtsp_streams[i];
1617ad97
 
         /* RTP/UDP */
90abbdba
         if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
85fb7b34
             char buf[256];
 
f830c9a4
             if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
                 port = reply->transports[0].client_port_min;
                 goto have_port;
             }
 
85fb7b34
             /* first try in specified port range */
d1ccf0e0
             if (RTSP_RTP_PORT_MIN != 0) {
c8965800
                 while (j <= RTSP_RTP_PORT_MAX) {
57b5555c
                     ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
                                 "?localport=%d", j);
c8965800
                     /* we will use two ports per rtp stream (rtp and rtcp) */
                     j += 2;
f87b1b37
                     if (ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_RDWR) == 0)
85fb7b34
                         goto rtp_opened;
                 }
1617ad97
             }
85fb7b34
 
c8965800
 #if 0
             /* then try on any port */
f87b1b37
             if (ffurl_open(&rtsp_st->rtp_handle, "rtp://", AVIO_RDONLY) < 0) {
c8965800
                 err = AVERROR_INVALIDDATA;
                 goto fail;
             }
a3b058b7
 #else
             av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
             err = AVERROR(EIO);
             goto fail;
c8965800
 #endif
85fb7b34
 
         rtp_opened:
67f34aaa
             port = rtp_get_local_rtp_port(rtsp_st->rtp_handle);
f830c9a4
         have_port:
0ad306bc
             snprintf(transport, sizeof(transport) - 1,
eee2cbff
                      "%s/UDP;", trans_pref);
             if (rt->server_type != RTSP_SERVER_REAL)
                 av_strlcat(transport, "unicast;", sizeof(transport));
             av_strlcatf(transport, sizeof(transport),
                      "client_port=%d", port);
f830c9a4
             if (rt->transport == RTSP_TRANSPORT_RTP &&
                 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
e9dea59f
                 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1617ad97
         }
 
         /* RTP/TCP */
90abbdba
         else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
07dc4a79
             /* For WMS streams, the application streams are only used for
090438cc
              * UDP. When trying to set it up for TCP streams, the server
              * will return an error. Therefore, we skip those streams. */
             if (rt->server_type == RTSP_SERVER_WMS &&
c8965800
                 s->streams[rtsp_st->stream_index]->codec->codec_type ==
72415b2a
                     AVMEDIA_TYPE_DATA)
090438cc
                 continue;
0ad306bc
             snprintf(transport, sizeof(transport) - 1,
d1c6e47c
                      "%s/TCP;", trans_pref);
895678f8
             if (rt->transport != RTSP_TRANSPORT_RDT)
d1c6e47c
                 av_strlcat(transport, "unicast;", sizeof(transport));
             av_strlcatf(transport, sizeof(transport),
                         "interleaved=%d-%d",
                         interleave, interleave + 1);
             interleave += 2;
1617ad97
         }
 
90abbdba
         else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
0ad306bc
             snprintf(transport, sizeof(transport) - 1,
e9dea59f
                      "%s/UDP;multicast", trans_pref);
1617ad97
         }
69adcc4f
         if (s->oformat) {
             av_strlcat(transport, ";mode=receive", sizeof(transport));
         } else if (rt->server_type == RTSP_SERVER_REAL ||
2efc97c2
                    rt->server_type == RTSP_SERVER_WMS)
e9dea59f
             av_strlcat(transport, ";mode=play", sizeof(transport));
115329f1
         snprintf(cmd, sizeof(cmd),
b6892136
                  "Transport: %s\r\n",
b17d11c6
                  transport);
44b70ce5
         if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
e9dea59f
             char real_res[41], real_csum[9];
             ff_rdt_calc_response_and_checksum(real_res, real_csum,
                                               real_challenge);
             av_strlcatf(cmd, sizeof(cmd),
                         "If-Match: %s\r\n"
                         "RealChallenge2: %s, sd=%s\r\n",
                         rt->session_id, real_res, real_csum);
         }
b17d11c6
         ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
8a8754d8
         if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
             err = 1;
             goto fail;
7e6ca34f
         } else if (reply->status_code != RTSP_STATUS_OK ||
                    reply->nb_transports != 1) {
1617ad97
             err = AVERROR_INVALIDDATA;
             goto fail;
         }
 
         /* XXX: same protocol for all streams is required */
         if (i > 0) {
119b4668
             if (reply->transports[0].lower_transport != rt->lower_transport ||
                 reply->transports[0].transport != rt->transport) {
1617ad97
                 err = AVERROR_INVALIDDATA;
                 goto fail;
             }
         } else {
90abbdba
             rt->lower_transport = reply->transports[0].lower_transport;
119b4668
             rt->transport = reply->transports[0].transport;
1617ad97
         }
 
8c579c1c
         /* Fail if the server responded with another lower transport mode
          * than what we requested. */
         if (reply->transports[0].lower_transport != lower_transport) {
             av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
             err = AVERROR_INVALIDDATA;
             goto fail;
1617ad97
         }
 
90abbdba
         switch(reply->transports[0].lower_transport) {
         case RTSP_LOWER_TRANSPORT_TCP:
1617ad97
             rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
             rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
             break;
115329f1
 
c8965800
         case RTSP_LOWER_TRANSPORT_UDP: {
a92c30d7
             char url[1024], options[30] = "";
c8965800
 
a92c30d7
             if (rt->filter_source)
                 av_strlcpy(options, "?connect=1", sizeof(options));
619298a8
             /* Use source address if specified */
             if (reply->transports[0].source[0]) {
                 ff_url_join(url, sizeof(url), "rtp", NULL,
                             reply->transports[0].source,
d8407339
                             reply->transports[0].server_port_min, "%s", options);
619298a8
             } else {
7bac991f
                 ff_url_join(url, sizeof(url), "rtp", NULL, host,
d8407339
                             reply->transports[0].server_port_min, "%s", options);
619298a8
             }
c8965800
             if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
                 rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
                 err = AVERROR_INVALIDDATA;
                 goto fail;
1617ad97
             }
9c8fa20d
             /* Try to initialize the connection state in a
              * potential NAT router by sending dummy packets.
              * RTP/RTCP dummy packets are used for RDT, too.
              */
44b70ce5
             if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
                 CONFIG_RTPDEC)
9c8fa20d
                 rtp_send_punch_packets(rtsp_st->rtp_handle);
1617ad97
             break;
c8965800
         }
         case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
7934b15d
             char url[1024], namebuf[50];
             struct sockaddr_storage addr;
c8965800
             int port, ttl;
 
7934b15d
             if (reply->transports[0].destination.ss_family) {
                 addr      = reply->transports[0].destination;
c8965800
                 port      = reply->transports[0].port_min;
                 ttl       = reply->transports[0].ttl;
             } else {
7934b15d
                 addr      = rtsp_st->sdp_ip;
c8965800
                 port      = rtsp_st->sdp_port;
                 ttl       = rtsp_st->sdp_ttl;
             }
7934b15d
             getnameinfo((struct sockaddr*) &addr, sizeof(addr),
                         namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
             ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
57b5555c
                         port, "?ttl=%d", ttl);
f87b1b37
             if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_RDWR) < 0) {
c8965800
                 err = AVERROR_INVALIDDATA;
                 goto fail;
1617ad97
             }
             break;
         }
c8965800
         }
d1ccf0e0
 
ee0cb67f
         if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
8b1ab7bf
             goto fail;
1617ad97
     }
 
30e79845
     if (reply->timeout > 0)
         rt->timeout = reply->timeout;
 
2e889ae4
     if (rt->server_type == RTSP_SERVER_REAL)
1256d16b
         rt->need_subscription = 1;
 
53620bba
     return 0;
 
 fail:
aeb2de1c
     ff_rtsp_undo_setup(s);
53620bba
     return err;
 }
 
b8c2c41d
 void ff_rtsp_close_connections(AVFormatContext *s)
 {
     RTSPState *rt = s->priv_data;
e52a9145
     if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
     ffurl_close(rt->rtsp_hd);
6217b645
     rt->rtsp_hd = rt->rtsp_hd_out = NULL;
b8c2c41d
 }
 
3307e6ea
 int ff_rtsp_connect(AVFormatContext *s)
53620bba
 {
     RTSPState *rt = s->priv_data;
921da217
     char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
     char *option_list, *option, *filename;
03f8fc08
     int port, err, tcp_fd;
354b7573
     RTSPMessageHeader reply1 = {0}, *reply = &reply1;
90abbdba
     int lower_transport_mask = 0;
2762a7a2
     char real_challenge[64] = "";
03f8fc08
     struct sockaddr_storage peer;
     socklen_t peer_len = sizeof(peer);
57b5555c
 
     if (!ff_network_init())
         return AVERROR(EIO);
c8965800
 redirect:
f5d33f52
     rt->control_transport = RTSP_MODE_PLAIN;
53620bba
     /* extract hostname and port */
f3bfe388
     av_url_split(NULL, 0, auth, sizeof(auth),
f984dcf6
                  host, sizeof(host), &port, path, sizeof(path), s->filename);
f9337897
     if (*auth) {
aa8bf2fb
         av_strlcpy(rt->auth, auth, sizeof(rt->auth));
f9337897
     }
53620bba
     if (port < 0)
         port = RTSP_DEFAULT_PORT;
 
     /* search for options */
602eb779
     option_list = strrchr(path, '?');
53620bba
     if (option_list) {
2a21adf9
         /* Strip out the RTSP specific options, write out the rest of
          * the options back into the same string. */
         filename = option_list;
c8965800
         while (option_list) {
53620bba
             /* move the option pointer */
921da217
             option = ++option_list;
53620bba
             option_list = strchr(option_list, '&');
             if (option_list)
921da217
                 *option_list = 0;
 
53620bba
             /* handle the options */
c8965800
             if (!strcmp(option, "udp")) {
7a033e08
                 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
c8965800
             } else if (!strcmp(option, "multicast")) {
7a033e08
                 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
c8965800
             } else if (!strcmp(option, "tcp")) {
7a033e08
                 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
f5d33f52
             } else if(!strcmp(option, "http")) {
                 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
                 rt->control_transport = RTSP_MODE_TUNNEL;
a92c30d7
             } else if (!strcmp(option, "filter_src")) {
                 rt->filter_source = 1;
c8965800
             } else {
2a21adf9
                 /* Write options back into the buffer, using memmove instead
                  * of strcpy since the strings may overlap. */
                 int len = strlen(option);
                 memmove(++filename, option, len);
                 filename += len;
921da217
                 if (option_list) *filename = '&';
             }
53620bba
         }
921da217
         *filename = 0;
53620bba
     }
 
90abbdba
     if (!lower_transport_mask)
2a1d51c5
         lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
53620bba
 
3e24c770
     if (s->oformat) {
b7dc88fc
         /* Only UDP or TCP - UDP multicast isn't supported. */
         lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
                                 (1 << RTSP_LOWER_TRANSPORT_TCP);
f5d33f52
         if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
3e24c770
             av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
b7dc88fc
                                     "only UDP and TCP are supported for output.\n");
3e24c770
             err = AVERROR(EINVAL);
             goto fail;
         }
     }
 
4bc5cc23
     /* Construct the URI used in request; this is similar to s->filename,
      * but with authentication credentials removed and RTSP specific options
      * stripped out. */
     ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
                 host, port, "%s", path);
 
f5d33f52
     if (rt->control_transport == RTSP_MODE_TUNNEL) {
         /* set up initial handshake for tunneling */
         char httpname[1024];
         char sessioncookie[17];
         char headers[1024];
 
10ed37b5
         ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
f5d33f52
         snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
                  av_get_random_seed(), av_get_random_seed());
 
         /* GET requests */
f87b1b37
         if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_RDONLY) < 0) {
f5d33f52
             err = AVERROR(EIO);
             goto fail;
         }
 
         /* generate GET headers */
         snprintf(headers, sizeof(headers),
                  "x-sessioncookie: %s\r\n"
                  "Accept: application/x-rtsp-tunnelled\r\n"
                  "Pragma: no-cache\r\n"
                  "Cache-Control: no-cache\r\n",
                  sessioncookie);
00e4a1f4
         ff_http_set_headers(rt->rtsp_hd, headers);
f5d33f52
 
         /* complete the connection */
62eaaeac
         if (ffurl_connect(rt->rtsp_hd)) {
f5d33f52
             err = AVERROR(EIO);
             goto fail;
         }
 
         /* POST requests */
f87b1b37
         if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_WRONLY) < 0 ) {
f5d33f52
             err = AVERROR(EIO);
             goto fail;
         }
 
         /* generate POST headers */
         snprintf(headers, sizeof(headers),
                  "x-sessioncookie: %s\r\n"
                  "Content-Type: application/x-rtsp-tunnelled\r\n"
                  "Pragma: no-cache\r\n"
                  "Cache-Control: no-cache\r\n"
                  "Content-Length: 32767\r\n"
                  "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
                  sessioncookie);
00e4a1f4
         ff_http_set_headers(rt->rtsp_hd_out, headers);
         ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
f5d33f52
 
a8ead332
         /* Initialize the authentication state for the POST session. The HTTP
          * protocol implementation doesn't properly handle multi-pass
          * authentication for POST requests, since it would require one of
          * the following:
          * - implementing Expect: 100-continue, which many HTTP servers
          *   don't support anyway, even less the RTSP servers that do HTTP
          *   tunneling
          * - sending the whole POST data until getting a 401 reply specifying
          *   what authentication method to use, then resending all that data
          * - waiting for potential 401 replies directly after sending the
          *   POST header (waiting for some unspecified time)
          * Therefore, we copy the full auth state, which works for both basic
          * and digest. (For digest, we would have to synchronize the nonce
          * count variable between the two sessions, if we'd do more requests
          * with the original session, though.)
          */
         ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
 
9290f15d
         /* complete the connection */
62eaaeac
         if (ffurl_connect(rt->rtsp_hd_out)) {
9290f15d
             err = AVERROR(EIO);
             goto fail;
         }
f5d33f52
     } else {
48e77473
         /* open the tcp connection */
41874d0a
         ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
f87b1b37
         if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_RDWR) < 0) {
41874d0a
             err = AVERROR(EIO);
             goto fail;
         }
00e4a1f4
         rt->rtsp_hd_out = rt->rtsp_hd;
f5d33f52
     }
53620bba
     rt->seq = 0;
 
1869ea03
     tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
03f8fc08
     if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
         getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
                     NULL, 0, NI_NUMERICHOST);
     }
 
c8965800
     /* request options supported by the server; this also detects server
      * type */
1cf151e9
     for (rt->server_type = RTSP_SERVER_RTP;;) {
b17d11c6
         cmd[0] = 0;
2e889ae4
         if (rt->server_type == RTSP_SERVER_REAL)
1cf151e9
             av_strlcat(cmd,
07dc4a79
                        /*
1cf151e9
                         * The following entries are required for proper
                         * streaming from a Realmedia server. They are
                         * interdependent in some way although we currently
                         * don't quite understand how. Values were copied
                         * from mplayer SVN r23589.
07dc4a79
                         *   ClientChallenge is a 16-byte ID in hex
                         *   CompanyID is a 16-byte ID in base64
1cf151e9
                         */
                        "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
                        "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
                        "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
                        "GUID: 00000000-0000-0000-0000-000000000000\r\n",
                        sizeof(cmd));
b17d11c6
         ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1cf151e9
         if (reply->status_code != RTSP_STATUS_OK) {
             err = AVERROR_INVALIDDATA;
             goto fail;
         }
 
         /* detect server type if not standard-compliant RTP */
2e889ae4
         if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
             rt->server_type = RTSP_SERVER_REAL;
1cf151e9
             continue;
7a86bafa
         } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
             rt->server_type = RTSP_SERVER_WMS;
c8965800
         } else if (rt->server_type == RTSP_SERVER_REAL)
1cf151e9
             strcpy(real_challenge, reply->real_challenge);
         break;
     }
 
44b70ce5
     if (s->iformat && CONFIG_RTSP_DEMUXER)
0526c6f7
         err = ff_rtsp_setup_input_streams(s, reply);
44b70ce5
     else if (CONFIG_RTSP_MUXER)
c2688f3a
         err = ff_rtsp_setup_output_streams(s, host);
e23d195d
     if (err)
53620bba
         goto fail;
 
8a8754d8
     do {
c8965800
         int lower_transport = ff_log2_tab[lower_transport_mask &
                                   ~(lower_transport_mask - 1)];
8a8754d8
 
fef5649a
         err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
2e889ae4
                                  rt->server_type == RTSP_SERVER_REAL ?
e9dea59f
                                      real_challenge : NULL);
8a8754d8
         if (err < 0)
7e6ca34f
             goto fail;
90abbdba
         lower_transport_mask &= ~(1 << lower_transport);
         if (lower_transport_mask == 0 && err == 1) {
28c4741a
             err = AVERROR(EPROTONOSUPPORT);
8a8754d8
             goto fail;
         }
     } while (err);
53620bba
 
2762a7a2
     rt->lower_transport_mask = lower_transport_mask;
     av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
ff762d6e
     rt->state = RTSP_STATE_IDLE;
c8965800
     rt->seek_timestamp = 0; /* default is to start stream at position zero */
1617ad97
     return 0;
  fail:
3307e6ea
     ff_rtsp_close_streams(s);
b8c2c41d
     ff_rtsp_close_connections(s);
35cfd646
     if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
d243ba30
         av_strlcpy(s->filename, reply->location, sizeof(s->filename));
         av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
                reply->status_code,
                s->filename);
         goto redirect;
     }
57b5555c
     ff_network_close();
1617ad97
     return err;
 }
2e802e38
 #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1617ad97
 
44b70ce5
 #if CONFIG_RTPDEC
0e59034e
 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
321259c1
                            uint8_t *buf, int buf_size, int64_t wait_end)
0e59034e
 {
     RTSPState *rt = s->priv_data;
     RTSPStream *rtsp_st;
a8475bbd
     int n, i, ret, tcp_fd, timeout_cnt = 0;
     int max_p = 0;
     struct pollfd *p = rt->p;
0e59034e
 
c8965800
     for (;;) {
0e59034e
         if (url_interrupt_cb())
c76374c6
             return AVERROR_EXIT;
321259c1
         if (wait_end && wait_end - av_gettime() < 0)
             return AVERROR(EAGAIN);
a8475bbd
         max_p = 0;
0e59034e
         if (rt->rtsp_hd) {
1869ea03
             tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
a8475bbd
             p[max_p].fd = tcp_fd;
             p[max_p++].events = POLLIN;
0e59034e
         } else {
             tcp_fd = -1;
         }
c8965800
         for (i = 0; i < rt->nb_rtsp_streams; i++) {
0e59034e
             rtsp_st = rt->rtsp_streams[i];
             if (rtsp_st->rtp_handle) {
1869ea03
                 p[max_p].fd = ffurl_get_file_handle(rtsp_st->rtp_handle);
a8475bbd
                 p[max_p++].events = POLLIN;
                 p[max_p].fd = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
                 p[max_p++].events = POLLIN;
0e59034e
             }
         }
a8475bbd
         n = poll(p, max_p, POLL_TIMEOUT_MS);
0e59034e
         if (n > 0) {
a8475bbd
             int j = 1 - (tcp_fd == -1);
9cba6f5f
             timeout_cnt = 0;
c8965800
             for (i = 0; i < rt->nb_rtsp_streams; i++) {
0e59034e
                 rtsp_st = rt->rtsp_streams[i];
                 if (rtsp_st->rtp_handle) {
a8475bbd
                     if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
bc371aca
                         ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
0e59034e
                         if (ret > 0) {
                             *prtsp_st = rtsp_st;
                             return ret;
                         }
                     }
a8475bbd
                     j+=2;
0e59034e
                 }
             }
5fe8021a
 #if CONFIG_RTSP_DEMUXER
a8475bbd
             if (tcp_fd != -1 && p[0].revents & POLLIN) {
0e59034e
                 RTSPMessageHeader reply;
 
3df54c6b
                 ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
3032276b
                 if (ret < 0)
                     return ret;
0e59034e
                 /* XXX: parse message */
c02fd3d2
                 if (rt->state != RTSP_STATE_STREAMING)
0e59034e
                     return 0;
             }
5fe8021a
 #endif
9cba6f5f
         } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
28c4741a
             return AVERROR(ETIMEDOUT);
9cba6f5f
         } else if (n < 0 && errno != EINTR)
             return AVERROR(errno);
0e59034e
     }
 }
 
0526c6f7
 int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
0e59034e
 {
     RTSPState *rt = s->priv_data;
     int ret, len;
321259c1
     RTSPStream *rtsp_st, *first_queue_st = NULL;
     int64_t wait_end = 0;
0e59034e
 
b20359f5
     if (rt->nb_byes == rt->nb_rtsp_streams)
         return AVERROR_EOF;
 
0e59034e
     /* get next frames from the same RTP packet */
     if (rt->cur_transport_priv) {
c8965800
         if (rt->transport == RTSP_TRANSPORT_RDT) {
0e59034e
             ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
c8965800
         } else
0e59034e
             ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
         if (ret == 0) {
             rt->cur_transport_priv = NULL;
             return 0;
         } else if (ret == 1) {
             return 0;
c8965800
         } else
0e59034e
             rt->cur_transport_priv = NULL;
     }
 
80818796
 redo:
321259c1
     if (rt->transport == RTSP_TRANSPORT_RTP) {
         int i;
         int64_t first_queue_time = 0;
         for (i = 0; i < rt->nb_rtsp_streams; i++) {
             RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
9e99f84f
             int64_t queue_time;
             if (!rtpctx)
                 continue;
             queue_time = ff_rtp_queued_packet_time(rtpctx);
321259c1
             if (queue_time && (queue_time - first_queue_time < 0 ||
                                !first_queue_time)) {
                 first_queue_time = queue_time;
                 first_queue_st   = rt->rtsp_streams[i];
             }
         }
80818796
         if (first_queue_time) {
321259c1
             wait_end = first_queue_time + s->max_delay;
80818796
         } else {
             wait_end = 0;
             first_queue_st = NULL;
         }
321259c1
     }
 
0e59034e
     /* read next RTP packet */
96a7c975
     if (!rt->recvbuf) {
         rt->recvbuf = av_malloc(RECVBUF_SIZE);
         if (!rt->recvbuf)
             return AVERROR(ENOMEM);
     }
 
0e59034e
     switch(rt->lower_transport) {
     default:
5fe8021a
 #if CONFIG_RTSP_DEMUXER
0e59034e
     case RTSP_LOWER_TRANSPORT_TCP:
0526c6f7
         len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
0e59034e
         break;
5fe8021a
 #endif
0e59034e
     case RTSP_LOWER_TRANSPORT_UDP:
     case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
321259c1
         len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
2c35a6bd
         if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
0e59034e
             rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
         break;
     }
321259c1
     if (len == AVERROR(EAGAIN) && first_queue_st &&
         rt->transport == RTSP_TRANSPORT_RTP) {
         rtsp_st = first_queue_st;
         ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
         goto end;
     }
0e59034e
     if (len < 0)
         return len;
     if (len == 0)
         return AVERROR_EOF;
c8965800
     if (rt->transport == RTSP_TRANSPORT_RDT) {
ad4ad27f
         ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
2cab6b48
     } else {
ad4ad27f
         ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
2cab6b48
         if (ret < 0) {
             /* Either bad packet, or a RTCP packet. Check if the
              * first_rtcp_ntp_time field was initialized. */
             RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
             if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
                 /* first_rtcp_ntp_time has been initialized for this stream,
                  * copy the same value to all other uninitialized streams,
                  * in order to map their timestamp origin to the same ntp time
                  * as this one. */
                 int i;
3a1cdcc7
                 AVStream *st = NULL;
                 if (rtsp_st->stream_index >= 0)
                     st = s->streams[rtsp_st->stream_index];
2cab6b48
                 for (i = 0; i < rt->nb_rtsp_streams; i++) {
744a882f
                     RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
3a1cdcc7
                     AVStream *st2 = NULL;
                     if (rt->rtsp_streams[i]->stream_index >= 0)
                         st2 = s->streams[rt->rtsp_streams[i]->stream_index];
                     if (rtpctx2 && st && st2 &&
                         rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
2cab6b48
                         rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
3a1cdcc7
                         rtpctx2->rtcp_ts_offset = av_rescale_q(
                             rtpctx->rtcp_ts_offset, st->time_base,
                             st2->time_base);
                     }
2cab6b48
                 }
             }
b20359f5
             if (ret == -RTCP_BYE) {
                 rt->nb_byes++;
 
                 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
                        rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
 
                 if (rt->nb_byes == rt->nb_rtsp_streams)
                     return AVERROR_EOF;
             }
2cab6b48
         }
     }
321259c1
 end:
0e59034e
     if (ret < 0)
         goto redo;
c8965800
     if (ret == 1)
0e59034e
         /* more packets may follow, so we save the RTP context */
         rt->cur_transport_priv = rtsp_st->transport_priv;
 
     return ret;
 }
44b70ce5
 #endif /* CONFIG_RTPDEC */
0e59034e
 
44b70ce5
 #if CONFIG_SDP_DEMUXER
cb1fdc61
 static int sdp_probe(AVProbeData *p1)
93ced3e8
 {
0e1ceacd
     const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
cb1fdc61
 
3fbd12d1
     /* we look for a line beginning "c=IN IP" */
0e1ceacd
     while (p < p_end && *p != '\0') {
3fbd12d1
         if (p + sizeof("c=IN IP") - 1 < p_end &&
             av_strstart(p, "c=IN IP", NULL))
cb1fdc61
             return AVPROBE_SCORE_MAX / 2;
0e1ceacd
 
c8965800
         while (p < p_end - 1 && *p != '\n') p++;
0e1ceacd
         if (++p >= p_end)
cb1fdc61
             break;
         if (*p == '\r')
             p++;
     }
93ced3e8
     return 0;
 }
 
c8965800
 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
93ced3e8
 {
8b1ab7bf
     RTSPState *rt = s->priv_data;
93ced3e8
     RTSPStream *rtsp_st;
     int size, i, err;
     char *content;
     char url[1024];
 
57b5555c
     if (!ff_network_init())
         return AVERROR(EIO);
 
93ced3e8
     /* read the whole sdp file */
     /* XXX: better loading */
     content = av_malloc(SDP_MAX_SIZE);
b7effd4e
     size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
93ced3e8
     if (size <= 0) {
         av_free(content);
         return AVERROR_INVALIDDATA;
     }
     content[size] ='\0';
 
f81c7ac7
     err = ff_sdp_parse(s, content);
93ced3e8
     av_free(content);
f81c7ac7
     if (err) goto fail;
93ced3e8
 
     /* open each RTP stream */
c8965800
     for (i = 0; i < rt->nb_rtsp_streams; i++) {
3fbd12d1
         char namebuf[50];
8b1ab7bf
         rtsp_st = rt->rtsp_streams[i];
115329f1
 
3fbd12d1
         getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
                     namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
57b5555c
         ff_url_join(url, sizeof(url), "rtp", NULL,
3fbd12d1
                     namebuf, rtsp_st->sdp_port,
57b5555c
                     "?localport=%d&ttl=%d", rtsp_st->sdp_port,
                     rtsp_st->sdp_ttl);
f87b1b37
         if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_RDWR) < 0) {
93ced3e8
             err = AVERROR_INVALIDDATA;
             goto fail;
         }
ee0cb67f
         if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
8b1ab7bf
             goto fail;
93ced3e8
     }
     return 0;
c8965800
 fail:
3307e6ea
     ff_rtsp_close_streams(s);
57b5555c
     ff_network_close();
93ced3e8
     return err;
 }
 
 static int sdp_read_close(AVFormatContext *s)
 {
3307e6ea
     ff_rtsp_close_streams(s);
57b5555c
     ff_network_close();
93ced3e8
     return 0;
 }
 
c6610a21
 AVInputFormat ff_sdp_demuxer = {
93ced3e8
     "sdp",
bde15e74
     NULL_IF_CONFIG_SMALL("SDP"),
93ced3e8
     sizeof(RTSPState),
     sdp_probe,
     sdp_read_header,
0526c6f7
     ff_rtsp_fetch_packet,
93ced3e8
     sdp_read_close,
 };
44b70ce5
 #endif /* CONFIG_SDP_DEMUXER */
44594cc7
 
44b70ce5
 #if CONFIG_RTP_DEMUXER
44594cc7
 static int rtp_probe(AVProbeData *p)
 {
     if (av_strstart(p->filename, "rtp:", NULL))
         return AVPROBE_SCORE_MAX;
     return 0;
 }
 
 static int rtp_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
 {
     uint8_t recvbuf[1500];
     char host[500], sdp[500];
     int ret, port;
     URLContext* in = NULL;
     int payload_type;
     AVCodecContext codec;
     struct sockaddr_storage addr;
ae628ec1
     AVIOContext pb;
44594cc7
     socklen_t addrlen = sizeof(addr);
 
     if (!ff_network_init())
         return AVERROR(EIO);
 
f87b1b37
     ret = ffurl_open(&in, s->filename, AVIO_RDONLY);
44594cc7
     if (ret)
         goto fail;
 
     while (1) {
bc371aca
         ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
44594cc7
         if (ret == AVERROR(EAGAIN))
             continue;
         if (ret < 0)
             goto fail;
         if (ret < 12) {
             av_log(s, AV_LOG_WARNING, "Received too short packet\n");
             continue;
         }
 
         if ((recvbuf[0] & 0xc0) != 0x80) {
             av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
                                       "received\n");
             continue;
         }
 
         payload_type = recvbuf[1] & 0x7f;
         break;
     }
1869ea03
     getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
e52a9145
     ffurl_close(in);
44594cc7
     in = NULL;
 
     memset(&codec, 0, sizeof(codec));
     if (ff_rtp_get_codec_info(&codec, payload_type)) {
         av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
                                 "without an SDP file describing it\n",
                                  payload_type);
         goto fail;
     }
     if (codec.codec_type != AVMEDIA_TYPE_DATA) {
         av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
                                   "properly you need an SDP file "
                                   "describing it\n");
     }
 
     av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
                  NULL, 0, s->filename);
 
     snprintf(sdp, sizeof(sdp),
              "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
              addr.ss_family == AF_INET ? 4 : 6, host,
              codec.codec_type == AVMEDIA_TYPE_DATA  ? "application" :
              codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
              port, payload_type);
     av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
 
e731b8d8
     ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
44594cc7
     s->pb = &pb;
 
     /* sdp_read_header initializes this again */
     ff_network_close();
 
     ret = sdp_read_header(s, ap);
     s->pb = NULL;
     return ret;
 
 fail:
     if (in)
e52a9145
         ffurl_close(in);
44594cc7
     ff_network_close();
     return ret;
 }
 
c6610a21
 AVInputFormat ff_rtp_demuxer = {
44594cc7
     "rtp",
     NULL_IF_CONFIG_SMALL("RTP input format"),
     sizeof(RTSPState),
     rtp_probe,
     rtp_read_header,
0526c6f7
     ff_rtsp_fetch_packet,
44594cc7
     sdp_read_close,
     .flags = AVFMT_NOFILE,
 };
44b70ce5
 #endif /* CONFIG_RTP_DEMUXER */
44594cc7