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