]> git.sesse.net Git - ffmpeg/blob - libavformat/rtsp.c
3d51ab9519a2435a268a635547171a750a1d8044
[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 /* needed by inet_aton() */
23 #define _SVID_SOURCE
24
25 #include "libavutil/base64.h"
26 #include "libavutil/avstring.h"
27 #include "libavutil/intreadwrite.h"
28 #include "avformat.h"
29
30 #include <sys/time.h>
31 #if HAVE_SYS_SELECT_H
32 #include <sys/select.h>
33 #endif
34 #include <strings.h>
35 #include "network.h"
36 #include "rtsp.h"
37
38 #include "rtpdec.h"
39 #include "rdt.h"
40 #include "rtp_asf.h"
41 #include "rtp_vorbis.h"
42
43 //#define DEBUG
44 //#define DEBUG_RTP_TCP
45
46 static int rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
47                            unsigned char **content_ptr,
48                            int return_on_interleaved_data);
49
50 #if LIBAVFORMAT_VERSION_INT < (53 << 16)
51 int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
52 #endif
53
54 #define SPACE_CHARS " \t\r\n"
55 /* we use memchr() instead of strchr() here because strchr() will return
56  * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */
57 #define redir_isspace(c) memchr(SPACE_CHARS, c, 4)
58 static void skip_spaces(const char **pp)
59 {
60     const char *p;
61     p = *pp;
62     while (redir_isspace(*p))
63         p++;
64     *pp = p;
65 }
66
67 static void get_word_until_chars(char *buf, int buf_size,
68                                  const char *sep, const char **pp)
69 {
70     const char *p;
71     char *q;
72
73     p = *pp;
74     skip_spaces(&p);
75     q = buf;
76     while (!strchr(sep, *p) && *p != '\0') {
77         if ((q - buf) < buf_size - 1)
78             *q++ = *p;
79         p++;
80     }
81     if (buf_size > 0)
82         *q = '\0';
83     *pp = p;
84 }
85
86 static void get_word_sep(char *buf, int buf_size, const char *sep,
87                          const char **pp)
88 {
89     if (**pp == '/') (*pp)++;
90     get_word_until_chars(buf, buf_size, sep, pp);
91 }
92
93 static void get_word(char *buf, int buf_size, const char **pp)
94 {
95     get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
96 }
97
98 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other
99    params>] */
100 static int sdp_parse_rtpmap(AVCodecContext *codec, RTSPStream *rtsp_st, int payload_type, const char *p)
101 {
102     char buf[256];
103     int i;
104     AVCodec *c;
105     const char *c_name;
106
107     /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
108        see if we can handle this kind of payload */
109     get_word_sep(buf, sizeof(buf), "/", &p);
110     if (payload_type >= RTP_PT_PRIVATE) {
111         RTPDynamicProtocolHandler *handler= RTPFirstDynamicPayloadHandler;
112         while(handler) {
113             if (!strcasecmp(buf, handler->enc_name) && (codec->codec_type == handler->codec_type)) {
114                 codec->codec_id = handler->codec_id;
115                 rtsp_st->dynamic_handler= handler;
116                 if(handler->open) {
117                     rtsp_st->dynamic_protocol_context= handler->open();
118                 }
119                 break;
120             }
121             handler= handler->next;
122         }
123     } else {
124         /* We are in a standard case ( from http://www.iana.org/assignments/rtp-parameters) */
125         /* search into AVRtpPayloadTypes[] */
126         codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
127     }
128
129     c = avcodec_find_decoder(codec->codec_id);
130     if (c && c->name)
131         c_name = c->name;
132     else
133         c_name = (char *)NULL;
134
135     if (c_name) {
136         get_word_sep(buf, sizeof(buf), "/", &p);
137         i = atoi(buf);
138         switch (codec->codec_type) {
139             case CODEC_TYPE_AUDIO:
140                 av_log(codec, 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 less than 22000Hz, faad upconverts to stereo and twice the
150                     //  frequency.  No problem, but the sample rate is being set here by the sdp line.  Upcoming patch forthcoming. (rdm)
151                 }
152                 av_log(codec, AV_LOG_DEBUG, " audio samplerate set to : %i\n", codec->sample_rate);
153                 av_log(codec, AV_LOG_DEBUG, " audio channels set to : %i\n", codec->channels);
154                 break;
155             case CODEC_TYPE_VIDEO:
156                 av_log(codec, AV_LOG_DEBUG, " video codec set to : %s\n", c_name);
157                 break;
158             default:
159                 break;
160         }
161         return 0;
162     }
163
164     return -1;
165 }
166
167 /* return the length and optionnaly the data */
168 static int hex_to_data(uint8_t *data, const char *p)
169 {
170     int c, len, v;
171
172     len = 0;
173     v = 1;
174     for(;;) {
175         skip_spaces(&p);
176         if (*p == '\0')
177             break;
178         c = toupper((unsigned char)*p++);
179         if (c >= '0' && c <= '9')
180             c = c - '0';
181         else if (c >= 'A' && c <= 'F')
182             c = c - 'A' + 10;
183         else
184             break;
185         v = (v << 4) | c;
186         if (v & 0x100) {
187             if (data)
188                 data[len] = v;
189             len++;
190             v = 1;
191         }
192     }
193     return len;
194 }
195
196 static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx,
197                                   char *attr, char *value)
198 {
199     switch (codec->codec_id) {
200         case CODEC_ID_MPEG4:
201         case CODEC_ID_AAC:
202             if (!strcmp(attr, "config")) {
203                 /* decode the hexa encoded parameter */
204                 int len = hex_to_data(NULL, value);
205                 if (codec->extradata)
206                     av_free(codec->extradata);
207                 codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
208                 if (!codec->extradata)
209                     return;
210                 codec->extradata_size = len;
211                 hex_to_data(codec->extradata, value);
212             }
213             break;
214         case CODEC_ID_VORBIS:
215             ff_vorbis_parse_fmtp_config(codec, ctx, attr, value);
216             break;
217         default:
218             break;
219     }
220     return;
221 }
222
223 typedef struct {
224     const char *str;
225     uint16_t type;
226     uint32_t offset;
227 } AttrNameMap;
228
229 /* All known fmtp parmeters and the corresping RTPAttrTypeEnum */
230 #define ATTR_NAME_TYPE_INT 0
231 #define ATTR_NAME_TYPE_STR 1
232 static const AttrNameMap attr_names[]=
233 {
234     {"SizeLength",       ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, sizelength)},
235     {"IndexLength",      ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, indexlength)},
236     {"IndexDeltaLength", ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, indexdeltalength)},
237     {"profile-level-id", ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, profile_level_id)},
238     {"StreamType",       ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, streamtype)},
239     {"mode",             ATTR_NAME_TYPE_STR, offsetof(RTPPayloadData, mode)},
240     {NULL, -1, -1},
241 };
242
243 /** parse the attribute line from the fmtp a line of an sdp resonse.  This is broken out as a function
244 * because it is used in rtp_h264.c, which is forthcoming.
245 */
246 int rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size)
247 {
248     skip_spaces(p);
249     if(**p) {
250         get_word_sep(attr, attr_size, "=", p);
251         if (**p == '=')
252             (*p)++;
253         get_word_sep(value, value_size, ";", p);
254         if (**p == ';')
255             (*p)++;
256         return 1;
257     }
258     return 0;
259 }
260
261 /* parse a SDP line and save stream attributes */
262 static void sdp_parse_fmtp(AVStream *st, const char *p)
263 {
264     char attr[256];
265     /* Vorbis setup headers can be up to 12KB and are sent base64
266      * encoded, giving a 12KB * (4/3) = 16KB FMTP line. */
267     char value[16384];
268     int i;
269
270     RTSPStream *rtsp_st = st->priv_data;
271     AVCodecContext *codec = st->codec;
272     RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data;
273
274     /* loop on each attribute */
275     while(rtsp_next_attr_and_value(&p, attr, sizeof(attr), value, sizeof(value)))
276     {
277         /* grab the codec extra_data from the config parameter of the fmtp line */
278         sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context,
279                               attr, value);
280         /* Looking for a known attribute */
281         for (i = 0; attr_names[i].str; ++i) {
282             if (!strcasecmp(attr, attr_names[i].str)) {
283                 if (attr_names[i].type == ATTR_NAME_TYPE_INT)
284                     *(int *)((char *)rtp_payload_data + attr_names[i].offset) = atoi(value);
285                 else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
286                     *(char **)((char *)rtp_payload_data + attr_names[i].offset) = av_strdup(value);
287             }
288         }
289     }
290 }
291
292 /** Parse a string \p in the form of Range:npt=xx-xx, and determine the start
293  *  and end time.
294  *  Used for seeking in the rtp stream.
295  */
296 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
297 {
298     char buf[256];
299
300     skip_spaces(&p);
301     if (!av_stristart(p, "npt=", &p))
302         return;
303
304     *start = AV_NOPTS_VALUE;
305     *end = AV_NOPTS_VALUE;
306
307     get_word_sep(buf, sizeof(buf), "-", &p);
308     *start = parse_date(buf, 1);
309     if (*p == '-') {
310         p++;
311         get_word_sep(buf, sizeof(buf), "-", &p);
312         *end = parse_date(buf, 1);
313     }
314 //    av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
315 //    av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
316 }
317
318 typedef struct SDPParseState {
319     /* SDP only */
320     struct in_addr default_ip;
321     int default_ttl;
322     int skip_media; ///< set if an unknown m= line occurs
323 } SDPParseState;
324
325 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
326                            int letter, const char *buf)
327 {
328     RTSPState *rt = s->priv_data;
329     char buf1[64], st_type[64];
330     const char *p;
331     enum CodecType codec_type;
332     int payload_type, i;
333     AVStream *st;
334     RTSPStream *rtsp_st;
335     struct in_addr sdp_ip;
336     int ttl;
337
338     dprintf(s, "sdp: %c='%s'\n", letter, buf);
339
340     p = buf;
341     if (s1->skip_media && letter != 'm')
342         return;
343     switch(letter) {
344     case 'c':
345         get_word(buf1, sizeof(buf1), &p);
346         if (strcmp(buf1, "IN") != 0)
347             return;
348         get_word(buf1, sizeof(buf1), &p);
349         if (strcmp(buf1, "IP4") != 0)
350             return;
351         get_word_sep(buf1, sizeof(buf1), "/", &p);
352         if (inet_aton(buf1, &sdp_ip) == 0)
353             return;
354         ttl = 16;
355         if (*p == '/') {
356             p++;
357             get_word_sep(buf1, sizeof(buf1), "/", &p);
358             ttl = atoi(buf1);
359         }
360         if (s->nb_streams == 0) {
361             s1->default_ip = sdp_ip;
362             s1->default_ttl = ttl;
363         } else {
364             st = s->streams[s->nb_streams - 1];
365             rtsp_st = st->priv_data;
366             rtsp_st->sdp_ip = sdp_ip;
367             rtsp_st->sdp_ttl = ttl;
368         }
369         break;
370     case 's':
371         av_metadata_set(&s->metadata, "title", p);
372         break;
373     case 'i':
374         if (s->nb_streams == 0) {
375             av_metadata_set(&s->metadata, "comment", p);
376             break;
377         }
378         break;
379     case 'm':
380         /* new stream */
381         s1->skip_media = 0;
382         get_word(st_type, sizeof(st_type), &p);
383         if (!strcmp(st_type, "audio")) {
384             codec_type = CODEC_TYPE_AUDIO;
385         } else if (!strcmp(st_type, "video")) {
386             codec_type = CODEC_TYPE_VIDEO;
387         } else if (!strcmp(st_type, "application")) {
388             codec_type = CODEC_TYPE_DATA;
389         } else {
390             s1->skip_media = 1;
391             return;
392         }
393         rtsp_st = av_mallocz(sizeof(RTSPStream));
394         if (!rtsp_st)
395             return;
396         rtsp_st->stream_index = -1;
397         dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
398
399         rtsp_st->sdp_ip = s1->default_ip;
400         rtsp_st->sdp_ttl = s1->default_ttl;
401
402         get_word(buf1, sizeof(buf1), &p); /* port */
403         rtsp_st->sdp_port = atoi(buf1);
404
405         get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
406
407         /* XXX: handle list of formats */
408         get_word(buf1, sizeof(buf1), &p); /* format list */
409         rtsp_st->sdp_payload_type = atoi(buf1);
410
411         if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
412             /* no corresponding stream */
413         } else {
414             st = av_new_stream(s, 0);
415             if (!st)
416                 return;
417             st->priv_data = rtsp_st;
418             rtsp_st->stream_index = st->index;
419             st->codec->codec_type = codec_type;
420             if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
421                 /* if standard payload type, we can find the codec right now */
422                 ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
423             }
424         }
425         /* put a default control url */
426         av_strlcpy(rtsp_st->control_url, s->filename, sizeof(rtsp_st->control_url));
427         break;
428     case 'a':
429         if (av_strstart(p, "control:", &p) && s->nb_streams > 0) {
430             char proto[32];
431             /* get the control url */
432             st = s->streams[s->nb_streams - 1];
433             rtsp_st = st->priv_data;
434
435             /* XXX: may need to add full url resolution */
436             url_split(proto, sizeof(proto), NULL, 0, NULL, 0, NULL, NULL, 0, p);
437             if (proto[0] == '\0') {
438                 /* relative control URL */
439                 av_strlcat(rtsp_st->control_url, "/", sizeof(rtsp_st->control_url));
440                 av_strlcat(rtsp_st->control_url, p,   sizeof(rtsp_st->control_url));
441             } else {
442                 av_strlcpy(rtsp_st->control_url, p,   sizeof(rtsp_st->control_url));
443             }
444         } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
445             /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
446             get_word(buf1, sizeof(buf1), &p);
447             payload_type = atoi(buf1);
448             st = s->streams[s->nb_streams - 1];
449             rtsp_st = st->priv_data;
450             sdp_parse_rtpmap(st->codec, rtsp_st, payload_type, p);
451         } else if (av_strstart(p, "fmtp:", &p)) {
452             /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
453             get_word(buf1, sizeof(buf1), &p);
454             payload_type = atoi(buf1);
455             for(i = 0; i < s->nb_streams;i++) {
456                 st = s->streams[i];
457                 rtsp_st = st->priv_data;
458                 if (rtsp_st->sdp_payload_type == payload_type) {
459                     if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
460                         if(!rtsp_st->dynamic_handler->parse_sdp_a_line(s, i, rtsp_st->dynamic_protocol_context, buf)) {
461                             sdp_parse_fmtp(st, p);
462                         }
463                     } else {
464                         sdp_parse_fmtp(st, p);
465                     }
466                 }
467             }
468         } else if(av_strstart(p, "framesize:", &p)) {
469             // let dynamic protocol handlers have a stab at the line.
470             get_word(buf1, sizeof(buf1), &p);
471             payload_type = atoi(buf1);
472             for(i = 0; i < s->nb_streams;i++) {
473                 st = s->streams[i];
474                 rtsp_st = st->priv_data;
475                 if (rtsp_st->sdp_payload_type == payload_type) {
476                     if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
477                         rtsp_st->dynamic_handler->parse_sdp_a_line(s, i, rtsp_st->dynamic_protocol_context, buf);
478                     }
479                 }
480             }
481         } else if(av_strstart(p, "range:", &p)) {
482             int64_t start, end;
483
484             // this is so that seeking on a streamed file can work.
485             rtsp_parse_range_npt(p, &start, &end);
486             s->start_time= start;
487             s->duration= (end==AV_NOPTS_VALUE)?AV_NOPTS_VALUE:end-start; // AV_NOPTS_VALUE means live broadcast (and can't seek)
488         } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
489             if (atoi(p) == 1)
490                 rt->transport = RTSP_TRANSPORT_RDT;
491         } else {
492             if (rt->server_type == RTSP_SERVER_WMS)
493                 ff_wms_parse_sdp_a_line(s, p);
494             if (s->nb_streams > 0) {
495                 if (rt->server_type == RTSP_SERVER_REAL)
496                     ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
497
498                 rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
499                 if (rtsp_st->dynamic_handler &&
500                     rtsp_st->dynamic_handler->parse_sdp_a_line)
501                     rtsp_st->dynamic_handler->parse_sdp_a_line(s, s->nb_streams - 1,
502                         rtsp_st->dynamic_protocol_context, buf);
503             }
504         }
505         break;
506     }
507 }
508
509 static int sdp_parse(AVFormatContext *s, const char *content)
510 {
511     const char *p;
512     int letter;
513     /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
514      * contain long SDP lines containing complete ASF Headers (several
515      * kB) or arrays of MDPR (RM stream descriptor) headers plus
516      * "rulebooks" describing their properties. Therefore, the SDP line
517      * buffer is large.
518      *
519      * The Vorbis FMTP line can be up to 16KB - see sdp_parse_fmtp. */
520     char buf[16384], *q;
521     SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
522
523     memset(s1, 0, sizeof(SDPParseState));
524     p = content;
525     for(;;) {
526         skip_spaces(&p);
527         letter = *p;
528         if (letter == '\0')
529             break;
530         p++;
531         if (*p != '=')
532             goto next_line;
533         p++;
534         /* get the content */
535         q = buf;
536         while (*p != '\n' && *p != '\r' && *p != '\0') {
537             if ((q - buf) < sizeof(buf) - 1)
538                 *q++ = *p;
539             p++;
540         }
541         *q = '\0';
542         sdp_parse_line(s, s1, letter, buf);
543     next_line:
544         while (*p != '\n' && *p != '\0')
545             p++;
546         if (*p == '\n')
547             p++;
548     }
549     return 0;
550 }
551
552 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
553                            uint8_t *buf, int buf_size)
554 {
555     RTSPState *rt = s->priv_data;
556     RTSPStream *rtsp_st;
557     fd_set rfds;
558     int fd, fd_max, n, i, ret, tcp_fd;
559     struct timeval tv;
560
561     for(;;) {
562         if (url_interrupt_cb())
563             return AVERROR(EINTR);
564         FD_ZERO(&rfds);
565         if (rt->rtsp_hd) {
566             tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
567             FD_SET(tcp_fd, &rfds);
568         } else {
569             fd_max = 0;
570             tcp_fd = -1;
571         }
572         for(i = 0; i < rt->nb_rtsp_streams; i++) {
573             rtsp_st = rt->rtsp_streams[i];
574             if (rtsp_st->rtp_handle) {
575                 /* currently, we cannot probe RTCP handle because of
576                  * blocking restrictions */
577                 fd = url_get_file_handle(rtsp_st->rtp_handle);
578                 if (fd > fd_max)
579                     fd_max = fd;
580                 FD_SET(fd, &rfds);
581             }
582         }
583         tv.tv_sec = 0;
584         tv.tv_usec = 100 * 1000;
585         n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
586         if (n > 0) {
587             for(i = 0; i < rt->nb_rtsp_streams; i++) {
588                 rtsp_st = rt->rtsp_streams[i];
589                 if (rtsp_st->rtp_handle) {
590                     fd = url_get_file_handle(rtsp_st->rtp_handle);
591                     if (FD_ISSET(fd, &rfds)) {
592                         ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
593                         if (ret > 0) {
594                             *prtsp_st = rtsp_st;
595                             return ret;
596                         }
597                     }
598                 }
599             }
600             if (FD_ISSET(tcp_fd, &rfds)) {
601                 RTSPMessageHeader reply;
602
603                 rtsp_read_reply(s, &reply, NULL, 0);
604                 /* XXX: parse message */
605                 if (rt->state != RTSP_STATE_PLAYING)
606                     return 0;
607             }
608         }
609     }
610 }
611
612 /* close and free RTSP streams */
613 static void rtsp_close_streams(RTSPState *rt)
614 {
615     int i;
616     RTSPStream *rtsp_st;
617
618     for(i=0;i<rt->nb_rtsp_streams;i++) {
619         rtsp_st = rt->rtsp_streams[i];
620         if (rtsp_st) {
621             if (rtsp_st->transport_priv) {
622                 if (rt->transport == RTSP_TRANSPORT_RDT)
623                     ff_rdt_parse_close(rtsp_st->transport_priv);
624                 else
625                     rtp_parse_close(rtsp_st->transport_priv);
626             }
627             if (rtsp_st->rtp_handle)
628                 url_close(rtsp_st->rtp_handle);
629             if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
630                 rtsp_st->dynamic_handler->close(rtsp_st->dynamic_protocol_context);
631         }
632     }
633     av_free(rt->rtsp_streams);
634     if (rt->asf_ctx) {
635         av_close_input_stream (rt->asf_ctx);
636         rt->asf_ctx = NULL;
637     }
638     av_freep(&rt->auth_b64);
639 }
640
641 static int
642 rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
643 {
644     RTSPState *rt = s->priv_data;
645     AVStream *st = NULL;
646
647     /* open the RTP context */
648     if (rtsp_st->stream_index >= 0)
649         st = s->streams[rtsp_st->stream_index];
650     if (!st)
651         s->ctx_flags |= AVFMTCTX_NOHEADER;
652
653     if (rt->transport == RTSP_TRANSPORT_RDT)
654         rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
655                                             rtsp_st->dynamic_protocol_context,
656                                             rtsp_st->dynamic_handler);
657     else
658         rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
659                                          rtsp_st->sdp_payload_type,
660                                          &rtsp_st->rtp_payload_data);
661
662     if (!rtsp_st->transport_priv) {
663          return AVERROR(ENOMEM);
664     } else if (rt->transport != RTSP_TRANSPORT_RDT) {
665         if(rtsp_st->dynamic_handler) {
666             rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
667                                            rtsp_st->dynamic_protocol_context,
668                                            rtsp_st->dynamic_handler);
669         }
670     }
671
672     return 0;
673 }
674
675 static int rtsp_probe(AVProbeData *p)
676 {
677     if (av_strstart(p->filename, "rtsp:", NULL))
678         return AVPROBE_SCORE_MAX;
679     return 0;
680 }
681
682 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
683 {
684     const char *p;
685     int v;
686
687     p = *pp;
688     skip_spaces(&p);
689     v = strtol(p, (char **)&p, 10);
690     if (*p == '-') {
691         p++;
692         *min_ptr = v;
693         v = strtol(p, (char **)&p, 10);
694         *max_ptr = v;
695     } else {
696         *min_ptr = v;
697         *max_ptr = v;
698     }
699     *pp = p;
700 }
701
702 /* XXX: only one transport specification is parsed */
703 static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
704 {
705     char transport_protocol[16];
706     char profile[16];
707     char lower_transport[16];
708     char parameter[16];
709     RTSPTransportField *th;
710     char buf[256];
711
712     reply->nb_transports = 0;
713
714     for(;;) {
715         skip_spaces(&p);
716         if (*p == '\0')
717             break;
718
719         th = &reply->transports[reply->nb_transports];
720
721         get_word_sep(transport_protocol, sizeof(transport_protocol),
722                      "/", &p);
723         if (!strcasecmp (transport_protocol, "rtp")) {
724             get_word_sep(profile, sizeof(profile), "/;,", &p);
725             lower_transport[0] = '\0';
726             /* rtp/avp/<protocol> */
727             if (*p == '/') {
728                 get_word_sep(lower_transport, sizeof(lower_transport),
729                              ";,", &p);
730             }
731             th->transport = RTSP_TRANSPORT_RTP;
732         } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
733                    !strcasecmp (transport_protocol, "x-real-rdt")) {
734             /* x-pn-tng/<protocol> */
735             get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
736             profile[0] = '\0';
737             th->transport = RTSP_TRANSPORT_RDT;
738         }
739         if (!strcasecmp(lower_transport, "TCP"))
740             th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
741         else
742             th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
743
744         if (*p == ';')
745             p++;
746         /* get each parameter */
747         while (*p != '\0' && *p != ',') {
748             get_word_sep(parameter, sizeof(parameter), "=;,", &p);
749             if (!strcmp(parameter, "port")) {
750                 if (*p == '=') {
751                     p++;
752                     rtsp_parse_range(&th->port_min, &th->port_max, &p);
753                 }
754             } else if (!strcmp(parameter, "client_port")) {
755                 if (*p == '=') {
756                     p++;
757                     rtsp_parse_range(&th->client_port_min,
758                                      &th->client_port_max, &p);
759                 }
760             } else if (!strcmp(parameter, "server_port")) {
761                 if (*p == '=') {
762                     p++;
763                     rtsp_parse_range(&th->server_port_min,
764                                      &th->server_port_max, &p);
765                 }
766             } else if (!strcmp(parameter, "interleaved")) {
767                 if (*p == '=') {
768                     p++;
769                     rtsp_parse_range(&th->interleaved_min,
770                                      &th->interleaved_max, &p);
771                 }
772             } else if (!strcmp(parameter, "multicast")) {
773                 if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
774                     th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
775             } else if (!strcmp(parameter, "ttl")) {
776                 if (*p == '=') {
777                     p++;
778                     th->ttl = strtol(p, (char **)&p, 10);
779                 }
780             } else if (!strcmp(parameter, "destination")) {
781                 struct in_addr ipaddr;
782
783                 if (*p == '=') {
784                     p++;
785                     get_word_sep(buf, sizeof(buf), ";,", &p);
786                     if (inet_aton(buf, &ipaddr))
787                         th->destination = ntohl(ipaddr.s_addr);
788                 }
789             }
790             while (*p != ';' && *p != '\0' && *p != ',')
791                 p++;
792             if (*p == ';')
793                 p++;
794         }
795         if (*p == ',')
796             p++;
797
798         reply->nb_transports++;
799     }
800 }
801
802 void rtsp_parse_line(RTSPMessageHeader *reply, const char *buf)
803 {
804     const char *p;
805
806     /* NOTE: we do case independent match for broken servers */
807     p = buf;
808     if (av_stristart(p, "Session:", &p)) {
809         int t;
810         get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
811         if (av_stristart(p, ";timeout=", &p) &&
812             (t = strtol(p, NULL, 10)) > 0) {
813             reply->timeout = t;
814         }
815     } else if (av_stristart(p, "Content-Length:", &p)) {
816         reply->content_length = strtol(p, NULL, 10);
817     } else if (av_stristart(p, "Transport:", &p)) {
818         rtsp_parse_transport(reply, p);
819     } else if (av_stristart(p, "CSeq:", &p)) {
820         reply->seq = strtol(p, NULL, 10);
821     } else if (av_stristart(p, "Range:", &p)) {
822         rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
823     } else if (av_stristart(p, "RealChallenge1:", &p)) {
824         skip_spaces(&p);
825         av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
826     } else if (av_stristart(p, "Server:", &p)) {
827         skip_spaces(&p);
828         av_strlcpy(reply->server, p, sizeof(reply->server));
829     } else if (av_stristart(p, "Notice:", &p) ||
830                av_stristart(p, "X-Notice:", &p)) {
831         reply->notice = strtol(p, NULL, 10);
832     } else if (av_stristart(p, "Location:", &p)) {
833         skip_spaces(&p);
834         av_strlcpy(reply->location, p , sizeof(reply->location));
835     }
836 }
837
838 /* skip a RTP/TCP interleaved packet */
839 static void rtsp_skip_packet(AVFormatContext *s)
840 {
841     RTSPState *rt = s->priv_data;
842     int ret, len, len1;
843     uint8_t buf[1024];
844
845     ret = url_read_complete(rt->rtsp_hd, buf, 3);
846     if (ret != 3)
847         return;
848     len = AV_RB16(buf + 1);
849
850     dprintf(s, "skipping RTP packet len=%d\n", len);
851
852     /* skip payload */
853     while (len > 0) {
854         len1 = len;
855         if (len1 > sizeof(buf))
856             len1 = sizeof(buf);
857         ret = url_read_complete(rt->rtsp_hd, buf, len1);
858         if (ret != len1)
859             return;
860         len -= len1;
861     }
862 }
863
864 /**
865  * Read a RTSP message from the server, or prepare to read data
866  * packets if we're reading data interleaved over the TCP/RTSP
867  * connection as well.
868  *
869  * @param s RTSP demuxer context
870  * @param reply pointer where the RTSP message header will be stored
871  * @param content_ptr pointer where the RTSP message body, if any, will
872  *                    be stored (length is in \p reply)
873  * @param return_on_interleaved_data whether the function may return if we
874  *                   encounter a data marker ('$'), which precedes data
875  *                   packets over interleaved TCP/RTSP connections. If this
876  *                   is set, this function will return 1 after encountering
877  *                   a '$'. If it is not set, the function will skip any
878  *                   data packets (if they are encountered), until a reply
879  *                   has been fully parsed. If no more data is available
880  *                   without parsing a reply, it will return an error.
881  *
882  * @returns 1 if a data packets is ready to be received, -1 on error,
883  *          and 0 on success.
884  */
885 static int
886 rtsp_read_reply (AVFormatContext *s, RTSPMessageHeader *reply,
887                  unsigned char **content_ptr, int return_on_interleaved_data)
888 {
889     RTSPState *rt = s->priv_data;
890     char buf[4096], buf1[1024], *q;
891     unsigned char ch;
892     const char *p;
893     int ret, content_length, line_count = 0;
894     unsigned char *content = NULL;
895
896     memset(reply, 0, sizeof(*reply));
897
898     /* parse reply (XXX: use buffers) */
899     rt->last_reply[0] = '\0';
900     for(;;) {
901         q = buf;
902         for(;;) {
903             ret = url_read_complete(rt->rtsp_hd, &ch, 1);
904 #ifdef DEBUG_RTP_TCP
905             dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
906 #endif
907             if (ret != 1)
908                 return -1;
909             if (ch == '\n')
910                 break;
911             if (ch == '$') {
912                 /* XXX: only parse it if first char on line ? */
913                 if (return_on_interleaved_data) {
914                     return 1;
915                 } else
916                 rtsp_skip_packet(s);
917             } else if (ch != '\r') {
918                 if ((q - buf) < sizeof(buf) - 1)
919                     *q++ = ch;
920             }
921         }
922         *q = '\0';
923
924         dprintf(s, "line='%s'\n", buf);
925
926         /* test if last line */
927         if (buf[0] == '\0')
928             break;
929         p = buf;
930         if (line_count == 0) {
931             /* get reply code */
932             get_word(buf1, sizeof(buf1), &p);
933             get_word(buf1, sizeof(buf1), &p);
934             reply->status_code = atoi(buf1);
935         } else {
936             rtsp_parse_line(reply, p);
937             av_strlcat(rt->last_reply, p,    sizeof(rt->last_reply));
938             av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
939         }
940         line_count++;
941     }
942
943     if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
944         av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
945
946     content_length = reply->content_length;
947     if (content_length > 0) {
948         /* leave some room for a trailing '\0' (useful for simple parsing) */
949         content = av_malloc(content_length + 1);
950         (void)url_read_complete(rt->rtsp_hd, content, content_length);
951         content[content_length] = '\0';
952     }
953     if (content_ptr)
954         *content_ptr = content;
955     else
956         av_free(content);
957
958     /* EOS */
959     if (reply->notice == 2101 /* End-of-Stream Reached */      ||
960         reply->notice == 2104 /* Start-of-Stream Reached */    ||
961         reply->notice == 2306 /* Continuous Feed Terminated */)
962         rt->state = RTSP_STATE_IDLE;
963     else if (reply->notice >= 4400 && reply->notice < 5500)
964         return AVERROR(EIO); /* data or server error */
965     else if (reply->notice == 2401 /* Ticket Expired */ ||
966              (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
967         return AVERROR(EPERM);
968
969     return 0;
970 }
971
972 static void rtsp_send_cmd_async (AVFormatContext *s,
973                           const char *cmd, RTSPMessageHeader *reply,
974                           unsigned char **content_ptr)
975 {
976     RTSPState *rt = s->priv_data;
977     char buf[4096], buf1[1024];
978
979     rt->seq++;
980     av_strlcpy(buf, cmd, sizeof(buf));
981     snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
982     av_strlcat(buf, buf1, sizeof(buf));
983     if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
984         snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
985         av_strlcat(buf, buf1, sizeof(buf));
986     }
987     if (rt->auth_b64)
988         av_strlcatf(buf, sizeof(buf),
989                     "Authorization: Basic %s\r\n",
990                     rt->auth_b64);
991     av_strlcat(buf, "\r\n", sizeof(buf));
992
993     dprintf(s, "Sending:\n%s--\n", buf);
994
995     url_write(rt->rtsp_hd, buf, strlen(buf));
996     rt->last_cmd_time = av_gettime();
997 }
998
999 static void rtsp_send_cmd (AVFormatContext *s,
1000                            const char *cmd, RTSPMessageHeader *reply,
1001                            unsigned char **content_ptr)
1002 {
1003     rtsp_send_cmd_async(s, cmd, reply, content_ptr);
1004
1005     rtsp_read_reply(s, reply, content_ptr, 0);
1006 }
1007
1008 /**
1009  * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
1010  */
1011 static int
1012 make_setup_request (AVFormatContext *s, const char *host, int port,
1013                     int lower_transport, const char *real_challenge)
1014 {
1015     RTSPState *rt = s->priv_data;
1016     int rtx, j, i, err, interleave = 0;
1017     RTSPStream *rtsp_st;
1018     RTSPMessageHeader reply1, *reply = &reply1;
1019     char cmd[2048];
1020     const char *trans_pref;
1021
1022     if (rt->transport == RTSP_TRANSPORT_RDT)
1023         trans_pref = "x-pn-tng";
1024     else
1025         trans_pref = "RTP/AVP";
1026
1027     /* default timeout: 1 minute */
1028     rt->timeout = 60;
1029
1030     /* for each stream, make the setup request */
1031     /* XXX: we assume the same server is used for the control of each
1032        RTSP stream */
1033
1034     for(j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
1035         char transport[2048];
1036
1037         /**
1038          * WMS serves all UDP data over a single connection, the RTX, which
1039          * isn't necessarily the first in the SDP but has to be the first
1040          * to be set up, else the second/third SETUP will fail with a 461.
1041          */
1042         if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1043              rt->server_type == RTSP_SERVER_WMS) {
1044             if (i == 0) {
1045                 /* rtx first */
1046                 for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1047                     int len = strlen(rt->rtsp_streams[rtx]->control_url);
1048                     if (len >= 4 &&
1049                         !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4, "/rtx"))
1050                         break;
1051                 }
1052                 if (rtx == rt->nb_rtsp_streams)
1053                     return -1; /* no RTX found */
1054                 rtsp_st = rt->rtsp_streams[rtx];
1055             } else
1056                 rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1057         } else
1058             rtsp_st = rt->rtsp_streams[i];
1059
1060         /* RTP/UDP */
1061         if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1062             char buf[256];
1063
1064             if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1065                 port = reply->transports[0].client_port_min;
1066                 goto have_port;
1067             }
1068
1069             /* first try in specified port range */
1070             if (RTSP_RTP_PORT_MIN != 0) {
1071                 while(j <= RTSP_RTP_PORT_MAX) {
1072                     snprintf(buf, sizeof(buf), "rtp://%s?localport=%d", host, j);
1073                     j += 2; /* we will use two port by rtp stream (rtp and rtcp) */
1074                     if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0) {
1075                         goto rtp_opened;
1076                     }
1077                 }
1078             }
1079
1080 /*            then try on any port
1081 **            if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
1082 **                err = AVERROR_INVALIDDATA;
1083 **                goto fail;
1084 **            }
1085 */
1086
1087         rtp_opened:
1088             port = rtp_get_local_port(rtsp_st->rtp_handle);
1089         have_port:
1090             snprintf(transport, sizeof(transport) - 1,
1091                      "%s/UDP;", trans_pref);
1092             if (rt->server_type != RTSP_SERVER_REAL)
1093                 av_strlcat(transport, "unicast;", sizeof(transport));
1094             av_strlcatf(transport, sizeof(transport),
1095                      "client_port=%d", port);
1096             if (rt->transport == RTSP_TRANSPORT_RTP &&
1097                 !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1098                 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1099         }
1100
1101         /* RTP/TCP */
1102         else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1103             /** For WMS streams, the application streams are only used for
1104              * UDP. When trying to set it up for TCP streams, the server
1105              * will return an error. Therefore, we skip those streams. */
1106             if (rt->server_type == RTSP_SERVER_WMS &&
1107                 s->streams[rtsp_st->stream_index]->codec->codec_type == CODEC_TYPE_DATA)
1108                 continue;
1109             snprintf(transport, sizeof(transport) - 1,
1110                      "%s/TCP;", trans_pref);
1111             if (rt->server_type == RTSP_SERVER_WMS)
1112                 av_strlcat(transport, "unicast;", sizeof(transport));
1113             av_strlcatf(transport, sizeof(transport),
1114                         "interleaved=%d-%d",
1115                         interleave, interleave + 1);
1116             interleave += 2;
1117         }
1118
1119         else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1120             snprintf(transport, sizeof(transport) - 1,
1121                      "%s/UDP;multicast", trans_pref);
1122         }
1123         if (rt->server_type == RTSP_SERVER_REAL ||
1124             rt->server_type == RTSP_SERVER_WMS)
1125             av_strlcat(transport, ";mode=play", sizeof(transport));
1126         snprintf(cmd, sizeof(cmd),
1127                  "SETUP %s RTSP/1.0\r\n"
1128                  "Transport: %s\r\n",
1129                  rtsp_st->control_url, transport);
1130         if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
1131             char real_res[41], real_csum[9];
1132             ff_rdt_calc_response_and_checksum(real_res, real_csum,
1133                                               real_challenge);
1134             av_strlcatf(cmd, sizeof(cmd),
1135                         "If-Match: %s\r\n"
1136                         "RealChallenge2: %s, sd=%s\r\n",
1137                         rt->session_id, real_res, real_csum);
1138         }
1139         rtsp_send_cmd(s, cmd, reply, NULL);
1140         if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1141             err = 1;
1142             goto fail;
1143         } else if (reply->status_code != RTSP_STATUS_OK ||
1144                    reply->nb_transports != 1) {
1145             err = AVERROR_INVALIDDATA;
1146             goto fail;
1147         }
1148
1149         /* XXX: same protocol for all streams is required */
1150         if (i > 0) {
1151             if (reply->transports[0].lower_transport != rt->lower_transport ||
1152                 reply->transports[0].transport != rt->transport) {
1153                 err = AVERROR_INVALIDDATA;
1154                 goto fail;
1155             }
1156         } else {
1157             rt->lower_transport = reply->transports[0].lower_transport;
1158             rt->transport = reply->transports[0].transport;
1159         }
1160
1161         /* close RTP connection if not choosen */
1162         if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
1163             (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
1164             url_close(rtsp_st->rtp_handle);
1165             rtsp_st->rtp_handle = NULL;
1166         }
1167
1168         switch(reply->transports[0].lower_transport) {
1169         case RTSP_LOWER_TRANSPORT_TCP:
1170             rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1171             rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1172             break;
1173
1174         case RTSP_LOWER_TRANSPORT_UDP:
1175             {
1176                 char url[1024];
1177
1178                 /* XXX: also use address if specified */
1179                 snprintf(url, sizeof(url), "rtp://%s:%d",
1180                          host, reply->transports[0].server_port_min);
1181                 if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1182                     rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1183                     err = AVERROR_INVALIDDATA;
1184                     goto fail;
1185                 }
1186             }
1187             break;
1188         case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1189             {
1190                 char url[1024];
1191                 struct in_addr in;
1192                 int port, ttl;
1193
1194                 if (reply->transports[0].destination) {
1195                     in.s_addr = htonl(reply->transports[0].destination);
1196                     port      = reply->transports[0].port_min;
1197                     ttl       = reply->transports[0].ttl;
1198                 } else {
1199                     in        = rtsp_st->sdp_ip;
1200                     port      = rtsp_st->sdp_port;
1201                     ttl       = rtsp_st->sdp_ttl;
1202                 }
1203                 snprintf(url, sizeof(url), "rtp://%s:%d?ttl=%d",
1204                          inet_ntoa(in), port, ttl);
1205                 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1206                     err = AVERROR_INVALIDDATA;
1207                     goto fail;
1208                 }
1209             }
1210             break;
1211         }
1212
1213         if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1214             goto fail;
1215     }
1216
1217     if (reply->timeout > 0)
1218         rt->timeout = reply->timeout;
1219
1220     if (rt->server_type == RTSP_SERVER_REAL)
1221         rt->need_subscription = 1;
1222
1223     return 0;
1224
1225 fail:
1226     for (i=0; i<rt->nb_rtsp_streams; i++) {
1227         if (rt->rtsp_streams[i]->rtp_handle) {
1228             url_close(rt->rtsp_streams[i]->rtp_handle);
1229             rt->rtsp_streams[i]->rtp_handle = NULL;
1230         }
1231     }
1232     return err;
1233 }
1234
1235 static int rtsp_read_play(AVFormatContext *s)
1236 {
1237     RTSPState *rt = s->priv_data;
1238     RTSPMessageHeader reply1, *reply = &reply1;
1239     char cmd[1024];
1240
1241     av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1242
1243     if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1244         if (rt->state == RTSP_STATE_PAUSED) {
1245             snprintf(cmd, sizeof(cmd),
1246                      "PLAY %s RTSP/1.0\r\n",
1247                      s->filename);
1248         } else {
1249             snprintf(cmd, sizeof(cmd),
1250                      "PLAY %s RTSP/1.0\r\n"
1251                      "Range: npt=%0.3f-\r\n",
1252                      s->filename,
1253                      (double)rt->seek_timestamp / AV_TIME_BASE);
1254         }
1255         rtsp_send_cmd(s, cmd, reply, NULL);
1256         if (reply->status_code != RTSP_STATUS_OK) {
1257             return -1;
1258         }
1259     }
1260     rt->state = RTSP_STATE_PLAYING;
1261     return 0;
1262 }
1263
1264 static int rtsp_read_header(AVFormatContext *s,
1265                             AVFormatParameters *ap)
1266 {
1267     RTSPState *rt = s->priv_data;
1268     char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1269     char *option_list, *option, *filename;
1270     URLContext *rtsp_hd;
1271     int port, ret, err;
1272     RTSPMessageHeader reply1, *reply = &reply1;
1273     unsigned char *content = NULL;
1274     int lower_transport_mask = 0;
1275     char real_challenge[64];
1276   redirect:
1277     /* extract hostname and port */
1278     url_split(NULL, 0, auth, sizeof(auth),
1279               host, sizeof(host), &port, path, sizeof(path), s->filename);
1280     if (*auth) {
1281         int auth_len = strlen(auth), b64_len = ((auth_len + 2) / 3) * 4 + 1;
1282
1283         if (!(rt->auth_b64 = av_malloc(b64_len)))
1284             return AVERROR(ENOMEM);
1285         if (!av_base64_encode(rt->auth_b64, b64_len, auth, auth_len)) {
1286             err = AVERROR(EINVAL);
1287             goto fail;
1288         }
1289     }
1290     if (port < 0)
1291         port = RTSP_DEFAULT_PORT;
1292
1293     /* search for options */
1294     option_list = strchr(path, '?');
1295     if (option_list) {
1296         filename = strchr(s->filename, '?');
1297         while(option_list) {
1298             /* move the option pointer */
1299             option = ++option_list;
1300             option_list = strchr(option_list, '&');
1301             if (option_list)
1302                 *option_list = 0;
1303
1304             /* handle the options */
1305             if (strcmp(option, "udp") == 0)
1306                 lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP);
1307             else if (strcmp(option, "multicast") == 0)
1308                 lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
1309             else if (strcmp(option, "tcp") == 0)
1310                 lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_TCP);
1311             else {
1312                 strcpy(++filename, option);
1313                 filename += strlen(option);
1314                 if (option_list) *filename = '&';
1315             }
1316         }
1317         *filename = 0;
1318     }
1319
1320     if (!lower_transport_mask)
1321         lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1322
1323     /* open the tcp connexion */
1324     snprintf(tcpname, sizeof(tcpname), "tcp://%s:%d", host, port);
1325     if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0) {
1326         err = AVERROR(EIO);
1327         goto fail;
1328     }
1329     rt->rtsp_hd = rtsp_hd;
1330     rt->seq = 0;
1331
1332     /* request options supported by the server; this also detects server type */
1333     for (rt->server_type = RTSP_SERVER_RTP;;) {
1334         snprintf(cmd, sizeof(cmd),
1335                  "OPTIONS %s RTSP/1.0\r\n", s->filename);
1336         if (rt->server_type == RTSP_SERVER_REAL)
1337             av_strlcat(cmd,
1338                        /**
1339                         * The following entries are required for proper
1340                         * streaming from a Realmedia server. They are
1341                         * interdependent in some way although we currently
1342                         * don't quite understand how. Values were copied
1343                         * from mplayer SVN r23589.
1344                         * @param CompanyID is a 16-byte ID in base64
1345                         * @param ClientChallenge is a 16-byte ID in hex
1346                         */
1347                        "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1348                        "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1349                        "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1350                        "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1351                        sizeof(cmd));
1352         rtsp_send_cmd(s, cmd, reply, NULL);
1353         if (reply->status_code != RTSP_STATUS_OK) {
1354             err = AVERROR_INVALIDDATA;
1355             goto fail;
1356         }
1357
1358         /* detect server type if not standard-compliant RTP */
1359         if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1360             rt->server_type = RTSP_SERVER_REAL;
1361             continue;
1362         } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1363             rt->server_type = RTSP_SERVER_WMS;
1364         } else if (rt->server_type == RTSP_SERVER_REAL) {
1365             strcpy(real_challenge, reply->real_challenge);
1366         }
1367         break;
1368     }
1369
1370     /* describe the stream */
1371     snprintf(cmd, sizeof(cmd),
1372              "DESCRIBE %s RTSP/1.0\r\n"
1373              "Accept: application/sdp\r\n",
1374              s->filename);
1375     if (rt->server_type == RTSP_SERVER_REAL) {
1376         /**
1377          * The Require: attribute is needed for proper streaming from
1378          * Realmedia servers.
1379          */
1380         av_strlcat(cmd,
1381                    "Require: com.real.retain-entity-for-setup\r\n",
1382                    sizeof(cmd));
1383     }
1384     rtsp_send_cmd(s, cmd, reply, &content);
1385     if (!content) {
1386         err = AVERROR_INVALIDDATA;
1387         goto fail;
1388     }
1389     if (reply->status_code != RTSP_STATUS_OK) {
1390         err = AVERROR_INVALIDDATA;
1391         goto fail;
1392     }
1393
1394     /* now we got the SDP description, we parse it */
1395     ret = sdp_parse(s, (const char *)content);
1396     av_freep(&content);
1397     if (ret < 0) {
1398         err = AVERROR_INVALIDDATA;
1399         goto fail;
1400     }
1401
1402     do {
1403         int lower_transport = ff_log2_tab[lower_transport_mask & ~(lower_transport_mask - 1)];
1404
1405         err = make_setup_request(s, host, port, lower_transport,
1406                                  rt->server_type == RTSP_SERVER_REAL ?
1407                                      real_challenge : NULL);
1408         if (err < 0)
1409             goto fail;
1410         lower_transport_mask &= ~(1 << lower_transport);
1411         if (lower_transport_mask == 0 && err == 1) {
1412             err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
1413             goto fail;
1414         }
1415     } while (err);
1416
1417     rt->state = RTSP_STATE_IDLE;
1418     rt->seek_timestamp = 0; /* default is to start stream at position
1419                                zero */
1420     if (ap->initial_pause) {
1421         /* do not start immediately */
1422     } else {
1423         if (rtsp_read_play(s) < 0) {
1424             err = AVERROR_INVALIDDATA;
1425             goto fail;
1426         }
1427     }
1428     return 0;
1429  fail:
1430     rtsp_close_streams(rt);
1431     av_freep(&content);
1432     url_close(rt->rtsp_hd);
1433     if (reply->status_code >=300 && reply->status_code < 400) {
1434         av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1435         av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1436                reply->status_code,
1437                s->filename);
1438         goto redirect;
1439     }
1440     return err;
1441 }
1442
1443 static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1444                            uint8_t *buf, int buf_size)
1445 {
1446     RTSPState *rt = s->priv_data;
1447     int id, len, i, ret;
1448     RTSPStream *rtsp_st;
1449
1450 #ifdef DEBUG_RTP_TCP
1451     dprintf(s, "tcp_read_packet:\n");
1452 #endif
1453  redo:
1454     for(;;) {
1455         RTSPMessageHeader reply;
1456
1457         ret = rtsp_read_reply(s, &reply, NULL, 1);
1458         if (ret == -1)
1459             return -1;
1460         if (ret == 1) /* received '$' */
1461             break;
1462         /* XXX: parse message */
1463         if (rt->state != RTSP_STATE_PLAYING)
1464             return 0;
1465     }
1466     ret = url_read_complete(rt->rtsp_hd, buf, 3);
1467     if (ret != 3)
1468         return -1;
1469     id = buf[0];
1470     len = AV_RB16(buf + 1);
1471 #ifdef DEBUG_RTP_TCP
1472     dprintf(s, "id=%d len=%d\n", id, len);
1473 #endif
1474     if (len > buf_size || len < 12)
1475         goto redo;
1476     /* get the data */
1477     ret = url_read_complete(rt->rtsp_hd, buf, len);
1478     if (ret != len)
1479         return -1;
1480     if (rt->transport == RTSP_TRANSPORT_RDT &&
1481         ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
1482         return -1;
1483
1484     /* find the matching stream */
1485     for(i = 0; i < rt->nb_rtsp_streams; i++) {
1486         rtsp_st = rt->rtsp_streams[i];
1487         if (id >= rtsp_st->interleaved_min &&
1488             id <= rtsp_st->interleaved_max)
1489             goto found;
1490     }
1491     goto redo;
1492  found:
1493     *prtsp_st = rtsp_st;
1494     return len;
1495 }
1496
1497 static int rtsp_read_packet(AVFormatContext *s,
1498                             AVPacket *pkt)
1499 {
1500     RTSPState *rt = s->priv_data;
1501     RTSPStream *rtsp_st;
1502     int ret, len;
1503     uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
1504     RTSPMessageHeader reply1, *reply = &reply1;
1505     char cmd[1024];
1506
1507     if (rt->server_type == RTSP_SERVER_REAL) {
1508         int i;
1509         enum AVDiscard cache[MAX_STREAMS];
1510
1511         for (i = 0; i < s->nb_streams; i++)
1512             cache[i] = s->streams[i]->discard;
1513
1514         if (!rt->need_subscription) {
1515             if (memcmp (cache, rt->real_setup_cache,
1516                         sizeof(enum AVDiscard) * s->nb_streams)) {
1517                 av_strlcatf(cmd, sizeof(cmd),
1518                             "SET_PARAMETER %s RTSP/1.0\r\n"
1519                             "Unsubscribe: %s\r\n",
1520                             s->filename, rt->last_subscription);
1521                 rtsp_send_cmd(s, cmd, reply, NULL);
1522                 if (reply->status_code != RTSP_STATUS_OK)
1523                     return AVERROR_INVALIDDATA;
1524                 rt->need_subscription = 1;
1525             }
1526         }
1527
1528         if (rt->need_subscription) {
1529             int r, rule_nr, first = 1;
1530
1531             memcpy(rt->real_setup_cache, cache,
1532                    sizeof(enum AVDiscard) * s->nb_streams);
1533             rt->last_subscription[0] = 0;
1534
1535             snprintf(cmd, sizeof(cmd),
1536                      "SET_PARAMETER %s RTSP/1.0\r\n"
1537                      "Subscribe: ",
1538                      s->filename);
1539             for (i = 0; i < rt->nb_rtsp_streams; i++) {
1540                 rule_nr = 0;
1541                 for (r = 0; r < s->nb_streams; r++) {
1542                     if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
1543                         if (s->streams[r]->discard != AVDISCARD_ALL) {
1544                             if (!first)
1545                                 av_strlcat(rt->last_subscription, ",",
1546                                            sizeof(rt->last_subscription));
1547                             ff_rdt_subscribe_rule(
1548                                 rt->last_subscription,
1549                                 sizeof(rt->last_subscription), i, rule_nr);
1550                             first = 0;
1551                         }
1552                         rule_nr++;
1553                     }
1554                 }
1555             }
1556             av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
1557             rtsp_send_cmd(s, cmd, reply, NULL);
1558             if (reply->status_code != RTSP_STATUS_OK)
1559                 return AVERROR_INVALIDDATA;
1560             rt->need_subscription = 0;
1561
1562             if (rt->state == RTSP_STATE_PLAYING)
1563                 rtsp_read_play (s);
1564         }
1565     }
1566
1567     /* get next frames from the same RTP packet */
1568     if (rt->cur_transport_priv) {
1569         if (rt->transport == RTSP_TRANSPORT_RDT)
1570             ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1571         else
1572             ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1573         if (ret == 0) {
1574             rt->cur_transport_priv = NULL;
1575             return 0;
1576         } else if (ret == 1) {
1577             return 0;
1578         } else {
1579             rt->cur_transport_priv = NULL;
1580         }
1581     }
1582
1583     /* read next RTP packet */
1584  redo:
1585     switch(rt->lower_transport) {
1586     default:
1587     case RTSP_LOWER_TRANSPORT_TCP:
1588         len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1589         break;
1590     case RTSP_LOWER_TRANSPORT_UDP:
1591     case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1592         len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1593         if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1594             rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1595         break;
1596     }
1597     if (len < 0)
1598         return len;
1599     if (len == 0)
1600         return AVERROR_EOF;
1601     if (rt->transport == RTSP_TRANSPORT_RDT)
1602         ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
1603     else
1604         ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
1605     if (ret < 0)
1606         goto redo;
1607     if (ret == 1) {
1608         /* more packets may follow, so we save the RTP context */
1609         rt->cur_transport_priv = rtsp_st->transport_priv;
1610     }
1611
1612     /* send dummy request to keep TCP connection alive */
1613     if ((rt->server_type == RTSP_SERVER_WMS ||
1614          rt->server_type == RTSP_SERVER_REAL) &&
1615         (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
1616         if (rt->server_type == RTSP_SERVER_WMS) {
1617             snprintf(cmd, sizeof(cmd) - 1,
1618                      "GET_PARAMETER %s RTSP/1.0\r\n",
1619                      s->filename);
1620             rtsp_send_cmd_async(s, cmd, reply, NULL);
1621         } else {
1622             rtsp_send_cmd_async(s, "OPTIONS * RTSP/1.0\r\n",
1623                                 reply, NULL);
1624         }
1625     }
1626
1627     return 0;
1628 }
1629
1630 /* pause the stream */
1631 static int rtsp_read_pause(AVFormatContext *s)
1632 {
1633     RTSPState *rt = s->priv_data;
1634     RTSPMessageHeader reply1, *reply = &reply1;
1635     char cmd[1024];
1636
1637     rt = s->priv_data;
1638
1639     if (rt->state != RTSP_STATE_PLAYING)
1640         return 0;
1641     else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1642         snprintf(cmd, sizeof(cmd),
1643                  "PAUSE %s RTSP/1.0\r\n",
1644                  s->filename);
1645         rtsp_send_cmd(s, cmd, reply, NULL);
1646         if (reply->status_code != RTSP_STATUS_OK) {
1647             return -1;
1648         }
1649     }
1650     rt->state = RTSP_STATE_PAUSED;
1651     return 0;
1652 }
1653
1654 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1655                           int64_t timestamp, int flags)
1656 {
1657     RTSPState *rt = s->priv_data;
1658
1659     rt->seek_timestamp = av_rescale_q(timestamp, s->streams[stream_index]->time_base, AV_TIME_BASE_Q);
1660     switch(rt->state) {
1661     default:
1662     case RTSP_STATE_IDLE:
1663         break;
1664     case RTSP_STATE_PLAYING:
1665         if (rtsp_read_pause(s) != 0)
1666             return -1;
1667         rt->state = RTSP_STATE_SEEKING;
1668         if (rtsp_read_play(s) != 0)
1669             return -1;
1670         break;
1671     case RTSP_STATE_PAUSED:
1672         rt->state = RTSP_STATE_IDLE;
1673         break;
1674     }
1675     return 0;
1676 }
1677
1678 static int rtsp_read_close(AVFormatContext *s)
1679 {
1680     RTSPState *rt = s->priv_data;
1681     RTSPMessageHeader reply1, *reply = &reply1;
1682     char cmd[1024];
1683
1684 #if 0
1685     /* NOTE: it is valid to flush the buffer here */
1686     if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1687         url_fclose(&rt->rtsp_gb);
1688     }
1689 #endif
1690     snprintf(cmd, sizeof(cmd),
1691              "TEARDOWN %s RTSP/1.0\r\n",
1692              s->filename);
1693     rtsp_send_cmd(s, cmd, reply, NULL);
1694
1695     rtsp_close_streams(rt);
1696     url_close(rt->rtsp_hd);
1697     return 0;
1698 }
1699
1700 #if CONFIG_RTSP_DEMUXER
1701 AVInputFormat rtsp_demuxer = {
1702     "rtsp",
1703     NULL_IF_CONFIG_SMALL("RTSP input format"),
1704     sizeof(RTSPState),
1705     rtsp_probe,
1706     rtsp_read_header,
1707     rtsp_read_packet,
1708     rtsp_read_close,
1709     rtsp_read_seek,
1710     .flags = AVFMT_NOFILE,
1711     .read_play = rtsp_read_play,
1712     .read_pause = rtsp_read_pause,
1713 };
1714 #endif
1715
1716 static int sdp_probe(AVProbeData *p1)
1717 {
1718     const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
1719
1720     /* we look for a line beginning "c=IN IP4" */
1721     while (p < p_end && *p != '\0') {
1722         if (p + sizeof("c=IN IP4") - 1 < p_end && av_strstart(p, "c=IN IP4", NULL))
1723             return AVPROBE_SCORE_MAX / 2;
1724
1725         while(p < p_end - 1 && *p != '\n') p++;
1726         if (++p >= p_end)
1727             break;
1728         if (*p == '\r')
1729             p++;
1730     }
1731     return 0;
1732 }
1733
1734 #define SDP_MAX_SIZE 8192
1735
1736 static int sdp_read_header(AVFormatContext *s,
1737                            AVFormatParameters *ap)
1738 {
1739     RTSPState *rt = s->priv_data;
1740     RTSPStream *rtsp_st;
1741     int size, i, err;
1742     char *content;
1743     char url[1024];
1744
1745     /* read the whole sdp file */
1746     /* XXX: better loading */
1747     content = av_malloc(SDP_MAX_SIZE);
1748     size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
1749     if (size <= 0) {
1750         av_free(content);
1751         return AVERROR_INVALIDDATA;
1752     }
1753     content[size] ='\0';
1754
1755     sdp_parse(s, content);
1756     av_free(content);
1757
1758     /* open each RTP stream */
1759     for(i=0;i<rt->nb_rtsp_streams;i++) {
1760         rtsp_st = rt->rtsp_streams[i];
1761
1762         snprintf(url, sizeof(url), "rtp://%s:%d?localport=%d&ttl=%d",
1763                  inet_ntoa(rtsp_st->sdp_ip),
1764                  rtsp_st->sdp_port,
1765                  rtsp_st->sdp_port,
1766                  rtsp_st->sdp_ttl);
1767         if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1768             err = AVERROR_INVALIDDATA;
1769             goto fail;
1770         }
1771         if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1772             goto fail;
1773     }
1774     return 0;
1775  fail:
1776     rtsp_close_streams(rt);
1777     return err;
1778 }
1779
1780 static int sdp_read_packet(AVFormatContext *s,
1781                             AVPacket *pkt)
1782 {
1783     return rtsp_read_packet(s, pkt);
1784 }
1785
1786 static int sdp_read_close(AVFormatContext *s)
1787 {
1788     RTSPState *rt = s->priv_data;
1789     rtsp_close_streams(rt);
1790     return 0;
1791 }
1792
1793 #if CONFIG_SDP_DEMUXER
1794 AVInputFormat sdp_demuxer = {
1795     "sdp",
1796     NULL_IF_CONFIG_SMALL("SDP"),
1797     sizeof(RTSPState),
1798     sdp_probe,
1799     sdp_read_header,
1800     sdp_read_packet,
1801     sdp_read_close,
1802 };
1803 #endif