Statistics
| Branch: | Revision:

ffmpeg / libavformat / rtsp.c @ ac11d562

History | View | Annotate | Download (64.4 KB)

1
/*
2
 * RTSP/SDP client
3
 * Copyright (c) 2002 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
#include "libavutil/base64.h"
23
#include "libavutil/avstring.h"
24
#include "libavutil/intreadwrite.h"
25
#include "avformat.h"
26

    
27
#include <sys/time.h>
28
#if HAVE_SYS_SELECT_H
29
#include <sys/select.h>
30
#endif
31
#include <strings.h>
32
#include "network.h"
33
#include "rtsp.h"
34

    
35
#include "rtpdec.h"
36
#include "rdt.h"
37
#include "rtpdec_asf.h"
38
#include "rtpdec_vorbis.h"
39

    
40
//#define DEBUG
41
//#define DEBUG_RTP_TCP
42

    
43
#if LIBAVFORMAT_VERSION_INT < (53 << 16)
44
int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
45
#endif
46

    
47
#define SPACE_CHARS " \t\r\n"
48
/* we use memchr() instead of strchr() here because strchr() will return
49
 * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */
50
#define redir_isspace(c) memchr(SPACE_CHARS, c, 4)
51
static void skip_spaces(const char **pp)
52
{
53
    const char *p;
54
    p = *pp;
55
    while (redir_isspace(*p))
56
        p++;
57
    *pp = p;
58
}
59

    
60
static void get_word_until_chars(char *buf, int buf_size,
61
                                 const char *sep, const char **pp)
62
{
63
    const char *p;
64
    char *q;
65

    
66
    p = *pp;
67
    skip_spaces(&p);
68
    q = buf;
69
    while (!strchr(sep, *p) && *p != '\0') {
70
        if ((q - buf) < buf_size - 1)
71
            *q++ = *p;
72
        p++;
73
    }
74
    if (buf_size > 0)
75
        *q = '\0';
76
    *pp = p;
77
}
78

    
79
static void get_word_sep(char *buf, int buf_size, const char *sep,
80
                         const char **pp)
81
{
82
    if (**pp == '/') (*pp)++;
83
    get_word_until_chars(buf, buf_size, sep, pp);
84
}
85

    
86
static void get_word(char *buf, int buf_size, const char **pp)
87
{
88
    get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
89
}
90

    
91
/* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
92
static int sdp_parse_rtpmap(AVFormatContext *s,
93
                            AVCodecContext *codec, RTSPStream *rtsp_st,
94
                            int payload_type, const char *p)
95
{
96
    char buf[256];
97
    int i;
98
    AVCodec *c;
99
    const char *c_name;
100

    
101
    /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
102
     * see if we can handle this kind of payload.
103
     * The space should normally not be there but some Real streams or
104
     * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
105
     * have a trailing space. */
106
    get_word_sep(buf, sizeof(buf), "/ ", &p);
107
    if (payload_type >= RTP_PT_PRIVATE) {
108
        RTPDynamicProtocolHandler *handler;
109
        for (handler = RTPFirstDynamicPayloadHandler;
110
             handler; handler = handler->next) {
111
            if (!strcasecmp(buf, handler->enc_name) &&
112
                codec->codec_type == handler->codec_type) {
113
                codec->codec_id          = handler->codec_id;
114
                rtsp_st->dynamic_handler = handler;
115
                if (handler->open)
116
                    rtsp_st->dynamic_protocol_context = handler->open();
117
                break;
118
            }
119
        }
120
    } else {
121
        /* We are in a standard case
122
         * (from http://www.iana.org/assignments/rtp-parameters). */
123
        /* search into AVRtpPayloadTypes[] */
124
        codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
125
    }
126

    
127
    c = avcodec_find_decoder(codec->codec_id);
128
    if (c && c->name)
129
        c_name = c->name;
130
    else
131
        c_name = "(null)";
132

    
133
    get_word_sep(buf, sizeof(buf), "/", &p);
134
    i = atoi(buf);
135
    switch (codec->codec_type) {
136
    case CODEC_TYPE_AUDIO:
137
        av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
138
        codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
139
        codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
140
        if (i > 0) {
141
            codec->sample_rate = i;
142
            get_word_sep(buf, sizeof(buf), "/", &p);
143
            i = atoi(buf);
144
            if (i > 0)
145
                codec->channels = i;
146
            // TODO: there is a bug here; if it is a mono stream, and
147
            // less than 22000Hz, faad upconverts to stereo and twice
148
            // the frequency.  No problem, but the sample rate is being
149
            // set here by the sdp line. Patch on its way. (rdm)
150
        }
151
        av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
152
               codec->sample_rate);
153
        av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
154
               codec->channels);
155
        break;
156
    case CODEC_TYPE_VIDEO:
157
        av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
158
        break;
159
    default:
160
        break;
161
    }
162
    return 0;
163
}
164

    
165
/* return the length and optionally the data */
166
static int hex_to_data(uint8_t *data, const char *p)
167
{
168
    int c, len, v;
169

    
170
    len = 0;
171
    v = 1;
172
    for (;;) {
173
        skip_spaces(&p);
174
        if (*p == '\0')
175
            break;
176
        c = toupper((unsigned char) *p++);
177
        if (c >= '0' && c <= '9')
178
            c = c - '0';
179
        else if (c >= 'A' && c <= 'F')
180
            c = c - 'A' + 10;
181
        else
182
            break;
183
        v = (v << 4) | c;
184
        if (v & 0x100) {
185
            if (data)
186
                data[len] = v;
187
            len++;
188
            v = 1;
189
        }
190
    }
191
    return len;
192
}
193

    
194
static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx,
195
                                  char *attr, char *value)
196
{
197
    switch (codec->codec_id) {
198
    case CODEC_ID_MPEG4:
199
    case CODEC_ID_AAC:
200
        if (!strcmp(attr, "config")) {
201
            /* decode the hexa encoded parameter */
202
            int len = hex_to_data(NULL, value);
203
            if (codec->extradata)
204
                av_free(codec->extradata);
205
            codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
206
            if (!codec->extradata)
207
                return;
208
            codec->extradata_size = len;
209
            hex_to_data(codec->extradata, value);
210
        }
211
        break;
212
    case CODEC_ID_VORBIS:
213
        ff_vorbis_parse_fmtp_config(codec, ctx, attr, value);
214
        break;
215
    default:
216
        break;
217
    }
218
    return;
219
}
220

    
221
typedef struct {
222
    const char *str;
223
    uint16_t    type;
224
    uint32_t    offset;
225
} AttrNameMap;
226

    
227
/* All known fmtp parmeters and the corresping RTPAttrTypeEnum */
228
#define ATTR_NAME_TYPE_INT 0
229
#define ATTR_NAME_TYPE_STR 1
230
static const AttrNameMap attr_names[]=
231
{
232
    { "SizeLength",       ATTR_NAME_TYPE_INT,
233
      offsetof(RTPPayloadData, sizelength) },
234
    { "IndexLength",      ATTR_NAME_TYPE_INT,
235
      offsetof(RTPPayloadData, indexlength) },
236
    { "IndexDeltaLength", ATTR_NAME_TYPE_INT,
237
      offsetof(RTPPayloadData, indexdeltalength) },
238
    { "profile-level-id", ATTR_NAME_TYPE_INT,
239
      offsetof(RTPPayloadData, profile_level_id) },
240
    { "StreamType",       ATTR_NAME_TYPE_INT,
241
      offsetof(RTPPayloadData, streamtype) },
242
    { "mode",             ATTR_NAME_TYPE_STR,
243
      offsetof(RTPPayloadData, mode) },
244
    { NULL, -1, -1 },
245
};
246

    
247
/* parse the attribute line from the fmtp a line of an sdp resonse. This
248
 * is broken out as a function because it is used in rtp_h264.c, which is
249
 * forthcoming. */
250
int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
251
                                char *value, int value_size)
252
{
253
    skip_spaces(p);
254
    if (**p) {
255
        get_word_sep(attr, attr_size, "=", p);
256
        if (**p == '=')
257
            (*p)++;
258
        get_word_sep(value, value_size, ";", p);
259
        if (**p == ';')
260
            (*p)++;
261
        return 1;
262
    }
263
    return 0;
264
}
265

    
266
/* parse a SDP line and save stream attributes */
267
static void sdp_parse_fmtp(AVStream *st, const char *p)
268
{
269
    char attr[256];
270
    /* Vorbis setup headers can be up to 12KB and are sent base64
271
     * encoded, giving a 12KB * (4/3) = 16KB FMTP line. */
272
    char value[16384];
273
    int i;
274
    RTSPStream *rtsp_st = st->priv_data;
275
    AVCodecContext *codec = st->codec;
276
    RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data;
277

    
278
    /* loop on each attribute */
279
    while (ff_rtsp_next_attr_and_value(&p, attr, sizeof(attr),
280
                                       value, sizeof(value))) {
281
        /* grab the codec extra_data from the config parameter of the fmtp
282
         * line */
283
        sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context,
284
                              attr, value);
285
        /* Looking for a known attribute */
286
        for (i = 0; attr_names[i].str; ++i) {
287
            if (!strcasecmp(attr, attr_names[i].str)) {
288
                if (attr_names[i].type == ATTR_NAME_TYPE_INT) {
289
                    *(int *)((char *)rtp_payload_data +
290
                        attr_names[i].offset) = atoi(value);
291
                } else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
292
                    *(char **)((char *)rtp_payload_data +
293
                        attr_names[i].offset) = av_strdup(value);
294
            }
295
        }
296
    }
