]> git.sesse.net Git - ffmpeg/blob - libavformat/rtsp.c
rtmp: Read and handle incoming packets while writing data
[ffmpeg] / libavformat / rtsp.c
1 /*
2  * RTSP/SDP client
3  * Copyright (c) 2002 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/base64.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/parseutils.h"
27 #include "libavutil/random_seed.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/opt.h"
30 #include "avformat.h"
31 #include "avio_internal.h"
32
33 #include <sys/time.h>
34 #if HAVE_POLL_H
35 #include <poll.h>
36 #endif
37 #include "internal.h"
38 #include "network.h"
39 #include "os_support.h"
40 #include "http.h"
41 #include "rtsp.h"
42
43 #include "rtpdec.h"
44 #include "rdt.h"
45 #include "rtpdec_formats.h"
46 #include "rtpenc_chain.h"
47 #include "url.h"
48 #include "rtpenc.h"
49
50 //#define DEBUG
51
52 /* Timeout values for socket poll, in ms,
53  * and read_packet(), in seconds  */
54 #define POLL_TIMEOUT_MS 100
55 #define READ_PACKET_TIMEOUT_S 10
56 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / POLL_TIMEOUT_MS
57 #define SDP_MAX_SIZE 16384
58 #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
59 #define DEFAULT_REORDERING_DELAY 100000
60
61 #define OFFSET(x) offsetof(RTSPState, x)
62 #define DEC AV_OPT_FLAG_DECODING_PARAM
63 #define ENC AV_OPT_FLAG_ENCODING_PARAM
64
65 #define RTSP_FLAG_OPTS(name, longname) \
66     { name, longname, OFFSET(rtsp_flags), AV_OPT_TYPE_FLAGS, {0}, INT_MIN, INT_MAX, DEC, "rtsp_flags" }, \
67     { "filter_src", "Only receive packets from the negotiated peer IP", 0, AV_OPT_TYPE_CONST, {RTSP_FLAG_FILTER_SRC}, 0, 0, DEC, "rtsp_flags" }
68
69 #define RTSP_MEDIATYPE_OPTS(name, longname) \
70     { name, longname, OFFSET(media_type_mask), AV_OPT_TYPE_FLAGS, { (1 << (AVMEDIA_TYPE_DATA+1)) - 1 }, INT_MIN, INT_MAX, DEC, "allowed_media_types" }, \
71     { "video", "Video", 0, AV_OPT_TYPE_CONST, {1 << AVMEDIA_TYPE_VIDEO}, 0, 0, DEC, "allowed_media_types" }, \
72     { "audio", "Audio", 0, AV_OPT_TYPE_CONST, {1 << AVMEDIA_TYPE_AUDIO}, 0, 0, DEC, "allowed_media_types" }, \
73     { "data", "Data", 0, AV_OPT_TYPE_CONST, {1 << AVMEDIA_TYPE_DATA}, 0, 0, DEC, "allowed_media_types" }
74
75 const AVOption ff_rtsp_options[] = {
76     { "initial_pause",  "Don't start playing the stream immediately", OFFSET(initial_pause), AV_OPT_TYPE_INT, {0}, 0, 1, DEC },
77     FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags)
78     { "rtsp_transport", "RTSP transport protocols", OFFSET(lower_transport_mask), AV_OPT_TYPE_FLAGS, {0}, INT_MIN, INT_MAX, DEC|ENC, "rtsp_transport" }, \
79     { "udp", "UDP", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_UDP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
80     { "tcp", "TCP", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_TCP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
81     { "udp_multicast", "UDP multicast", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_UDP_MULTICAST}, 0, 0, DEC, "rtsp_transport" },
82     { "http", "HTTP tunneling", 0, AV_OPT_TYPE_CONST, {(1 << RTSP_LOWER_TRANSPORT_HTTP)}, 0, 0, DEC, "rtsp_transport" },
83     RTSP_FLAG_OPTS("rtsp_flags", "RTSP flags"),
84     RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
85     { "min_port", "Minimum local UDP port", OFFSET(rtp_port_min), AV_OPT_TYPE_INT, {RTSP_RTP_PORT_MIN}, 0, 65535, DEC|ENC },
86     { "max_port", "Maximum local UDP port", OFFSET(rtp_port_max), AV_OPT_TYPE_INT, {RTSP_RTP_PORT_MAX}, 0, 65535, DEC|ENC },
87     { NULL },
88 };
89
90 static const AVOption sdp_options[] = {
91     RTSP_FLAG_OPTS("sdp_flags", "SDP flags"),
92     RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
93     { NULL },
94 };
95
96 static const AVOption rtp_options[] = {
97     RTSP_FLAG_OPTS("rtp_flags", "RTP flags"),
98     { NULL },
99 };
100
101 static void get_word_until_chars(char *buf, int buf_size,
102                                  const char *sep, const char **pp)
103 {
104     const char *p;
105     char *q;
106
107     p = *pp;
108     p += strspn(p, SPACE_CHARS);
109     q = buf;
110     while (!strchr(sep, *p) && *p != '\0') {
111         if ((q - buf) < buf_size - 1)
112             *q++ = *p;
113         p++;
114     }
115     if (buf_size > 0)
116         *q = '\0';
117     *pp = p;
118 }
119
120 static void get_word_sep(char *buf, int buf_size, const char *sep,
121                          const char **pp)
122 {
123     if (**pp == '/') (*pp)++;
124     get_word_until_chars(buf, buf_size, sep, pp);
125 }
126
127 static void get_word(char *buf, int buf_size, const char **pp)
128 {
129     get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
130 }
131
132 /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
133  *  and end time.
134  *  Used for seeking in the rtp stream.
135  */
136 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
137 {
138     char buf[256];
139
140     p += strspn(p, SPACE_CHARS);
141     if (!av_stristart(p, "npt=", &p))
142         return;
143
144     *start = AV_NOPTS_VALUE;
145     *end = AV_NOPTS_VALUE;
146
147     get_word_sep(buf, sizeof(buf), "-", &p);
148     av_parse_time(start, buf, 1);
149     if (*p == '-') {
150         p++;
151         get_word_sep(buf, sizeof(buf), "-", &p);
152         av_parse_time(end, buf, 1);
153     }
154 //    av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
155 //    av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
156 }
157
158 static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
159 {
160     struct addrinfo hints = { 0 }, *ai = NULL;
161     hints.ai_flags = AI_NUMERICHOST;
162     if (getaddrinfo(buf, NULL, &hints, &ai))
163         return -1;
164     memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
165     freeaddrinfo(ai);
166     return 0;
167 }
168
169 #if CONFIG_RTPDEC
170 static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
171                              RTSPStream *rtsp_st, AVCodecContext *codec)
172 {
173     if (!handler)
174         return;
175     codec->codec_id          = handler->codec_id;
176     rtsp_st->dynamic_handler = handler;
177     if (handler->alloc) {
178         rtsp_st->dynamic_protocol_context = handler->alloc();
179         if (!rtsp_st->dynamic_protocol_context)
180             rtsp_st->dynamic_handler = NULL;
181     }
182 }
183
184 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
185 static int sdp_parse_rtpmap(AVFormatContext *s,
186                             AVStream *st, RTSPStream *rtsp_st,
187                             int payload_type, const char *p)
188 {
189     AVCodecContext *codec = st->codec;
190     char buf[256];
191     int i;
192     AVCodec *c;
193     const char *c_name;
194
195     /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
196      * see if we can handle this kind of payload.
197      * The space should normally not be there but some Real streams or
198      * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
199      * have a trailing space. */
200     get_word_sep(buf, sizeof(buf), "/ ", &p);
201     if (payload_type < RTP_PT_PRIVATE) {
202         /* We are in a standard case
203          * (from http://www.iana.org/assignments/rtp-parameters). */
204         /* search into AVRtpPayloadTypes[] */
205         codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
206     }
207
208     if (codec->codec_id == CODEC_ID_NONE) {
209         RTPDynamicProtocolHandler *handler =
210             ff_rtp_handler_find_by_name(buf, codec->codec_type);
211         init_rtp_handler(handler, rtsp_st, codec);
212         /* If no dynamic handler was found, check with the list of standard
213          * allocated types, if such a stream for some reason happens to
214          * use a private payload type. This isn't handled in rtpdec.c, since
215          * the format name from the rtpmap line never is passed into rtpdec. */
216         if (!rtsp_st->dynamic_handler)
217             codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
218     }
219
220     c = avcodec_find_decoder(codec->codec_id);
221     if (c && c->name)
222         c_name = c->name;
223     else
224         c_name = "(null)";
225
226     get_word_sep(buf, sizeof(buf), "/", &p);
227     i = atoi(buf);
228     switch (codec->codec_type) {
229     case AVMEDIA_TYPE_AUDIO:
230         av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
231         codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
232         codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
233         if (i > 0) {
234             codec->sample_rate = i;
235             avpriv_set_pts_info(st, 32, 1, codec->sample_rate);
236             get_word_sep(buf, sizeof(buf), "/", &p);
237             i = atoi(buf);
238             if (i > 0)
239                 codec->channels = i;
240             // TODO: there is a bug here; if it is a mono stream, and
241             // less than 22000Hz, faad upconverts to stereo and twice
242             // the frequency.  No problem, but the sample rate is being
243             // set here by the sdp line. Patch on its way. (rdm)
244         }
245         av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
246                codec->sample_rate);
247         av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
248                codec->channels);
249         break;
250     case AVMEDIA_TYPE_VIDEO:
251         av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
252         if (i > 0)
253             avpriv_set_pts_info(st, 32, 1, i);
254         break;
255     default:
256         break;
257     }
258     if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->init)
259         rtsp_st->dynamic_handler->init(s, st->index,
260                                        rtsp_st->dynamic_protocol_context);
261     return 0;
262 }
263
264 /* parse the attribute line from the fmtp a line of an sdp response. This
265  * is broken out as a function because it is used in rtp_h264.c, which is
266  * forthcoming. */
267 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
268                                 char *value, int value_size)
269 {
270     *p += strspn(*p, SPACE_CHARS);
271     if (**p) {
272         get_word_sep(attr, attr_size, "=", p);
273         if (**p == '=')
274             (*p)++;
275         get_word_sep(value, value_size, ";", p);
276         if (**p == ';')
277             (*p)++;
278         return 1;
279     }
280     return 0;
281 }
282
283 typedef struct SDPParseState {
284     /* SDP only */
285     struct sockaddr_storage default_ip;
286     int            default_ttl;
287     int            skip_media;  ///< set if an unknown m= line occurs
288 } SDPParseState;
289
290 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
291                            int letter, const char *buf)
292 {
293     RTSPState *rt = s->priv_data;
294     char buf1[64], st_type[64];
295     const char *p;
296     enum AVMediaType codec_type;
297     int payload_type, i;
298     AVStream *st;
299     RTSPStream *rtsp_st;
300     struct sockaddr_storage sdp_ip;
301     int ttl;
302
303     av_dlog(s, "sdp: %c='%s'\n", letter, buf);
304
305     p = buf;
306     if (s1->skip_media && letter != 'm')
307         return;
308     switch (letter) {
309     case 'c':
310         get_word(buf1, sizeof(buf1), &p);
311         if (strcmp(buf1, "IN") != 0)
312             return;
313         get_word(buf1, sizeof(buf1), &p);
314         if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
315             return;
316         get_word_sep(buf1, sizeof(buf1), "/", &p);
317         if (get_sockaddr(buf1, &sdp_ip))
318             return;
319         ttl = 16;
320         if (*p == '/') {
321             p++;
322             get_word_sep(buf1, sizeof(buf1), "/", &p);
323             ttl = atoi(buf1);
324         }
325         if (s->nb_streams == 0) {
326             s1->default_ip = sdp_ip;
327             s1->default_ttl = ttl;
328         } else {
329             rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
330             rtsp_st->sdp_ip = sdp_ip;
331             rtsp_st->sdp_ttl = ttl;
332         }
333         break;
334     case 's':
335         av_dict_set(&s->metadata, "title", p, 0);
336         break;
337     case 'i':
338         if (s->nb_streams == 0) {
339             av_dict_set(&s->metadata, "comment", p, 0);
340             break;
341         }
342         break;
343     case 'm':
344         /* new stream */
345         s1->skip_media = 0;
346         codec_type = AVMEDIA_TYPE_UNKNOWN;
347         get_word(st_type, sizeof(st_type), &p);
348         if (!strcmp(st_type, "audio")) {
349             codec_type = AVMEDIA_TYPE_AUDIO;
350         } else if (!strcmp(st_type, "video")) {
351             codec_type = AVMEDIA_TYPE_VIDEO;
352         } else if (!strcmp(st_type, "application")) {
353             codec_type = AVMEDIA_TYPE_DATA;
354         }
355         if (codec_type == AVMEDIA_TYPE_UNKNOWN || !(rt->media_type_mask & (1 << codec_type))) {
356             s1->skip_media = 1;
357             return;
358         }
359         rtsp_st = av_mallocz(sizeof(RTSPStream));
360         if (!rtsp_st)
361             return;
362         rtsp_st->stream_index = -1;
363         dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
364
365         rtsp_st->sdp_ip = s1->default_ip;
366         rtsp_st->sdp_ttl = s1->default_ttl;
367
368         get_word(buf1, sizeof(buf1), &p); /* port */
369         rtsp_st->sdp_port = atoi(buf1);
370
371         get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
372
373         /* XXX: handle list of formats */
374         get_word(buf1, sizeof(buf1), &p); /* format list */
375         rtsp_st->sdp_payload_type = atoi(buf1);
376
377         if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
378             /* no corresponding stream */
379         } else if (rt->server_type == RTSP_SERVER_WMS &&
380                    codec_type == AVMEDIA_TYPE_DATA) {
381             /* RTX stream, a stream that carries all the other actual
382              * audio/video streams. Don't expose this to the callers. */
383         } else {
384             st = avformat_new_stream(s, NULL);
385             if (!st)
386                 return;
387             st->id = rt->nb_rtsp_streams - 1;
388             rtsp_st->stream_index = st->index;
389             st->codec->codec_type = codec_type;
390             if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
391                 RTPDynamicProtocolHandler *handler;
392                 /* if standard payload type, we can find the codec right now */
393                 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
394                 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
395                     st->codec->sample_rate > 0)
396                     avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);
397                 /* Even static payload types may need a custom depacketizer */
398                 handler = ff_rtp_handler_find_by_id(
399                               rtsp_st->sdp_payload_type, st->codec->codec_type);
400                 init_rtp_handler(handler, rtsp_st, st->codec);
401                 if (handler && handler->init)
402                     handler->init(s, st->index,
403                                   rtsp_st->dynamic_protocol_context);
404             }
405         }
406         /* put a default control url */
407         av_strlcpy(rtsp_st->control_url, rt->control_uri,
408                    sizeof(rtsp_st->control_url));
409         break;
410     case 'a':
411         if (av_strstart(p, "control:", &p)) {
412             if (s->nb_streams == 0) {
413                 if (!strncmp(p, "rtsp://", 7))
414                     av_strlcpy(rt->control_uri, p,
415                                sizeof(rt->control_uri));
416             } else {
417                 char proto[32];
418                 /* get the control url */
419                 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
420
421                 /* XXX: may need to add full url resolution */
422                 av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
423                              NULL, NULL, 0, p);
424                 if (proto[0] == '\0') {
425                     /* relative control URL */
426                     if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
427                     av_strlcat(rtsp_st->control_url, "/",
428                                sizeof(rtsp_st->control_url));
429                     av_strlcat(rtsp_st->control_url, p,
430                                sizeof(rtsp_st->control_url));
431                 } else
432                     av_strlcpy(rtsp_st->control_url, p,
433                                sizeof(rtsp_st->control_url));
434             }
435         } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
436             /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
437             get_word(buf1, sizeof(buf1), &p);
438             payload_type = atoi(buf1);
439             rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
440             if (rtsp_st->stream_index >= 0) {
441                 st = s->streams[rtsp_st->stream_index];
442                 sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
443             }
444         } else if (av_strstart(p, "fmtp:", &p) ||
445                    av_strstart(p, "framesize:", &p)) {
446             /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
447             // let dynamic protocol handlers have a stab at the line.
448             get_word(buf1, sizeof(buf1), &p);
449             payload_type = atoi(buf1);
450             for (i = 0; i < rt->nb_rtsp_streams; i++) {
451                 rtsp_st = rt->rtsp_streams[i];
452                 if (rtsp_st->sdp_payload_type == payload_type &&
453                     rtsp_st->dynamic_handler &&
454                     rtsp_st->dynamic_handler->parse_sdp_a_line)
455                     rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
456                         rtsp_st->dynamic_protocol_context, buf);
457             }
458         } else if (av_strstart(p, "range:", &p)) {
459             int64_t start, end;
460
461             // this is so that seeking on a streamed file can work.
462             rtsp_parse_range_npt(p, &start, &end);
463             s->start_time = start;
464             /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
465             s->duration   = (end == AV_NOPTS_VALUE) ?
466                             AV_NOPTS_VALUE : end - start;
467         } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
468             if (atoi(p) == 1)
469                 rt->transport = RTSP_TRANSPORT_RDT;
470         } else if (av_strstart(p, "SampleRate:integer;", &p) &&
471                    s->nb_streams > 0) {
472             st = s->streams[s->nb_streams - 1];
473             st->codec->sample_rate = atoi(p);
474         } else {
475             if (rt->server_type == RTSP_SERVER_WMS)
476                 ff_wms_parse_sdp_a_line(s, p);
477             if (s->nb_streams > 0) {
478                 rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
479
480                 if (rt->server_type == RTSP_SERVER_REAL)
481                     ff_real_parse_sdp_a_line(s, rtsp_st->stream_index, p);
482
483                 if (rtsp_st->dynamic_handler &&
484                     rtsp_st->dynamic_handler->parse_sdp_a_line)
485                     rtsp_st->dynamic_handler->parse_sdp_a_line(s,
486                         rtsp_st->stream_index,
487                         rtsp_st->dynamic_protocol_context, buf);
488             }
489         }
490         break;
491     }
492 }
493
494 int ff_sdp_parse(AVFormatContext *s, const char *content)
495 {
496     RTSPState *rt = s->priv_data;
497     const char *p;
498     int letter;
499     /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
500      * contain long SDP lines containing complete ASF Headers (several
501      * kB) or arrays of MDPR (RM stream descriptor) headers plus
502      * "rulebooks" describing their properties. Therefore, the SDP line
503      * buffer is large.
504      *
505      * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
506      * in rtpdec_xiph.c. */
507     char buf[16384], *q;
508     SDPParseState sdp_parse_state = { { 0 } }, *s1 = &sdp_parse_state;
509
510     p = content;
511     for (;;) {
512         p += strspn(p, SPACE_CHARS);
513         letter = *p;
514         if (letter == '\0')
515             break;
516         p++;
517         if (*p != '=')
518             goto next_line;
519         p++;
520         /* get the content */
521         q = buf;
522         while (*p != '\n' && *p != '\r' && *p != '\0') {
523             if ((q - buf) < sizeof(buf) - 1)
524                 *q++ = *p;
525             p++;
526         }
527         *q = '\0';
528         sdp_parse_line(s, s1, letter, buf);
529     next_line:
530         while (*p != '\n' && *p != '\0')
531             p++;
532         if (*p == '\n')
533             p++;
534     }
535     rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
536     if (!rt->p) return AVERROR(ENOMEM);
537     return 0;
538 }
539 #endif /* CONFIG_RTPDEC */
540
541 void ff_rtsp_undo_setup(AVFormatContext *s)
542 {
543     RTSPState *rt = s->priv_data;
544     int i;
545
546     for (i = 0; i < rt->nb_rtsp_streams; i++) {
547         RTSPStream *rtsp_st = rt->rtsp_streams[i];
548         if (!rtsp_st)
549             continue;
550         if (rtsp_st->transport_priv) {
551             if (s->oformat) {
552                 AVFormatContext *rtpctx = rtsp_st->transport_priv;
553                 av_write_trailer(rtpctx);
554                 if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
555                     uint8_t *ptr;
556                     avio_close_dyn_buf(rtpctx->pb, &ptr);
557                     av_free(ptr);
558                 } else {
559                     avio_close(rtpctx->pb);
560                 }
561                 avformat_free_context(rtpctx);
562             } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
563                 ff_rdt_parse_close(rtsp_st->transport_priv);
564             else if (CONFIG_RTPDEC)
565                 ff_rtp_parse_close(rtsp_st->transport_priv);
566         }
567         rtsp_st->transport_priv = NULL;
568         if (rtsp_st->rtp_handle)
569             ffurl_close(rtsp_st->rtp_handle);
570         rtsp_st->rtp_handle = NULL;
571     }
572 }
573
574 /* close and free RTSP streams */
575 void ff_rtsp_close_streams(AVFormatContext *s)
576 {
577     RTSPState *rt = s->priv_data;
578     int i;
579     RTSPStream *rtsp_st;
580
581     ff_rtsp_undo_setup(s);
582     for (i = 0; i < rt->nb_rtsp_streams; i++) {
583         rtsp_st = rt->rtsp_streams[i];
584         if (rtsp_st) {
585             if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
586                 rtsp_st->dynamic_handler->free(
587                     rtsp_st->dynamic_protocol_context);
588             av_free(rtsp_st);
589         }
590     }
591     av_free(rt->rtsp_streams);
592     if (rt->asf_ctx) {
593         avformat_close_input(&rt->asf_ctx);
594     }
595     av_free(rt->p);
596     av_free(rt->recvbuf);
597 }
598
599 static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
600 {
601     RTSPState *rt = s->priv_data;
602     AVStream *st = NULL;
603
604     /* open the RTP context */
605     if (rtsp_st->stream_index >= 0)
606         st = s->streams[rtsp_st->stream_index];
607     if (!st)
608         s->ctx_flags |= AVFMTCTX_NOHEADER;
609
610     if (s->oformat && CONFIG_RTSP_MUXER) {
611         int ret = ff_rtp_chain_mux_open(&rtsp_st->transport_priv, s, st,
612                                         rtsp_st->rtp_handle,
613                                         RTSP_TCP_MAX_PACKET_SIZE);
614         /* Ownership of rtp_handle is passed to the rtp mux context */
615         rtsp_st->rtp_handle = NULL;
616         if (ret < 0)
617             return ret;
618     } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
619         rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
620                                             rtsp_st->dynamic_protocol_context,
621                                             rtsp_st->dynamic_handler);
622     else if (CONFIG_RTPDEC)
623         rtsp_st->transport_priv = ff_rtp_parse_open(s, st, rtsp_st->rtp_handle,
624                                          rtsp_st->sdp_payload_type,
625             (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
626             ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
627
628     if (!rtsp_st->transport_priv) {
629          return AVERROR(ENOMEM);
630     } else if (rt->transport != RTSP_TRANSPORT_RDT && CONFIG_RTPDEC) {
631         if (rtsp_st->dynamic_handler) {
632             ff_rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
633                                               rtsp_st->dynamic_protocol_context,
634                                               rtsp_st->dynamic_handler);
635         }
636     }
637
638     return 0;
639 }
640
641 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
642 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
643 {
644     const char *q;
645     char *p;
646     int v;
647
648     q = *pp;
649     q += strspn(q, SPACE_CHARS);
650     v = strtol(q, &p, 10);
651     if (*p == '-') {
652         p++;
653         *min_ptr = v;
654         v = strtol(p, &p, 10);
655         *max_ptr = v;
656     } else {
657         *min_ptr = v;
658         *max_ptr = v;
659     }
660     *pp = p;
661 }
662
663 /* XXX: only one transport specification is parsed */
664 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
665 {
666     char transport_protocol[16];
667     char profile[16];
668     char lower_transport[16];
669     char parameter[16];
670     RTSPTransportField *th;
671     char buf[256];
672
673     reply->nb_transports = 0;
674
675     for (;;) {
676         p += strspn(p, SPACE_CHARS);
677         if (*p == '\0')
678             break;
679
680         th = &reply->transports[reply->nb_transports];
681
682         get_word_sep(transport_protocol, sizeof(transport_protocol),
683                      "/", &p);
684         if (!av_strcasecmp (transport_protocol, "rtp")) {
685             get_word_sep(profile, sizeof(profile), "/;,", &p);
686             lower_transport[0] = '\0';
687             /* rtp/avp/<protocol> */
688             if (*p == '/') {
689                 get_word_sep(lower_transport, sizeof(lower_transport),
690                              ";,", &p);
691             }
692             th->transport = RTSP_TRANSPORT_RTP;
693         } else if (!av_strcasecmp (transport_protocol, "x-pn-tng") ||
694                    !av_strcasecmp (transport_protocol, "x-real-rdt")) {
695             /* x-pn-tng/<protocol> */
696             get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
697             profile[0] = '\0';
698             th->transport = RTSP_TRANSPORT_RDT;
699         }
700         if (!av_strcasecmp(lower_transport, "TCP"))
701             th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
702         else
703             th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
704
705         if (*p == ';')
706             p++;
707         /* get each parameter */
708         while (*p != '\0' && *p != ',') {
709             get_word_sep(parameter, sizeof(parameter), "=;,", &p);
710             if (!strcmp(parameter, "port")) {
711                 if (*p == '=') {
712                     p++;
713                     rtsp_parse_range(&th->port_min, &th->port_max, &p);
714                 }
715             } else if (!strcmp(parameter, "client_port")) {
716                 if (*p == '=') {
717                     p++;
718                     rtsp_parse_range(&th->client_port_min,
719                                      &th->client_port_max, &p);
720                 }
721             } else if (!strcmp(parameter, "server_port")) {
722                 if (*p == '=') {
723                     p++;
724                     rtsp_parse_range(&th->server_port_min,
725                                      &th->server_port_max, &p);
726                 }
727             } else if (!strcmp(parameter, "interleaved")) {
728                 if (*p == '=') {
729                     p++;
730                     rtsp_parse_range(&th->interleaved_min,
731                                      &th->interleaved_max, &p);
732                 }
733             } else if (!strcmp(parameter, "multicast")) {
734                 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
735                     th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
736             } else if (!strcmp(parameter, "ttl")) {
737                 if (*p == '=') {
738                     p++;
739                     th->ttl = strtol(p, (char **)&p, 10);
740                 }
741             } else if (!strcmp(parameter, "destination")) {
742                 if (*p == '=') {
743                     p++;
744                     get_word_sep(buf, sizeof(buf), ";,", &p);
745                     get_sockaddr(buf, &th->destination);
746                 }
747             } else if (!strcmp(parameter, "source")) {
748                 if (*p == '=') {
749                     p++;
750                     get_word_sep(buf, sizeof(buf), ";,", &p);
751                     av_strlcpy(th->source, buf, sizeof(th->source));
752                 }
753             }
754
755             while (*p != ';' && *p != '\0' && *p != ',')
756                 p++;
757             if (*p == ';')
758                 p++;
759         }
760         if (*p == ',')
761             p++;
762
763         reply->nb_transports++;
764     }
765 }
766
767 static void handle_rtp_info(RTSPState *rt, const char *url,
768                             uint32_t seq, uint32_t rtptime)
769 {
770     int i;
771     if (!rtptime || !url[0])
772         return;
773     if (rt->transport != RTSP_TRANSPORT_RTP)
774         return;
775     for (i = 0; i < rt->nb_rtsp_streams; i++) {
776         RTSPStream *rtsp_st = rt->rtsp_streams[i];
777         RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
778         if (!rtpctx)
779             continue;
780         if (!strcmp(rtsp_st->control_url, url)) {
781             rtpctx->base_timestamp = rtptime;
782             break;
783         }
784     }
785 }
786
787 static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
788 {
789     int read = 0;
790     char key[20], value[1024], url[1024] = "";
791     uint32_t seq = 0, rtptime = 0;
792
793     for (;;) {
794         p += strspn(p, SPACE_CHARS);
795         if (!*p)
796             break;
797         get_word_sep(key, sizeof(key), "=", &p);
798         if (*p != '=')
799             break;
800         p++;
801         get_word_sep(value, sizeof(value), ";, ", &p);
802         read++;
803         if (!strcmp(key, "url"))
804             av_strlcpy(url, value, sizeof(url));
805         else if (!strcmp(key, "seq"))
806             seq = strtoul(value, NULL, 10);
807         else if (!strcmp(key, "rtptime"))
808             rtptime = strtoul(value, NULL, 10);
809         if (*p == ',') {
810             handle_rtp_info(rt, url, seq, rtptime);
811             url[0] = '\0';
812             seq = rtptime = 0;
813             read = 0;
814         }
815         if (*p)
816             p++;
817     }
818     if (read > 0)
819         handle_rtp_info(rt, url, seq, rtptime);
820 }
821
822 void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
823                         RTSPState *rt, const char *method)
824 {
825     const char *p;
826
827     /* NOTE: we do case independent match for broken servers */
828     p = buf;
829     if (av_stristart(p, "Session:", &p)) {
830         int t;
831         get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
832         if (av_stristart(p, ";timeout=", &p) &&
833             (t = strtol(p, NULL, 10)) > 0) {
834             reply->timeout = t;
835         }
836     } else if (av_stristart(p, "Content-Length:", &p)) {
837         reply->content_length = strtol(p, NULL, 10);
838     } else if (av_stristart(p, "Transport:", &p)) {
839         rtsp_parse_transport(reply, p);
840     } else if (av_stristart(p, "CSeq:", &p)) {
841         reply->seq = strtol(p, NULL, 10);
842     } else if (av_stristart(p, "Range:", &p)) {
843         rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
844     } else if (av_stristart(p, "RealChallenge1:", &p)) {
845         p += strspn(p, SPACE_CHARS);
846         av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
847     } else if (av_stristart(p, "Server:", &p)) {
848         p += strspn(p, SPACE_CHARS);
849         av_strlcpy(reply->server, p, sizeof(reply->server));
850     } else if (av_stristart(p, "Notice:", &p) ||
851                av_stristart(p, "X-Notice:", &p)) {
852         reply->notice = strtol(p, NULL, 10);
853     } else if (av_stristart(p, "Location:", &p)) {
854         p += strspn(p, SPACE_CHARS);
855         av_strlcpy(reply->location, p , sizeof(reply->location));
856     } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
857         p += strspn(p, SPACE_CHARS);
858         ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
859     } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
860         p += strspn(p, SPACE_CHARS);
861         ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
862     } else if (av_stristart(p, "Content-Base:", &p) && rt) {
863         p += strspn(p, SPACE_CHARS);
864         if (method && !strcmp(method, "DESCRIBE"))
865             av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
866     } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
867         p += strspn(p, SPACE_CHARS);
868         if (method && !strcmp(method, "PLAY"))
869             rtsp_parse_rtp_info(rt, p);
870     } else if (av_stristart(p, "Public:", &p) && rt) {
871         if (strstr(p, "GET_PARAMETER") &&
872             method && !strcmp(method, "OPTIONS"))
873             rt->get_parameter_supported = 1;
874     } else if (av_stristart(p, "x-Accept-Dynamic-Rate:", &p) && rt) {
875         p += strspn(p, SPACE_CHARS);
876         rt->accept_dynamic_rate = atoi(p);
877     } else if (av_stristart(p, "Content-Type:", &p)) {
878         p += strspn(p, SPACE_CHARS);
879         av_strlcpy(reply->content_type, p, sizeof(reply->content_type));
880     }
881 }
882
883 /* skip a RTP/TCP interleaved packet */
884 void ff_rtsp_skip_packet(AVFormatContext *s)
885 {
886     RTSPState *rt = s->priv_data;
887     int ret, len, len1;
888     uint8_t buf[1024];
889
890     ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
891     if (ret != 3)
892         return;
893     len = AV_RB16(buf + 1);
894
895     av_dlog(s, "skipping RTP packet len=%d\n", len);
896
897     /* skip payload */
898     while (len > 0) {
899         len1 = len;
900         if (len1 > sizeof(buf))
901             len1 = sizeof(buf);
902         ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
903         if (ret != len1)
904             return;
905         len -= len1;
906     }
907 }
908
909 int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
910                        unsigned char **content_ptr,
911                        int return_on_interleaved_data, const char *method)
912 {
913     RTSPState *rt = s->priv_data;
914     char buf[4096], buf1[1024], *q;
915     unsigned char ch;
916     const char *p;
917     int ret, content_length, line_count = 0, request = 0;
918     unsigned char *content = NULL;
919
920 start:
921     line_count = 0;
922     request = 0;
923     content = NULL;
924     memset(reply, 0, sizeof(*reply));
925
926     /* parse reply (XXX: use buffers) */
927     rt->last_reply[0] = '\0';
928     for (;;) {
929         q = buf;
930         for (;;) {
931             ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
932             av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
933             if (ret != 1)
934                 return AVERROR_EOF;
935             if (ch == '\n')
936                 break;
937             if (ch == '$') {
938                 /* XXX: only parse it if first char on line ? */
939                 if (return_on_interleaved_data) {
940                     return 1;
941                 } else
942                     ff_rtsp_skip_packet(s);
943             } else if (ch != '\r') {
944                 if ((q - buf) < sizeof(buf) - 1)
945                     *q++ = ch;
946             }
947         }
948         *q = '\0';
949
950         av_dlog(s, "line='%s'\n", buf);
951
952         /* test if last line */
953         if (buf[0] == '\0')
954             break;
955         p = buf;
956         if (line_count == 0) {
957             /* get reply code */
958             get_word(buf1, sizeof(buf1), &p);
959             if (!strncmp(buf1, "RTSP/", 5)) {
960                 get_word(buf1, sizeof(buf1), &p);
961                 reply->status_code = atoi(buf1);
962                 av_strlcpy(reply->reason, p, sizeof(reply->reason));
963             } else {
964                 av_strlcpy(reply->reason, buf1, sizeof(reply->reason)); // method
965                 get_word(buf1, sizeof(buf1), &p); // object
966                 request = 1;
967             }
968         } else {
969             ff_rtsp_parse_line(reply, p, rt, method);
970             av_strlcat(rt->last_reply, p,    sizeof(rt->last_reply));
971             av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
972         }
973         line_count++;
974     }
975
976     if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0' && !request)
977         av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
978
979     content_length = reply->content_length;
980     if (content_length > 0) {
981         /* leave some room for a trailing '\0' (useful for simple parsing) */
982         content = av_malloc(content_length + 1);
983         ffurl_read_complete(rt->rtsp_hd, content, content_length);
984         content[content_length] = '\0';
985     }
986     if (content_ptr)
987         *content_ptr = content;
988     else
989         av_free(content);
990
991     if (request) {
992         char buf[1024];
993         char base64buf[AV_BASE64_SIZE(sizeof(buf))];
994         const char* ptr = buf;
995
996         if (!strcmp(reply->reason, "OPTIONS")) {
997             snprintf(buf, sizeof(buf), "RTSP/1.0 200 OK\r\n");
998             if (reply->seq)
999                 av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", reply->seq);
1000             if (reply->session_id[0])
1001                 av_strlcatf(buf, sizeof(buf), "Session: %s\r\n",
1002                                               reply->session_id);
1003         } else {
1004             snprintf(buf, sizeof(buf), "RTSP/1.0 501 Not Implemented\r\n");
1005         }
1006         av_strlcat(buf, "\r\n", sizeof(buf));
1007
1008         if (rt->control_transport == RTSP_MODE_TUNNEL) {
1009             av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1010             ptr = base64buf;
1011         }
1012         ffurl_write(rt->rtsp_hd_out, ptr, strlen(ptr));
1013
1014         rt->last_cmd_time = av_gettime();
1015         /* Even if the request from the server had data, it is not the data
1016          * that the caller wants or expects. The memory could also be leaked
1017          * if the actual following reply has content data. */
1018         if (content_ptr)
1019             av_freep(content_ptr);
1020         /* If method is set, this is called from ff_rtsp_send_cmd,
1021          * where a reply to exactly this request is awaited. For
1022          * callers from within packet receiving, we just want to
1023          * return to the caller and go back to receiving packets. */
1024         if (method)
1025             goto start;
1026         return 0;
1027     }
1028
1029     if (rt->seq != reply->seq) {
1030         av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
1031             rt->seq, reply->seq);
1032     }
1033
1034     /* EOS */
1035     if (reply->notice == 2101 /* End-of-Stream Reached */      ||
1036         reply->notice == 2104 /* Start-of-Stream Reached */    ||
1037         reply->notice == 2306 /* Continuous Feed Terminated */) {
1038         rt->state = RTSP_STATE_IDLE;
1039     } else if (reply->notice >= 4400 && reply->notice < 5500) {
1040         return AVERROR(EIO); /* data or server error */
1041     } else if (reply->notice == 2401 /* Ticket Expired */ ||
1042              (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
1043         return AVERROR(EPERM);
1044
1045     return 0;
1046 }
1047
1048 /**
1049  * Send a command to the RTSP server without waiting for the reply.
1050  *
1051  * @param s RTSP (de)muxer context
1052  * @param method the method for the request
1053  * @param url the target url for the request
1054  * @param headers extra header lines to include in the request
1055  * @param send_content if non-null, the data to send as request body content
1056  * @param send_content_length the length of the send_content data, or 0 if
1057  *                            send_content is null
1058  *
1059  * @return zero if success, nonzero otherwise
1060  */
1061 static int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
1062                                                const char *method, const char *url,
1063                                                const char *headers,
1064                                                const unsigned char *send_content,
1065                                                int send_content_length)
1066 {
1067     RTSPState *rt = s->priv_data;
1068     char buf[4096], *out_buf;
1069     char base64buf[AV_BASE64_SIZE(sizeof(buf))];
1070
1071     /* Add in RTSP headers */
1072     out_buf = buf;
1073     rt->seq++;
1074     snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
1075     if (headers)
1076         av_strlcat(buf, headers, sizeof(buf));
1077     av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
1078     if (rt->session_id[0] != '\0' && (!headers ||
1079         !strstr(headers, "\nIf-Match:"))) {
1080         av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
1081     }
1082     if (rt->auth[0]) {
1083         char *str = ff_http_auth_create_response(&rt->auth_state,
1084                                                  rt->auth, url, method);
1085         if (str)
1086             av_strlcat(buf, str, sizeof(buf));
1087         av_free(str);
1088     }
1089     if (send_content_length > 0 && send_content)
1090         av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
1091     av_strlcat(buf, "\r\n", sizeof(buf));
1092
1093     /* base64 encode rtsp if tunneling */
1094     if (rt->control_transport == RTSP_MODE_TUNNEL) {
1095         av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1096         out_buf = base64buf;
1097     }
1098
1099     av_dlog(s, "Sending:\n%s--\n", buf);
1100
1101     ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
1102     if (send_content_length > 0 && send_content) {
1103         if (rt->control_transport == RTSP_MODE_TUNNEL) {
1104             av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
1105                                     "with content data not supported\n");
1106             return AVERROR_PATCHWELCOME;
1107         }
1108         ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
1109     }
1110     rt->last_cmd_time = av_gettime();
1111
1112     return 0;
1113 }
1114
1115 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
1116                            const char *url, const char *headers)
1117 {
1118     return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
1119 }
1120
1121 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
1122                      const char *headers, RTSPMessageHeader *reply,
1123                      unsigned char **content_ptr)
1124 {
1125     return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
1126                                          content_ptr, NULL, 0);
1127 }
1128
1129 int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
1130                                   const char *method, const char *url,
1131                                   const char *header,
1132                                   RTSPMessageHeader *reply,
1133                                   unsigned char **content_ptr,
1134                                   const unsigned char *send_content,
1135                                   int send_content_length)
1136 {
1137     RTSPState *rt = s->priv_data;
1138     HTTPAuthType cur_auth_type;
1139     int ret, attempts = 0;
1140
1141 retry:
1142     cur_auth_type = rt->auth_state.auth_type;
1143     if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
1144                                                    send_content,
1145                                                    send_content_length)))
1146         return ret;
1147
1148     if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
1149         return ret;
1150     attempts++;
1151
1152     if (reply->status_code == 401 &&
1153         (cur_auth_type == HTTP_AUTH_NONE || rt->auth_state.stale) &&
1154         rt->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2)
1155         goto retry;
1156
1157     if (reply->status_code > 400){
1158         av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
1159                method,
1160                reply->status_code,
1161                reply->reason);
1162         av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
1163     }
1164
1165     return 0;
1166 }
1167
1168 int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
1169                               int lower_transport, const char *real_challenge)
1170 {
1171     RTSPState *rt = s->priv_data;
1172     int rtx = 0, j, i, err, interleave = 0, port_off;
1173     RTSPStream *rtsp_st;
1174     RTSPMessageHeader reply1, *reply = &reply1;
1175     char cmd[2048];
1176     const char *trans_pref;
1177
1178     if (rt->transport == RTSP_TRANSPORT_RDT)
1179         trans_pref = "x-pn-tng";
1180     else
1181         trans_pref = "RTP/AVP";
1182
1183     /* default timeout: 1 minute */
1184     rt->timeout = 60;
1185
1186     /* for each stream, make the setup request */
1187     /* XXX: we assume the same server is used for the control of each
1188      * RTSP stream */
1189
1190     /* Choose a random starting offset within the first half of the
1191      * port range, to allow for a number of ports to try even if the offset
1192      * happens to be at the end of the random range. */
1193     port_off = av_get_random_seed() % ((rt->rtp_port_max - rt->rtp_port_min)/2);
1194     /* even random offset */
1195     port_off -= port_off & 0x01;
1196
1197     for (j = rt->rtp_port_min + port_off, i = 0; i < rt->nb_rtsp_streams; ++i) {
1198         char transport[2048];
1199
1200         /*
1201          * WMS serves all UDP data over a single connection, the RTX, which
1202          * isn't necessarily the first in the SDP but has to be the first
1203          * to be set up, else the second/third SETUP will fail with a 461.
1204          */
1205         if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1206              rt->server_type == RTSP_SERVER_WMS) {
1207             if (i == 0) {
1208                 /* rtx first */
1209                 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1210                     int len = strlen(rt->rtsp_streams[rtx]->control_url);
1211                     if (len >= 4 &&
1212                         !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1213                                 "/rtx"))
1214                         break;
1215                 }
1216                 if (rtx == rt->nb_rtsp_streams)
1217                     return -1; /* no RTX found */
1218                 rtsp_st = rt->rtsp_streams[rtx];
1219             } else
1220                 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1221         } else
1222             rtsp_st = rt->rtsp_streams[i];
1223
1224         /* RTP/UDP */
1225         if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1226             char buf[256];
1227
1228             if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1229                 port = reply->transports[0].client_port_min;
1230                 goto have_port;
1231             }
1232
1233             /* first try in specified port range */
1234             while (j <= rt->rtp_port_max) {
1235                 ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1236                             "?localport=%d", j);
1237                 /* we will use two ports per rtp stream (rtp and rtcp) */
1238                 j += 2;
1239                 if (!ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE,
1240                                &s->interrupt_callback, NULL))
1241                     goto rtp_opened;
1242             }
1243
1244             av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
1245             err = AVERROR(EIO);
1246             goto fail;
1247
1248         rtp_opened:
1249             port = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
1250         have_port:
1251             snprintf(transport, sizeof(transport) - 1,
1252                      "%s/UDP;", trans_pref);
1253             if (rt->server_type != RTSP_SERVER_REAL)
1254                 av_strlcat(transport, "unicast;", sizeof(transport));
1255             av_strlcatf(transport, sizeof(transport),
1256                      "client_port=%d", port);
1257             if (rt->transport == RTSP_TRANSPORT_RTP &&
1258                 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1259                 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1260         }
1261
1262         /* RTP/TCP */
1263         else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1264             /* For WMS streams, the application streams are only used for
1265              * UDP. When trying to set it up for TCP streams, the server
1266              * will return an error. Therefore, we skip those streams. */
1267             if (rt->server_type == RTSP_SERVER_WMS &&
1268                 (rtsp_st->stream_index < 0 ||
1269                  s->streams[rtsp_st->stream_index]->codec->codec_type ==
1270                     AVMEDIA_TYPE_DATA))
1271                 continue;
1272             snprintf(transport, sizeof(transport) - 1,
1273                      "%s/TCP;", trans_pref);
1274             if (rt->transport != RTSP_TRANSPORT_RDT)
1275                 av_strlcat(transport, "unicast;", sizeof(transport));
1276             av_strlcatf(transport, sizeof(transport),
1277                         "interleaved=%d-%d",
1278                         interleave, interleave + 1);
1279             interleave += 2;
1280         }
1281
1282         else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1283             snprintf(transport, sizeof(transport) - 1,
1284                      "%s/UDP;multicast", trans_pref);
1285         }
1286         if (s->oformat) {
1287             av_strlcat(transport, ";mode=receive", sizeof(transport));
1288         } else if (rt->server_type == RTSP_SERVER_REAL ||
1289                    rt->server_type == RTSP_SERVER_WMS)
1290             av_strlcat(transport, ";mode=play", sizeof(transport));
1291         snprintf(cmd, sizeof(cmd),
1292                  "Transport: %s\r\n",
1293                  transport);
1294         if (rt->accept_dynamic_rate)
1295             av_strlcat(cmd, "x-Dynamic-Rate: 0\r\n", sizeof(cmd));
1296         if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
1297             char real_res[41], real_csum[9];
1298             ff_rdt_calc_response_and_checksum(real_res, real_csum,
1299                                               real_challenge);
1300             av_strlcatf(cmd, sizeof(cmd),
1301                         "If-Match: %s\r\n"
1302                         "RealChallenge2: %s, sd=%s\r\n",
1303                         rt->session_id, real_res, real_csum);
1304         }
1305         ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1306         if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1307             err = 1;
1308             goto fail;
1309         } else if (reply->status_code != RTSP_STATUS_OK ||
1310                    reply->nb_transports != 1) {
1311             err = AVERROR_INVALIDDATA;
1312             goto fail;
1313         }
1314
1315         /* XXX: same protocol for all streams is required */
1316         if (i > 0) {
1317             if (reply->transports[0].lower_transport != rt->lower_transport ||
1318                 reply->transports[0].transport != rt->transport) {
1319                 err = AVERROR_INVALIDDATA;
1320                 goto fail;
1321             }
1322         } else {
1323             rt->lower_transport = reply->transports[0].lower_transport;
1324             rt->transport = reply->transports[0].transport;
1325         }
1326
1327         /* Fail if the server responded with another lower transport mode
1328          * than what we requested. */
1329         if (reply->transports[0].lower_transport != lower_transport) {
1330             av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
1331             err = AVERROR_INVALIDDATA;
1332             goto fail;
1333         }
1334
1335         switch(reply->transports[0].lower_transport) {
1336         case RTSP_LOWER_TRANSPORT_TCP:
1337             rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1338             rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1339             break;
1340
1341         case RTSP_LOWER_TRANSPORT_UDP: {
1342             char url[1024], options[30] = "";
1343
1344             if (rt->rtsp_flags & RTSP_FLAG_FILTER_SRC)
1345                 av_strlcpy(options, "?connect=1", sizeof(options));
1346             /* Use source address if specified */
1347             if (reply->transports[0].source[0]) {
1348                 ff_url_join(url, sizeof(url), "rtp", NULL,
1349                             reply->transports[0].source,
1350                             reply->transports[0].server_port_min, "%s", options);
1351             } else {
1352                 ff_url_join(url, sizeof(url), "rtp", NULL, host,
1353                             reply->transports[0].server_port_min, "%s", options);
1354             }
1355             if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1356                 ff_rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1357                 err = AVERROR_INVALIDDATA;
1358                 goto fail;
1359             }
1360             /* Try to initialize the connection state in a
1361              * potential NAT router by sending dummy packets.
1362              * RTP/RTCP dummy packets are used for RDT, too.
1363              */
1364             if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
1365                 CONFIG_RTPDEC)
1366                 ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
1367             break;
1368         }
1369         case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1370             char url[1024], namebuf[50], optbuf[20] = "";
1371             struct sockaddr_storage addr;
1372             int port, ttl;
1373
1374             if (reply->transports[0].destination.ss_family) {
1375                 addr      = reply->transports[0].destination;
1376                 port      = reply->transports[0].port_min;
1377                 ttl       = reply->transports[0].ttl;
1378             } else {
1379                 addr      = rtsp_st->sdp_ip;
1380                 port      = rtsp_st->sdp_port;
1381                 ttl       = rtsp_st->sdp_ttl;
1382             }
1383             if (ttl > 0)
1384                 snprintf(optbuf, sizeof(optbuf), "?ttl=%d", ttl);
1385             getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1386                         namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1387             ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
1388                         port, "%s", optbuf);
1389             if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
1390                            &s->interrupt_callback, NULL) < 0) {
1391                 err = AVERROR_INVALIDDATA;
1392                 goto fail;
1393             }
1394             break;
1395         }
1396         }
1397
1398         if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1399             goto fail;
1400     }
1401
1402     if (rt->nb_rtsp_streams && reply->timeout > 0)
1403         rt->timeout = reply->timeout;
1404
1405     if (rt->server_type == RTSP_SERVER_REAL)
1406         rt->need_subscription = 1;
1407
1408     return 0;
1409
1410 fail:
1411     ff_rtsp_undo_setup(s);
1412     return err;
1413 }
1414
1415 void ff_rtsp_close_connections(AVFormatContext *s)
1416 {
1417     RTSPState *rt = s->priv_data;
1418     if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
1419     ffurl_close(rt->rtsp_hd);
1420     rt->rtsp_hd = rt->rtsp_hd_out = NULL;
1421 }
1422
1423 int ff_rtsp_connect(AVFormatContext *s)
1424 {
1425     RTSPState *rt = s->priv_data;
1426     char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1427     int port, err, tcp_fd;
1428     RTSPMessageHeader reply1 = {0}, *reply = &reply1;
1429     int lower_transport_mask = 0;
1430     char real_challenge[64] = "";
1431     struct sockaddr_storage peer;
1432     socklen_t peer_len = sizeof(peer);
1433
1434     if (rt->rtp_port_max < rt->rtp_port_min) {
1435         av_log(s, AV_LOG_ERROR, "Invalid UDP port range, max port %d less "
1436                                 "than min port %d\n", rt->rtp_port_max,
1437                                                       rt->rtp_port_min);
1438         return AVERROR(EINVAL);
1439     }
1440
1441     if (!ff_network_init())
1442         return AVERROR(EIO);
1443
1444     if (s->max_delay < 0) /* Not set by the caller */
1445         s->max_delay = s->iformat ? DEFAULT_REORDERING_DELAY : 0;
1446
1447     rt->control_transport = RTSP_MODE_PLAIN;
1448     if (rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_HTTP)) {
1449         rt->lower_transport_mask = 1 << RTSP_LOWER_TRANSPORT_TCP;
1450         rt->control_transport = RTSP_MODE_TUNNEL;
1451     }
1452     /* Only pass through valid flags from here */
1453     rt->lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1454
1455 redirect:
1456     lower_transport_mask = rt->lower_transport_mask;
1457     /* extract hostname and port */
1458     av_url_split(NULL, 0, auth, sizeof(auth),
1459                  host, sizeof(host), &port, path, sizeof(path), s->filename);
1460     if (*auth) {
1461         av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1462     }
1463     if (port < 0)
1464         port = RTSP_DEFAULT_PORT;
1465
1466     if (!lower_transport_mask)
1467         lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1468
1469     if (s->oformat) {
1470         /* Only UDP or TCP - UDP multicast isn't supported. */
1471         lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1472                                 (1 << RTSP_LOWER_TRANSPORT_TCP);
1473         if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
1474             av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1475                                     "only UDP and TCP are supported for output.\n");
1476             err = AVERROR(EINVAL);
1477             goto fail;
1478         }
1479     }
1480
1481     /* Construct the URI used in request; this is similar to s->filename,
1482      * but with authentication credentials removed and RTSP specific options
1483      * stripped out. */
1484     ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1485                 host, port, "%s", path);
1486
1487     if (rt->control_transport == RTSP_MODE_TUNNEL) {
1488         /* set up initial handshake for tunneling */
1489         char httpname[1024];
1490         char sessioncookie[17];
1491         char headers[1024];
1492
1493         ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
1494         snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1495                  av_get_random_seed(), av_get_random_seed());
1496
1497         /* GET requests */
1498         if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_FLAG_READ,
1499                         &s->interrupt_callback) < 0) {
1500             err = AVERROR(EIO);
1501             goto fail;
1502         }
1503
1504         /* generate GET headers */
1505         snprintf(headers, sizeof(headers),
1506                  "x-sessioncookie: %s\r\n"
1507                  "Accept: application/x-rtsp-tunnelled\r\n"
1508                  "Pragma: no-cache\r\n"
1509                  "Cache-Control: no-cache\r\n",
1510                  sessioncookie);
1511         av_opt_set(rt->rtsp_hd->priv_data, "headers", headers, 0);
1512
1513         /* complete the connection */
1514         if (ffurl_connect(rt->rtsp_hd, NULL)) {
1515             err = AVERROR(EIO);
1516             goto fail;
1517         }
1518
1519         /* POST requests */
1520         if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_FLAG_WRITE,
1521                         &s->interrupt_callback) < 0 ) {
1522             err = AVERROR(EIO);
1523             goto fail;
1524         }
1525
1526         /* generate POST headers */
1527         snprintf(headers, sizeof(headers),
1528                  "x-sessioncookie: %s\r\n"
1529                  "Content-Type: application/x-rtsp-tunnelled\r\n"
1530                  "Pragma: no-cache\r\n"
1531                  "Cache-Control: no-cache\r\n"
1532                  "Content-Length: 32767\r\n"
1533                  "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1534                  sessioncookie);
1535         av_opt_set(rt->rtsp_hd_out->priv_data, "headers", headers, 0);
1536         av_opt_set(rt->rtsp_hd_out->priv_data, "chunked_post", "0", 0);
1537
1538         /* Initialize the authentication state for the POST session. The HTTP
1539          * protocol implementation doesn't properly handle multi-pass
1540          * authentication for POST requests, since it would require one of
1541          * the following:
1542          * - implementing Expect: 100-continue, which many HTTP servers
1543          *   don't support anyway, even less the RTSP servers that do HTTP
1544          *   tunneling
1545          * - sending the whole POST data until getting a 401 reply specifying
1546          *   what authentication method to use, then resending all that data
1547          * - waiting for potential 401 replies directly after sending the
1548          *   POST header (waiting for some unspecified time)
1549          * Therefore, we copy the full auth state, which works for both basic
1550          * and digest. (For digest, we would have to synchronize the nonce
1551          * count variable between the two sessions, if we'd do more requests
1552          * with the original session, though.)
1553          */
1554         ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1555
1556         /* complete the connection */
1557         if (ffurl_connect(rt->rtsp_hd_out, NULL)) {
1558             err = AVERROR(EIO);
1559             goto fail;
1560         }
1561     } else {
1562         /* open the tcp connection */
1563         ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
1564         if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
1565                        &s->interrupt_callback, NULL) < 0) {
1566             err = AVERROR(EIO);
1567             goto fail;
1568         }
1569         rt->rtsp_hd_out = rt->rtsp_hd;
1570     }
1571     rt->seq = 0;
1572
1573     tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
1574     if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1575         getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1576                     NULL, 0, NI_NUMERICHOST);
1577     }
1578
1579     /* request options supported by the server; this also detects server
1580      * type */
1581     for (rt->server_type = RTSP_SERVER_RTP;;) {
1582         cmd[0] = 0;
1583         if (rt->server_type == RTSP_SERVER_REAL)
1584             av_strlcat(cmd,
1585                        /*
1586                         * The following entries are required for proper
1587                         * streaming from a Realmedia server. They are
1588                         * interdependent in some way although we currently
1589                         * don't quite understand how. Values were copied
1590                         * from mplayer SVN r23589.
1591                         *   ClientChallenge is a 16-byte ID in hex
1592                         *   CompanyID is a 16-byte ID in base64
1593                         */
1594                        "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1595                        "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1596                        "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1597                        "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1598                        sizeof(cmd));
1599         ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1600         if (reply->status_code != RTSP_STATUS_OK) {
1601             err = AVERROR_INVALIDDATA;
1602             goto fail;
1603         }
1604
1605         /* detect server type if not standard-compliant RTP */
1606         if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1607             rt->server_type = RTSP_SERVER_REAL;
1608             continue;
1609         } else if (!av_strncasecmp(reply->server, "WMServer/", 9)) {
1610             rt->server_type = RTSP_SERVER_WMS;
1611         } else if (rt->server_type == RTSP_SERVER_REAL)
1612             strcpy(real_challenge, reply->real_challenge);
1613         break;
1614     }
1615
1616     if (s->iformat && CONFIG_RTSP_DEMUXER)
1617         err = ff_rtsp_setup_input_streams(s, reply);
1618     else if (CONFIG_RTSP_MUXER)
1619         err = ff_rtsp_setup_output_streams(s, host);
1620     if (err)
1621         goto fail;
1622
1623     do {
1624         int lower_transport = ff_log2_tab[lower_transport_mask &
1625                                   ~(lower_transport_mask - 1)];
1626
1627         err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
1628                                  rt->server_type == RTSP_SERVER_REAL ?
1629                                      real_challenge : NULL);
1630         if (err < 0)
1631             goto fail;
1632         lower_transport_mask &= ~(1 << lower_transport);
1633         if (lower_transport_mask == 0 && err == 1) {
1634             err = AVERROR(EPROTONOSUPPORT);
1635             goto fail;
1636         }
1637     } while (err);
1638
1639     rt->lower_transport_mask = lower_transport_mask;
1640     av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
1641     rt->state = RTSP_STATE_IDLE;
1642     rt->seek_timestamp = 0; /* default is to start stream at position zero */
1643     return 0;
1644  fail:
1645     ff_rtsp_close_streams(s);
1646     ff_rtsp_close_connections(s);
1647     if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1648         av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1649         av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1650                reply->status_code,
1651                s->filename);
1652         goto redirect;
1653     }
1654     ff_network_close();
1655     return err;
1656 }
1657 #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1658
1659 #if CONFIG_RTPDEC
1660 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1661                            uint8_t *buf, int buf_size, int64_t wait_end)
1662 {
1663     RTSPState *rt = s->priv_data;
1664     RTSPStream *rtsp_st;
1665     int n, i, ret, tcp_fd, timeout_cnt = 0;
1666     int max_p = 0;
1667     struct pollfd *p = rt->p;
1668
1669     for (;;) {
1670         if (ff_check_interrupt(&s->interrupt_callback))
1671             return AVERROR_EXIT;
1672         if (wait_end && wait_end - av_gettime() < 0)
1673             return AVERROR(EAGAIN);
1674         max_p = 0;
1675         if (rt->rtsp_hd) {
1676             tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
1677             p[max_p].fd = tcp_fd;
1678             p[max_p++].events = POLLIN;
1679         } else {
1680             tcp_fd = -1;
1681         }
1682         for (i = 0; i < rt->nb_rtsp_streams; i++) {
1683             rtsp_st = rt->rtsp_streams[i];
1684             if (rtsp_st->rtp_handle) {
1685                 p[max_p].fd = ffurl_get_file_handle(rtsp_st->rtp_handle);
1686                 p[max_p++].events = POLLIN;
1687                 p[max_p].fd = ff_rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1688                 p[max_p++].events = POLLIN;
1689             }
1690         }
1691         n = poll(p, max_p, POLL_TIMEOUT_MS);
1692         if (n > 0) {
1693             int j = 1 - (tcp_fd == -1);
1694             timeout_cnt = 0;
1695             for (i = 0; i < rt->nb_rtsp_streams; i++) {
1696                 rtsp_st = rt->rtsp_streams[i];
1697                 if (rtsp_st->rtp_handle) {
1698                     if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
1699                         ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
1700                         if (ret > 0) {
1701                             *prtsp_st = rtsp_st;
1702                             return ret;
1703                         }
1704                     }
1705                     j+=2;
1706                 }
1707             }
1708 #if CONFIG_RTSP_DEMUXER
1709             if (tcp_fd != -1 && p[0].revents & POLLIN) {
1710                 RTSPMessageHeader reply;
1711
1712                 ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
1713                 if (ret < 0)
1714                     return ret;
1715                 /* XXX: parse message */
1716                 if (rt->state != RTSP_STATE_STREAMING)
1717                     return 0;
1718             }
1719 #endif
1720         } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1721             return AVERROR(ETIMEDOUT);
1722         } else if (n < 0 && errno != EINTR)
1723             return AVERROR(errno);
1724     }
1725 }
1726
1727 int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1728 {
1729     RTSPState *rt = s->priv_data;
1730     int ret, len;
1731     RTSPStream *rtsp_st, *first_queue_st = NULL;
1732     int64_t wait_end = 0;
1733
1734     if (rt->nb_byes == rt->nb_rtsp_streams)
1735         return AVERROR_EOF;
1736
1737     /* get next frames from the same RTP packet */
1738     if (rt->cur_transport_priv) {
1739         if (rt->transport == RTSP_TRANSPORT_RDT) {
1740             ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1741         } else
1742             ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1743         if (ret == 0) {
1744             rt->cur_transport_priv = NULL;
1745             return 0;
1746         } else if (ret == 1) {
1747             return 0;
1748         } else
1749             rt->cur_transport_priv = NULL;
1750     }
1751
1752     if (rt->transport == RTSP_TRANSPORT_RTP) {
1753         int i;
1754         int64_t first_queue_time = 0;
1755         for (i = 0; i < rt->nb_rtsp_streams; i++) {
1756             RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
1757             int64_t queue_time;
1758             if (!rtpctx)
1759                 continue;
1760             queue_time = ff_rtp_queued_packet_time(rtpctx);
1761             if (queue_time && (queue_time - first_queue_time < 0 ||
1762                                !first_queue_time)) {
1763                 first_queue_time = queue_time;
1764                 first_queue_st   = rt->rtsp_streams[i];
1765             }
1766         }
1767         if (first_queue_time)
1768             wait_end = first_queue_time + s->max_delay;
1769     }
1770
1771     /* read next RTP packet */
1772  redo:
1773     if (!rt->recvbuf) {
1774         rt->recvbuf = av_malloc(RECVBUF_SIZE);
1775         if (!rt->recvbuf)
1776             return AVERROR(ENOMEM);
1777     }
1778
1779     switch(rt->lower_transport) {
1780     default:
1781 #if CONFIG_RTSP_DEMUXER
1782     case RTSP_LOWER_TRANSPORT_TCP:
1783         len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
1784         break;
1785 #endif
1786     case RTSP_LOWER_TRANSPORT_UDP:
1787     case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1788         len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
1789         if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1790             ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1791         break;
1792     }
1793     if (len == AVERROR(EAGAIN) && first_queue_st &&
1794         rt->transport == RTSP_TRANSPORT_RTP) {
1795         rtsp_st = first_queue_st;
1796         ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
1797         goto end;
1798     }
1799     if (len < 0)
1800         return len;
1801     if (len == 0)
1802         return AVERROR_EOF;
1803     if (rt->transport == RTSP_TRANSPORT_RDT) {
1804         ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
1805     } else {
1806         ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
1807         if (ret < 0) {
1808             /* Either bad packet, or a RTCP packet. Check if the
1809              * first_rtcp_ntp_time field was initialized. */
1810             RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1811             if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
1812                 /* first_rtcp_ntp_time has been initialized for this stream,
1813                  * copy the same value to all other uninitialized streams,
1814                  * in order to map their timestamp origin to the same ntp time
1815                  * as this one. */
1816                 int i;
1817                 AVStream *st = NULL;
1818                 if (rtsp_st->stream_index >= 0)
1819                     st = s->streams[rtsp_st->stream_index];
1820                 for (i = 0; i < rt->nb_rtsp_streams; i++) {
1821                     RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
1822                     AVStream *st2 = NULL;
1823                     if (rt->rtsp_streams[i]->stream_index >= 0)
1824                         st2 = s->streams[rt->rtsp_streams[i]->stream_index];
1825                     if (rtpctx2 && st && st2 &&
1826                         rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
1827                         rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
1828                         rtpctx2->rtcp_ts_offset = av_rescale_q(
1829                             rtpctx->rtcp_ts_offset, st->time_base,
1830                             st2->time_base);
1831                     }
1832                 }
1833             }
1834             if (ret == -RTCP_BYE) {
1835                 rt->nb_byes++;
1836
1837                 av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
1838                        rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
1839
1840                 if (rt->nb_byes == rt->nb_rtsp_streams)
1841                     return AVERROR_EOF;
1842             }
1843         }
1844     }
1845 end:
1846     if (ret < 0)
1847         goto redo;
1848     if (ret == 1)
1849         /* more packets may follow, so we save the RTP context */
1850         rt->cur_transport_priv = rtsp_st->transport_priv;
1851
1852     return ret;
1853 }
1854 #endif /* CONFIG_RTPDEC */
1855
1856 #if CONFIG_SDP_DEMUXER
1857 static int sdp_probe(AVProbeData *p1)
1858 {
1859     const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
1860
1861     /* we look for a line beginning "c=IN IP" */
1862     while (p < p_end && *p != '\0') {
1863         if (p + sizeof("c=IN IP") - 1 < p_end &&
1864             av_strstart(p, "c=IN IP", NULL))
1865             return AVPROBE_SCORE_MAX / 2;
1866
1867         while (p < p_end - 1 && *p != '\n') p++;
1868         if (++p >= p_end)
1869             break;
1870         if (*p == '\r')
1871             p++;
1872     }
1873     return 0;
1874 }
1875
1876 static int sdp_read_header(AVFormatContext *s)
1877 {
1878     RTSPState *rt = s->priv_data;
1879     RTSPStream *rtsp_st;
1880     int size, i, err;
1881     char *content;
1882     char url[1024];
1883
1884     if (!ff_network_init())
1885         return AVERROR(EIO);
1886
1887     if (s->max_delay < 0) /* Not set by the caller */
1888         s->max_delay = DEFAULT_REORDERING_DELAY;
1889
1890     /* read the whole sdp file */
1891     /* XXX: better loading */
1892     content = av_malloc(SDP_MAX_SIZE);
1893     size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
1894     if (size <= 0) {
1895         av_free(content);
1896         return AVERROR_INVALIDDATA;
1897     }
1898     content[size] ='\0';
1899
1900     err = ff_sdp_parse(s, content);
1901     av_free(content);
1902     if (err) goto fail;
1903
1904     /* open each RTP stream */
1905     for (i = 0; i < rt->nb_rtsp_streams; i++) {
1906         char namebuf[50];
1907         rtsp_st = rt->rtsp_streams[i];
1908
1909         getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
1910                     namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1911         ff_url_join(url, sizeof(url), "rtp", NULL,
1912                     namebuf, rtsp_st->sdp_port,
1913                     "?localport=%d&ttl=%d&connect=%d", rtsp_st->sdp_port,
1914                     rtsp_st->sdp_ttl,
1915                     rt->rtsp_flags & RTSP_FLAG_FILTER_SRC ? 1 : 0);
1916         if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
1917                        &s->interrupt_callback, NULL) < 0) {
1918             err = AVERROR_INVALIDDATA;
1919             goto fail;
1920         }
1921         if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1922             goto fail;
1923     }
1924     return 0;
1925 fail:
1926     ff_rtsp_close_streams(s);
1927     ff_network_close();
1928     return err;
1929 }
1930
1931 static int sdp_read_close(AVFormatContext *s)
1932 {
1933     ff_rtsp_close_streams(s);
1934     ff_network_close();
1935     return 0;
1936 }
1937
1938 static const AVClass sdp_demuxer_class = {
1939     .class_name     = "SDP demuxer",
1940     .item_name      = av_default_item_name,
1941     .option         = sdp_options,
1942     .version        = LIBAVUTIL_VERSION_INT,
1943 };
1944
1945 AVInputFormat ff_sdp_demuxer = {
1946     .name           = "sdp",
1947     .long_name      = NULL_IF_CONFIG_SMALL("SDP"),
1948     .priv_data_size = sizeof(RTSPState),
1949     .read_probe     = sdp_probe,
1950     .read_header    = sdp_read_header,
1951     .read_packet    = ff_rtsp_fetch_packet,
1952     .read_close     = sdp_read_close,
1953     .priv_class     = &sdp_demuxer_class,
1954 };
1955 #endif /* CONFIG_SDP_DEMUXER */
1956
1957 #if CONFIG_RTP_DEMUXER
1958 static int rtp_probe(AVProbeData *p)
1959 {
1960     if (av_strstart(p->filename, "rtp:", NULL))
1961         return AVPROBE_SCORE_MAX;
1962     return 0;
1963 }
1964
1965 static int rtp_read_header(AVFormatContext *s)
1966 {
1967     uint8_t recvbuf[1500];
1968     char host[500], sdp[500];
1969     int ret, port;
1970     URLContext* in = NULL;
1971     int payload_type;
1972     AVCodecContext codec = { 0 };
1973     struct sockaddr_storage addr;
1974     AVIOContext pb;
1975     socklen_t addrlen = sizeof(addr);
1976     RTSPState *rt = s->priv_data;
1977
1978     if (!ff_network_init())
1979         return AVERROR(EIO);
1980
1981     ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ,
1982                      &s->interrupt_callback, NULL);
1983     if (ret)
1984         goto fail;
1985
1986     while (1) {
1987         ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
1988         if (ret == AVERROR(EAGAIN))
1989             continue;
1990         if (ret < 0)
1991             goto fail;
1992         if (ret < 12) {
1993             av_log(s, AV_LOG_WARNING, "Received too short packet\n");
1994             continue;
1995         }
1996
1997         if ((recvbuf[0] & 0xc0) != 0x80) {
1998             av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
1999                                       "received\n");
2000             continue;
2001         }
2002
2003         if (RTP_PT_IS_RTCP(recvbuf[1]))
2004             continue;
2005
2006         payload_type = recvbuf[1] & 0x7f;
2007         break;
2008     }
2009     getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
2010     ffurl_close(in);
2011     in = NULL;
2012
2013     if (ff_rtp_get_codec_info(&codec, payload_type)) {
2014         av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
2015                                 "without an SDP file describing it\n",
2016                                  payload_type);
2017         goto fail;
2018     }
2019     if (codec.codec_type != AVMEDIA_TYPE_DATA) {
2020         av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
2021                                   "properly you need an SDP file "
2022                                   "describing it\n");
2023     }
2024
2025     av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
2026                  NULL, 0, s->filename);
2027
2028     snprintf(sdp, sizeof(sdp),
2029              "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
2030              addr.ss_family == AF_INET ? 4 : 6, host,
2031              codec.codec_type == AVMEDIA_TYPE_DATA  ? "application" :
2032              codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
2033              port, payload_type);
2034     av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
2035
2036     ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
2037     s->pb = &pb;
2038
2039     /* sdp_read_header initializes this again */
2040     ff_network_close();
2041
2042     rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;
2043
2044     ret = sdp_read_header(s);
2045     s->pb = NULL;
2046     return ret;
2047
2048 fail:
2049     if (in)
2050         ffurl_close(in);
2051     ff_network_close();
2052     return ret;
2053 }
2054
2055 static const AVClass rtp_demuxer_class = {
2056     .class_name     = "RTP demuxer",
2057     .item_name      = av_default_item_name,
2058     .option         = rtp_options,
2059     .version        = LIBAVUTIL_VERSION_INT,
2060 };
2061
2062 AVInputFormat ff_rtp_demuxer = {
2063     .name           = "rtp",
2064     .long_name      = NULL_IF_CONFIG_SMALL("RTP input format"),
2065     .priv_data_size = sizeof(RTSPState),
2066     .read_probe     = rtp_probe,
2067     .read_header    = rtp_read_header,
2068     .read_packet    = ff_rtsp_fetch_packet,
2069     .read_close     = sdp_read_close,
2070     .flags          = AVFMT_NOFILE,
2071     .priv_class     = &rtp_demuxer_class,
2072 };
2073 #endif /* CONFIG_RTP_DEMUXER */