• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

libavformat/rtsp.c

Go to the documentation of this file.
00001 /*
00002  * RTSP/SDP client
00003  * Copyright (c) 2002 Fabrice Bellard
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include "libavutil/base64.h"
00023 #include "libavutil/avstring.h"
00024 #include "libavutil/intreadwrite.h"
00025 #include "libavutil/parseutils.h"
00026 #include "libavutil/random_seed.h"
00027 #include "libavutil/dict.h"
00028 #include "avformat.h"
00029 #include "avio_internal.h"
00030 
00031 #include <sys/time.h>
00032 #if HAVE_POLL_H
00033 #include <poll.h>
00034 #endif
00035 #include <strings.h>
00036 #include "internal.h"
00037 #include "network.h"
00038 #include "os_support.h"
00039 #include "http.h"
00040 #include "rtsp.h"
00041 
00042 #include "rtpdec.h"
00043 #include "rdt.h"
00044 #include "rtpdec_formats.h"
00045 #include "rtpenc_chain.h"
00046 #include "url.h"
00047 
00048 //#define DEBUG
00049 
00050 /* Timeout values for socket poll, in ms,
00051  * and read_packet(), in seconds  */
00052 #define POLL_TIMEOUT_MS 100
00053 #define READ_PACKET_TIMEOUT_S 10
00054 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / POLL_TIMEOUT_MS
00055 #define SDP_MAX_SIZE 16384
00056 #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
00057 
00058 static void get_word_until_chars(char *buf, int buf_size,
00059                                  const char *sep, const char **pp)
00060 {
00061     const char *p;
00062     char *q;
00063 
00064     p = *pp;
00065     p += strspn(p, SPACE_CHARS);
00066     q = buf;
00067     while (!strchr(sep, *p) && *p != '\0') {
00068         if ((q - buf) < buf_size - 1)
00069             *q++ = *p;
00070         p++;
00071     }
00072     if (buf_size > 0)
00073         *q = '\0';
00074     *pp = p;
00075 }
00076 
00077 static void get_word_sep(char *buf, int buf_size, const char *sep,
00078                          const char **pp)
00079 {
00080     if (**pp == '/') (*pp)++;
00081     get_word_until_chars(buf, buf_size, sep, pp);
00082 }
00083 
00084 static void get_word(char *buf, int buf_size, const char **pp)
00085 {
00086     get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
00087 }
00088 
00093 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
00094 {
00095     char buf[256];
00096 
00097     p += strspn(p, SPACE_CHARS);
00098     if (!av_stristart(p, "npt=", &p))
00099         return;
00100 
00101     *start = AV_NOPTS_VALUE;
00102     *end = AV_NOPTS_VALUE;
00103 
00104     get_word_sep(buf, sizeof(buf), "-", &p);
00105     av_parse_time(start, buf, 1);
00106     if (*p == '-') {
00107         p++;
00108         get_word_sep(buf, sizeof(buf), "-", &p);
00109         av_parse_time(end, buf, 1);
00110     }
00111 //    av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
00112 //    av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
00113 }
00114 
00115 static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
00116 {
00117     struct addrinfo hints, *ai = NULL;
00118     memset(&hints, 0, sizeof(hints));
00119     hints.ai_flags = AI_NUMERICHOST;
00120     if (getaddrinfo(buf, NULL, &hints, &ai))
00121         return -1;
00122     memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
00123     freeaddrinfo(ai);
00124     return 0;
00125 }
00126 
00127 #if CONFIG_RTPDEC
00128 static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
00129                              RTSPStream *rtsp_st, AVCodecContext *codec)
00130 {
00131     if (!handler)
00132         return;
00133     codec->codec_id          = handler->codec_id;
00134     rtsp_st->dynamic_handler = handler;
00135     if (handler->alloc)
00136         rtsp_st->dynamic_protocol_context = handler->alloc();
00137 }
00138 
00139 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
00140 static int sdp_parse_rtpmap(AVFormatContext *s,
00141                             AVStream *st, RTSPStream *rtsp_st,
00142                             int payload_type, const char *p)
00143 {
00144     AVCodecContext *codec = st->codec;
00145     char buf[256];
00146     int i;
00147     AVCodec *c;
00148     const char *c_name;
00149 
00150     /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
00151      * see if we can handle this kind of payload.
00152      * The space should normally not be there but some Real streams or
00153      * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
00154      * have a trailing space. */
00155     get_word_sep(buf, sizeof(buf), "/ ", &p);
00156     if (payload_type >= RTP_PT_PRIVATE) {
00157         RTPDynamicProtocolHandler *handler =
00158             ff_rtp_handler_find_by_name(buf, codec->codec_type);
00159         init_rtp_handler(handler, rtsp_st, codec);
00160         /* If no dynamic handler was found, check with the list of standard
00161          * allocated types, if such a stream for some reason happens to
00162          * use a private payload type. This isn't handled in rtpdec.c, since
00163          * the format name from the rtpmap line never is passed into rtpdec. */
00164         if (!rtsp_st->dynamic_handler)
00165             codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
00166     } else {
00167         /* We are in a standard case
00168          * (from http://www.iana.org/assignments/rtp-parameters). */
00169         /* search into AVRtpPayloadTypes[] */
00170         codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
00171     }
00172 
00173     c = avcodec_find_decoder(codec->codec_id);
00174     if (c && c->name)
00175         c_name = c->name;
00176     else
00177         c_name = "(null)";
00178 
00179     get_word_sep(buf, sizeof(buf), "/", &p);
00180     i = atoi(buf);
00181     switch (codec->codec_type) {
00182     case AVMEDIA_TYPE_AUDIO:
00183         av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
00184         codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
00185         codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
00186         if (i > 0) {
00187             codec->sample_rate = i;
00188             av_set_pts_info(st, 32, 1, codec->sample_rate);
00189             get_word_sep(buf, sizeof(buf), "/", &p);
00190             i = atoi(buf);
00191             if (i > 0)
00192                 codec->channels = i;
00193             // TODO: there is a bug here; if it is a mono stream, and
00194             // less than 22000Hz, faad upconverts to stereo and twice
00195             // the frequency.  No problem, but the sample rate is being
00196             // set here by the sdp line. Patch on its way. (rdm)
00197         }
00198         av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
00199                codec->sample_rate);
00200         av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
00201                codec->channels);
00202         break;
00203     case AVMEDIA_TYPE_VIDEO:
00204         av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
00205         if (i > 0)
00206             av_set_pts_info(st, 32, 1, i);
00207         break;
00208     default:
00209         break;
00210     }
00211     return 0;
00212 }
00213 
00214 /* parse the attribute line from the fmtp a line of an sdp response. This
00215  * is broken out as a function because it is used in rtp_h264.c, which is
00216  * forthcoming. */
00217 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
00218                                 char *value, int value_size)
00219 {
00220     *p += strspn(*p, SPACE_CHARS);
00221     if (**p) {
00222         get_word_sep(attr, attr_size, "=", p);
00223         if (**p == '=')
00224             (*p)++;
00225         get_word_sep(value, value_size, ";", p);
00226         if (**p == ';')
00227             (*p)++;
00228         return 1;
00229     }
00230     return 0;
00231 }
00232 
00233 typedef struct SDPParseState {
00234     /* SDP only */
00235     struct sockaddr_storage default_ip;
00236     int            default_ttl;
00237     int            skip_media;  
00238 } SDPParseState;
00239 
00240 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
00241                            int letter, const char *buf)
00242 {
00243     RTSPState *rt = s->priv_data;
00244     char buf1[64], st_type[64];
00245     const char *p;
00246     enum AVMediaType codec_type;
00247     int payload_type, i;
00248     AVStream *st;
00249     RTSPStream *rtsp_st;
00250     struct sockaddr_storage sdp_ip;
00251     int ttl;
00252 
00253     av_dlog(s, "sdp: %c='%s'\n", letter, buf);
00254 
00255     p = buf;
00256     if (s1->skip_media && letter != 'm')
00257         return;
00258     switch (letter) {
00259     case 'c':
00260         get_word(buf1, sizeof(buf1), &p);
00261         if (strcmp(buf1, "IN") != 0)
00262             return;
00263         get_word(buf1, sizeof(buf1), &p);
00264         if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
00265             return;
00266         get_word_sep(buf1, sizeof(buf1), "/", &p);
00267         if (get_sockaddr(buf1, &sdp_ip))
00268             return;
00269         ttl = 16;
00270         if (*p == '/') {
00271             p++;
00272             get_word_sep(buf1, sizeof(buf1), "/", &p);
00273             ttl = atoi(buf1);
00274         }
00275         if (s->nb_streams == 0) {
00276             s1->default_ip = sdp_ip;
00277             s1->default_ttl = ttl;
00278         } else {
00279             rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
00280             rtsp_st->sdp_ip = sdp_ip;
00281             rtsp_st->sdp_ttl = ttl;
00282         }
00283         break;
00284     case 's':
00285         av_dict_set(&s->metadata, "title", p, 0);
00286         break;
00287     case 'i':
00288         if (s->nb_streams == 0) {
00289             av_dict_set(&s->metadata, "comment", p, 0);
00290             break;
00291         }
00292         break;
00293     case 'm':
00294         /* new stream */
00295         s1->skip_media = 0;
00296         get_word(st_type, sizeof(st_type), &p);
00297         if (!strcmp(st_type, "audio")) {
00298             codec_type = AVMEDIA_TYPE_AUDIO;
00299         } else if (!strcmp(st_type, "video")) {
00300             codec_type = AVMEDIA_TYPE_VIDEO;
00301         } else if (!strcmp(st_type, "application")) {
00302             codec_type = AVMEDIA_TYPE_DATA;
00303         } else {
00304             s1->skip_media = 1;
00305             return;
00306         }
00307         rtsp_st = av_mallocz(sizeof(RTSPStream));
00308         if (!rtsp_st)
00309             return;
00310         rtsp_st->stream_index = -1;
00311         dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
00312 
00313         rtsp_st->sdp_ip = s1->default_ip;
00314         rtsp_st->sdp_ttl = s1->default_ttl;
00315 
00316         get_word(buf1, sizeof(buf1), &p); /* port */
00317         rtsp_st->sdp_port = atoi(buf1);
00318 
00319         get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
00320 
00321         /* XXX: handle list of formats */
00322         get_word(buf1, sizeof(buf1), &p); /* format list */
00323         rtsp_st->sdp_payload_type = atoi(buf1);
00324 
00325         if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
00326             /* no corresponding stream */
00327         } else {
00328             st = av_new_stream(s, rt->nb_rtsp_streams - 1);
00329             if (!st)
00330                 return;
00331             rtsp_st->stream_index = st->index;
00332             st->codec->codec_type = codec_type;
00333             if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
00334                 RTPDynamicProtocolHandler *handler;
00335                 /* if standard payload type, we can find the codec right now */
00336                 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
00337                 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
00338                     st->codec->sample_rate > 0)
00339                     av_set_pts_info(st, 32, 1, st->codec->sample_rate);
00340                 /* Even static payload types may need a custom depacketizer */
00341                 handler = ff_rtp_handler_find_by_id(
00342                               rtsp_st->sdp_payload_type, st->codec->codec_type);
00343                 init_rtp_handler(handler, rtsp_st, st->codec);
00344             }
00345         }
00346         /* put a default control url */
00347         av_strlcpy(rtsp_st->control_url, rt->control_uri,
00348                    sizeof(rtsp_st->control_url));
00349         break;
00350     case 'a':
00351         if (av_strstart(p, "control:", &p)) {
00352             if (s->nb_streams == 0) {
00353                 if (!strncmp(p, "rtsp://", 7))
00354                     av_strlcpy(rt->control_uri, p,
00355                                sizeof(rt->control_uri));
00356             } else {
00357                 char proto[32];
00358                 /* get the control url */
00359                 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
00360 
00361                 /* XXX: may need to add full url resolution */
00362                 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
00363                              NULL, NULL, 0, p);
00364                 if (proto[0] == '\0') {
00365                     /* relative control URL */
00366                     if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
00367                     av_strlcat(rtsp_st->control_url, "/",
00368                                sizeof(rtsp_st->control_url));
00369                     av_strlcat(rtsp_st->control_url, p,
00370                                sizeof(rtsp_st->control_url));
00371                 } else
00372                     av_strlcpy(rtsp_st->control_url, p,
00373                                sizeof(rtsp_st->control_url));
00374             }
00375         } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
00376             /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
00377             get_word(buf1, sizeof(buf1), &p);
00378             payload_type = atoi(buf1);
00379             st = s->streams[s->nb_streams - 1];
00380             rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
00381             sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
00382         } else if (av_strstart(p, "fmtp:", &p) ||
00383                    av_strstart(p, "framesize:", &p)) {
00384             /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
00385             // let dynamic protocol handlers have a stab at the line.
00386             get_word(buf1, sizeof(buf1), &p);
00387             payload_type = atoi(buf1);
00388             for (i = 0; i < rt->nb_rtsp_streams; i++) {
00389                 rtsp_st = rt->rtsp_streams[i];
00390                 if (rtsp_st->sdp_payload_type == payload_type &&
00391                     rtsp_st->dynamic_handler &&
00392                     rtsp_st->dynamic_handler->parse_sdp_a_line)
00393                     rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
00394                         rtsp_st->dynamic_protocol_context, buf);
00395             }
00396         } else if (av_strstart(p, "range:", &p)) {
00397             int64_t start, end;
00398 
00399             // this is so that seeking on a streamed file can work.
00400             rtsp_parse_range_npt(p, &start, &end);
00401             s->start_time = start;
00402             /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
00403             s->duration   = (end == AV_NOPTS_VALUE) ?
00404                             AV_NOPTS_VALUE : end - start;
00405         } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
00406             if (atoi(p) == 1)
00407                 rt->transport = RTSP_TRANSPORT_RDT;
00408         } else if (av_strstart(p, "SampleRate:integer;", &p) &&
00409                    s->nb_streams > 0) {
00410             st = s->streams[s->nb_streams - 1];
00411             st->codec->sample_rate = atoi(p);
00412         } else {
00413             if (rt->server_type == RTSP_SERVER_WMS)
00414                 ff_wms_parse_sdp_a_line(s, p);
00415             if (s->nb_streams > 0) {
00416                 if (rt->server_type == RTSP_SERVER_REAL)
00417                     ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
00418 
00419                 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
00420                 if (rtsp_st->dynamic_handler &&
00421                     rtsp_st->dynamic_handler->parse_sdp_a_line)
00422                     rtsp_st->dynamic_handler->parse_sdp_a_line(s,
00423                         s->nb_streams - 1,
00424                         rtsp_st->dynamic_protocol_context, buf);
00425             }
00426         }
00427         break;
00428     }
00429 }
00430 
00431 int ff_sdp_parse(AVFormatContext *s, const char *content)
00432 {
00433     RTSPState *rt = s->priv_data;
00434     const char *p;
00435     int letter;
00436     /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
00437      * contain long SDP lines containing complete ASF Headers (several
00438      * kB) or arrays of MDPR (RM stream descriptor) headers plus
00439      * "rulebooks" describing their properties. Therefore, the SDP line
00440      * buffer is large.
00441      *
00442      * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
00443      * in rtpdec_xiph.c. */
00444     char buf[16384], *q;
00445     SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
00446 
00447     memset(s1, 0, sizeof(SDPParseState));
00448     p = content;
00449     for (;;) {
00450         p += strspn(p, SPACE_CHARS);
00451         letter = *p;
00452         if (letter == '\0')
00453             break;
00454         p++;
00455         if (*p != '=')
00456             goto next_line;
00457         p++;
00458         /* get the content */
00459         q = buf;
00460         while (*p != '\n' && *p != '\r' && *p != '\0') {
00461             if ((q - buf) < sizeof(buf) - 1)
00462                 *q++ = *p;
00463             p++;
00464         }
00465         *q = '\0';
00466         sdp_parse_line(s, s1, letter, buf);
00467     next_line:
00468         while (*p != '\n' && *p != '\0')
00469             p++;
00470         if (*p == '\n')
00471             p++;
00472     }
00473     rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
00474     if (!rt->p) return AVERROR(ENOMEM);
00475     return 0;
00476 }
00477 #endif /* CONFIG_RTPDEC */
00478 
00479 void ff_rtsp_undo_setup(AVFormatContext *s)
00480 {
00481     RTSPState *rt = s->priv_data;
00482     int i;
00483 
00484     for (i = 0; i < rt->nb_rtsp_streams; i++) {
00485         RTSPStream *rtsp_st = rt->rtsp_streams[i];
00486         if (!rtsp_st)
00487             continue;
00488         if (rtsp_st->transport_priv) {
00489             if (s->oformat) {
00490                 AVFormatContext *rtpctx = rtsp_st->transport_priv;
00491                 av_write_trailer(rtpctx);
00492                 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
00493                     uint8_t *ptr;
00494                     avio_close_dyn_buf(rtpctx->pb, &ptr);
00495                     av_free(ptr);
00496                 } else {
00497                     avio_close(rtpctx->pb);
00498                 }
00499                 avformat_free_context(rtpctx);
00500             } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
00501                 ff_rdt_parse_close(rtsp_st->transport_priv);
00502             else if (CONFIG_RTPDEC)
00503                 rtp_parse_close(rtsp_st->transport_priv);
00504         }
00505         rtsp_st->transport_priv = NULL;
00506         if (rtsp_st->rtp_handle)
00507             ffurl_close(rtsp_st->rtp_handle);
00508         rtsp_st->rtp_handle = NULL;
00509     }
00510 }
00511 
00512 /* close and free RTSP streams */
00513 void ff_rtsp_close_streams(AVFormatContext *s)
00514 {
00515     RTSPState *rt = s->priv_data;
00516     int i;
00517     RTSPStream *rtsp_st;
00518 
00519     ff_rtsp_undo_setup(s);
00520     for (i = 0; i < rt->nb_rtsp_streams; i++) {
00521         rtsp_st = rt->rtsp_streams[i];
00522         if (rtsp_st) {
00523             if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
00524                 rtsp_st->dynamic_handler->free(
00525                     rtsp_st->dynamic_protocol_context);
00526             av_free(rtsp_st);
00527         }
00528     }
00529     av_free(rt->rtsp_streams);
00530     if (rt->asf_ctx) {
00531         av_close_input_stream (rt->asf_ctx);
00532         rt->asf_ctx = NULL;
00533     }
00534     av_free(rt->p);
00535     av_free(rt->recvbuf);
00536 }
00537 
00538 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
00539 {
00540     RTSPState *rt = s->priv_data;
00541     AVStream *st = NULL;
00542 
00543     /* open the RTP context */
00544     if (rtsp_st->stream_index >= 0)
00545         st = s->streams[rtsp_st->stream_index];
00546     if (!st)
00547         s->ctx_flags |= AVFMTCTX_NOHEADER;
00548 
00549     if (s->oformat && CONFIG_RTSP_MUXER) {
00550         rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
00551                                       rtsp_st->rtp_handle,
00552                                       RTSP_TCP_MAX_PACKET_SIZE);
00553         /* Ownership of rtp_handle is passed to the rtp mux context */
00554         rtsp_st->rtp_handle = NULL;
00555     } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
00556         rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
00557                                             rtsp_st->dynamic_protocol_context,
00558                                             rtsp_st->dynamic_handler);
00559     else if (CONFIG_RTPDEC)
00560         rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
00561                                          rtsp_st->sdp_payload_type,
00562             (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
00563             ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
00564 
00565     if (!rtsp_st->transport_priv) {
00566          return AVERROR(ENOMEM);
00567     } else if (rt->transport != RTSP_TRANSPORT_RDT && CONFIG_RTPDEC) {
00568         if (rtsp_st->dynamic_handler) {
00569             rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
00570                                            rtsp_st->dynamic_protocol_context,
00571                                            rtsp_st->dynamic_handler);
00572         }
00573     }
00574 
00575     return 0;
00576 }
00577 
00578 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
00579 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
00580 {
00581     const char *p;
00582     int v;
00583 
00584     p = *pp;
00585     p += strspn(p, SPACE_CHARS);
00586     v = strtol(p, (char **)&p, 10);
00587     if (*p == '-') {
00588         p++;
00589         *min_ptr = v;
00590         v = strtol(p, (char **)&p, 10);
00591         *max_ptr = v;
00592     } else {
00593         *min_ptr = v;
00594         *max_ptr = v;
00595     }
00596     *pp = p;
00597 }
00598 
00599 /* XXX: only one transport specification is parsed */
00600 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
00601 {
00602     char transport_protocol[16];
00603     char profile[16];
00604     char lower_transport[16];
00605     char parameter[16];
00606     RTSPTransportField *th;
00607     char buf[256];
00608 
00609     reply->nb_transports = 0;
00610 
00611     for (;;) {
00612         p += strspn(p, SPACE_CHARS);
00613         if (*p == '\0')
00614             break;
00615 
00616         th = &reply->transports[reply->nb_transports];
00617 
00618         get_word_sep(transport_protocol, sizeof(transport_protocol),
00619                      "/", &p);
00620         if (!strcasecmp (transport_protocol, "rtp")) {
00621             get_word_sep(profile, sizeof(profile), "/;,", &p);
00622             lower_transport[0] = '\0';
00623             /* rtp/avp/<protocol> */
00624             if (*p == '/') {
00625                 get_word_sep(lower_transport, sizeof(lower_transport),
00626                              ";,", &p);
00627             }
00628             th->transport = RTSP_TRANSPORT_RTP;
00629         } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
00630                    !strcasecmp (transport_protocol, "x-real-rdt")) {
00631             /* x-pn-tng/<protocol> */
00632             get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
00633             profile[0] = '\0';
00634             th->transport = RTSP_TRANSPORT_RDT;
00635         }
00636         if (!strcasecmp(lower_transport, "TCP"))
00637             th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
00638         else
00639             th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
00640 
00641         if (*p == ';')
00642             p++;
00643         /* get each parameter */
00644         while (*p != '\0' && *p != ',') {
00645             get_word_sep(parameter, sizeof(parameter), "=;,", &p);
00646             if (!strcmp(parameter, "port")) {
00647                 if (*p == '=') {
00648                     p++;
00649                     rtsp_parse_range(&th->port_min, &th->port_max, &p);
00650                 }
00651             } else if (!strcmp(parameter, "client_port")) {
00652                 if (*p == '=') {
00653                     p++;
00654                     rtsp_parse_range(&th->client_port_min,
00655                                      &th->client_port_max, &p);
00656                 }
00657             } else if (!strcmp(parameter, "server_port")) {
00658                 if (*p == '=') {
00659                     p++;
00660                     rtsp_parse_range(&th->server_port_min,
00661                                      &th->server_port_max, &p);
00662                 }
00663             } else if (!strcmp(parameter, "interleaved")) {
00664                 if (*p == '=') {
00665                     p++;
00666                     rtsp_parse_range(&th->interleaved_min,
00667                                      &th->interleaved_max, &p);
00668                 }
00669             } else if (!strcmp(parameter, "multicast")) {
00670                 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
00671                     th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
00672             } else if (!strcmp(parameter, "ttl")) {
00673                 if (*p == '=') {
00674                     p++;
00675                     th->ttl = strtol(p, (char **)&p, 10);
00676                 }
00677             } else if (!strcmp(parameter, "destination")) {
00678                 if (*p == '=') {
00679                     p++;
00680                     get_word_sep(buf, sizeof(buf), ";,", &p);
00681                     get_sockaddr(buf, &th->destination);
00682                 }
00683             } else if (!strcmp(parameter, "source")) {
00684                 if (*p == '=') {
00685                     p++;
00686                     get_word_sep(buf, sizeof(buf), ";,", &p);
00687                     av_strlcpy(th->source, buf, sizeof(th->source));
00688                 }
00689             }
00690 
00691             while (*p != ';' && *p != '\0' && *p != ',')
00692                 p++;
00693             if (*p == ';')
00694                 p++;
00695         }
00696         if (*p == ',')
00697             p++;
00698 
00699         reply->nb_transports++;
00700     }
00701 }
00702 
00703 static void handle_rtp_info(RTSPState *rt, const char *url,
00704                             uint32_t seq, uint32_t rtptime)
00705 {
00706     int i;
00707     if (!rtptime || !url[0])
00708         return;
00709     if (rt->transport != RTSP_TRANSPORT_RTP)
00710         return;
00711     for (i = 0; i < rt->nb_rtsp_streams; i++) {
00712         RTSPStream *rtsp_st = rt->rtsp_streams[i];
00713         RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
00714         if (!rtpctx)
00715             continue;
00716         if (!strcmp(rtsp_st->control_url, url)) {
00717             rtpctx->base_timestamp = rtptime;
00718             break;
00719         }
00720     }
00721 }
00722 
00723 static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
00724 {
00725     int read = 0;
00726     char key[20], value[1024], url[1024] = "";
00727     uint32_t seq = 0, rtptime = 0;
00728 
00729     for (;;) {
00730         p += strspn(p, SPACE_CHARS);
00731         if (!*p)
00732             break;
00733         get_word_sep(key, sizeof(key), "=", &p);
00734         if (*p != '=')
00735             break;
00736         p++;
00737         get_word_sep(value, sizeof(value), ";, ", &p);
00738         read++;
00739         if (!strcmp(key, "url"))
00740             av_strlcpy(url, value, sizeof(url));
00741         else if (!strcmp(key, "seq"))
00742             seq = strtoul(value, NULL, 10);
00743         else if (!strcmp(key, "rtptime"))
00744             rtptime = strtoul(value, NULL, 10);
00745         if (*p == ',') {
00746             handle_rtp_info(rt, url, seq, rtptime);
00747             url[0] = '\0';
00748             seq = rtptime = 0;
00749             read = 0;
00750         }
00751         if (*p)
00752             p++;
00753     }
00754     if (read > 0)
00755         handle_rtp_info(rt, url, seq, rtptime);
00756 }
00757 
00758 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
00759                         RTSPState *rt, const char *method)
00760 {
00761     const char *p;
00762 
00763     /* NOTE: we do case independent match for broken servers */
00764     p = buf;
00765     if (av_stristart(p, "Session:", &p)) {
00766         int t;
00767         get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
00768         if (av_stristart(p, ";timeout=", &p) &&
00769             (t = strtol(p, NULL, 10)) > 0) {
00770             reply->timeout = t;
00771         }
00772     } else if (av_stristart(p, "Content-Length:", &p)) {
00773         reply->content_length = strtol(p, NULL, 10);
00774     } else if (av_stristart(p, "Transport:", &p)) {
00775         rtsp_parse_transport(reply, p);
00776     } else if (av_stristart(p, "CSeq:", &p)) {
00777         reply->seq = strtol(p, NULL, 10);
00778     } else if (av_stristart(p, "Range:", &p)) {
00779         rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
00780     } else if (av_stristart(p, "RealChallenge1:", &p)) {
00781         p += strspn(p, SPACE_CHARS);
00782         av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
00783     } else if (av_stristart(p, "Server:", &p)) {
00784         p += strspn(p, SPACE_CHARS);
00785         av_strlcpy(reply->server, p, sizeof(reply->server));
00786     } else if (av_stristart(p, "Notice:", &p) ||
00787                av_stristart(p, "X-Notice:", &p)) {
00788         reply->notice = strtol(p, NULL, 10);
00789     } else if (av_stristart(p, "Location:", &p)) {
00790         p += strspn(p, SPACE_CHARS);
00791         av_strlcpy(reply->location, p , sizeof(reply->location));
00792     } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
00793         p += strspn(p, SPACE_CHARS);
00794         ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
00795     } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
00796         p += strspn(p, SPACE_CHARS);
00797         ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
00798     } else if (av_stristart(p, "Content-Base:", &p) && rt) {
00799         p += strspn(p, SPACE_CHARS);
00800         if (method && !strcmp(method, "DESCRIBE"))
00801             av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
00802     } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
00803         p += strspn(p, SPACE_CHARS);
00804         if (method && !strcmp(method, "PLAY"))
00805             rtsp_parse_rtp_info(rt, p);
00806     } else if (av_stristart(p, "Public:", &p) && rt) {
00807         if (strstr(p, "GET_PARAMETER") &&
00808             method && !strcmp(method, "OPTIONS"))
00809             rt->get_parameter_supported = 1;
00810     }
00811 }
00812 
00813 /* skip a RTP/TCP interleaved packet */
00814 void ff_rtsp_skip_packet(AVFormatContext *s)
00815 {
00816     RTSPState *rt = s->priv_data;
00817     int ret, len, len1;
00818     uint8_t buf[1024];
00819 
00820     ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
00821     if (ret != 3)
00822         return;
00823     len = AV_RB16(buf + 1);
00824 
00825     av_dlog(s, "skipping RTP packet len=%d\n", len);
00826 
00827     /* skip payload */
00828     while (len > 0) {
00829         len1 = len;
00830         if (len1 > sizeof(buf))
00831             len1 = sizeof(buf);
00832         ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
00833         if (ret != len1)
00834             return;
00835         len -= len1;
00836     }
00837 }
00838 
00839 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
00840                        unsigned char **content_ptr,
00841                        int return_on_interleaved_data, const char *method)
00842 {
00843     RTSPState *rt = s->priv_data;
00844     char buf[4096], buf1[1024], *q;
00845     unsigned char ch;
00846     const char *p;
00847     int ret, content_length, line_count = 0;
00848     unsigned char *content = NULL;
00849 
00850     memset(reply, 0, sizeof(*reply));
00851 
00852     /* parse reply (XXX: use buffers) */
00853     rt->last_reply[0] = '\0';
00854     for (;;) {
00855         q = buf;
00856         for (;;) {
00857             ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
00858             av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
00859             if (ret != 1)
00860                 return AVERROR_EOF;
00861             if (ch == '\n')
00862                 break;
00863             if (ch == '$') {
00864                 /* XXX: only parse it if first char on line ? */
00865                 if (return_on_interleaved_data) {
00866                     return 1;
00867                 } else
00868                     ff_rtsp_skip_packet(s);
00869             } else if (ch != '\r') {
00870                 if ((q - buf) < sizeof(buf) - 1)
00871                     *q++ = ch;
00872             }
00873         }
00874         *q = '\0';
00875 
00876         av_dlog(s, "line='%s'\n", buf);
00877 
00878         /* test if last line */
00879         if (buf[0] == '\0')
00880             break;
00881         p = buf;
00882         if (line_count == 0) {
00883             /* get reply code */
00884             get_word(buf1, sizeof(buf1), &p);
00885             get_word(buf1, sizeof(buf1), &p);
00886             reply->status_code = atoi(buf1);
00887             av_strlcpy(reply->reason, p, sizeof(reply->reason));
00888         } else {
00889             ff_rtsp_parse_line(reply, p, rt, method);
00890             av_strlcat(rt->last_reply, p,    sizeof(rt->last_reply));
00891             av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
00892         }
00893         line_count++;
00894     }
00895 
00896     if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
00897         av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
00898 
00899     content_length = reply->content_length;
00900     if (content_length > 0) {
00901         /* leave some room for a trailing '\0' (useful for simple parsing) */
00902         content = av_malloc(content_length + 1);
00903         ffurl_read_complete(rt->rtsp_hd, content, content_length);
00904         content[content_length] = '\0';
00905     }
00906     if (content_ptr)
00907         *content_ptr = content;
00908     else
00909         av_free(content);
00910 
00911     if (rt->seq != reply->seq) {
00912         av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
00913             rt->seq, reply->seq);
00914     }
00915 
00916     /* EOS */
00917     if (reply->notice == 2101 /* End-of-Stream Reached */      ||
00918         reply->notice == 2104 /* Start-of-Stream Reached */    ||
00919         reply->notice == 2306 /* Continuous Feed Terminated */) {
00920         rt->state = RTSP_STATE_IDLE;
00921     } else if (reply->notice >= 4400 && reply->notice < 5500) {
00922         return AVERROR(EIO); /* data or server error */
00923     } else if (reply->notice == 2401 /* Ticket Expired */ ||
00924              (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
00925         return AVERROR(EPERM);
00926 
00927     return 0;
00928 }
00929 
00943 static int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
00944                                                const char *method, const char *url,
00945                                                const char *headers,
00946                                                const unsigned char *send_content,
00947                                                int send_content_length)
00948 {
00949     RTSPState *rt = s->priv_data;
00950     char buf[4096], *out_buf;
00951     char base64buf[AV_BASE64_SIZE(sizeof(buf))];
00952 
00953     /* Add in RTSP headers */
00954     out_buf = buf;
00955     rt->seq++;
00956     snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
00957     if (headers)
00958         av_strlcat(buf, headers, sizeof(buf));
00959     av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
00960     if (rt->session_id[0] != '\0' && (!headers ||
00961         !strstr(headers, "\nIf-Match:"))) {
00962         av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
00963     }
00964     if (rt->auth[0]) {
00965         char *str = ff_http_auth_create_response(&rt->auth_state,
00966                                                  rt->auth, url, method);
00967         if (str)
00968             av_strlcat(buf, str, sizeof(buf));
00969         av_free(str);
00970     }
00971     if (send_content_length > 0 && send_content)
00972         av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
00973     av_strlcat(buf, "\r\n", sizeof(buf));
00974 
00975     /* base64 encode rtsp if tunneling */
00976     if (rt->control_transport == RTSP_MODE_TUNNEL) {
00977         av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
00978         out_buf = base64buf;
00979     }
00980 
00981     av_dlog(s, "Sending:\n%s--\n", buf);
00982 
00983     ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
00984     if (send_content_length > 0 && send_content) {
00985         if (rt->control_transport == RTSP_MODE_TUNNEL) {
00986             av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
00987                                     "with content data not supported\n");
00988             return AVERROR_PATCHWELCOME;
00989         }
00990         ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
00991     }
00992     rt->last_cmd_time = av_gettime();
00993 
00994     return 0;
00995 }
00996 
00997 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
00998                            const char *url, const char *headers)
00999 {
01000     return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
01001 }
01002 
01003 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
01004                      const char *headers, RTSPMessageHeader *reply,
01005                      unsigned char **content_ptr)
01006 {
01007     return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
01008                                          content_ptr, NULL, 0);
01009 }
01010 
01011 int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
01012                                   const char *method, const char *url,
01013                                   const char *header,
01014                                   RTSPMessageHeader *reply,
01015                                   unsigned char **content_ptr,
01016                                   const unsigned char *send_content,
01017                                   int send_content_length)
01018 {
01019     RTSPState *rt = s->priv_data;
01020     HTTPAuthType cur_auth_type;
01021     int ret;
01022 
01023 retry:
01024     cur_auth_type = rt->auth_state.auth_type;
01025     if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
01026                                                    send_content,
01027                                                    send_content_length)))
01028         return ret;
01029 
01030     if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
01031         return ret;
01032 
01033     if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
01034         rt->auth_state.auth_type != HTTP_AUTH_NONE)
01035         goto retry;
01036 
01037     if (reply->status_code > 400){
01038         av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
01039                method,
01040                reply->status_code,
01041                reply->reason);
01042         av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
01043     }
01044 
01045     return 0;
01046 }
01047 
01048 int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
01049                               int lower_transport, const char *real_challenge)
01050 {
01051     RTSPState *rt = s->priv_data;
01052     int rtx, j, i, err, interleave = 0;
01053     RTSPStream *rtsp_st;
01054     RTSPMessageHeader reply1, *reply = &reply1;
01055     char cmd[2048];
01056     const char *trans_pref;
01057 
01058     if (rt->transport == RTSP_TRANSPORT_RDT)
01059         trans_pref = "x-pn-tng";
01060     else
01061         trans_pref = "RTP/AVP";
01062 
01063     /* default timeout: 1 minute */
01064     rt->timeout = 60;
01065 
01066     /* for each stream, make the setup request */
01067     /* XXX: we assume the same server is used for the control of each
01068      * RTSP stream */
01069 
01070     for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
01071         char transport[2048];
01072 
01073         /*
01074          * WMS serves all UDP data over a single connection, the RTX, which
01075          * isn't necessarily the first in the SDP but has to be the first
01076          * to be set up, else the second/third SETUP will fail with a 461.
01077          */
01078         if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
01079              rt->server_type == RTSP_SERVER_WMS) {
01080             if (i == 0) {
01081                 /* rtx first */
01082                 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
01083                     int len = strlen(rt->rtsp_streams[rtx]->control_url);
01084                     if (len >= 4 &&
01085                         !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
01086                                 "/rtx"))
01087                         break;
01088                 }
01089                 if (rtx == rt->nb_rtsp_streams)
01090                     return -1; /* no RTX found */
01091                 rtsp_st = rt->rtsp_streams[rtx];
01092             } else
01093                 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
01094         } else
01095             rtsp_st = rt->rtsp_streams[i];
01096 
01097         /* RTP/UDP */
01098         if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
01099             char buf[256];
01100 
01101             if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
01102                 port = reply->transports[0].client_port_min;
01103                 goto have_port;
01104             }
01105 
01106             /* first try in specified port range */
01107             if (RTSP_RTP_PORT_MIN != 0) {
01108                 while (j <= RTSP_RTP_PORT_MAX) {
01109                     ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
01110                                 "?localport=%d", j);
01111                     /* we will use two ports per rtp stream (rtp and rtcp) */
01112                     j += 2;
01113                     if (ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_RDWR) == 0)
01114                         goto rtp_opened;
01115                 }
01116             }
01117 
01118 #if 0
01119             /* then try on any port */
01120             if (ffurl_open(&rtsp_st->rtp_handle, "rtp://", AVIO_RDONLY) < 0) {
01121                 err = AVERROR_INVALIDDATA;
01122                 goto fail;
01123             }
01124 #else
01125             av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
01126             err = AVERROR(EIO);
01127             goto fail;
01128 #endif
01129 
01130         rtp_opened:
01131             port = rtp_get_local_rtp_port(rtsp_st->rtp_handle);
01132         have_port:
01133             snprintf(transport, sizeof(transport) - 1,
01134                      "%s/UDP;", trans_pref);
01135             if (rt->server_type != RTSP_SERVER_REAL)
01136                 av_strlcat(transport, "unicast;", sizeof(transport));
01137             av_strlcatf(transport, sizeof(transport),
01138                      "client_port=%d", port);
01139             if (rt->transport == RTSP_TRANSPORT_RTP &&
01140                 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
01141                 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
01142         }
01143 
01144         /* RTP/TCP */
01145         else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
01146             /* For WMS streams, the application streams are only used for
01147              * UDP. When trying to set it up for TCP streams, the server
01148              * will return an error. Therefore, we skip those streams. */
01149             if (rt->server_type == RTSP_SERVER_WMS &&
01150                 s->streams[rtsp_st->stream_index]->codec->codec_type ==
01151                     AVMEDIA_TYPE_DATA)
01152                 continue;
01153             snprintf(transport, sizeof(transport) - 1,
01154                      "%s/TCP;", trans_pref);
01155             if (rt->transport != RTSP_TRANSPORT_RDT)
01156                 av_strlcat(transport, "unicast;", sizeof(transport));
01157             av_strlcatf(transport, sizeof(transport),
01158                         "interleaved=%d-%d",
01159                         interleave, interleave + 1);
01160             interleave += 2;
01161         }
01162 
01163         else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
01164             snprintf(transport, sizeof(transport) - 1,
01165                      "%s/UDP;multicast", trans_pref);
01166         }
01167         if (s->oformat) {
01168             av_strlcat(transport, ";mode=receive", sizeof(transport));
01169         } else if (rt->server_type == RTSP_SERVER_REAL ||
01170                    rt->server_type == RTSP_SERVER_WMS)
01171             av_strlcat(transport, ";mode=play", sizeof(transport));
01172         snprintf(cmd, sizeof(cmd),
01173                  "Transport: %s\r\n",
01174                  transport);
01175         if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
01176             char real_res[41], real_csum[9];
01177             ff_rdt_calc_response_and_checksum(real_res, real_csum,
01178                                               real_challenge);
01179             av_strlcatf(cmd, sizeof(cmd),
01180                         "If-Match: %s\r\n"
01181                         "RealChallenge2: %s, sd=%s\r\n",
01182                         rt->session_id, real_res, real_csum);
01183         }
01184         ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
01185         if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
01186             err = 1;
01187             goto fail;
01188         } else if (reply->status_code != RTSP_STATUS_OK ||
01189                    reply->nb_transports != 1) {
01190             err = AVERROR_INVALIDDATA;
01191             goto fail;
01192         }
01193 
01194         /* XXX: same protocol for all streams is required */
01195         if (i > 0) {
01196             if (reply->transports[0].lower_transport != rt->lower_transport ||
01197                 reply->transports[0].transport != rt->transport) {
01198                 err = AVERROR_INVALIDDATA;
01199                 goto fail;
01200             }
01201         } else {
01202             rt->lower_transport = reply->transports[0].lower_transport;
01203             rt->transport = reply->transports[0].transport;
01204         }
01205 
01206         /* Fail if the server responded with another lower transport mode
01207          * than what we requested. */
01208         if (reply->transports[0].lower_transport != lower_transport) {
01209             av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
01210             err = AVERROR_INVALIDDATA;
01211             goto fail;
01212         }
01213 
01214         switch(reply->transports[0].lower_transport) {
01215         case RTSP_LOWER_TRANSPORT_TCP:
01216             rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
01217             rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
01218             break;
01219 
01220         case RTSP_LOWER_TRANSPORT_UDP: {
01221             char url[1024], options[30] = "";
01222 
01223             if (rt->filter_source)
01224                 av_strlcpy(options, "?connect=1", sizeof(options));
01225             /* Use source address if specified */
01226             if (reply->transports[0].source[0]) {
01227                 ff_url_join(url, sizeof(url), "rtp", NULL,
01228                             reply->transports[0].source,
01229                             reply->transports[0].server_port_min, "%s", options);
01230             } else {
01231                 ff_url_join(url, sizeof(url), "rtp", NULL, host,
01232                             reply->transports[0].server_port_min, "%s", options);
01233             }
01234             if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
01235                 rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
01236                 err = AVERROR_INVALIDDATA;
01237                 goto fail;
01238             }
01239             /* Try to initialize the connection state in a
01240              * potential NAT router by sending dummy packets.
01241              * RTP/RTCP dummy packets are used for RDT, too.
01242              */
01243             if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
01244                 CONFIG_RTPDEC)
01245                 rtp_send_punch_packets(rtsp_st->rtp_handle);
01246             break;
01247         }
01248         case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
01249             char url[1024], namebuf[50];
01250             struct sockaddr_storage addr;
01251             int port, ttl;
01252 
01253             if (reply->transports[0].destination.ss_family) {
01254                 addr      = reply->transports[0].destination;
01255                 port      = reply->transports[0].port_min;
01256                 ttl       = reply->transports[0].ttl;
01257             } else {
01258                 addr      = rtsp_st->sdp_ip;
01259                 port      = rtsp_st->sdp_port;
01260                 ttl       = rtsp_st->sdp_ttl;
01261             }
01262             getnameinfo((struct sockaddr*) &addr, sizeof(addr),
01263                         namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
01264             ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
01265                         port, "?ttl=%d", ttl);
01266             if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_RDWR) < 0) {
01267                 err = AVERROR_INVALIDDATA;
01268                 goto fail;
01269             }
01270             break;
01271         }
01272         }
01273 
01274         if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
01275             goto fail;
01276     }
01277 
01278     if (reply->timeout > 0)
01279         rt->timeout = reply->timeout;
01280 
01281     if (rt->server_type == RTSP_SERVER_REAL)
01282         rt->need_subscription = 1;
01283 
01284     return 0;
01285 
01286 fail:
01287     ff_rtsp_undo_setup(s);
01288     return err;
01289 }
01290 
01291 void ff_rtsp_close_connections(AVFormatContext *s)
01292 {
01293     RTSPState *rt = s->priv_data;
01294     if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
01295     ffurl_close(rt->rtsp_hd);
01296     rt->rtsp_hd = rt->rtsp_hd_out = NULL;
01297 }
01298 
01299 int ff_rtsp_connect(AVFormatContext *s)
01300 {
01301     RTSPState *rt = s->priv_data;
01302     char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
01303     char *option_list, *option, *filename;
01304     int port, err, tcp_fd;
01305     RTSPMessageHeader reply1 = {0}, *reply = &reply1;
01306     int lower_transport_mask = 0;
01307     char real_challenge[64] = "";
01308     struct sockaddr_storage peer;
01309     socklen_t peer_len = sizeof(peer);
01310 
01311     if (!ff_network_init())
01312         return AVERROR(EIO);
01313 redirect:
01314     rt->control_transport = RTSP_MODE_PLAIN;
01315     /* extract hostname and port */
01316     av_url_split(NULL, 0, auth, sizeof(auth),
01317                  host, sizeof(host), &port, path, sizeof(path), s->filename);
01318     if (*auth) {
01319         av_strlcpy(rt->auth, auth, sizeof(rt->auth));
01320     }
01321     if (port < 0)
01322         port = RTSP_DEFAULT_PORT;
01323 
01324     /* search for options */
01325     option_list = strrchr(path, '?');
01326     if (option_list) {
01327         /* Strip out the RTSP specific options, write out the rest of
01328          * the options back into the same string. */
01329         filename = option_list;
01330         while (option_list) {
01331             /* move the option pointer */
01332             option = ++option_list;
01333             option_list = strchr(option_list, '&');
01334             if (option_list)
01335                 *option_list = 0;
01336 
01337             /* handle the options */
01338             if (!strcmp(option, "udp")) {
01339                 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
01340             } else if (!strcmp(option, "multicast")) {
01341                 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
01342             } else if (!strcmp(option, "tcp")) {
01343                 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
01344             } else if(!strcmp(option, "http")) {
01345                 lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
01346                 rt->control_transport = RTSP_MODE_TUNNEL;
01347             } else if (!strcmp(option, "filter_src")) {
01348                 rt->filter_source = 1;
01349             } else {
01350                 /* Write options back into the buffer, using memmove instead
01351                  * of strcpy since the strings may overlap. */
01352                 int len = strlen(option);
01353                 memmove(++filename, option, len);
01354                 filename += len;
01355                 if (option_list) *filename = '&';
01356             }
01357         }
01358         *filename = 0;
01359     }
01360 
01361     if (!lower_transport_mask)
01362         lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
01363 
01364     if (s->oformat) {
01365         /* Only UDP or TCP - UDP multicast isn't supported. */
01366         lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
01367                                 (1 << RTSP_LOWER_TRANSPORT_TCP);
01368         if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
01369             av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
01370                                     "only UDP and TCP are supported for output.\n");
01371             err = AVERROR(EINVAL);
01372             goto fail;
01373         }
01374     }
01375 
01376     /* Construct the URI used in request; this is similar to s->filename,
01377      * but with authentication credentials removed and RTSP specific options
01378      * stripped out. */
01379     ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
01380                 host, port, "%s", path);
01381 
01382     if (rt->control_transport == RTSP_MODE_TUNNEL) {
01383         /* set up initial handshake for tunneling */
01384         char httpname[1024];
01385         char sessioncookie[17];
01386         char headers[1024];
01387 
01388         ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
01389         snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
01390                  av_get_random_seed(), av_get_random_seed());
01391 
01392         /* GET requests */
01393         if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_RDONLY) < 0) {
01394             err = AVERROR(EIO);
01395             goto fail;
01396         }
01397 
01398         /* generate GET headers */
01399         snprintf(headers, sizeof(headers),
01400                  "x-sessioncookie: %s\r\n"
01401                  "Accept: application/x-rtsp-tunnelled\r\n"
01402                  "Pragma: no-cache\r\n"
01403                  "Cache-Control: no-cache\r\n",
01404                  sessioncookie);
01405         ff_http_set_headers(rt->rtsp_hd, headers);
01406 
01407         /* complete the connection */
01408         if (ffurl_connect(rt->rtsp_hd)) {
01409             err = AVERROR(EIO);
01410             goto fail;
01411         }
01412 
01413         /* POST requests */
01414         if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_WRONLY) < 0 ) {
01415             err = AVERROR(EIO);
01416             goto fail;
01417         }
01418 
01419         /* generate POST headers */
01420         snprintf(headers, sizeof(headers),
01421                  "x-sessioncookie: %s\r\n"
01422                  "Content-Type: application/x-rtsp-tunnelled\r\n"
01423                  "Pragma: no-cache\r\n"
01424                  "Cache-Control: no-cache\r\n"
01425                  "Content-Length: 32767\r\n"
01426                  "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
01427                  sessioncookie);
01428         ff_http_set_headers(rt->rtsp_hd_out, headers);
01429         ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
01430 
01431         /* Initialize the authentication state for the POST session. The HTTP
01432          * protocol implementation doesn't properly handle multi-pass
01433          * authentication for POST requests, since it would require one of
01434          * the following:
01435          * - implementing Expect: 100-continue, which many HTTP servers
01436          *   don't support anyway, even less the RTSP servers that do HTTP
01437          *   tunneling
01438          * - sending the whole POST data until getting a 401 reply specifying
01439          *   what authentication method to use, then resending all that data
01440          * - waiting for potential 401 replies directly after sending the
01441          *   POST header (waiting for some unspecified time)
01442          * Therefore, we copy the full auth state, which works for both basic
01443          * and digest. (For digest, we would have to synchronize the nonce
01444          * count variable between the two sessions, if we'd do more requests
01445          * with the original session, though.)
01446          */
01447         ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
01448 
01449         /* complete the connection */
01450         if (ffurl_connect(rt->rtsp_hd_out)) {
01451             err = AVERROR(EIO);
01452             goto fail;
01453         }
01454     } else {
01455         /* open the tcp connection */
01456         ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
01457         if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_RDWR) < 0) {
01458             err = AVERROR(EIO);
01459             goto fail;
01460         }
01461         rt->rtsp_hd_out = rt->rtsp_hd;
01462     }
01463     rt->seq = 0;
01464 
01465     tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
01466     if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
01467         getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
01468                     NULL, 0, NI_NUMERICHOST);
01469     }
01470 
01471     /* request options supported by the server; this also detects server
01472      * type */
01473     for (rt->server_type = RTSP_SERVER_RTP;;) {
01474         cmd[0] = 0;
01475         if (rt->server_type == RTSP_SERVER_REAL)
01476             av_strlcat(cmd,
01477                        /*
01478                         * The following entries are required for proper
01479                         * streaming from a Realmedia server. They are
01480                         * interdependent in some way although we currently
01481                         * don't quite understand how. Values were copied
01482                         * from mplayer SVN r23589.
01483                         *   ClientChallenge is a 16-byte ID in hex
01484                         *   CompanyID is a 16-byte ID in base64
01485                         */
01486                        "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
01487                        "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
01488                        "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
01489                        "GUID: 00000000-0000-0000-0000-000000000000\r\n",
01490                        sizeof(cmd));
01491         ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
01492         if (reply->status_code != RTSP_STATUS_OK) {
01493             err = AVERROR_INVALIDDATA;
01494             goto fail;
01495         }
01496 
01497         /* detect server type if not standard-compliant RTP */
01498         if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
01499             rt->server_type = RTSP_SERVER_REAL;
01500             continue;
01501         } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
01502             rt->server_type = RTSP_SERVER_WMS;
01503         } else if (rt->server_type == RTSP_SERVER_REAL)
01504             strcpy(real_challenge, reply->real_challenge);
01505         break;
01506     }
01507 
01508     if (s->iformat && CONFIG_RTSP_DEMUXER)
01509         err = ff_rtsp_setup_input_streams(s, reply);
01510     else if (CONFIG_RTSP_MUXER)
01511         err = ff_rtsp_setup_output_streams(s, host);
01512     if (err)
01513         goto fail;
01514 
01515     do {
01516         int lower_transport = ff_log2_tab[lower_transport_mask &
01517                                   ~(lower_transport_mask - 1)];
01518 
01519         err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
01520                                  rt->server_type == RTSP_SERVER_REAL ?
01521                                      real_challenge : NULL);
01522         if (err < 0)
01523             goto fail;
01524         lower_transport_mask &= ~(1 << lower_transport);
01525         if (lower_transport_mask == 0 && err == 1) {
01526             err = AVERROR(EPROTONOSUPPORT);
01527             goto fail;
01528         }
01529     } while (err);
01530 
01531     rt->lower_transport_mask = lower_transport_mask;
01532     av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
01533     rt->state = RTSP_STATE_IDLE;
01534     rt->seek_timestamp = 0; /* default is to start stream at position zero */
01535     return 0;
01536  fail:
01537     ff_rtsp_close_streams(s);
01538     ff_rtsp_close_connections(s);
01539     if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
01540         av_strlcpy(s->filename, reply->location, sizeof(s->filename));
01541         av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
01542                reply->status_code,
01543                s->filename);
01544         goto redirect;
01545     }
01546     ff_network_close();
01547     return err;
01548 }
01549 #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
01550 
01551 #if CONFIG_RTPDEC
01552 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
01553                            uint8_t *buf, int buf_size, int64_t wait_end)
01554 {
01555     RTSPState *rt = s->priv_data;
01556     RTSPStream *rtsp_st;
01557     int n, i, ret, tcp_fd, timeout_cnt = 0;
01558     int max_p = 0;
01559     struct pollfd *p = rt->p;
01560 
01561     for (;;) {
01562         if (url_interrupt_cb())
01563             return AVERROR_EXIT;
01564         if (wait_end && wait_end - av_gettime() < 0)
01565             return AVERROR(EAGAIN);
01566         max_p = 0;
01567         if (rt->rtsp_hd) {
01568             tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
01569             p[max_p].fd = tcp_fd;
01570             p[max_p++].events = POLLIN;
01571         } else {
01572             tcp_fd = -1;
01573         }
01574         for (i = 0; i < rt->nb_rtsp_streams; i++) {
01575             rtsp_st = rt->rtsp_streams[i];
01576             if (rtsp_st->rtp_handle) {
01577                 p[max_p].fd = ffurl_get_file_handle(rtsp_st->rtp_handle);
01578                 p[max_p++].events = POLLIN;
01579                 p[max_p].fd = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
01580                 p[max_p++].events = POLLIN;
01581             }
01582         }
01583         n = poll(p, max_p, POLL_TIMEOUT_MS);
01584         if (n > 0) {
01585             int j = 1 - (tcp_fd == -1);
01586             timeout_cnt = 0;
01587             for (i = 0; i < rt->nb_rtsp_streams; i++) {
01588                 rtsp_st = rt->rtsp_streams[i];
01589                 if (rtsp_st->rtp_handle) {
01590                     if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
01591                         ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
01592                         if (ret > 0) {
01593                             *prtsp_st = rtsp_st;
01594                             return ret;
01595                         }
01596                     }
01597                     j+=2;
01598                 }
01599             }
01600 #if CONFIG_RTSP_DEMUXER
01601             if (tcp_fd != -1 && p[0].revents & POLLIN) {
01602                 RTSPMessageHeader reply;
01603 
01604                 ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
01605                 if (ret < 0)
01606                     return ret;
01607                 /* XXX: parse message */
01608                 if (rt->state != RTSP_STATE_STREAMING)
01609                     return 0;
01610             }
01611 #endif
01612         } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
01613             return AVERROR(ETIMEDOUT);
01614         } else if (n < 0 && errno != EINTR)
01615             return AVERROR(errno);
01616     }
01617 }
01618 
01619 int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
01620 {
01621     RTSPState *rt = s->priv_data;
01622     int ret, len;
01623     RTSPStream *rtsp_st, *first_queue_st = NULL;
01624     int64_t wait_end = 0;
01625 
01626     if (rt->nb_byes == rt->nb_rtsp_streams)
01627         return AVERROR_EOF;
01628 
01629     /* get next frames from the same RTP packet */
01630     if (rt->cur_transport_priv) {
01631         if (rt->transport == RTSP_TRANSPORT_RDT) {
01632             ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
01633         } else
01634             ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
01635         if (ret == 0) {
01636             rt->cur_transport_priv = NULL;
01637             return 0;
01638         } else if (ret == 1) {
01639             return 0;
01640         } else
01641             rt->cur_transport_priv = NULL;
01642     }
01643 
01644     if (rt->transport == RTSP_TRANSPORT_RTP) {
01645         int i;
01646         int64_t first_queue_time = 0;
01647         for (i = 0; i < rt->nb_rtsp_streams; i++) {
01648             RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
01649             int64_t queue_time;
01650             if (!rtpctx)
01651                 continue;
01652             queue_time = ff_rtp_queued_packet_time(rtpctx);
01653             if (queue_time && (queue_time - first_queue_time < 0 ||
01654                                !first_queue_time)) {
01655                 first_queue_time = queue_time;
01656                 first_queue_st   = rt->rtsp_streams[i];
01657             }
01658         }
01659         if (first_queue_time)
01660             wait_end = first_queue_time + s->max_delay;
01661     }
01662 
01663     /* read next RTP packet */
01664  redo:
01665     if (!rt->recvbuf) {
01666         rt->recvbuf = av_malloc(RECVBUF_SIZE);
01667         if (!rt->recvbuf)
01668             return AVERROR(ENOMEM);
01669     }
01670 
01671     switch(rt->lower_transport) {
01672     default:
01673 #if CONFIG_RTSP_DEMUXER
01674     case RTSP_LOWER_TRANSPORT_TCP:
01675         len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
01676         break;
01677 #endif
01678     case RTSP_LOWER_TRANSPORT_UDP:
01679     case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
01680         len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
01681         if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
01682             rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
01683         break;
01684     }
01685     if (len == AVERROR(EAGAIN) && first_queue_st &&
01686         rt->transport == RTSP_TRANSPORT_RTP) {
01687         rtsp_st = first_queue_st;
01688         ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
01689         goto end;
01690     }
01691     if (len < 0)
01692         return len;
01693     if (len == 0)
01694         return AVERROR_EOF;
01695     if (rt->transport == RTSP_TRANSPORT_RDT) {
01696         ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
01697     } else {
01698         ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
01699         if (ret < 0) {
01700             /* Either bad packet, or a RTCP packet. Check if the
01701              * first_rtcp_ntp_time field was initialized. */
01702             RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
01703             if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
01704                 /* first_rtcp_ntp_time has been initialized for this stream,
01705                  * copy the same value to all other uninitialized streams,
01706                  * in order to map their timestamp origin to the same ntp time
01707                  * as this one. */
01708                 int i;
01709                 AVStream *st = NULL;
01710                 if (rtsp_st->stream_index >= 0)
01711                     st = s->streams[rtsp_st->stream_index];
01712                 for (i = 0; i < rt->nb_rtsp_streams; i++) {
01713                     RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
01714                     AVStream *st2 = NULL;
01715                     if (rt->rtsp_streams[i]->stream_index >= 0)
01716                         st2 = s->streams[rt->rtsp_streams[i]->stream_index];
01717                     if (rtpctx2 && st && st2 &&
01718                         rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
01719                         rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
01720                         rtpctx2->rtcp_ts_offset = av_rescale_q(
01721                             rtpctx->rtcp_ts_offset, st->time_base,
01722                             st2->time_base);
01723                     }
01724                 }
01725             }
01726             if (ret == -RTCP_BYE) {
01727                 rt->nb_byes++;
01728 
01729                 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
01730                        rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
01731 
01732                 if (rt->nb_byes == rt->nb_rtsp_streams)
01733                     return AVERROR_EOF;
01734             }
01735         }
01736     }
01737 end:
01738     if (ret < 0)
01739         goto redo;
01740     if (ret == 1)
01741         /* more packets may follow, so we save the RTP context */
01742         rt->cur_transport_priv = rtsp_st->transport_priv;
01743 
01744     return ret;
01745 }
01746 #endif /* CONFIG_RTPDEC */
01747 
01748 #if CONFIG_SDP_DEMUXER
01749 static int sdp_probe(AVProbeData *p1)
01750 {
01751     const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
01752 
01753     /* we look for a line beginning "c=IN IP" */
01754     while (p < p_end && *p != '\0') {
01755         if (p + sizeof("c=IN IP") - 1 < p_end &&
01756             av_strstart(p, "c=IN IP", NULL))
01757             return AVPROBE_SCORE_MAX / 2;
01758 
01759         while (p < p_end - 1 && *p != '\n') p++;
01760         if (++p >= p_end)
01761             break;
01762         if (*p == '\r')
01763             p++;
01764     }
01765     return 0;
01766 }
01767 
01768 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
01769 {
01770     RTSPState *rt = s->priv_data;
01771     RTSPStream *rtsp_st;
01772     int size, i, err;
01773     char *content;
01774     char url[1024];
01775 
01776     if (!ff_network_init())
01777         return AVERROR(EIO);
01778 
01779     /* read the whole sdp file */
01780     /* XXX: better loading */
01781     content = av_malloc(SDP_MAX_SIZE);
01782     size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
01783     if (size <= 0) {
01784         av_free(content);
01785         return AVERROR_INVALIDDATA;
01786     }
01787     content[size] ='\0';
01788 
01789     err = ff_sdp_parse(s, content);
01790     av_free(content);
01791     if (err) goto fail;
01792 
01793     /* open each RTP stream */
01794     for (i = 0; i < rt->nb_rtsp_streams; i++) {
01795         char namebuf[50];
01796         rtsp_st = rt->rtsp_streams[i];
01797 
01798         getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
01799                     namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
01800         ff_url_join(url, sizeof(url), "rtp", NULL,
01801                     namebuf, rtsp_st->sdp_port,
01802                     "?localport=%d&ttl=%d", rtsp_st->sdp_port,
01803                     rtsp_st->sdp_ttl);
01804         if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_RDWR) < 0) {
01805             err = AVERROR_INVALIDDATA;
01806             goto fail;
01807         }
01808         if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
01809             goto fail;
01810     }
01811     return 0;
01812 fail:
01813     ff_rtsp_close_streams(s);
01814     ff_network_close();
01815     return err;
01816 }
01817 
01818 static int sdp_read_close(AVFormatContext *s)
01819 {
01820     ff_rtsp_close_streams(s);
01821     ff_network_close();
01822     return 0;
01823 }
01824 
01825 AVInputFormat ff_sdp_demuxer = {
01826     "sdp",
01827     NULL_IF_CONFIG_SMALL("SDP"),
01828     sizeof(RTSPState),
01829     sdp_probe,
01830     sdp_read_header,
01831     ff_rtsp_fetch_packet,
01832     sdp_read_close,
01833 };
01834 #endif /* CONFIG_SDP_DEMUXER */
01835 
01836 #if CONFIG_RTP_DEMUXER
01837 static int rtp_probe(AVProbeData *p)
01838 {
01839     if (av_strstart(p->filename, "rtp:", NULL))
01840         return AVPROBE_SCORE_MAX;
01841     return 0;
01842 }
01843 
01844 static int rtp_read_header(AVFormatContext *s,
01845                            AVFormatParameters *ap)
01846 {
01847     uint8_t recvbuf[1500];
01848     char host[500], sdp[500];
01849     int ret, port;
01850     URLContext* in = NULL;
01851     int payload_type;
01852     AVCodecContext codec;
01853     struct sockaddr_storage addr;
01854     AVIOContext pb;
01855     socklen_t addrlen = sizeof(addr);
01856 
01857     if (!ff_network_init())
01858         return AVERROR(EIO);
01859 
01860     ret = ffurl_open(&in, s->filename, AVIO_RDONLY);
01861     if (ret)
01862         goto fail;
01863 
01864     while (1) {
01865         ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
01866         if (ret == AVERROR(EAGAIN))
01867             continue;
01868         if (ret < 0)
01869             goto fail;
01870         if (ret < 12) {
01871             av_log(s, AV_LOG_WARNING, "Received too short packet\n");
01872             continue;
01873         }
01874 
01875         if ((recvbuf[0] & 0xc0) != 0x80) {
01876             av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
01877                                       "received\n");
01878             continue;
01879         }
01880 
01881         payload_type = recvbuf[1] & 0x7f;
01882         break;
01883     }
01884     getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
01885     ffurl_close(in);
01886     in = NULL;
01887 
01888     memset(&codec, 0, sizeof(codec));
01889     if (ff_rtp_get_codec_info(&codec, payload_type)) {
01890         av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
01891                                 "without an SDP file describing it\n",
01892                                  payload_type);
01893         goto fail;
01894     }
01895     if (codec.codec_type != AVMEDIA_TYPE_DATA) {
01896         av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
01897                                   "properly you need an SDP file "
01898                                   "describing it\n");
01899     }
01900 
01901     av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
01902                  NULL, 0, s->filename);
01903 
01904     snprintf(sdp, sizeof(sdp),
01905              "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
01906              addr.ss_family == AF_INET ? 4 : 6, host,
01907              codec.codec_type == AVMEDIA_TYPE_DATA  ? "application" :
01908              codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
01909              port, payload_type);
01910     av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
01911 
01912     ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
01913     s->pb = &pb;
01914 
01915     /* sdp_read_header initializes this again */
01916     ff_network_close();
01917 
01918     ret = sdp_read_header(s, ap);
01919     s->pb = NULL;
01920     return ret;
01921 
01922 fail:
01923     if (in)
01924         ffurl_close(in);
01925     ff_network_close();
01926     return ret;
01927 }
01928 
01929 AVInputFormat ff_rtp_demuxer = {
01930     "rtp",
01931     NULL_IF_CONFIG_SMALL("RTP input format"),
01932     sizeof(RTSPState),
01933     rtp_probe,
01934     rtp_read_header,
01935     ff_rtsp_fetch_packet,
01936     sdp_read_close,
01937     .flags = AVFMT_NOFILE,
01938 };
01939 #endif /* CONFIG_RTP_DEMUXER */
01940 

Generated on Wed Apr 11 2012 07:31:37 for FFmpeg by  doxygen 1.7.1