297
}
298

    
299
/** Parse a string p in the form of Range:npt=xx-xx, and determine the start
300
 *  and end time.
301
 *  Used for seeking in the rtp stream.
302
 */
303
static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
304
{
305
    char buf[256];
306

    
307
    skip_spaces(&p);
308
    if (!av_stristart(p, "npt=", &p))
309
        return;
310

    
311
    *start = AV_NOPTS_VALUE;
312
    *end = AV_NOPTS_VALUE;
313

    
314
    get_word_sep(buf, sizeof(buf), "-", &p);
315
    *start = parse_date(buf, 1);
316
    if (*p == '-') {
317
        p++;
318
        get_word_sep(buf, sizeof(buf), "-", &p);
319
        *end = parse_date(buf, 1);
320
    }
321
//    av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
322
//    av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
323
}
324

    
325
typedef struct SDPParseState {
326
    /* SDP only */
327
    struct in_addr default_ip;
328
    int            default_ttl;
329
    int            skip_media;  ///< set if an unknown m= line occurs
330
} SDPParseState;
331

    
332
static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
333
                           int letter, const char *buf)
334
{
335
    RTSPState *rt = s->priv_data;
336
    char buf1[64], st_type[64];
337
    const char *p;
338
    enum CodecType codec_type;
339
    int payload_type, i;
340
    AVStream *st;
341
    RTSPStream *rtsp_st;
342
    struct in_addr sdp_ip;
343
    int ttl;
344

    
345
    dprintf(s, "sdp: %c='%s'\n", letter, buf);
346

    
347
    p = buf;
348
    if (s1->skip_media && letter != 'm')
349
        return;
350
    switch (letter) {
351
    case 'c':
352
        get_word(buf1, sizeof(buf1), &p);
353
        if (strcmp(buf1, "IN") != 0)
354
            return;
355
        get_word(buf1, sizeof(buf1), &p);
356
        if (strcmp(buf1, "IP4") != 0)
357
            return;
358
        get_word_sep(buf1, sizeof(buf1), "/", &p);
359
        if (ff_inet_aton(buf1, &sdp_ip) == 0)
360
            return;
361
        ttl = 16;
362
        if (*p == '/') {
363
            p++;
364
            get_word_sep(buf1, sizeof(buf1), "/", &p);
365
            ttl = atoi(buf1);
366
        }
367
        if (s->nb_streams == 0) {
368
            s1->default_ip = sdp_ip;
369
            s1->default_ttl = ttl;
370
        } else {
371
            st = s->streams[s->nb_streams - 1];
372
            rtsp_st = st->priv_data;
373
            rtsp_st->sdp_ip = sdp_ip;
374
            rtsp_st->sdp_ttl = ttl;
375
        }
376
        break;
377
    case 's':
378
        av_metadata_set(&s->metadata, "title", p);
379
        break;
380
    case 'i':
381
        if (s->nb_streams == 0) {
382
            av_metadata_set(&s->metadata, "comment", p);
383
            break;
384
        }
385
        break;
386
    case 'm':
387
        /* new stream */
388
        s1->skip_media = 0;
389
        get_word(st_type, sizeof(st_type), &p);
390
        if (!strcmp(st_type, "audio")) {
391
            codec_type = CODEC_TYPE_AUDIO;
392
        } else if (!strcmp(st_type, "video")) {
393
            codec_type = CODEC_TYPE_VIDEO;
394
        } else if (!strcmp(st_type, "application")) {
395
            codec_type = CODEC_TYPE_DATA;
396
        } else {
397
            s1->skip_media = 1;
398
            return;
399
        }
400
        rtsp_st = av_mallocz(sizeof(RTSPStream));
401
        if (!rtsp_st)
402
            return;
403
        rtsp_st->stream_index = -1;
404
        dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
405

    
406
        rtsp_st->sdp_ip = s1->default_ip;
407
        rtsp_st->sdp_ttl = s1->default_ttl;
408

    
409
        get_word(buf1, sizeof(buf1), &p); /* port */
410
        rtsp_st->sdp_port = atoi(buf1);
411

    
412
        get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
413

    
414
        /* XXX: handle list of formats */
415
        get_word(buf1, sizeof(buf1), &p); /* format list */
416
        rtsp_st->sdp_payload_type = atoi(buf1);
417

    
418
        if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
419
            /* no corresponding stream */
420
        } else {
421
            st = av_new_stream(s, 0);
422
            if (!st)
423
                return;
424
            st->priv_data = rtsp_st;
425
            rtsp_st->stream_index = st->index;
426
            st->codec->codec_type = codec_type;
427
            if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
428
                /* if standard payload type, we can find the codec right now */
429
                ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
430
            }
431
        }
432
        /* put a default control url */
433
        av_strlcpy(rtsp_st->control_url, rt->control_uri,
434
                   sizeof(rtsp_st->control_url));
435
        break;
436
    case 'a':
437
        if (av_strstart(p, "control:", &p)) {
438
            if (s->nb_streams == 0) {
439
                if (!strncmp(p, "rtsp://", 7))
440
                    av_strlcpy(rt->control_uri, p,
441
                               sizeof(rt->control_uri));
442
            } else {
443
            char proto[32];
444
            /* get the control url */
445
            st = s->streams[s->nb_streams - 1];
446
            rtsp_st = st->priv_data;
447

    
448
            /* XXX: may need to add full url resolution */
449
            url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
450
                      NULL, NULL, 0, p);
451
            if (proto[0] == '\0') {
452
                /* relative control URL */
453
                if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
454
                av_strlcat(rtsp_st->control_url, "/",
455
                           sizeof(rtsp_st->control_url));
456
                av_strlcat(rtsp_st->control_url, p,
457
                           sizeof(rtsp_st->control_url));
458
            } else
459
                av_strlcpy(rtsp_st->control_url, p,
460
                           sizeof(rtsp_st->control_url));
461
            }
462
        } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
463
            /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
464
            get_word(buf1, sizeof(buf1), &p);
465
            payload_type = atoi(buf1);
466
            st = s->streams[s->nb_streams - 1];
467
            rtsp_st = st->priv_data;
468
            sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
469
        } else if (av_strstart(p, "fmtp:", &p)) {
470
            /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
471
            get_word(buf1, sizeof(buf1), &p);
472
            payload_type = atoi(buf1);
473
            for (i = 0; i < s->nb_streams; i++) {
474
                st      = s->streams[i];
475
                rtsp_st = st->priv_data;
476
                if (rtsp_st->sdp_payload_type == payload_type) {
477
                    if (!(rtsp_st->dynamic_handler &&
478
                          rtsp_st->dynamic_handler->parse_sdp_a_line &&
479
                          rtsp_st->dynamic_handler->parse_sdp_a_line(s,
480
                              i, rtsp_st->dynamic_protocol_context, buf)))
481
                        sdp_parse_fmtp(st, p);
482
                }
483
            }
484
        } else if (av_strstart(p, "framesize:", &p)) {
485
            // let dynamic protocol handlers have a stab at the line.
486
            get_word(buf1, sizeof(buf1), &p);
487
            payload_type = atoi(buf1);
488
            for (i = 0; i < s->nb_streams; i++) {
489
                st      = s->streams[i];
490
                rtsp_st = st->priv_data;
491
                if (rtsp_st->sdp_payload_type == payload_type &&
492
                    rtsp_st->dynamic_handler &&
493
                    rtsp_st->dynamic_handler->parse_sdp_a_line)
494
                    rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
495
                        rtsp_st->dynamic_protocol_context, buf);
496
            }
497
        } else if (av_strstart(p, "range:", &p)) {
498
            int64_t start, end;
499

    
500
            // this is so that seeking on a streamed file can work.
501
            rtsp_parse_range_npt(p, &start, &end);
502
            s->start_time = start;
503
            /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
504
            s->duration   = (end == AV_NOPTS_VALUE) ?
505
                            AV_NOPTS_VALUE : end - start;
506
        } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
507
            if (atoi(p) == 1)
508
                rt->transport = RTSP_TRANSPORT_RDT;
509
        } else {
510
            if (rt->server_type == RTSP_SERVER_WMS)
511
                ff_wms_parse_sdp_a_line(s, p);
512
            if (s->nb_streams > 0) {
513
                if (rt->server_type == RTSP_SERVER_REAL)
514
                    ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
515

    
516
                rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
517
                if (rtsp_st->dynamic_handler &&
518
                    rtsp_st->dynamic_handler->parse_sdp_a_line)
519
                    rtsp_st->dynamic_handler->parse_sdp_a_line(s,
520
                        s->nb_streams - 1,
521
                        rtsp_st->dynamic_protocol_context, buf);
522
            }
523
        }
