Statistics
| Branch: | Revision:

ffmpeg / libavformat / rtsp.c @ 03f8fc08

History | View | Annotate | Download (64.7 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
            ff_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, tcp_fd;
1385
    RTSPMessageHeader reply1, *reply = &reply1;
1386
    int lower_transport_mask = 0;
1387
    char real_challenge[64];
1388
    struct sockaddr_storage peer;
1389
    socklen_t peer_len = sizeof(peer);
1390

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

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

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

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

    
1437
    if (!lower_transport_mask)
1438
        lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1439

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

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

    
1460
    tcp_fd = url_get_file_handle(rtsp_hd);
1461
    if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1462
        getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1463
                    NULL, 0, NI_NUMERICHOST);
1464
    }
1465

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

    
1495
        /* detect server type if not standard-compliant RTP */
1496
        if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1497
            rt->server_type = RTSP_SERVER_REAL;
1498
            continue;
1499
        } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1500
            rt->server_type = RTSP_SERVER_WMS;
1501
        } else if (rt->server_type == RTSP_SERVER_REAL)
1502
            strcpy(real_challenge, reply->real_challenge);
1503
        break;
1504
    }
1505

    
1506
    if (s->iformat)
1507
        err = rtsp_setup_input_streams(s);
1508
    else
1509
        err = rtsp_setup_output_streams(s);
1510
    if (err)
1511
        goto fail;
1512

    
1513
    do {
1514
        int lower_transport = ff_log2_tab[lower_transport_mask &
1515
                                  ~(lower_transport_mask - 1)];
1516

    
1517
        err = make_setup_request(s, host, port, lower_transport,
1518
                                 rt->server_type == RTSP_SERVER_REAL ?
1519
                                     real_challenge : NULL);
1520
        if (err < 0)
1521
            goto fail;
1522
        lower_transport_mask &= ~(1 << lower_transport);
1523
        if (lower_transport_mask == 0 && err == 1) {
1524
            err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
1525
            goto fail;
1526
        }
1527
    } while (err);
1528

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

    
1547
#if CONFIG_RTSP_DEMUXER
1548
static int rtsp_read_header(AVFormatContext *s,
1549
                            AVFormatParameters *ap)
1550
{
1551
    RTSPState *rt = s->priv_data;
1552
    int ret;
1553

    
1554
    ret = ff_rtsp_connect(s);
1555
    if (ret)
1556
        return ret;
1557

    
1558
    if (ap->initial_pause) {
1559
         /* do not start immediately */
1560
    } else {
1561
         if (rtsp_read_play(s) < 0) {
1562
            ff_rtsp_close_streams(s);
1563
            url_close(rt->rtsp_hd);
1564
            return AVERROR_INVALIDDATA;
1565
        }
1566
    }
1567

    
1568
    return 0;
1569
}
1570

    
1571
static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1572
                           uint8_t *buf, int buf_size)
1573
{
1574
    RTSPState *rt = s->priv_data;
1575
    RTSPStream *rtsp_st;
1576
    fd_set rfds;
1577
    int fd, fd_max, n, i, ret, tcp_fd;
1578
    struct timeval tv;
1579

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

    
1623
                ff_rtsp_read_reply(s, &reply, NULL, 0);
1624
                /* XXX: parse message */
1625
                if (rt->state != RTSP_STATE_STREAMING)
1626
                    return 0;
1627
            }
1628
#endif
1629
        }
1630
    }
1631
}
1632

    
1633
static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1634
                           uint8_t *buf, int buf_size)
