Statistics
| Branch: | Revision:

ffmpeg / libavformat / rtsp.c @ 9cba6f5f

History | View | Annotate | Download (67.8 KB)

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