524
        break;
525
    }
526
}
527

    
528
static int sdp_parse(AVFormatContext *s, const char *content)
529
{
530
    const char *p;
531
    int letter;
532
    /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
533
     * contain long SDP lines containing complete ASF Headers (several
534
     * kB) or arrays of MDPR (RM stream descriptor) headers plus
535
     * "rulebooks" describing their properties. Therefore, the SDP line
536
     * buffer is large.
537
     *
538
     * The Vorbis FMTP line can be up to 16KB - see sdp_parse_fmtp. */
539
    char buf[16384], *q;
540
    SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
541

    
542
    memset(s1, 0, sizeof(SDPParseState));
543
    p = content;
544
    for (;;) {
545
        skip_spaces(&p);
546
        letter = *p;
547
        if (letter == '\0')
548
            break;
549
        p++;
550
        if (*p != '=')
551
            goto next_line;
552
        p++;
553
        /* get the content */
554
        q = buf;
555
        while (*p != '\n' && *p != '\r' && *p != '\0') {
556
            if ((q - buf) < sizeof(buf) - 1)
557
                *q++ = *p;
558
            p++;
559
        }
560
        *q = '\0';
561
        sdp_parse_line(s, s1, letter, buf);
562
    next_line:
563
        while (*p != '\n' && *p != '\0')
564
            p++;
565
        if (*p == '\n')
566
            p++;
567
    }
568
    return 0;
569
}
570

    
571
/* close and free RTSP streams */
572
void ff_rtsp_close_streams(AVFormatContext *s)
573
{
574
    RTSPState *rt = s->priv_data;
575
    int i;
576
    RTSPStream *rtsp_st;
577

    
578
    for (i = 0; i < rt->nb_rtsp_streams; i++) {
579
        rtsp_st = rt->rtsp_streams[i];
580
        if (rtsp_st) {
581
            if (rtsp_st->transport_priv) {
582
                if (s->oformat) {
583
                    AVFormatContext *rtpctx = rtsp_st->transport_priv;
584
                    av_write_trailer(rtpctx);
585
                    url_fclose(rtpctx->pb);
586
                    av_metadata_free(&rtpctx->streams[0]->metadata);
587
                    av_metadata_free(&rtpctx->metadata);
588
                    av_free(rtpctx->streams[0]);
589
                    av_free(rtpctx);
590
                } else if (rt->transport == RTSP_TRANSPORT_RDT)
591
                    ff_rdt_parse_close(rtsp_st->transport_priv);
592
                else
593
                    rtp_parse_close(rtsp_st->transport_priv);
594
            }
595
            if (rtsp_st->rtp_handle)
596
                url_close(rtsp_st->rtp_handle);
597
            if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
598
                rtsp_st->dynamic_handler->close(
599
                    rtsp_st->dynamic_protocol_context);
600
        }
601
    }
602
    av_free(rt->rtsp_streams);
603
    if (rt->asf_ctx) {
604
        av_close_input_stream (rt->asf_ctx);
605
        rt->asf_ctx = NULL;
606
    }
607
    av_freep(&rt->auth_b64);
608
}
609

    
610
static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st, URLContext *handle) {
611
    AVFormatContext *rtpctx;
612
    int ret;
613
    AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
614

    
615
    if (!rtp_format)
616
        return NULL;
617

    
618
    /* Allocate an AVFormatContext for each output stream */
619
    rtpctx = avformat_alloc_context();
620
    if (!rtpctx)
621
        return NULL;
622

    
623
    rtpctx->oformat = rtp_format;
624
    if (!av_new_stream(rtpctx, 0)) {
625
        av_free(rtpctx);
626
        return NULL;
627
    }
628
    /* Copy the max delay setting; the rtp muxer reads this. */
629
    rtpctx->max_delay = s->max_delay;
630
    /* Copy other stream parameters. */
631
    rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
632

    
633
    /* Remove the local codec, link to the original codec
634
     * context instead, to give the rtp muxer access to
635
     * codec parameters. */
636
    av_free(rtpctx->streams[0]->codec);
637
    rtpctx->streams[0]->codec = st->codec;
638

    
639
    url_fdopen(&rtpctx->pb, handle);
640
    ret = av_write_header(rtpctx);
641

    
642
    if (ret) {
643
        url_fclose(rtpctx->pb);
644
        av_free(rtpctx->streams[0]);
645
        av_free(rtpctx);
646
        return NULL;
647
    }
648

    
649
    /* Copy the RTP AVStream timebase back to the original AVStream */
650
    st->time_base = rtpctx->streams[0]->time_base;
651
    return rtpctx;
652
}
653

    
654
static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
655
{
656
    RTSPState *rt = s->priv_data;
657
    AVStream *st = NULL;
658

    
659
    /* open the RTP context */
660
    if (rtsp_st->stream_index >= 0)
661
        st = s->streams[rtsp_st->stream_index];
662
    if (!st)
663
        s->ctx_flags |= AVFMTCTX_NOHEADER;
664

    
665
    if (s->oformat) {
666
        rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
667
        /* Ownage of rtp_handle is passed to the rtp mux context */
668
        rtsp_st->rtp_handle = NULL;
669
    } else if (rt->transport == RTSP_TRANSPORT_RDT)
670
        rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
671
                                            rtsp_st->dynamic_protocol_context,
672
                                            rtsp_st->dynamic_handler);
673
    else
674
        rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
675
                                         rtsp_st->sdp_payload_type,
676
                                         &rtsp_st->rtp_payload_data);
677

    
678
    if (!rtsp_st->transport_priv) {
679
         return AVERROR(ENOMEM);
680
    } else if (rt->transport != RTSP_TRANSPORT_RDT) {
681
        if (rtsp_st->dynamic_handler) {
682
            rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
683
                                           rtsp_st->dynamic_protocol_context,
684
                                           rtsp_st->dynamic_handler);
685
        }
686
    }
687

    
688
    return 0;
689
}
690

    
691
#if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
692
static int rtsp_probe(AVProbeData *p)
693
{
694
    if (av_strstart(p->filename, "rtsp:", NULL))
695
        return AVPROBE_SCORE_MAX;
696
    return 0;
697
}
698

    
699
static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
700
{
701
    const char *p;
702
    int v;
703

    
704
    p = *pp;
705
    skip_spaces(&p);
706
    v = strtol(p, (char **)&p, 10);
707
    if (*p == '-') {
708
        p++;
709
        *min_ptr = v;
710
        v = strtol(p, (char **)&p, 10);
711
        *max_ptr = v;
712
    } else {
713
        *min_ptr = v;
714
        *max_ptr = v;
715
    }
716
    *pp = p;
717
}
718

    
719
/* XXX: only one transport specification is parsed */
720
static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
721
{
722
    char transport_protocol[16];
723
    char profile[16];
724
    char lower_transport[16];
725
    char parameter[16];
726
    RTSPTransportField *th;
727
    char buf[256];
728

    
729
    reply->nb_transports = 0;
730

    
731
    for (;;) {
732
        skip_spaces(&p);
733
        if (*p == '\0')
734
            break;
735

    
736
        th = &reply->transports[reply->nb_transports];
737

    
738
        get_word_sep(transport_protocol, sizeof(transport_protocol),
739
                     "/", &p);
740
        if (!strcasecmp (transport_protocol, "rtp")) {
741
            get_word_sep(profile, sizeof(profile), "/;,", &p);
742
            lower_transport[0] = '\0';
743
            /* rtp/avp/<protocol> */
744
            if (*p == '/') {
745
                get_word_sep(lower_transport, sizeof(lower_transport),
746
                             ";,", &p);
747
            }
748
            th->transport = RTSP_TRANSPORT_RTP;
749
        } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
750
                   !strcasecmp (transport_protocol, "x-real-rdt")) {
751
            /* x-pn-tng/<protocol> */
752
            get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
753
            profile[0] = '\0';
754
            th->transport = RTSP_TRANSPORT_RDT;
755
        }
756
        if (!strcasecmp(lower_transport, "TCP"))
757
            th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
758
        else
759
            th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
760

    
761
        if (*p == ';')
762
            p++;
763
        /* get each parameter */
764
        while (*p != '\0' && *p != ',') {
765
            get_word_sep(parameter, sizeof(parameter), "=;,", &p);
766
            if (!strcmp(parameter, "port")) {
767
                if (*p == '=') {
768
                    p++;
769
                    rtsp_parse_range(&th->port_min, &th->port_max, &p);
770
                }
771
            } else if (!strcmp(parameter, "client_port")) {
772
                if (*p == '=') {
773
                    p++;
774
                    rtsp_parse_range(&th->client_port_min,
775
                                     &th->client_port_max, &p);
776
                }
777
            } else if (!strcmp(parameter, "server_port")) {
778
                if (*p == '=') {
779
                    p++;
780
                    rtsp_parse_range(&th->server_port_min,
781
                                     &th->server_port_max, &p);
782
                }
783
            } else if (!strcmp(parameter, "interleaved")) {
784
                if (*p == '=') {
785
                    p++;
786
                    rtsp_parse_range(&th->interleaved_min,
787
                                     &th->interleaved_max, &p);
788
                }
789
            } else if (!strcmp(parameter, "multicast")) {
790
                if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
791
                    th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
792
            } else if (!strcmp(parameter, "ttl")) {
793
                if (*p == '=') {
794
                    p++;
795
                    th->ttl = strtol(p, (char **)&p, 10);
796
                }
797
            } else if (!strcmp(parameter, "destination")) {
798
                struct in_addr ipaddr;
799

    
800
                if (*p == '=') {
801
                    p++;
802
                    get_word_sep(buf, sizeof(buf), ";,", &p);
803
                    if (ff_inet_aton(buf, &ipaddr))
804
                        th->destination = ntohl(ipaddr.s_addr);
805
                }
806
            }
807
            while (*p != ';' && *p != '\0' && *p != ',')
808
                p++;
809
            if (*p == ';')
810
                p++;
811
        }
812
        if (*p == ',')
813
            p++;
814

    
815
        reply->nb_transports++;
816
    }