1635
{
1636
    RTSPState *rt = s->priv_data;
1637
    int id, len, i, ret;
1638
    RTSPStream *rtsp_st;
1639

    
1640
#ifdef DEBUG_RTP_TCP
1641
    dprintf(s, "tcp_read_packet:\n");
1642
#endif
1643
redo:
1644
    for (;;) {
1645
        RTSPMessageHeader reply;
1646

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

    
1674
    /* find the matching stream */
1675
    for (i = 0; i < rt->nb_rtsp_streams; i++) {
1676
        rtsp_st = rt->rtsp_streams[i];
1677
        if (id >= rtsp_st->interleaved_min &&
1678
            id <= rtsp_st->interleaved_max)
1679
            goto found;
1680
    }
1681
    goto redo;
1682
found:
1683
    *prtsp_st = rtsp_st;
1684
    return len;
1685
}
1686

    
1687
static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1688
{
1689
    RTSPState *rt = s->priv_data;
1690
    int ret, len;
1691
    uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
1692
    RTSPStream *rtsp_st;
1693

    
1694
    /* get next frames from the same RTP packet */
1695
    if (rt->cur_transport_priv) {
1696
        if (rt->transport == RTSP_TRANSPORT_RDT) {
1697
            ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1698
        } else
1699
            ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1700
        if (ret == 0) {
1701
            rt->cur_transport_priv = NULL;
1702
            return 0;
1703
        } else if (ret == 1) {
1704
            return 0;
1705
        } else
1706
            rt->cur_transport_priv = NULL;
1707
    }
1708

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

    
1739
    return ret;
1740
}
1741

    
1742
static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
1743
{
1744
    RTSPState *rt = s->priv_data;
1745
    int ret;
1746
    RTSPMessageHeader reply1, *reply = &reply1;
1747
    char cmd[1024];
1748

    
1749
    if (rt->server_type == RTSP_SERVER_REAL) {
1750
        int i;
1751
        enum AVDiscard cache[MAX_STREAMS];
1752

    
1753
        for (i = 0; i < s->nb_streams; i++)
1754
            cache[i] = s->streams[i]->discard;
1755

    
1756
        if (!rt->need_subscription) {
1757
            if (memcmp (cache, rt->real_setup_cache,
1758
                        sizeof(enum AVDiscard) * s->nb_streams)) {
1759
                snprintf(cmd, sizeof(cmd),
1760
                         "SET_PARAMETER %s RTSP/1.0\r\n"
1761
                         "Unsubscribe: %s\r\n",
1762
                         rt->control_uri, rt->last_subscription);
1763
                ff_rtsp_send_cmd(s, cmd, reply, NULL);
1764
                if (reply->status_code != RTSP_STATUS_OK)
1765
                    return AVERROR_INVALIDDATA;
1766
                rt->need_subscription = 1;
1767
            }
1768
        }
1769

    
1770
        if (rt->need_subscription) {
1771
            int r, rule_nr, first = 1;
1772

    
1773
            memcpy(rt->real_setup_cache, cache,
1774
                   sizeof(enum AVDiscard) * s->nb_streams);
1775
            rt->last_subscription[0] = 0;
1776

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

    
1804
            if (rt->state == RTSP_STATE_STREAMING)
1805
                rtsp_read_play (s);
1806
        }
1807
    }
1808

    
1809
    ret = rtsp_fetch_packet(s, pkt);
1810
    if (ret < 0)
1811
        return ret;
1812

    
1813
    /* send dummy request to keep TCP connection alive */
1814
    if ((rt->server_type == RTSP_SERVER_WMS ||
1815
         rt->server_type == RTSP_SERVER_REAL) &&
1816
        (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
1817
        if (rt->server_type == RTSP_SERVER_WMS) {
1818
            snprintf(cmd, sizeof(cmd) - 1,
1819
                     "GET_PARAMETER %s RTSP/1.0\r\n",
1820
                     rt->control_uri);
1821
            ff_rtsp_send_cmd_async(s, cmd);
1822
        } else {
1823
            ff_rtsp_send_cmd_async(s, "OPTIONS * RTSP/1.0\r\n");
1824
        }
1825
    }
1826

    
1827
    return 0;
1828
}
1829

    
1830
/* pause the stream */
1831
static int rtsp_read_pause(AVFormatContext *s)
1832
{
1833
    RTSPState *rt = s->priv_data;
1834
    RTSPMessageHeader reply1, *reply = &reply1;
1835
    char cmd[1024];
1836

    
1837
    rt = s->priv_data;
1838

    
1839
    if (rt->state != RTSP_STATE_STREAMING)
1840
        return 0;
1841
    else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1842
        snprintf(cmd, sizeof(cmd),
1843
                 "PAUSE %s RTSP/1.0\r\n",
1844
                 rt->control_uri);
1845
        ff_rtsp_send_cmd(s, cmd, reply, NULL);
1846
        if (reply->status_code != RTSP_STATUS_OK) {
1847
            return -1;
1848
        }
1849
    }
1850
    rt->state = RTSP_STATE_PAUSED;
1851
    return 0;
1852
}
1853

    
1854
static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1855
                          int64_t timestamp, int flags)
