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