817
}
818

    
819
void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf)
820
{
821
    const char *p;
822

    
823
    /* NOTE: we do case independent match for broken servers */
824
    p = buf;
825
    if (av_stristart(p, "Session:", &p)) {
826
        int t;
827
        get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
828
        if (av_stristart(p, ";timeout=", &p) &&
829
            (t = strtol(p, NULL, 10)) > 0) {
830
            reply->timeout = t;
831
        }
832
    } else if (av_stristart(p, "Content-Length:", &p)) {
833
        reply->content_length = strtol(p, NULL, 10);
834
    } else if (av_stristart(p, "Transport:", &p)) {
835
        rtsp_parse_transport(reply, p);
836
    } else if (av_stristart(p, "CSeq:", &p)) {
837
        reply->seq = strtol(p, NULL, 10);
838
    } else if (av_stristart(p, "Range:", &p)) {
839
        rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
840
    } else if (av_stristart(p, "RealChallenge1:", &p)) {
841
        skip_spaces(&p);
842
        av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
843
    } else if (av_stristart(p, "Server:", &p)) {
844
        skip_spaces(&p);
845
        av_strlcpy(reply->server, p, sizeof(reply->server));
846
    } else if (av_stristart(p, "Notice:", &p) ||
847
               av_stristart(p, "X-Notice:", &p)) {
848
        reply->notice = strtol(p, NULL, 10);
849
    } else if (av_stristart(p, "Location:", &p)) {
850
        skip_spaces(&p);
851
        av_strlcpy(reply->location, p , sizeof(reply->location));
852
    }
853
}
854

    
855
/* skip a RTP/TCP interleaved packet */
856
static void rtsp_skip_packet(AVFormatContext *s)
857
{
858
    RTSPState *rt = s->priv_data;
859
    int ret, len, len1;
860
    uint8_t buf[1024];
861

    
862
    ret = url_read_complete(rt->rtsp_hd, buf, 3);
863
    if (ret != 3)
864
        return;
865
    len = AV_RB16(buf + 1);
866

    
867
    dprintf(s, "skipping RTP packet len=%d\n", len);
868

    
869
    /* skip payload */
870
    while (len > 0) {
871
        len1 = len;
872
        if (len1 > sizeof(buf))
873
            len1 = sizeof(buf);
874
        ret = url_read_complete(rt->rtsp_hd, buf, len1);
875
        if (ret != len1)
876
            return;
877
        len -= len1;
878
    }
879
}
880

    
881
int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
882
                       unsigned char **content_ptr,
883
                       int return_on_interleaved_data)
884
{
885
    RTSPState *rt = s->priv_data;
886
    char buf[4096], buf1[1024], *q;
887
    unsigned char ch;
888
    const char *p;
889
    int ret, content_length, line_count = 0;
890
    unsigned char *content = NULL;
891

    
892
    memset(reply, 0, sizeof(*reply));
893

    
894
    /* parse reply (XXX: use buffers) */
895
    rt->last_reply[0] = '\0';
896
    for (;;) {
897
        q = buf;
898
        for (;;) {
899
            ret = url_read_complete(rt->rtsp_hd, &ch, 1);
900
#ifdef DEBUG_RTP_TCP
901
            dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
902
#endif
903
            if (ret != 1)
904
                return -1;
905
            if (ch == '\n')
906
                break;
907
            if (ch == '$') {
908
                /* XXX: only parse it if first char on line ? */
909
                if (return_on_interleaved_data) {
910
                    return 1;
911
                } else
912
                rtsp_skip_packet(s);
913
            } else if (ch != '\r') {
914
                if ((q - buf) < sizeof(buf) - 1)
915
                    *q++ = ch;
916
            }
917
        }
918
        *q = '\0';
919

    
920
        dprintf(s, "line='%s'\n", buf);
921

    
922
        /* test if last line */
923
        if (buf[0] == '\0')
924
            break;
925
        p = buf;
926
        if (line_count == 0) {
927
            /* get reply code */
928
            get_word(buf1, sizeof(buf1), &p);
929
            get_word(buf1, sizeof(buf1), &p);
930
            reply->status_code = atoi(buf1);
931
        } else {
932
            ff_rtsp_parse_line(reply, p);
933
            av_strlcat(rt->last_reply, p,    sizeof(rt->last_reply));
934
            av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
935
        }
936
        line_count++;
937
    }
938

    
939
    if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
940
        av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
941

    
942
    content_length = reply->content_length;
943
    if (content_length > 0) {
944
        /* leave some room for a trailing '\0' (useful for simple parsing) */
945
        content = av_malloc(content_length + 1);
946
        (void)url_read_complete(rt->rtsp_hd, content, content_length);
947
        content[content_length] = '\0';
948
    }
949
    if (content_ptr)
950
        *content_ptr = content;
951
    else
952
        av_free(content);
953

    
954
    /* EOS */
955
    if (reply->notice == 2101 /* End-of-Stream Reached */      ||
956
        reply->notice == 2104 /* Start-of-Stream Reached */    ||
957
        reply->notice == 2306 /* Continuous Feed Terminated */) {
958
        rt->state = RTSP_STATE_IDLE;
959
    } else if (reply->notice >= 4400 && reply->notice < 5500) {
960
        return AVERROR(EIO); /* data or server error */
961
    } else if (reply->notice == 2401 /* Ticket Expired */ ||
962
             (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
963
        return AVERROR(EPERM);
964

    
965
    return 0;
966
}
967

    
968
void ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
969
                                         const char *cmd,
970
                                         const unsigned char *send_content,
971
                                         int send_content_length)
972
{
973
    RTSPState *rt = s->priv_data;
974
    char buf[4096], buf1[1024];
975

    
976
    rt->seq++;
977
    av_strlcpy(buf, cmd, sizeof(buf));
978
    snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
979
    av_strlcat(buf, buf1, sizeof(buf));
980
    if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
981
        snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
982
        av_strlcat(buf, buf1, sizeof(buf));
983
    }
984
    if (rt->auth_b64)
985
        av_strlcatf(buf, sizeof(buf),
986
                    "Authorization: Basic %s\r\n",
987
                    rt->auth_b64);
988
    if (send_content_length > 0 && send_content)
989
        av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
990
    av_strlcat(buf, "\r\n", sizeof(buf));
991

    
992
    dprintf(s, "Sending:\n%s--\n", buf);
993

    
994
    url_write(rt->rtsp_hd, buf, strlen(buf));
995
    if (send_content_length > 0 && send_content)
996
        url_write(rt->rtsp_hd, send_content, send_content_length);
997
    rt->last_cmd_time = av_gettime();
998
}
999

    
1000
void ff_rtsp_send_cmd_async(AVFormatContext *s, const char *cmd)
1001
{
1002
    ff_rtsp_send_cmd_with_content_async(s, cmd, NULL, 0);
1003
}
1004

    
1005
void ff_rtsp_send_cmd(AVFormatContext *s,
1006
                      const char *cmd, RTSPMessageHeader *reply,
1007
                      unsigned char **content_ptr)
1008
{
1009
    ff_rtsp_send_cmd_async(s, cmd);
1010

    
1011
    ff_rtsp_read_reply(s, reply, content_ptr, 0);
1012
}
1013

    
1014
void ff_rtsp_send_cmd_with_content(AVFormatContext *s,
1015
                                const char *cmd,
1016
                                RTSPMessageHeader *reply,
1017
                                unsigned char **content_ptr,
1018
                                const unsigned char *send_content,
1019
                                int send_content_length)