1856
{
1857
    RTSPState *rt = s->priv_data;
1858

    
1859
    rt->seek_timestamp = av_rescale_q(timestamp,
1860
                                      s->streams[stream_index]->time_base,
1861
                                      AV_TIME_BASE_Q);
1862
    switch(rt->state) {
1863
    default:
1864
    case RTSP_STATE_IDLE:
1865
        break;
1866
    case RTSP_STATE_STREAMING:
1867
        if (rtsp_read_pause(s) != 0)
1868
            return -1;
1869
        rt->state = RTSP_STATE_SEEKING;
1870
        if (rtsp_read_play(s) != 0)
1871
            return -1;
1872
        break;
1873
    case RTSP_STATE_PAUSED:
1874
        rt->state = RTSP_STATE_IDLE;
1875
        break;
1876
    }
1877
    return 0;
1878
}
1879

    
1880
static int rtsp_read_close(AVFormatContext *s)
1881
{
1882
    RTSPState *rt = s->priv_data;
1883
    char cmd[1024];
1884

    
1885
#if 0
1886
    /* NOTE: it is valid to flush the buffer here */
1887
    if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1888
        url_fclose(&rt->rtsp_gb);
1889
    }
1890
#endif
1891
    snprintf(cmd, sizeof(cmd),
1892
             "TEARDOWN %s RTSP/1.0\r\n",
1893
             s->filename);
1894
    ff_rtsp_send_cmd_async(s, cmd);
1895

    
1896
    ff_rtsp_close_streams(s);
1897
    url_close(rt->rtsp_hd);
1898
    ff_network_close();
1899
    return 0;
1900
}
1901

    
1902
AVInputFormat rtsp_demuxer = {
1903
    "rtsp",
1904
    NULL_IF_CONFIG_SMALL("RTSP input format"),
1905
    sizeof(RTSPState),
1906
    rtsp_probe,
1907
    rtsp_read_header,
1908
    rtsp_read_packet,
1909
    rtsp_read_close,
1910
    rtsp_read_seek,
1911
    .flags = AVFMT_NOFILE,
1912
    .read_play = rtsp_read_play,
1913
    .read_pause = rtsp_read_pause,
1914
};
1915
#endif
1916

    
1917
static int sdp_probe(AVProbeData *p1)
1918
{
1919
    const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
1920

    
1921
    /* we look for a line beginning "c=IN IP4" */
1922
    while (p < p_end && *p != '\0') {
1923
        if (p + sizeof("c=IN IP4") - 1 < p_end &&
1924
            av_strstart(p, "c=IN IP4", NULL))
1925
            return AVPROBE_SCORE_MAX / 2;
1926

    
1927
        while (p < p_end - 1 && *p != '\n') p++;
1928
        if (++p >= p_end)
1929
            break;
1930
        if (*p == '\r')
1931
            p++;
1932
    }
1933
    return 0;
1934
}
1935

    
1936
#define SDP_MAX_SIZE 8192
1937

    
1938
static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
1939
{
1940
    RTSPState *rt = s->priv_data;
1941
    RTSPStream *rtsp_st;
1942
    int size, i, err;
1943
    char *content;
1944
    char url[1024];
1945

    
1946
    if (!ff_network_init())
1947
        return AVERROR(EIO);
1948

    
1949
    /* read the whole sdp file */
1950
    /* XXX: better loading */
1951
    content = av_malloc(SDP_MAX_SIZE);
1952
    size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
1953
    if (size <= 0) {
1954
        av_free(content);
1955
        return AVERROR_INVALIDDATA;
1956
    }
1957
    content[size] ='\0';
1958

    
1959
    sdp_parse(s, content);
1960
    av_free(content);
1961

    
1962
    /* open each RTP stream */
1963
    for (i = 0; i < rt->nb_rtsp_streams; i++) {
1964
        rtsp_st = rt->rtsp_streams[i];
1965

    
1966
        ff_url_join(url, sizeof(url), "rtp", NULL,
1967
                    inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
1968
                    "?localport=%d&ttl=%d", rtsp_st->sdp_port,
1969
                    rtsp_st->sdp_ttl);
1970
        if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1971
            err = AVERROR_INVALIDDATA;
1972
            goto fail;
1973
        }
1974
        if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1975
            goto fail;
1976
    }
1977
    return 0;
1978
fail:
1979
    ff_rtsp_close_streams(s);
1980
    ff_network_close();
1981
    return err;
1982
}
1983

    
1984
static int sdp_read_close(AVFormatContext *s)
1985
{
1986
    ff_rtsp_close_streams(s);
1987
    ff_network_close();
1988
    return 0;
1989
}
1990

    
1991
AVInputFormat sdp_demuxer = {
1992
    "sdp",
1993
    NULL_IF_CONFIG_SMALL("SDP"),
1994
    sizeof(RTSPState),
1995
    sdp_probe,
1996
    sdp_read_header,
1997
    rtsp_fetch_packet,
1998
    sdp_read_close,
1999
};