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