1020
{
1021
    ff_rtsp_send_cmd_with_content_async(s, cmd, send_content, send_content_length);
1022

    
1023
    ff_rtsp_read_reply(s, reply, content_ptr, 0);
1024
}
1025

    
1026
/**
1027
 * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
1028
 */
1029
static int make_setup_request(AVFormatContext *s, const char *host, int port,
1030
                              int lower_transport, const char *real_challenge)
1031
{
1032
    RTSPState *rt = s->priv_data;
1033
    int rtx, j, i, err, interleave = 0;
1034
    RTSPStream *rtsp_st;
1035
    RTSPMessageHeader reply1, *reply = &reply1;
1036
    char cmd[2048];
1037
    const char *trans_pref;
1038

    
1039
    if (rt->transport == RTSP_TRANSPORT_RDT)
1040
        trans_pref = "x-pn-tng";
1041
    else
1042
        trans_pref = "RTP/AVP";
1043

    
1044
    /* default timeout: 1 minute */
1045
    rt->timeout = 60;
1046

    
1047
    /* for each stream, make the setup request */
1048
    /* XXX: we assume the same server is used for the control of each
1049
     * RTSP stream */
1050

    
1051
    for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
1052
        char transport[2048];
1053

    
1054
        /**
1055
         * WMS serves all UDP data over a single connection, the RTX, which
1056
         * isn't necessarily the first in the SDP but has to be the first
1057
         * to be set up, else the second/third SETUP will fail with a 461.
1058
         */
1059
        if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1060
             rt->server_type == RTSP_SERVER_WMS) {
1061
            if (i == 0) {
1062
                /* rtx first */
1063
                for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1064
                    int len = strlen(rt->rtsp_streams[rtx]->control_url);
1065
                    if (len >= 4 &&
1066
                        !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1067
                                "/rtx"))
1068
                        break;
1069
                }
1070
                if (rtx == rt->nb_rtsp_streams)
1071
                    return -1; /* no RTX found */
1072
                rtsp_st = rt->rtsp_streams[rtx];
1073
            } else
1074
                rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1075
        } else
1076
            rtsp_st = rt->rtsp_streams[i];
1077

    
1078
        /* RTP/UDP */
1079
        if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1080
            char buf[256];
1081

    
1082
            if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1083
                port = reply->transports[0].client_port_min;
1084
                goto have_port;
1085
            }
1086

    
1087
            /* first try in specified port range */
1088
            if (RTSP_RTP_PORT_MIN != 0) {
1089
                while (j <= RTSP_RTP_PORT_MAX) {
1090
                    ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1091
                                "?localport=%d", j);
1092
                    /* we will use two ports per rtp stream (rtp and rtcp) */
1093
                    j += 2;
1094
                    if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
1095
                        goto rtp_opened;
1096
                }
1097
            }
1098

    
1099
#if 0
1100
            /* then try on any port */
1101
            if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
1102
                err = AVERROR_INVALIDDATA;
1103
                goto fail;
1104
            }
1105
#endif
1106

    
1107
        rtp_opened:
1108
            port = rtp_get_local_port(rtsp_st->rtp_handle);
1109
        have_port:
1110
            snprintf(transport, sizeof(transport) - 1,
1111
                     "%s/UDP;", trans_pref);
1112
            if (rt->server_type != RTSP_SERVER_REAL)
1113
                av_strlcat(transport, "unicast;", sizeof(transport));
1114
            av_strlcatf(transport, sizeof(transport),
1115
                     "client_port=%d", port);
1116
            if (rt->transport == RTSP_TRANSPORT_RTP &&
1117
                !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1118
                av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1119
        }
1120

    
1121
        /* RTP/TCP */
1122
        else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1123
            /** For WMS streams, the application streams are only used for
1124
             * UDP. When trying to set it up for TCP streams, the server
1125
             * will return an error. Therefore, we skip those streams. */
1126
            if (rt->server_type == RTSP_SERVER_WMS &&
1127
                s->streams[rtsp_st->stream_index]->codec->codec_type ==
1128
                    CODEC_TYPE_DATA)
1129
                continue;
1130
            snprintf(transport, sizeof(transport) - 1,
1131
                     "%s/TCP;", trans_pref);
1132
            if (rt->server_type == RTSP_SERVER_WMS)
1133
                av_strlcat(transport, "unicast;", sizeof(transport));
1134
            av_strlcatf(transport, sizeof(transport),
1135
                        "interleaved=%d-%d",
1136
                        interleave, interleave + 1);
1137
            interleave += 2;
1138
        }
1139

    
1140
        else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1141
            snprintf(transport, sizeof(transport) - 1,
1142
                     "%s/UDP;multicast", trans_pref);
1143
        }
1144
        if (s->oformat) {
1145
            av_strlcat(transport, ";mode=receive", sizeof(transport));
1146
        } else if (rt->server_type == RTSP_SERVER_REAL ||
1147
                   rt->server_type == RTSP_SERVER_WMS)
1148
            av_strlcat(transport, ";mode=play", sizeof(transport));
1149
        snprintf(cmd, sizeof(cmd),
1150
                 "SETUP %s RTSP/1.0\r\n"
1151
                 "Transport: %s\r\n",
1152
                 rtsp_st->control_url, transport);
1153
        if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
1154
            char real_res[41], real_csum[9];
1155
            ff_rdt_calc_response_and_checksum(real_res, real_csum,
1156
                                              real_challenge);
1157
            av_strlcatf(cmd, sizeof(cmd),
1158
                        "If-Match: %s\r\n"
1159
                        "RealChallenge2: %s, sd=%s\r\n",
1160
                        rt->session_id, real_res, real_csum);
1161
        }
1162
        ff_rtsp_send_cmd(s, cmd, reply, NULL);
1163
        if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1164
            err = 1;
1165
            goto fail;
1166
        } else if (reply->status_code != RTSP_STATUS_OK ||
1167
                   reply->nb_transports != 1) {
1168
            err = AVERROR_INVALIDDATA;
1169
            goto fail;
1170
        }
1171

    
1172
        /* XXX: same protocol for all streams is required */
1173
        if (i > 0) {
1174
            if (reply->transports[0].lower_transport != rt->lower_transport ||
1175
                reply->transports[0].transport != rt->transport) {
1176
                err = AVERROR_INVALIDDATA;
1177
                goto fail;
1178
            }
1179
        } else {
1180
            rt->lower_transport = reply->transports[0].lower_transport;
1181
            rt->transport = reply->transports[0].transport;
1182
        }
1183

    
1184
        /* close RTP connection if not choosen */
1185
        if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
1186
            (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
1187
            url_close(rtsp_st->rtp_handle);
1188
            rtsp_st->rtp_handle = NULL;
1189
        }
1190

    
1191
        switch(reply->transports[0].lower_transport) {
1192
        case RTSP_LOWER_TRANSPORT_TCP:
1193
            rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1194
            rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1195
            break;
1196

    
1197
        case RTSP_LOWER_TRANSPORT_UDP: {
1198
            char url[1024];
1199

    
1200
            /* XXX: also use address if specified */
1201
            ff_url_join(url, sizeof(url), "rtp", NULL, host,
1202
                        reply->transports[0].server_port_min, NULL);
1203
            if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1204
                rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1205
                err = AVERROR_INVALIDDATA;
1206
                goto fail;
1207
            }
1208
            /* Try to initialize the connection state in a
1209
             * potential NAT router by sending dummy packets.
1210
             * RTP/RTCP dummy packets are used for RDT, too.
1211
             */
1212
            if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
1213
                rtp_send_punch_packets(rtsp_st->rtp_handle);
1214
            break;
1215
        }
1216
        case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1217
            char url[1024];
1218
            struct in_addr in;
1219
            int port, ttl;
1220

    
1221
            if (reply->transports[0].destination) {
1222
                in.s_addr = htonl(reply->transports[0].destination);
1223
                port      = reply->transports[0].port_min;
1224
                ttl       = reply->transports[0].ttl;
1225
            } else {
1226
                in        = rtsp_st->sdp_ip;
1227
                port      = rtsp_st->sdp_port;
1228
                ttl       = rtsp_st->sdp_ttl;
1229
            }
1230
            ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in),
1231
                        port, "?ttl=%d", ttl);
1232
            if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1233
                err = AVERROR_INVALIDDATA;
1234
                goto fail;
1235
            }
1236
            break;
1237
        }
1238
        }
1239

    
1240
        if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1241
            goto fail;
1242
    }
1243

    
1244
    if (reply->timeout > 0)
1245
        rt->timeout = reply->timeout;
1246

    
1247
    if (rt->server_type == RTSP_SERVER_REAL)
1248
        rt->need_subscription = 1;
1249

    
1250
    return 0;
1251

    
1252
fail:
1253
    for (i = 0; i < rt->nb_rtsp_streams; i++) {
1254
        if (rt->rtsp_streams[i]->rtp_handle) {
1255
            url_close(rt->rtsp_streams[i]->rtp_handle);
1256
            rt->rtsp_streams[i]->rtp_handle = NULL;
1257
        }
1258
    }
1259
    return err;
1260
}
1261

    
1262
static int rtsp_read_play(AVFormatContext *s)
1263
{
1264
    RTSPState *rt = s->priv_data;
1265
    RTSPMessageHeader reply1, *reply = &reply1;
1266
    char cmd[1024];
1267

    
1268
    av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1269

    
1270
    if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1271
        if (rt->state == RTSP_STATE_PAUSED) {
1272
            snprintf(cmd, sizeof(cmd),
1273
                     "PLAY %s RTSP/1.0\r\n",
1274
                     rt->control_uri);
1275
        } else {
1276
            snprintf(cmd, sizeof(cmd),
1277
                     "PLAY %s RTSP/1.0\r\n"
1278
                     "Range: npt=%0.3f-\r\n",
1279
                     rt->control_uri,
1280
                     (double)rt->seek_timestamp / AV_TIME_BASE);
1281
        }
1282
        ff_rtsp_send_cmd(s, cmd, reply, NULL);
1283
        if (reply->status_code != RTSP_STATUS_OK) {
1284
            return -1;
1285
        }
1286
    }
1287
    rt->state = RTSP_STATE_STREAMING;
1288
    return 0;
1289
}
1290

    
1291
static int rtsp_setup_input_streams(AVFormatContext *s)
1292
{
1293
    RTSPState *rt = s->priv_data;
1294
    RTSPMessageHeader reply1, *reply = &reply1;
1295
    char cmd[1024];
1296
    unsigned char *content = NULL;
1297
    int ret;
1298

    
1299
    /* describe the stream */
1300
    snprintf(cmd, sizeof(cmd),
1301
             "DESCRIBE %s RTSP/1.0\r\n"
1302
             "Accept: application/sdp\r\n",
1303
             s->filename);
1304
    if (rt->server_type == RTSP_SERVER_REAL) {
1305
        /**
1306
         * The Require: attribute is needed for proper streaming from
1307
         * Realmedia servers.
1308
         */
1309
        av_strlcat(cmd,
1310
                   "Require: com.real.retain-entity-for-setup\r\n",
1311
                   sizeof(cmd));
1312
    }
1313
    ff_rtsp_send_cmd(s, cmd, reply, &content);
1314
    if (!content)
1315
        return AVERROR_INVALIDDATA;
1316
    if (reply->status_code != RTSP_STATUS_OK) {
1317
        av_freep(&content);
1318
        return AVERROR_INVALIDDATA;
1319
    }
1320

    
1321
    /* now we got the SDP description, we parse it */
1322
    ret = sdp_parse(s, (const char *)content);
1323
    av_freep(&content);
1324
    if (ret < 0)
1325
        return AVERROR_INVALIDDATA;
1326

    
1327
    return 0;
1328
}
1329

    
1330
static int rtsp_setup_output_streams(AVFormatContext *s)
1331
{
1332
    RTSPState *rt = s->priv_data;
1333
    RTSPMessageHeader reply1, *reply = &reply1;
1334
    char cmd[1024];
1335
    int i;
1336
    char *sdp;
1337

    
1338
    /* Announce the stream */
1339
    snprintf(cmd, sizeof(cmd),
1340
             "ANNOUNCE %s RTSP/1.0\r\n"
1341
             "Content-Type: application/sdp\r\n",
1342
             s->filename);
1343
    sdp = av_mallocz(8192);
1344
    if (sdp == NULL)
1345
        return AVERROR(ENOMEM);
1346
    if (avf_sdp_create(&s, 1, sdp, 8192)) {
1347
        av_free(sdp);
1348
        return AVERROR_INVALIDDATA;
1349
    }
1350
    av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
1351
    ff_rtsp_send_cmd_with_content(s, cmd, reply, NULL, sdp, strlen(sdp));
1352
    av_free(sdp);
1353
    if (reply->status_code != RTSP_STATUS_OK)
1354
        return AVERROR_INVALIDDATA;
1355

    
1356
    /* Set up the RTSPStreams for each AVStream */
1357
    for (i = 0; i < s->nb_streams; i++) {
1358
        RTSPStream *rtsp_st;
1359
        AVStream *st = s->streams[i];
1360

    
1361
        rtsp_st = av_mallocz(sizeof(RTSPStream));
1362
        if (!rtsp_st)
1363
            return AVERROR(ENOMEM);
1364
        dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
1365

    
1366
        st->priv_data = rtsp_st;
1367
        rtsp_st->stream_index = i;
1368

    
1369
        av_strlcpy(rtsp_st->control_url, s->filename, sizeof(rtsp_st->control_url));
1370
        /* Note, this must match the relative uri set in the sdp content */
1371
        av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
1372
                    "/streamid=%d", i);
1373
    }
1374

    
1375
    return 0;
1376
}
1377

    
1378
int ff_rtsp_connect(AVFormatContext *s)
1379
{
1380
    RTSPState *rt = s->priv_data;
1381
    char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1382
    char *option_list, *option, *filename;
1383
    URLContext *rtsp_hd;
1384
    int port, err;
1385
    RTSPMessageHeader reply1, *reply = &reply1;
1386
    int lower_transport_mask = 0;
1387
    char real_challenge[64];
1388

    
1389
    if (!ff_network_init())
1390
        return AVERROR(EIO);
1391
redirect:
1392
    /* extract hostname and port */
1393
    url_split(NULL, 0, auth, sizeof(auth),
1394
              host, sizeof(host), &port, path, sizeof(path), s->filename);
1395
    if (*auth) {
1396
        int auth_len = strlen(auth), b64_len = ((auth_len + 2) / 3) * 4 + 1;
1397

    
1398
        if (!(rt->auth_b64 = av_malloc(b64_len)))
1399
            return AVERROR(ENOMEM);
1400
        if (!av_base64_encode(rt->auth_b64, b64_len, auth, auth_len)) {
1401
            err = AVERROR(EINVAL);
1402
            goto fail;
1403
        }
1404
    }
1405
    if (port < 0)
1406
        port = RTSP_DEFAULT_PORT;
1407

    
1408
    /* search for options */
1409
    option_list = strchr(path, '?');
1410
    if (option_list) {
1411
        filename = strchr(s->filename, '?');
1412
        while (option_list) {
1413
            /* move the option pointer */
1414
            option = ++option_list;
1415
            option_list = strchr(option_list, '&');
1416
            if (option_list)
1417
                *option_list = 0;
1418

    
1419
            /* handle the options */
1420
            if (!strcmp(option, "udp")) {
1421
                lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP);
1422
            } else if (!strcmp(option, "multicast")) {
1423
                lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
1424
            } else if (!strcmp(option, "tcp")) {
1425
                lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_TCP);
1426
            } else {
1427
                strcpy(++filename, option);
1428
                filename += strlen(option);
1429
                if (option_list) *filename = '&';
1430
            }
1431
        }
1432
        *filename = 0;
1433
    }
1434

    
1435
    if (!lower_transport_mask)
1436
        lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1437

    
1438
    if (s->oformat) {
1439
        /* Only UDP output is supported at the moment. */
1440
        lower_transport_mask &= 1 << RTSP_LOWER_TRANSPORT_UDP;
1441
        if (!lower_transport_mask) {
1442
            av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1443
                                    "only UDP is supported for output.\n");
1444
            err = AVERROR(EINVAL);
1445
            goto fail;
1446
        }
1447
    }
1448

    
1449
    /* open the tcp connexion */
1450
    ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
1451
    if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0) {
1452
        err = AVERROR(EIO);
1453
        goto fail;
1454
    }
1455
    rt->rtsp_hd = rtsp_hd;
1456
    rt->seq = 0;
1457

    
1458
    /* request options supported by the server; this also detects server
1459
     * type */
1460
    av_strlcpy(rt->control_uri, s->filename,
1461
               sizeof(rt->control_uri));
1462
    for (rt->server_type = RTSP_SERVER_RTP;;) {
1463
        snprintf(cmd, sizeof(cmd),
1464
                 "OPTIONS %s RTSP/1.0\r\n", s->filename);
1465
        if (rt->server_type == RTSP_SERVER_REAL)
1466
            av_strlcat(cmd,
1467
                       /**
1468
                        * The following entries are required for proper
1469
                        * streaming from a Realmedia server. They are
1470
                        * interdependent in some way although we currently
1471
                        * don't quite understand how. Values were copied
1472
                        * from mplayer SVN r23589.
1473
                        * @param CompanyID is a 16-byte ID in base64
1474
                        * @param ClientChallenge is a 16-byte ID in hex
1475
                        */
1476
                       "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1477
                       "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1478
                       "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1479
                       "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1480
                       sizeof(cmd));
1481
        ff_rtsp_send_cmd(s, cmd, reply, NULL);
1482
        if (reply->status_code != RTSP_STATUS_OK) {
1483
            err = AVERROR_INVALIDDATA;
1484
            goto fail;
1485
        }
1486

    
1487
        /* detect server type if not standard-compliant RTP */
1488
        if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1489
            rt->server_type = RTSP_SERVER_REAL;
1490
            continue;
1491
        } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1492
            rt->server_type = RTSP_SERVER_WMS;
1493
        } else if (rt->server_type == RTSP_SERVER_REAL)
1494
            strcpy(real_challenge, reply->real_challenge);
1495
        break;
1496
    }
1497

    
1498
    if (s->iformat)
1499
        err = rtsp_setup_input_streams(s);
1500
    else
1501
        err = rtsp_setup_output_streams(s);
1502
    if (err)
1503
        goto fail;
1504

    
1505
    do {
1506
        int lower_transport = ff_log2_tab[lower_transport_mask &
1507
                                  ~(lower_transport_mask - 1)];
1508

    
1509
        err = make_setup_request(s, host, port, lower_transport,
1510
                                 rt->server_type == RTSP_SERVER_REAL ?
1511
                                     real_challenge : NULL);
1512
        if (err < 0)
1513
            goto fail;
1514
        lower_transport_mask &= ~(1 << lower_transport);
1515
        if (lower_transport_mask == 0 && err == 1) {
1516
            err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
1517
            goto fail;
1518
        }
1519
    } while (err);
1520

    
1521
    rt->state = RTSP_STATE_IDLE;
1522
    rt->seek_timestamp = 0; /* default is to start stream at position zero */
1523
    return 0;
1524
 fail:
1525
    ff_rtsp_close_streams(s);
1526
    url_close(rt->rtsp_hd);
1527
    if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1528
        av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1529
        av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1530
               reply->status_code,
1531
               s->filename);
1532
        goto redirect;
1533
    }
1534
    ff_network_close();
1535
    return err;
1536
}
1537
#endif
1538

    
1539
#if CONFIG_RTSP_DEMUXER
1540
static int rtsp_read_header(AVFormatContext *s,
1541
                            AVFormatParameters *ap)
1542
{
1543
    RTSPState *rt = s->priv_data;
1544
    int ret;
1545

    
1546
    ret = ff_rtsp_connect(s);
1547
    if (ret)
1548
        return ret;
1549

    
1550
    if (ap->initial_pause) {
1551
         /* do not start immediately */
1552
    } else {
1553
         if (rtsp_read_play(s) < 0) {
1554
            ff_rtsp_close_streams(s);
1555
            url_close(rt->rtsp_hd);
1556
            return AVERROR_INVALIDDATA;
1557
        }
1558
    }
1559

    
1560
    return 0;
1561
}
1562

    
1563
static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1564
                           uint8_t *buf, int buf_size)
1565
{
1566
    RTSPState *rt = s->priv_data;
1567
    RTSPStream *rtsp_st;
1568
    fd_set rfds;
1569
    int fd, fd_max, n, i, ret, tcp_fd;
1570
    struct timeval tv;
1571

    
1572
    for (;;) {
1573
        if (url_interrupt_cb())
1574
            return AVERROR(EINTR);
1575
        FD_ZERO(&rfds);
1576
        if (rt->rtsp_hd) {
1577
            tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
1578
            FD_SET(tcp_fd, &rfds);
1579
        } else {
1580
            fd_max = 0;
1581
            tcp_fd = -1;
1582
        }
1583
        for (i = 0; i < rt->nb_rtsp_streams; i++) {
1584
            rtsp_st = rt->rtsp_streams[i];
1585
            if (rtsp_st->rtp_handle) {
1586
                /* currently, we cannot probe RTCP handle because of
1587
                 * blocking restrictions */
1588
                fd = url_get_file_handle(rtsp_st->rtp_handle);
1589
                if (fd > fd_max)
1590
                    fd_max = fd;
1591
                FD_SET(fd, &rfds);
1592
            }
1593
        }
1594
        tv.tv_sec = 0;
1595
        tv.tv_usec = 100 * 1000;
1596
        n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1597
        if (n > 0) {
1598
            for (i = 0; i < rt->nb_rtsp_streams; i++) {
1599
                rtsp_st = rt->rtsp_streams[i];
1600
                if (rtsp_st->rtp_handle) {
1601
                    fd = url_get_file_handle(rtsp_st->rtp_handle);
1602
                    if (FD_ISSET(fd, &rfds)) {
1603
                        ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1604
                        if (ret > 0) {
1605
                            *prtsp_st = rtsp_st;
1606
                            return ret;
1607
                        }
1608
                    }
1609
                }
1610
            }
1611
#if CONFIG_RTSP_DEMUXER
1612
            if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
1613
                RTSPMessageHeader reply;
1614

    
1615
                ff_rtsp_read_reply(s, &reply, NULL, 0);
1616
                /* XXX: parse message */
1617
                if (rt->state != RTSP_STATE_STREAMING)
1618
                    return 0;
1619
            }
1620
#endif
1621
        }
1622
    }
1623
}
1624

    
1625
static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1626
                           uint8_t *buf, int buf_size)
1627
{
1628
    RTSPState *rt = s->priv_data;
1629
    int id, len, i, ret;
1630
    RTSPStream *rtsp_st;
1631

    
1632
#ifdef DEBUG_RTP_TCP
1633
    dprintf(s, "tcp_read_packet:\n");
1634
#endif
1635
redo:
1636
    for (;;) {
1637
        RTSPMessageHeader reply;
1638

    
1639
        ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
1640
        if (ret == -1)
1641
            return -1;
1642
        if (ret == 1) /* received '$' */
1643
            break;
1644
        /* XXX: parse message */
1645
        if (rt->state != RTSP_STATE_STREAMING)
1646
            return 0;
1647
    }
1648
    ret = url_read_complete(rt->rtsp_hd, buf, 3);
1649
    if (ret != 3)
1650
        return -1;
1651
    id  = buf[0];
1652
    len = AV_RB16(buf + 1);
1653
#ifdef DEBUG_RTP_TCP
1654
    dprintf(s, "id=%d len=%d\n", id, len);
1655
#endif
1656
    if (len > buf_size || len < 12)
1657
        goto redo;
1658
    /* get the data */
1659
    ret = url_read_complete(rt->rtsp_hd, buf, len);
1660
    if (ret != len)
1661
        return -1;
1662
    if (rt->transport == RTSP_TRANSPORT_RDT &&
1663
        ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
1664
        return -1;
1665

    
1666
    /* find the matching stream */
1667
    for (i = 0; i < rt->nb_rtsp_streams; i++) {
1668
        rtsp_st = rt->rtsp_streams[i];
1669
        if (id >= rtsp_st->interleaved_min &&
1670
            id <= rtsp_st->interleaved_max)
1671
            goto found;
1672
    }
1673
    goto redo;
1674
found:
1675
    *prtsp_st = rtsp_st;
1676
    return len;
1677
}
1678

    
1679
static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1680
{
1681
    RTSPState *rt = s->priv_data;
1682
    int ret, len;
1683
    uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
1684
    RTSPStream *rtsp_st;
1685

    
1686
    /* get next frames from the same RTP packet */
1687
    if (rt->cur_transport_priv) {
1688
        if (rt->transport == RTSP_TRANSPORT_RDT) {
1689
            ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1690
        } else
1691
            ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1692
        if (ret == 0) {
1693
            rt->cur_transport_priv = NULL;
1694
            return 0;
1695
        } else if (ret == 1) {
1696
            return 0;
1697
        } else
1698
            rt->cur_transport_priv = NULL;
1699
    }
1700

    
1701
    /* read next RTP packet */
1702
 redo:
1703
    switch(rt->lower_transport) {
1704
    default:
1705
#if CONFIG_RTSP_DEMUXER
1706
    case RTSP_LOWER_TRANSPORT_TCP:
1707
        len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1708
        break;
1709
#endif
1710
    case RTSP_LOWER_TRANSPORT_UDP:
1711
    case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1712
        len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1713
        if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1714
            rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1715
        break;
1716
    }
1717
    if (len < 0)
1718
        return len;
1719
    if (len == 0)
1720
        return AVERROR_EOF;
1721
    if (rt->transport == RTSP_TRANSPORT_RDT) {
1722
        ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
1723
    } else
1724
        ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
1725
    if (ret < 0)
1726
        goto redo;
1727
    if (ret == 1)
1728
        /* more packets may follow, so we save the RTP context */
1729
        rt->cur_transport_priv = rtsp_st->transport_priv;
1730

    
1731
    return ret;
1732
}
1733

    
1734
static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
1735
{
1736
    RTSPState *rt = s->priv_data;
1737
    int ret;
1738
    RTSPMessageHeader reply1, *reply = &reply1;
1739
    char cmd[1024];
1740

    
1741
    if (rt->server_type == RTSP_SERVER_REAL) {
1742
        int i;
1743
        enum AVDiscard cache[MAX_STREAMS];
1744

    
1745
        for (i = 0; i < s->nb_streams; i++)
1746
            cache[i] = s->streams[i]->discard;
1747

    
1748
        if (!rt->need_subscription) {
1749
            if (memcmp (cache, rt->real_setup_cache,
1750
                        sizeof(enum AVDiscard) * s->nb_streams)) {
1751
                snprintf(cmd, sizeof(cmd),
1752
                         "SET_PARAMETER %s RTSP/1.0\r\n"
1753
                         "Unsubscribe: %s\r\n",
1754
                         rt->control_uri, rt->last_subscription);
1755
                ff_rtsp_send_cmd(s, cmd, reply, NULL);
1756
                if (reply->status_code != RTSP_STATUS_OK)
1757
                    return AVERROR_INVALIDDATA;
1758
                rt->need_subscription = 1;
1759
            }
1760
        }
1761

    
1762
        if (rt->need_subscription) {
1763
            int r, rule_nr, first = 1;
1764

    
1765
            memcpy(rt->real_setup_cache, cache,
1766
                   sizeof(enum AVDiscard) * s->nb_streams);
1767
            rt->last_subscription[0] = 0;
1768

    
1769
            snprintf(cmd, sizeof(cmd),
1770
                     "SET_PARAMETER %s RTSP/1.0\r\n"
1771
                     "Subscribe: ",
1772
                     rt->control_uri);
1773
            for (i = 0; i < rt->nb_rtsp_streams; i++) {
1774
                rule_nr = 0;
1775
                for (r = 0; r < s->nb_streams; r++) {
1776
                    if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
1777
                        if (s->streams[r]->discard != AVDISCARD_ALL) {
1778
                            if (!first)
1779
                                av_strlcat(rt->last_subscription, ",",
1780
                                           sizeof(rt->last_subscription));
1781
                            ff_rdt_subscribe_rule(
1782
                                rt->last_subscription,
1783
                                sizeof(rt->last_subscription), i, rule_nr);
1784
                            first = 0;
1785
                        }
1786
                        rule_nr++;
1787
                    }
1788
                }
1789
            }
1790
            av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
1791
            ff_rtsp_send_cmd(s, cmd, reply, NULL);
1792
            if (reply->status_code != RTSP_STATUS_OK)
1793
                return AVERROR_INVALIDDATA;
1794
            rt->need_subscription = 0;
1795

    
1796
            if (rt->state == RTSP_STATE_STREAMING)
1797
                rtsp_read_play (s);
1798
        }
1799
    }
1800

    
1801
    ret = rtsp_fetch_packet(s, pkt);
1802
    if (ret < 0)
1803
        return ret;
1804

    
1805
    /* send dummy request to keep TCP connection alive */
1806
    if ((rt->server_type == RTSP_SERVER_WMS ||
1807
         rt->server_type == RTSP_SERVER_REAL) &&
1808
        (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
1809
        if (rt->server_type == RTSP_SERVER_WMS) {
1810
            snprintf(cmd, sizeof(cmd) - 1,
1811
                     "GET_PARAMETER %s RTSP/1.0\r\n",
1812
                     rt->control_uri);
1813
            ff_rtsp_send_cmd_async(s, cmd);
1814
        } else {
1815
            ff_rtsp_send_cmd_async(s, "OPTIONS * RTSP/1.0\r\n");
1816
        }
1817
    }
1818

    
1819
    return 0;
1820
}
1821

    
1822
/* pause the stream */
1823
static int rtsp_read_pause(AVFormatContext *s)
1824
{
1825
    RTSPState *rt = s->priv_data;
1826
    RTSPMessageHeader reply1, *reply = &reply1;
1827
    char cmd[1024];
1828

    
1829
    rt = s->priv_data;
1830

    
1831
    if (rt->state != RTSP_STATE_STREAMING)
1832
        return 0;
1833
    else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1834
        snprintf(cmd, sizeof(cmd),
1835
                 "PAUSE %s RTSP/1.0\r\n",
1836
                 rt->control_uri);
1837
        ff_rtsp_send_cmd(s, cmd, reply, NULL);
1838
        if (reply->status_code != RTSP_STATUS_OK) {
1839
            return -1;
1840
        }
1841
    }
1842
    rt->state = RTSP_STATE_PAUSED;
1843
    return 0;
1844
}
1845

    
1846
static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1847
                          int64_t timestamp, int flags)
1848
{
1849
    RTSPState *rt = s->priv_data;
1850

    
1851
    rt->seek_timestamp = av_rescale_q(timestamp,
1852
                                      s->streams[stream_index]->time_base,
1853
                                      AV_TIME_BASE_Q);
1854
    switch(rt->state) {
1855
    default:
1856
    case RTSP_STATE_IDLE:
1857
        break;
1858
    case RTSP_STATE_STREAMING:
1859
        if (rtsp_read_pause(s) != 0)
1860
            return -1;
1861
        rt->state = RTSP_STATE_SEEKING;
1862
        if (rtsp_read_play(s) != 0)
1863
            return -1;
1864
        break;
1865
    case RTSP_STATE_PAUSED:
1866
        rt->state = RTSP_STATE_IDLE;
1867
        break;
1868
    }
1869
    return 0;
1870
}
1871

    
1872
static int rtsp_read_close(AVFormatContext *s)
1873
{
1874
    RTSPState *rt = s->priv_data;
1875
    char cmd[1024];
1876

    
1877
#if 0
1878
    /* NOTE: it is valid to flush the buffer here */
1879
    if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1880
        url_fclose(&rt->rtsp_gb);
1881
    }
1882
#endif
1883
    snprintf(cmd, sizeof(cmd),
1884
             "TEARDOWN %s RTSP/1.0\r\n",
1885
             s->filename);
1886
    ff_rtsp_send_cmd_async(s, cmd);
1887

    
1888
    ff_rtsp_close_streams(s);
1889
    url_close(rt->rtsp_hd);
1890
    ff_network_close();
1891
    return 0;
1892
}
1893

    
1894
AVInputFormat rtsp_demuxer = {
1895
    "rtsp",
1896
    NULL_IF_CONFIG_SMALL("RTSP input format"),
1897
    sizeof(RTSPState),
1898
    rtsp_probe,
1899
    rtsp_read_header,
1900
    rtsp_read_packet,
1901
    rtsp_read_close,
1902
    rtsp_read_seek,
1903
    .flags = AVFMT_NOFILE,
1904
    .read_play = rtsp_read_play,
1905
    .read_pause = rtsp_read_pause,
1906
};
1907
#endif
1908

    
1909
static int sdp_probe(AVProbeData *p1)
1910
{
1911
    const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
1912

    
1913
    /* we look for a line beginning "c=IN IP4" */
1914
    while (p < p_end && *p != '\0') {
1915
        if (p + sizeof("c=IN IP4") - 1 < p_end &&
1916
            av_strstart(p, "c=IN IP4", NULL))
1917
            return AVPROBE_SCORE_MAX / 2;
1918

    
1919
        while (p < p_end - 1 && *p != '\n') p++;
1920
        if (++p >= p_end)
1921
            break;
1922
        if (*p == '\r')
1923
            p++;
1924
    }
1925
    return 0;
1926
}
1927

    
1928
#define SDP_MAX_SIZE 8192
1929

    
1930
static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
1931
{
1932
    RTSPState *rt = s->priv_data;
1933
    RTSPStream *rtsp_st;
1934
    int size, i, err;
1935
    char *content;
1936
    char url[1024];
1937

    
1938
    if (!ff_network_init())
1939
        return AVERROR(EIO);
1940

    
1941
    /* read the whole sdp file */
1942
    /* XXX: better loading */
1943
    content = av_malloc(SDP_MAX_SIZE);
1944
    size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
1945
    if (size <= 0) {
1946
        av_free(content);
1947
        return AVERROR_INVALIDDATA;
1948
    }
1949
    content[size] ='\0';
1950

    
1951
    sdp_parse(s, content);
1952
    av_free(content);
1953

    
1954
    /* open each RTP stream */
1955
    for (i = 0; i < rt->nb_rtsp_streams; i++) {
1956
        rtsp_st = rt->rtsp_streams[i];
1957

    
1958
        ff_url_join(url, sizeof(url), "rtp", NULL,
1959
                    inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
1960
                    "?localport=%d&ttl=%d", rtsp_st->sdp_port,
1961
                    rtsp_st->sdp_ttl);
1962
        if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1963
            err = AVERROR_INVALIDDATA;
1964
            goto fail;
1965
        }
1966
        if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1967
            goto fail;
1968
    }
1969
    return 0;
1970
fail:
1971
    ff_rtsp_close_streams(s);
1972
    ff_network_close();
1973
    return err;
1974
}
1975

    
1976
static int sdp_read_close(AVFormatContext *s)
1977
{
1978
    ff_rtsp_close_streams(s);
1979
    ff_network_close();
1980
    return 0;
1981
}
1982

    
1983
AVInputFormat sdp_demuxer = {
1984
    "sdp",
1985
    NULL_IF_CONFIG_SMALL("SDP"),
1986
    sizeof(RTSPState),
1987
    sdp_probe,
1988
    sdp_read_header,
1989
    rtsp_fetch_packet,
1990
    sdp_read_close,
1991
};