Statistics
| Branch: | Revision:

ffmpeg / libavformat / rtsp.c @ a493f80a

History | View | Annotate | Download (72.1 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 "libavutil/random_seed.h"
26
#include "avformat.h"
27

    
28
#include <sys/time.h>
29
#if HAVE_SYS_SELECT_H
30
#include <sys/select.h>
31
#endif
32
#include <strings.h>
33
#include "internal.h"
34
#include "network.h"
35
#include "os_support.h"
36
#include "http.h"
37
#include "rtsp.h"
38

    
39
#include "rtpdec.h"
40
#include "rdt.h"
41
#include "rtpdec_formats.h"
42
#include "rtpenc_chain.h"
43

    
44
//#define DEBUG
45
//#define DEBUG_RTP_TCP
46

    
47
#if LIBAVFORMAT_VERSION_INT < (53 << 16)
48
int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
49
#endif
50

    
51
/* Timeout values for socket select, in ms,
52
 * and read_packet(), in seconds  */
53
#define SELECT_TIMEOUT_MS 100
54
#define READ_PACKET_TIMEOUT_S 10
55
#define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
56
#define SDP_MAX_SIZE 16384
57
#define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
58

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

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

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

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

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

    
100
    /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
101
     * see if we can handle this kind of payload.
102
     * The space should normally not be there but some Real streams or
103
     * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
104
     * have a trailing space. */
105
    get_word_sep(buf, sizeof(buf), "/ ", &p);
106
    if (payload_type >= RTP_PT_PRIVATE) {
107
        RTPDynamicProtocolHandler *handler;
108
        for (handler = RTPFirstDynamicPayloadHandler;
109
             handler; handler = handler->next) {
110
            if (!strcasecmp(buf, handler->enc_name) &&
111
                codec->codec_type == handler->codec_type) {
112
                codec->codec_id          = handler->codec_id;
113
                rtsp_st->dynamic_handler = handler;
114
                if (handler->open)
115
                    rtsp_st->dynamic_protocol_context = handler->open();
116
                break;
117
            }
118
        }
119
        /* If no dynamic handler was found, check with the list of standard
120
         * allocated types, if such a stream for some reason happens to
121
         * use a private payload type. This isn't handled in rtpdec.c, since
122
         * the format name from the rtpmap line never is passed into rtpdec. */
123
        if (!rtsp_st->dynamic_handler)
124
            codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
125
    } else {
126
        /* We are in a standard case
127
         * (from http://www.iana.org/assignments/rtp-parameters). */
128
        /* search into AVRtpPayloadTypes[] */
129
        codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
130
    }
131

    
132
    c = avcodec_find_decoder(codec->codec_id);
133
    if (c && c->name)
134
        c_name = c->name;
135
    else
136
        c_name = "(null)";
137

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

    
170
/* parse the attribute line from the fmtp a line of an sdp response. This
171
 * is broken out as a function because it is used in rtp_h264.c, which is
172
 * forthcoming. */
173
int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
174
                                char *value, int value_size)
175
{
176
    *p += strspn(*p, SPACE_CHARS);
177
    if (**p) {
178
        get_word_sep(attr, attr_size, "=", p);
179
        if (**p == '=')
180
            (*p)++;
181
        get_word_sep(value, value_size, ";", p);
182
        if (**p == ';')
183
            (*p)++;
184
        return 1;
185
    }
186
    return 0;
187
}
188

    
189
/** Parse a string p in the form of Range:npt=xx-xx, and determine the start
190
 *  and end time.
191
 *  Used for seeking in the rtp stream.
192
 */
193
static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
194
{
195
    char buf[256];
196

    
197
    p += strspn(p, SPACE_CHARS);
198
    if (!av_stristart(p, "npt=", &p))
199
        return;
200

    
201
    *start = AV_NOPTS_VALUE;
202
    *end = AV_NOPTS_VALUE;
203

    
204
    get_word_sep(buf, sizeof(buf), "-", &p);
205
    *start = parse_date(buf, 1);
206
    if (*p == '-') {
207
        p++;
208
        get_word_sep(buf, sizeof(buf), "-", &p);
209
        *end = parse_date(buf, 1);
210
    }
211
//    av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
212
//    av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
213
}
214

    
215
static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
216
{
217
    struct addrinfo hints, *ai = NULL;
218
    memset(&hints, 0, sizeof(hints));
219
    hints.ai_flags = AI_NUMERICHOST;
220
    if (getaddrinfo(buf, NULL, &hints, &ai))
221
        return -1;
222
    memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
223
    freeaddrinfo(ai);
224
    return 0;
225
}
226

    
227
typedef struct SDPParseState {
228
    /* SDP only */
229
    struct sockaddr_storage default_ip;
230
    int            default_ttl;
231
    int            skip_media;  ///< set if an unknown m= line occurs
232
} SDPParseState;
233

    
234
static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
235
                           int letter, const char *buf)
236
{
237
    RTSPState *rt = s->priv_data;
238
    char buf1[64], st_type[64];
239
    const char *p;
240
    enum AVMediaType codec_type;
241
    int payload_type, i;
242
    AVStream *st;
243
    RTSPStream *rtsp_st;
244
    struct sockaddr_storage sdp_ip;
245
    int ttl;
246

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

    
249
    p = buf;
250
    if (s1->skip_media && letter != 'm')
251
        return;
252
    switch (letter) {
253
    case 'c':
254
        get_word(buf1, sizeof(buf1), &p);
255
        if (strcmp(buf1, "IN") != 0)
256
            return;
257
        get_word(buf1, sizeof(buf1), &p);
258
        if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
259
            return;
260
        get_word_sep(buf1, sizeof(buf1), "/", &p);
261
        if (get_sockaddr(buf1, &sdp_ip))
262
            return;
263
        ttl = 16;
264
        if (*p == '/') {
265
            p++;
266
            get_word_sep(buf1, sizeof(buf1), "/", &p);
267
            ttl = atoi(buf1);
268
        }
269
        if (s->nb_streams == 0) {
270
            s1->default_ip = sdp_ip;
271
            s1->default_ttl = ttl;
272
        } else {
273
            st = s->streams[s->nb_streams - 1];
274
            rtsp_st = st->priv_data;
275
            rtsp_st->sdp_ip = sdp_ip;
276
            rtsp_st->sdp_ttl = ttl;
277
        }
278
        break;
279
    case 's':
280
        av_metadata_set2(&s->metadata, "title", p, 0);
281
        break;
282
    case 'i':
283
        if (s->nb_streams == 0) {
284
            av_metadata_set2(&s->metadata, "comment", p, 0);
285
            break;
286
        }
287
        break;
288
    case 'm':
289
        /* new stream */
290
        s1->skip_media = 0;
291
        get_word(st_type, sizeof(st_type), &p);
292
        if (!strcmp(st_type, "audio")) {
293
            codec_type = AVMEDIA_TYPE_AUDIO;
294
        } else if (!strcmp(st_type, "video")) {
295
            codec_type = AVMEDIA_TYPE_VIDEO;
296
        } else if (!strcmp(st_type, "application")) {
297
            codec_type = AVMEDIA_TYPE_DATA;
298
        } else {
299
            s1->skip_media = 1;
300
            return;
301
        }
302
        rtsp_st = av_mallocz(sizeof(RTSPStream));
303
        if (!rtsp_st)
304
            return;
305
        rtsp_st->stream_index = -1;
306
        dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
307

    
308
        rtsp_st->sdp_ip = s1->default_ip;
309
        rtsp_st->sdp_ttl = s1->default_ttl;
310

    
311
        get_word(buf1, sizeof(buf1), &p); /* port */
312
        rtsp_st->sdp_port = atoi(buf1);
313

    
314
        get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
315

    
316
        /* XXX: handle list of formats */
317
        get_word(buf1, sizeof(buf1), &p); /* format list */
318
        rtsp_st->sdp_payload_type = atoi(buf1);
319

    
320
        if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
321
            /* no corresponding stream */
322
        } else {
323
            st = av_new_stream(s, 0);
324
            if (!st)
325
                return;
326
            st->priv_data = rtsp_st;
327
            rtsp_st->stream_index = st->index;
328
            st->codec->codec_type = codec_type;
329
            if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
330
                /* if standard payload type, we can find the codec right now */
331
                ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
332
            }
333
        }
334
        /* put a default control url */
335
        av_strlcpy(rtsp_st->control_url, rt->control_uri,
336
                   sizeof(rtsp_st->control_url));
337
        break;
338
    case 'a':
339
        if (av_strstart(p, "control:", &p)) {
340
            if (s->nb_streams == 0) {
341
                if (!strncmp(p, "rtsp://", 7))
342
                    av_strlcpy(rt->control_uri, p,
343
                               sizeof(rt->control_uri));
344
            } else {
345
            char proto[32];
346
            /* get the control url */
347
            st = s->streams[s->nb_streams - 1];
348
            rtsp_st = st->priv_data;
349

    
350
            /* XXX: may need to add full url resolution */
351
            av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
352
                         NULL, NULL, 0, p);
353
            if (proto[0] == '\0') {
354
                /* relative control URL */
355
                if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
356
                av_strlcat(rtsp_st->control_url, "/",
357
                           sizeof(rtsp_st->control_url));
358
                av_strlcat(rtsp_st->control_url, p,
359
                           sizeof(rtsp_st->control_url));
360
            } else
361
                av_strlcpy(rtsp_st->control_url, p,
362
                           sizeof(rtsp_st->control_url));
363
            }
364
        } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
365
            /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
366
            get_word(buf1, sizeof(buf1), &p);
367
            payload_type = atoi(buf1);
368
            st = s->streams[s->nb_streams - 1];
369
            rtsp_st = st->priv_data;
370
            sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
371
        } else if (av_strstart(p, "fmtp:", &p) ||
372
                   av_strstart(p, "framesize:", &p)) {
373
            /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
374
            // let dynamic protocol handlers have a stab at the line.
375
            get_word(buf1, sizeof(buf1), &p);
376
            payload_type = atoi(buf1);
377
            for (i = 0; i < s->nb_streams; i++) {
378
                st      = s->streams[i];
379
                rtsp_st = st->priv_data;
380
                if (rtsp_st->sdp_payload_type == payload_type &&
381
                    rtsp_st->dynamic_handler &&
382
                    rtsp_st->dynamic_handler->parse_sdp_a_line)
383
                    rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
384
                        rtsp_st->dynamic_protocol_context, buf);
385
            }
386
        } else if (av_strstart(p, "range:", &p)) {
387
            int64_t start, end;
388

    
389
            // this is so that seeking on a streamed file can work.
390
            rtsp_parse_range_npt(p, &start, &end);
391
            s->start_time = start;
392
            /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
393
            s->duration   = (end == AV_NOPTS_VALUE) ?
394
                            AV_NOPTS_VALUE : end - start;
395
        } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
396
            if (atoi(p) == 1)
397
                rt->transport = RTSP_TRANSPORT_RDT;
398
        } else {
399
            if (rt->server_type == RTSP_SERVER_WMS)
400
                ff_wms_parse_sdp_a_line(s, p);
401
            if (s->nb_streams > 0) {
402
                if (rt->server_type == RTSP_SERVER_REAL)
403
                    ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
404

    
405
                rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
406
                if (rtsp_st->dynamic_handler &&
407
                    rtsp_st->dynamic_handler->parse_sdp_a_line)
408
                    rtsp_st->dynamic_handler->parse_sdp_a_line(s,
409
                        s->nb_streams - 1,
410
                        rtsp_st->dynamic_protocol_context, buf);
411
            }
412
        }
413
        break;
414
    }
415
}
416

    
417
static int sdp_parse(AVFormatContext *s, const char *content)
418
{
419
    const char *p;
420
    int letter;
421
    /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
422
     * contain long SDP lines containing complete ASF Headers (several
423
     * kB) or arrays of MDPR (RM stream descriptor) headers plus
424
     * "rulebooks" describing their properties. Therefore, the SDP line
425
     * buffer is large.
426
     *
427
     * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
428
     * in rtpdec_xiph.c. */
429
    char buf[16384], *q;
430
    SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
431

    
432
    memset(s1, 0, sizeof(SDPParseState));
433
    p = content;
434
    for (;;) {
435
        p += strspn(p, SPACE_CHARS);
436
        letter = *p;
437
        if (letter == '\0')
438
            break;
439
        p++;
440
        if (*p != '=')
441
            goto next_line;
442
        p++;
443
        /* get the content */
444
        q = buf;
445
        while (*p != '\n' && *p != '\r' && *p != '\0') {
446
            if ((q - buf) < sizeof(buf) - 1)
447
                *q++ = *p;
448
            p++;
449
        }
450
        *q = '\0';
451
        sdp_parse_line(s, s1, letter, buf);
452
    next_line:
453
        while (*p != '\n' && *p != '\0')
454
            p++;
455
        if (*p == '\n')
456
            p++;
457
    }
458
    return 0;
459
}
460

    
461
/* close and free RTSP streams */
462
void ff_rtsp_close_streams(AVFormatContext *s)
463
{
464
    RTSPState *rt = s->priv_data;
465
    int i;
466
    RTSPStream *rtsp_st;
467

    
468
    for (i = 0; i < rt->nb_rtsp_streams; i++) {
469
        rtsp_st = rt->rtsp_streams[i];
470
        if (rtsp_st) {
471
            if (rtsp_st->transport_priv) {
472
                if (s->oformat) {
473
                    AVFormatContext *rtpctx = rtsp_st->transport_priv;
474
                    av_write_trailer(rtpctx);
475
                    if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
476
                        uint8_t *ptr;
477
                        url_close_dyn_buf(rtpctx->pb, &ptr);
478
                        av_free(ptr);
479
                    } else {
480
                        url_fclose(rtpctx->pb);
481
                    }
482
                    av_metadata_free(&rtpctx->streams[0]->metadata);
483
                    av_metadata_free(&rtpctx->metadata);
484
                    av_free(rtpctx->streams[0]);
485
                    av_free(rtpctx);
486
                } else if (rt->transport == RTSP_TRANSPORT_RDT)
487
                    ff_rdt_parse_close(rtsp_st->transport_priv);
488
                else
489
                    rtp_parse_close(rtsp_st->transport_priv);
490
            }
491
            if (rtsp_st->rtp_handle)
492
                url_close(rtsp_st->rtp_handle);
493
            if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
494
                rtsp_st->dynamic_handler->close(
495
                    rtsp_st->dynamic_protocol_context);
496
        }
497
    }
498
    av_free(rt->rtsp_streams);
499
    if (rt->asf_ctx) {
500
        av_close_input_stream (rt->asf_ctx);
501
        rt->asf_ctx = NULL;
502
    }
503
    av_free(rt->recvbuf);
504
}
505

    
506
static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
507
{
508
    RTSPState *rt = s->priv_data;
509
    AVStream *st = NULL;
510

    
511
    /* open the RTP context */
512
    if (rtsp_st->stream_index >= 0)
513
        st = s->streams[rtsp_st->stream_index];
514
    if (!st)
515
        s->ctx_flags |= AVFMTCTX_NOHEADER;
516

    
517
    if (s->oformat) {
518
        rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
519
                                      rtsp_st->rtp_handle,
520
                                      RTSP_TCP_MAX_PACKET_SIZE);
521
        /* Ownership of rtp_handle is passed to the rtp mux context */
522
        rtsp_st->rtp_handle = NULL;
523
    } else if (rt->transport == RTSP_TRANSPORT_RDT)
524
        rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
525
                                            rtsp_st->dynamic_protocol_context,
526
                                            rtsp_st->dynamic_handler);
527
    else
528
        rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
529
                                         rtsp_st->sdp_payload_type,
530
            (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
531
            ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
532

    
533
    if (!rtsp_st->transport_priv) {
534
         return AVERROR(ENOMEM);
535
    } else if (rt->transport != RTSP_TRANSPORT_RDT) {
536
        if (rtsp_st->dynamic_handler) {
537
            rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
538
                                           rtsp_st->dynamic_protocol_context,
539
                                           rtsp_st->dynamic_handler);
540
        }
541
    }
542

    
543
    return 0;
544
}
545

    
546
#if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
547
static int rtsp_probe(AVProbeData *p)
548
{
549
    if (av_strstart(p->filename, "rtsp:", NULL))
550
        return AVPROBE_SCORE_MAX;
551
    return 0;
552
}
553

    
554
static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
555
{
556
    const char *p;
557
    int v;
558

    
559
    p = *pp;
560
    p += strspn(p, SPACE_CHARS);
561
    v = strtol(p, (char **)&p, 10);
562
    if (*p == '-') {
563
        p++;
564
        *min_ptr = v;
565
        v = strtol(p, (char **)&p, 10);
566
        *max_ptr = v;
567
    } else {
568
        *min_ptr = v;
569
        *max_ptr = v;
570
    }
571
    *pp = p;
572
}
573

    
574
/* XXX: only one transport specification is parsed */
575
static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
576
{
577
    char transport_protocol[16];
578
    char profile[16];
579
    char lower_transport[16];
580
    char parameter[16];
581
    RTSPTransportField *th;
582
    char buf[256];
583

    
584
    reply->nb_transports = 0;
585

    
586
    for (;;) {
587
        p += strspn(p, SPACE_CHARS);
588
        if (*p == '\0')
589
            break;
590

    
591
        th = &reply->transports[reply->nb_transports];
592

    
593
        get_word_sep(transport_protocol, sizeof(transport_protocol),
594
                     "/", &p);
595
        if (!strcasecmp (transport_protocol, "rtp")) {
596
            get_word_sep(profile, sizeof(profile), "/;,", &p);
597
            lower_transport[0] = '\0';
598
            /* rtp/avp/<protocol> */
599
            if (*p == '/') {
600
                get_word_sep(lower_transport, sizeof(lower_transport),
601
                             ";,", &p);
602
            }
603
            th->transport = RTSP_TRANSPORT_RTP;
604
        } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
605
                   !strcasecmp (transport_protocol, "x-real-rdt")) {
606
            /* x-pn-tng/<protocol> */
607
            get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
608
            profile[0] = '\0';
609
            th->transport = RTSP_TRANSPORT_RDT;
610
        }
611
        if (!strcasecmp(lower_transport, "TCP"))
612
            th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
613
        else
614
            th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
615

    
616
        if (*p == ';')
617
            p++;
618
        /* get each parameter */
619
        while (*p != '\0' && *p != ',') {
620
            get_word_sep(parameter, sizeof(parameter), "=;,", &p);
621
            if (!strcmp(parameter, "port")) {
622
                if (*p == '=') {
623
                    p++;
624
                    rtsp_parse_range(&th->port_min, &th->port_max, &p);
625
                }
626
            } else if (!strcmp(parameter, "client_port")) {
627
                if (*p == '=') {
628
                    p++;
629
                    rtsp_parse_range(&th->client_port_min,
630
                                     &th->client_port_max, &p);
631
                }
632
            } else if (!strcmp(parameter, "server_port")) {
633
                if (*p == '=') {
634
                    p++;
635
                    rtsp_parse_range(&th->server_port_min,
636
                                     &th->server_port_max, &p);
637
                }
638
            } else if (!strcmp(parameter, "interleaved")) {
639
                if (*p == '=') {
640
                    p++;
641
                    rtsp_parse_range(&th->interleaved_min,
642
                                     &th->interleaved_max, &p);
643
                }
644
            } else if (!strcmp(parameter, "multicast")) {
645
                if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
646
                    th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
647
            } else if (!strcmp(parameter, "ttl")) {
648
                if (*p == '=') {
649
                    p++;
650
                    th->ttl = strtol(p, (char **)&p, 10);
651
                }
652
            } else if (!strcmp(parameter, "destination")) {
653
                if (*p == '=') {
654
                    p++;
655
                    get_word_sep(buf, sizeof(buf), ";,", &p);
656
                    get_sockaddr(buf, &th->destination);
657
                }
658
            } else if (!strcmp(parameter, "source")) {
659
                if (*p == '=') {
660
                    p++;
661
                    get_word_sep(buf, sizeof(buf), ";,", &p);
662
                    av_strlcpy(th->source, buf, sizeof(th->source));
663
                }
664
            }
665

    
666
            while (*p != ';' && *p != '\0' && *p != ',')
667
                p++;
668
            if (*p == ';')
669
                p++;
670
        }
671
        if (*p == ',')
672
            p++;
673

    
674
        reply->nb_transports++;
675
    }
676
}
677

    
678
void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
679
                        HTTPAuthState *auth_state)
680
{
681
    const char *p;
682

    
683
    /* NOTE: we do case independent match for broken servers */
684
    p = buf;
685
    if (av_stristart(p, "Session:", &p)) {
686
        int t;
687
        get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
688
        if (av_stristart(p, ";timeout=", &p) &&
689
            (t = strtol(p, NULL, 10)) > 0) {
690
            reply->timeout = t;
691
        }
692
    } else if (av_stristart(p, "Content-Length:", &p)) {
693
        reply->content_length = strtol(p, NULL, 10);
694
    } else if (av_stristart(p, "Transport:", &p)) {
695
        rtsp_parse_transport(reply, p);
696
    } else if (av_stristart(p, "CSeq:", &p)) {
697
        reply->seq = strtol(p, NULL, 10);
698
    } else if (av_stristart(p, "Range:", &p)) {
699
        rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
700
    } else if (av_stristart(p, "RealChallenge1:", &p)) {
701
        p += strspn(p, SPACE_CHARS);
702
        av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
703
    } else if (av_stristart(p, "Server:", &p)) {
704
        p += strspn(p, SPACE_CHARS);
705
        av_strlcpy(reply->server, p, sizeof(reply->server));
706
    } else if (av_stristart(p, "Notice:", &p) ||
707
               av_stristart(p, "X-Notice:", &p)) {
708
        reply->notice = strtol(p, NULL, 10);
709
    } else if (av_stristart(p, "Location:", &p)) {
710
        p += strspn(p, SPACE_CHARS);
711
        av_strlcpy(reply->location, p , sizeof(reply->location));
712
    } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
713
        p += strspn(p, SPACE_CHARS);
714
        ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
715
    } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
716
        p += strspn(p, SPACE_CHARS);
717
        ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
718
    }
719
}
720

    
721
/* skip a RTP/TCP interleaved packet */
722
void ff_rtsp_skip_packet(AVFormatContext *s)
723
{
724
    RTSPState *rt = s->priv_data;
725
    int ret, len, len1;
726
    uint8_t buf[1024];
727

    
728
    ret = url_read_complete(rt->rtsp_hd, buf, 3);
729
    if (ret != 3)
730
        return;
731
    len = AV_RB16(buf + 1);
732

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

    
735
    /* skip payload */
736
    while (len > 0) {
737
        len1 = len;
738
        if (len1 > sizeof(buf))
739
            len1 = sizeof(buf);
740
        ret = url_read_complete(rt->rtsp_hd, buf, len1);
741
        if (ret != len1)
742
            return;
743
        len -= len1;
744
    }
745
}
746

    
747
int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
748
                       unsigned char **content_ptr,
749
                       int return_on_interleaved_data)
750
{
751
    RTSPState *rt = s->priv_data;
752
    char buf[4096], buf1[1024], *q;
753
    unsigned char ch;
754
    const char *p;
755
    int ret, content_length, line_count = 0;
756
    unsigned char *content = NULL;
757

    
758
    memset(reply, 0, sizeof(*reply));
759

    
760
    /* parse reply (XXX: use buffers) */
761
    rt->last_reply[0] = '\0';
762
    for (;;) {
763
        q = buf;
764
        for (;;) {
765
            ret = url_read_complete(rt->rtsp_hd, &ch, 1);
766
#ifdef DEBUG_RTP_TCP
767
            dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
768
#endif
769
            if (ret != 1)
770
                return AVERROR_EOF;
771
            if (ch == '\n')
772
                break;
773
            if (ch == '$') {
774
                /* XXX: only parse it if first char on line ? */
775
                if (return_on_interleaved_data) {
776
                    return 1;
777
                } else
778
                    ff_rtsp_skip_packet(s);
779
            } else if (ch != '\r') {
780
                if ((q - buf) < sizeof(buf) - 1)
781
                    *q++ = ch;
782
            }
783
        }
784
        *q = '\0';
785

    
786
        dprintf(s, "line='%s'\n", buf);
787

    
788
        /* test if last line */
789
        if (buf[0] == '\0')
790
            break;
791
        p = buf;
792
        if (line_count == 0) {
793
            /* get reply code */
794
            get_word(buf1, sizeof(buf1), &p);
795
            get_word(buf1, sizeof(buf1), &p);
796
            reply->status_code = atoi(buf1);
797
            av_strlcpy(reply->reason, p, sizeof(reply->reason));
798
        } else {
799
            ff_rtsp_parse_line(reply, p, &rt->auth_state);
800
            av_strlcat(rt->last_reply, p,    sizeof(rt->last_reply));
801
            av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
802
        }
803
        line_count++;
804
    }
805

    
806
    if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
807
        av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
808

    
809
    content_length = reply->content_length;
810
    if (content_length > 0) {
811
        /* leave some room for a trailing '\0' (useful for simple parsing) */
812
        content = av_malloc(content_length + 1);
813
        (void)url_read_complete(rt->rtsp_hd, content, content_length);
814
        content[content_length] = '\0';
815
    }
816
    if (content_ptr)
817
        *content_ptr = content;
818
    else
819
        av_free(content);
820

    
821
    if (rt->seq != reply->seq) {
822
        av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
823
            rt->seq, reply->seq);
824
    }
825

    
826
    /* EOS */
827
    if (reply->notice == 2101 /* End-of-Stream Reached */      ||
828
        reply->notice == 2104 /* Start-of-Stream Reached */    ||
829
        reply->notice == 2306 /* Continuous Feed Terminated */) {
830
        rt->state = RTSP_STATE_IDLE;
831
    } else if (reply->notice >= 4400 && reply->notice < 5500) {
832
        return AVERROR(EIO); /* data or server error */
833
    } else if (reply->notice == 2401 /* Ticket Expired */ ||
834
             (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
835
        return AVERROR(EPERM);
836

    
837
    return 0;
838
}
839

    
840
int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
841
                                        const char *method, const char *url,
842
                                        const char *headers,
843
                                        const unsigned char *send_content,
844
                                        int send_content_length)
845
{
846
    RTSPState *rt = s->priv_data;
847
    char buf[4096], *out_buf;
848
    char base64buf[AV_BASE64_SIZE(sizeof(buf))];
849

    
850
    /* Add in RTSP headers */
851
    out_buf = buf;
852
    rt->seq++;
853
    snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
854
    if (headers)
855
        av_strlcat(buf, headers, sizeof(buf));
856
    av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
857
    if (rt->session_id[0] != '\0' && (!headers ||
858
        !strstr(headers, "\nIf-Match:"))) {
859
        av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
860
    }
861
    if (rt->auth[0]) {
862
        char *str = ff_http_auth_create_response(&rt->auth_state,
863
                                                 rt->auth, url, method);
864
        if (str)
865
            av_strlcat(buf, str, sizeof(buf));
866
        av_free(str);
867
    }
868
    if (send_content_length > 0 && send_content)
869
        av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
870
    av_strlcat(buf, "\r\n", sizeof(buf));
871

    
872
    /* base64 encode rtsp if tunneling */
873
    if (rt->control_transport == RTSP_MODE_TUNNEL) {
874
        av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
875
        out_buf = base64buf;
876
    }
877

    
878
    dprintf(s, "Sending:\n%s--\n", buf);
879

    
880
    url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
881
    if (send_content_length > 0 && send_content) {
882
        if (rt->control_transport == RTSP_MODE_TUNNEL) {
883
            av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
884
                                    "with content data not supported\n");
885
            return AVERROR_PATCHWELCOME;
886
        }
887
        url_write(rt->rtsp_hd_out, send_content, send_content_length);
888
    }
889
    rt->last_cmd_time = av_gettime();
890

    
891
    return 0;
892
}
893

    
894
int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
895
                           const char *url, const char *headers)
896
{
897
    return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
898
}
899

    
900
int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
901
                     const char *headers, RTSPMessageHeader *reply,
902
                     unsigned char **content_ptr)
903
{
904
    return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
905
                                         content_ptr, NULL, 0);
906
}
907

    
908
int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
909
                                  const char *method, const char *url,
910
                                  const char *header,
911
                                  RTSPMessageHeader *reply,
912
                                  unsigned char **content_ptr,
913
                                  const unsigned char *send_content,
914
                                  int send_content_length)
915
{
916
    RTSPState *rt = s->priv_data;
917
    HTTPAuthType cur_auth_type;
918
    int ret;
919

    
920
retry:
921
    cur_auth_type = rt->auth_state.auth_type;
922
    if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
923
                                                   send_content,
924
                                                   send_content_length)))
925
        return ret;
926

    
927
    if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
928
        return ret;
929

    
930
    if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
931
        rt->auth_state.auth_type != HTTP_AUTH_NONE)
932
        goto retry;
933

    
934
    if (reply->status_code > 400){
935
        av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
936
               method,
937
               reply->status_code,
938
               reply->reason);
939
        av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
940
    }
941

    
942
    return 0;
943
}
944

    
945
/**
946
 * @return 0 on success, <0 on error, 1 if protocol is unavailable.
947
 */
948
static int make_setup_request(AVFormatContext *s, const char *host, int port,
949
                              int lower_transport, const char *real_challenge)
950
{
951
    RTSPState *rt = s->priv_data;
952
    int rtx, j, i, err, interleave = 0;
953
    RTSPStream *rtsp_st;
954
    RTSPMessageHeader reply1, *reply = &reply1;
955
    char cmd[2048];
956
    const char *trans_pref;
957

    
958
    if (rt->transport == RTSP_TRANSPORT_RDT)
959
        trans_pref = "x-pn-tng";
960
    else
961
        trans_pref = "RTP/AVP";
962

    
963
    /* default timeout: 1 minute */
964
    rt->timeout = 60;
965

    
966
    /* for each stream, make the setup request */
967
    /* XXX: we assume the same server is used for the control of each
968
     * RTSP stream */
969

    
970
    for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
971
        char transport[2048];
972

    
973
        /**
974
         * WMS serves all UDP data over a single connection, the RTX, which
975
         * isn't necessarily the first in the SDP but has to be the first
976
         * to be set up, else the second/third SETUP will fail with a 461.
977
         */
978
        if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
979
             rt->server_type == RTSP_SERVER_WMS) {
980
            if (i == 0) {
981
                /* rtx first */
982
                for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
983
                    int len = strlen(rt->rtsp_streams[rtx]->control_url);
984
                    if (len >= 4 &&
985
                        !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
986
                                "/rtx"))
987
                        break;
988
                }
989
                if (rtx == rt->nb_rtsp_streams)
990
                    return -1; /* no RTX found */
991
                rtsp_st = rt->rtsp_streams[rtx];
992
            } else
993
                rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
994
        } else
995
            rtsp_st = rt->rtsp_streams[i];
996

    
997
        /* RTP/UDP */
998
        if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
999
            char buf[256];
1000

    
1001
            if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1002
                port = reply->transports[0].client_port_min;
1003
                goto have_port;
1004
            }
1005

    
1006
            /* first try in specified port range */
1007
            if (RTSP_RTP_PORT_MIN != 0) {
1008
                while (j <= RTSP_RTP_PORT_MAX) {
1009
                    ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1010
                                "?localport=%d", j);
1011
                    /* we will use two ports per rtp stream (rtp and rtcp) */
1012
                    j += 2;
1013
                    if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
1014
                        goto rtp_opened;
1015
                }
1016
            }
1017

    
1018
#if 0
1019
            /* then try on any port */
1020
            if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
1021
                err = AVERROR_INVALIDDATA;
1022
                goto fail;
1023
            }
1024
#endif
1025

    
1026
        rtp_opened:
1027
            port = rtp_get_local_port(rtsp_st->rtp_handle);
1028
        have_port:
1029
            snprintf(transport, sizeof(transport) - 1,
1030
                     "%s/UDP;", trans_pref);
1031
            if (rt->server_type != RTSP_SERVER_REAL)
1032
                av_strlcat(transport, "unicast;", sizeof(transport));
1033
            av_strlcatf(transport, sizeof(transport),
1034
                     "client_port=%d", port);
1035
            if (rt->transport == RTSP_TRANSPORT_RTP &&
1036
                !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1037
                av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1038
        }
1039

    
1040
        /* RTP/TCP */
1041
        else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1042
            /** For WMS streams, the application streams are only used for
1043
             * UDP. When trying to set it up for TCP streams, the server
1044
             * will return an error. Therefore, we skip those streams. */
1045
            if (rt->server_type == RTSP_SERVER_WMS &&
1046
                s->streams[rtsp_st->stream_index]->codec->codec_type ==
1047
                    AVMEDIA_TYPE_DATA)
1048
                continue;
1049
            snprintf(transport, sizeof(transport) - 1,
1050
                     "%s/TCP;", trans_pref);
1051
            if (rt->server_type == RTSP_SERVER_WMS)
1052
                av_strlcat(transport, "unicast;", sizeof(transport));
1053
            av_strlcatf(transport, sizeof(transport),
1054
                        "interleaved=%d-%d",
1055
                        interleave, interleave + 1);
1056
            interleave += 2;
1057
        }
1058

    
1059
        else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1060
            snprintf(transport, sizeof(transport) - 1,
1061
                     "%s/UDP;multicast", trans_pref);
1062
        }
1063
        if (s->oformat) {
1064
            av_strlcat(transport, ";mode=receive", sizeof(transport));
1065
        } else if (rt->server_type == RTSP_SERVER_REAL ||
1066
                   rt->server_type == RTSP_SERVER_WMS)
1067
            av_strlcat(transport, ";mode=play", sizeof(transport));
1068
        snprintf(cmd, sizeof(cmd),
1069
                 "Transport: %s\r\n",
1070
                 transport);
1071
        if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
1072
            char real_res[41], real_csum[9];
1073
            ff_rdt_calc_response_and_checksum(real_res, real_csum,
1074
                                              real_challenge);
1075
            av_strlcatf(cmd, sizeof(cmd),
1076
                        "If-Match: %s\r\n"
1077
                        "RealChallenge2: %s, sd=%s\r\n",
1078
                        rt->session_id, real_res, real_csum);
1079
        }
1080
        ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1081
        if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1082
            err = 1;
1083
            goto fail;
1084
        } else if (reply->status_code != RTSP_STATUS_OK ||
1085
                   reply->nb_transports != 1) {
1086
            err = AVERROR_INVALIDDATA;
1087
            goto fail;
1088
        }
1089

    
1090
        /* XXX: same protocol for all streams is required */
1091
        if (i > 0) {
1092
            if (reply->transports[0].lower_transport != rt->lower_transport ||
1093
                reply->transports[0].transport != rt->transport) {
1094
                err = AVERROR_INVALIDDATA;
1095
                goto fail;
1096
            }
1097
        } else {
1098
            rt->lower_transport = reply->transports[0].lower_transport;
1099
            rt->transport = reply->transports[0].transport;
1100
        }
1101

    
1102
        /* close RTP connection if not chosen */
1103
        if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
1104
            (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
1105
            url_close(rtsp_st->rtp_handle);
1106
            rtsp_st->rtp_handle = NULL;
1107
        }
1108

    
1109
        switch(reply->transports[0].lower_transport) {
1110
        case RTSP_LOWER_TRANSPORT_TCP:
1111
            rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1112
            rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1113
            break;
1114

    
1115
        case RTSP_LOWER_TRANSPORT_UDP: {
1116
            char url[1024];
1117

    
1118
            /* Use source address if specified */
1119
            if (reply->transports[0].source[0]) {
1120
                ff_url_join(url, sizeof(url), "rtp", NULL,
1121
                            reply->transports[0].source,
1122
                            reply->transports[0].server_port_min, NULL);
1123
            } else {
1124
                ff_url_join(url, sizeof(url), "rtp", NULL, host,
1125
                            reply->transports[0].server_port_min, NULL);
1126
            }
1127
            if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1128
                rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1129
                err = AVERROR_INVALIDDATA;
1130
                goto fail;
1131
            }
1132
            /* Try to initialize the connection state in a
1133
             * potential NAT router by sending dummy packets.
1134
             * RTP/RTCP dummy packets are used for RDT, too.
1135
             */
1136
            if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
1137
                rtp_send_punch_packets(rtsp_st->rtp_handle);
1138
            break;
1139
        }
1140
        case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
1141
            char url[1024], namebuf[50];
1142
            struct sockaddr_storage addr;
1143
            int port, ttl;
1144

    
1145
            if (reply->transports[0].destination.ss_family) {
1146
                addr      = reply->transports[0].destination;
1147
                port      = reply->transports[0].port_min;
1148
                ttl       = reply->transports[0].ttl;
1149
            } else {
1150
                addr      = rtsp_st->sdp_ip;
1151
                port      = rtsp_st->sdp_port;
1152
                ttl       = rtsp_st->sdp_ttl;
1153
            }
1154
            getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1155
                        namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1156
            ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
1157
                        port, "?ttl=%d", ttl);
1158
            if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1159
                err = AVERROR_INVALIDDATA;
1160
                goto fail;
1161
            }
1162
            break;
1163
        }
1164
        }
1165

    
1166
        if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
1167
            goto fail;
1168
    }
1169

    
1170
    if (reply->timeout > 0)
1171
        rt->timeout = reply->timeout;
1172

    
1173
    if (rt->server_type == RTSP_SERVER_REAL)
1174
        rt->need_subscription = 1;
1175

    
1176
    return 0;
1177

    
1178
fail:
1179
    for (i = 0; i < rt->nb_rtsp_streams; i++) {
1180
        if (rt->rtsp_streams[i]->rtp_handle) {
1181
            url_close(rt->rtsp_streams[i]->rtp_handle);
1182
            rt->rtsp_streams[i]->rtp_handle = NULL;
1183
        }
1184
    }
1185
    return err;
1186
}
1187

    
1188
static int rtsp_read_play(AVFormatContext *s)
1189
{
1190
    RTSPState *rt = s->priv_data;
1191
    RTSPMessageHeader reply1, *reply = &reply1;
1192
    int i;
1193
    char cmd[1024];
1194

    
1195
    av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1196
    rt->nb_byes = 0;
1197

    
1198
    if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1199
        if (rt->state == RTSP_STATE_PAUSED) {
1200
            cmd[0] = 0;
1201
        } else {
1202
            snprintf(cmd, sizeof(cmd),
1203
                     "Range: npt=%0.3f-\r\n",
1204
                     (double)rt->seek_timestamp / AV_TIME_BASE);
1205
        }
1206
        ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
1207
        if (reply->status_code != RTSP_STATUS_OK) {
1208
            return -1;
1209
        }
1210
        if (rt->transport == RTSP_TRANSPORT_RTP) {
1211
            for (i = 0; i < rt->nb_rtsp_streams; i++) {
1212
                RTSPStream *rtsp_st = rt->rtsp_streams[i];
1213
                RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1214
                AVStream *st = NULL;
1215
                if (!rtpctx)
1216
                    continue;
1217
                if (rtsp_st->stream_index >= 0)
1218
                    st = s->streams[rtsp_st->stream_index];
1219
                ff_rtp_reset_packet_queue(rtpctx);
1220
                if (reply->range_start != AV_NOPTS_VALUE) {
1221
                    rtpctx->last_rtcp_ntp_time  = AV_NOPTS_VALUE;
1222
                    rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
1223
                    if (st)
1224
                        rtpctx->range_start_offset =
1225
                            av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
1226
                                         st->time_base);
1227
                }
1228
            }
1229
        }
1230
    }
1231
    rt->state = RTSP_STATE_STREAMING;
1232
    return 0;
1233
}
1234

    
1235
static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
1236
{
1237
    RTSPState *rt = s->priv_data;
1238
    char cmd[1024];
1239
    unsigned char *content = NULL;
1240
    int ret;
1241

    
1242
    /* describe the stream */
1243
    snprintf(cmd, sizeof(cmd),
1244
             "Accept: application/sdp\r\n");
1245
    if (rt->server_type == RTSP_SERVER_REAL) {
1246
        /**
1247
         * The Require: attribute is needed for proper streaming from
1248
         * Realmedia servers.
1249
         */
1250
        av_strlcat(cmd,
1251
                   "Require: com.real.retain-entity-for-setup\r\n",
1252
                   sizeof(cmd));
1253
    }
1254
    ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
1255
    if (!content)
1256
        return AVERROR_INVALIDDATA;
1257
    if (reply->status_code != RTSP_STATUS_OK) {
1258
        av_freep(&content);
1259
        return AVERROR_INVALIDDATA;
1260
    }
1261

    
1262
    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
1263
    /* now we got the SDP description, we parse it */
1264
    ret = sdp_parse(s, (const char *)content);
1265
    av_freep(&content);
1266
    if (ret < 0)
1267
        return AVERROR_INVALIDDATA;
1268

    
1269
    return 0;
1270
}
1271

    
1272
static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
1273
{
1274
    RTSPState *rt = s->priv_data;
1275
    RTSPMessageHeader reply1, *reply = &reply1;
1276
    int i;
1277
    char *sdp;
1278
    AVFormatContext sdp_ctx, *ctx_array[1];
1279

    
1280
    s->start_time_realtime = av_gettime();
1281

    
1282
    /* Announce the stream */
1283
    sdp = av_mallocz(SDP_MAX_SIZE);
1284
    if (sdp == NULL)
1285
        return AVERROR(ENOMEM);
1286
    /* We create the SDP based on the RTSP AVFormatContext where we
1287
     * aren't allowed to change the filename field. (We create the SDP
1288
     * based on the RTSP context since the contexts for the RTP streams
1289
     * don't exist yet.) In order to specify a custom URL with the actual
1290
     * peer IP instead of the originally specified hostname, we create
1291
     * a temporary copy of the AVFormatContext, where the custom URL is set.
1292
     *
1293
     * FIXME: Create the SDP without copying the AVFormatContext.
1294
     * This either requires setting up the RTP stream AVFormatContexts
1295
     * already here (complicating things immensely) or getting a more
1296
     * flexible SDP creation interface.
1297
     */
1298
    sdp_ctx = *s;
1299
    ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
1300
                "rtsp", NULL, addr, -1, NULL);
1301
    ctx_array[0] = &sdp_ctx;
1302
    if (avf_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
1303
        av_free(sdp);
1304
        return AVERROR_INVALIDDATA;
1305
    }
1306
    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
1307
    ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
1308
                                  "Content-Type: application/sdp\r\n",
1309
                                  reply, NULL, sdp, strlen(sdp));
1310
    av_free(sdp);
1311
    if (reply->status_code != RTSP_STATUS_OK)
1312
        return AVERROR_INVALIDDATA;
1313

    
1314
    /* Set up the RTSPStreams for each AVStream */
1315
    for (i = 0; i < s->nb_streams; i++) {
1316
        RTSPStream *rtsp_st;
1317
        AVStream *st = s->streams[i];
1318

    
1319
        rtsp_st = av_mallocz(sizeof(RTSPStream));
1320
        if (!rtsp_st)
1321
            return AVERROR(ENOMEM);
1322
        dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
1323

    
1324
        st->priv_data = rtsp_st;
1325
        rtsp_st->stream_index = i;
1326

    
1327
        av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
1328
        /* Note, this must match the relative uri set in the sdp content */
1329
        av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
1330
                    "/streamid=%d", i);
1331
    }
1332

    
1333
    return 0;
1334
}
1335

    
1336
void ff_rtsp_close_connections(AVFormatContext *s)
1337
{
1338
    RTSPState *rt = s->priv_data;
1339
    if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
1340
    url_close(rt->rtsp_hd);
1341
    rt->rtsp_hd = rt->rtsp_hd_out = NULL;
1342
}
1343

    
1344
int ff_rtsp_connect(AVFormatContext *s)
1345
{
1346
    RTSPState *rt = s->priv_data;
1347
    char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
1348
    char *option_list, *option, *filename;
1349
    int port, err, tcp_fd;
1350
    RTSPMessageHeader reply1 = {0}, *reply = &reply1;
1351
    int lower_transport_mask = 0;
1352
    char real_challenge[64];
1353
    struct sockaddr_storage peer;
1354
    socklen_t peer_len = sizeof(peer);
1355

    
1356
    if (!ff_network_init())
1357
        return AVERROR(EIO);
1358
redirect:
1359
    rt->control_transport = RTSP_MODE_PLAIN;
1360
    /* extract hostname and port */
1361
    av_url_split(NULL, 0, auth, sizeof(auth),
1362
                 host, sizeof(host), &port, path, sizeof(path), s->filename);
1363
    if (*auth) {
1364
        av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1365
    }
1366
    if (port < 0)
1367
        port = RTSP_DEFAULT_PORT;
1368

    
1369
    /* search for options */
1370
    option_list = strrchr(path, '?');
1371
    if (option_list) {
1372
        /* Strip out the RTSP specific options, write out the rest of
1373
         * the options back into the same string. */
1374
        filename = option_list;
1375
        while (option_list) {
1376
            /* move the option pointer */
1377
            option = ++option_list;
1378
            option_list = strchr(option_list, '&');
1379
            if (option_list)
1380
                *option_list = 0;
1381

    
1382
            /* handle the options */
1383
            if (!strcmp(option, "udp")) {
1384
                lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
1385
            } else if (!strcmp(option, "multicast")) {
1386
                lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
1387
            } else if (!strcmp(option, "tcp")) {
1388
                lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1389
            } else if(!strcmp(option, "http")) {
1390
                lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
1391
                rt->control_transport = RTSP_MODE_TUNNEL;
1392
            } else {
1393
                /* Write options back into the buffer, using memmove instead
1394
                 * of strcpy since the strings may overlap. */
1395
                int len = strlen(option);
1396
                memmove(++filename, option, len);
1397
                filename += len;
1398
                if (option_list) *filename = '&';
1399
            }
1400
        }
1401
        *filename = 0;
1402
    }
1403

    
1404
    if (!lower_transport_mask)
1405
        lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1406

    
1407
    if (s->oformat) {
1408
        /* Only UDP or TCP - UDP multicast isn't supported. */
1409
        lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1410
                                (1 << RTSP_LOWER_TRANSPORT_TCP);
1411
        if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
1412
            av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1413
                                    "only UDP and TCP are supported for output.\n");
1414
            err = AVERROR(EINVAL);
1415
            goto fail;
1416
        }
1417
    }
1418

    
1419
    /* Construct the URI used in request; this is similar to s->filename,
1420
     * but with authentication credentials removed and RTSP specific options
1421
     * stripped out. */
1422
    ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
1423
                host, port, "%s", path);
1424

    
1425
    if (rt->control_transport == RTSP_MODE_TUNNEL) {
1426
        /* set up initial handshake for tunneling */
1427
        char httpname[1024];
1428
        char sessioncookie[17];
1429
        char headers[1024];
1430

    
1431
        ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
1432
        snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1433
                 av_get_random_seed(), av_get_random_seed());
1434

    
1435
        /* GET requests */
1436
        if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
1437
            err = AVERROR(EIO);
1438
            goto fail;
1439
        }
1440

    
1441
        /* generate GET headers */
1442
        snprintf(headers, sizeof(headers),
1443
                 "x-sessioncookie: %s\r\n"
1444
                 "Accept: application/x-rtsp-tunnelled\r\n"
1445
                 "Pragma: no-cache\r\n"
1446
                 "Cache-Control: no-cache\r\n",
1447
                 sessioncookie);
1448
        ff_http_set_headers(rt->rtsp_hd, headers);
1449

    
1450
        /* complete the connection */
1451
        if (url_connect(rt->rtsp_hd)) {
1452
            err = AVERROR(EIO);
1453
            goto fail;
1454
        }
1455

    
1456
        /* POST requests */
1457
        if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
1458
            err = AVERROR(EIO);
1459
            goto fail;
1460
        }
1461

    
1462
        /* generate POST headers */
1463
        snprintf(headers, sizeof(headers),
1464
                 "x-sessioncookie: %s\r\n"
1465
                 "Content-Type: application/x-rtsp-tunnelled\r\n"
1466
                 "Pragma: no-cache\r\n"
1467
                 "Cache-Control: no-cache\r\n"
1468
                 "Content-Length: 32767\r\n"
1469
                 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1470
                 sessioncookie);
1471
        ff_http_set_headers(rt->rtsp_hd_out, headers);
1472
        ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
1473

    
1474
        /* Initialize the authentication state for the POST session. The HTTP
1475
         * protocol implementation doesn't properly handle multi-pass
1476
         * authentication for POST requests, since it would require one of
1477
         * the following:
1478
         * - implementing Expect: 100-continue, which many HTTP servers
1479
         *   don't support anyway, even less the RTSP servers that do HTTP
1480
         *   tunneling
1481
         * - sending the whole POST data until getting a 401 reply specifying
1482
         *   what authentication method to use, then resending all that data
1483
         * - waiting for potential 401 replies directly after sending the
1484
         *   POST header (waiting for some unspecified time)
1485
         * Therefore, we copy the full auth state, which works for both basic
1486
         * and digest. (For digest, we would have to synchronize the nonce
1487
         * count variable between the two sessions, if we'd do more requests
1488
         * with the original session, though.)
1489
         */
1490
        ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
1491

    
1492
        /* complete the connection */
1493
        if (url_connect(rt->rtsp_hd_out)) {
1494
            err = AVERROR(EIO);
1495
            goto fail;
1496
        }
1497
    } else {
1498
        /* open the tcp connection */
1499
        ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
1500
        if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
1501
            err = AVERROR(EIO);
1502
            goto fail;
1503
        }
1504
        rt->rtsp_hd_out = rt->rtsp_hd;
1505
    }
1506
    rt->seq = 0;
1507

    
1508
    tcp_fd = url_get_file_handle(rt->rtsp_hd);
1509
    if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1510
        getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1511
                    NULL, 0, NI_NUMERICHOST);
1512
    }
1513

    
1514
    /* request options supported by the server; this also detects server
1515
     * type */
1516
    for (rt->server_type = RTSP_SERVER_RTP;;) {
1517
        cmd[0] = 0;
1518
        if (rt->server_type == RTSP_SERVER_REAL)
1519
            av_strlcat(cmd,
1520
                       /**
1521
                        * The following entries are required for proper
1522
                        * streaming from a Realmedia server. They are
1523
                        * interdependent in some way although we currently
1524
                        * don't quite understand how. Values were copied
1525
                        * from mplayer SVN r23589.
1526
                        * @param CompanyID is a 16-byte ID in base64
1527
                        * @param ClientChallenge is a 16-byte ID in hex
1528
                        */
1529
                       "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1530
                       "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1531
                       "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1532
                       "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1533
                       sizeof(cmd));
1534
        ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1535
        if (reply->status_code != RTSP_STATUS_OK) {
1536
            err = AVERROR_INVALIDDATA;
1537
            goto fail;
1538
        }
1539

    
1540
        /* detect server type if not standard-compliant RTP */
1541
        if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1542
            rt->server_type = RTSP_SERVER_REAL;
1543
            continue;
1544
        } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
1545
            rt->server_type = RTSP_SERVER_WMS;
1546
        } else if (rt->server_type == RTSP_SERVER_REAL)
1547
            strcpy(real_challenge, reply->real_challenge);
1548
        break;
1549
    }
1550

    
1551
    if (s->iformat)
1552
        err = rtsp_setup_input_streams(s, reply);
1553
    else
1554
        err = rtsp_setup_output_streams(s, host);
1555
    if (err)
1556
        goto fail;
1557

    
1558
    do {
1559
        int lower_transport = ff_log2_tab[lower_transport_mask &
1560
                                  ~(lower_transport_mask - 1)];
1561

    
1562
        err = make_setup_request(s, host, port, lower_transport,
1563
                                 rt->server_type == RTSP_SERVER_REAL ?
1564
                                     real_challenge : NULL);
1565
        if (err < 0)
1566
            goto fail;
1567
        lower_transport_mask &= ~(1 << lower_transport);
1568
        if (lower_transport_mask == 0 && err == 1) {
1569
            err = FF_NETERROR(EPROTONOSUPPORT);
1570
            goto fail;
1571
        }
1572
    } while (err);
1573

    
1574
    rt->state = RTSP_STATE_IDLE;
1575
    rt->seek_timestamp = 0; /* default is to start stream at position zero */
1576
    return 0;
1577
 fail:
1578
    ff_rtsp_close_streams(s);
1579
    ff_rtsp_close_connections(s);
1580
    if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1581
        av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1582
        av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1583
               reply->status_code,
1584
               s->filename);
1585
        goto redirect;
1586
    }
1587
    ff_network_close();
1588
    return err;
1589
}
1590
#endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1591

    
1592
static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1593
                           uint8_t *buf, int buf_size, int64_t wait_end)
1594
{
1595
    RTSPState *rt = s->priv_data;
1596
    RTSPStream *rtsp_st;
1597
    fd_set rfds;
1598
    int fd, fd_rtcp, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
1599
    struct timeval tv;
1600

    
1601
    for (;;) {
1602
        if (url_interrupt_cb())
1603
            return AVERROR(EINTR);
1604
        if (wait_end && wait_end - av_gettime() < 0)
1605
            return AVERROR(EAGAIN);
1606
        FD_ZERO(&rfds);
1607
        if (rt->rtsp_hd) {
1608
            tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
1609
            FD_SET(tcp_fd, &rfds);
1610
        } else {
1611
            fd_max = 0;
1612
            tcp_fd = -1;
1613
        }
1614
        for (i = 0; i < rt->nb_rtsp_streams; i++) {
1615
            rtsp_st = rt->rtsp_streams[i];
1616
            if (rtsp_st->rtp_handle) {
1617
                fd = url_get_file_handle(rtsp_st->rtp_handle);
1618
                fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1619
                if (FFMAX(fd, fd_rtcp) > fd_max)
1620
                    fd_max = FFMAX(fd, fd_rtcp);
1621
                FD_SET(fd, &rfds);
1622
                FD_SET(fd_rtcp, &rfds);
1623
            }
1624
        }
1625
        tv.tv_sec = 0;
1626
        tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
1627
        n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1628
        if (n > 0) {
1629
            timeout_cnt = 0;
1630
            for (i = 0; i < rt->nb_rtsp_streams; i++) {
1631
                rtsp_st = rt->rtsp_streams[i];
1632
                if (rtsp_st->rtp_handle) {
1633
                    fd = url_get_file_handle(rtsp_st->rtp_handle);
1634
                    fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
1635
                    if (FD_ISSET(fd_rtcp, &rfds) || FD_ISSET(fd, &rfds)) {
1636
                        ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1637
                        if (ret > 0) {
1638
                            *prtsp_st = rtsp_st;
1639
                            return ret;
1640
                        }
1641
                    }
1642
                }
1643
            }
1644
#if CONFIG_RTSP_DEMUXER
1645
            if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
1646
                RTSPMessageHeader reply;
1647

    
1648
                ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
1649
                if (ret < 0)
1650
                    return ret;
1651
                /* XXX: parse message */
1652
                if (rt->state != RTSP_STATE_STREAMING)
1653
                    return 0;
1654
            }
1655
#endif
1656
        } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1657
            return FF_NETERROR(ETIMEDOUT);
1658
        } else if (n < 0 && errno != EINTR)
1659
            return AVERROR(errno);
1660
    }
1661
}
1662

    
1663
static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1664
                           uint8_t *buf, int buf_size);
1665

    
1666
static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
1667
{
1668
    RTSPState *rt = s->priv_data;
1669
    int ret, len;
1670
    RTSPStream *rtsp_st, *first_queue_st = NULL;
1671
    int64_t wait_end = 0;
1672

    
1673
    if (rt->nb_byes == rt->nb_rtsp_streams)
1674
        return AVERROR_EOF;
1675

    
1676
    /* get next frames from the same RTP packet */
1677
    if (rt->cur_transport_priv) {
1678
        if (rt->transport == RTSP_TRANSPORT_RDT) {
1679
            ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1680
        } else
1681
            ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
1682
        if (ret == 0) {
1683
            rt->cur_transport_priv = NULL;
1684
            return 0;
1685
        } else if (ret == 1) {
1686
            return 0;
1687
        } else
1688
            rt->cur_transport_priv = NULL;
1689
    }
1690

    
1691
    if (rt->transport == RTSP_TRANSPORT_RTP) {
1692
        int i;
1693
        int64_t first_queue_time = 0;
1694
        for (i = 0; i < rt->nb_rtsp_streams; i++) {
1695
            RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
1696
            int64_t queue_time = ff_rtp_queued_packet_time(rtpctx);
1697
            if (queue_time && (queue_time - first_queue_time < 0 ||
1698
                               !first_queue_time)) {
1699
                first_queue_time = queue_time;
1700
                first_queue_st   = rt->rtsp_streams[i];
1701
            }
1702
        }
1703
        if (first_queue_time)
1704
            wait_end = first_queue_time + s->max_delay;
1705
    }
1706

    
1707
    /* read next RTP packet */
1708
 redo:
1709
    if (!rt->recvbuf) {
1710
        rt->recvbuf = av_malloc(RECVBUF_SIZE);
1711
        if (!rt->recvbuf)
1712
            return AVERROR(ENOMEM);
1713
    }
1714

    
1715
    switch(rt->lower_transport) {
1716
    default:
1717
#if CONFIG_RTSP_DEMUXER
1718
    case RTSP_LOWER_TRANSPORT_TCP:
1719
        len = tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
1720
        break;
1721
#endif
1722
    case RTSP_LOWER_TRANSPORT_UDP:
1723
    case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
1724
        len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
1725
        if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
1726
            rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
1727
        break;
1728
    }
1729
    if (len == AVERROR(EAGAIN) && first_queue_st &&
1730
        rt->transport == RTSP_TRANSPORT_RTP) {
1731
        rtsp_st = first_queue_st;
1732
        ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
1733
        goto end;
1734
    }
1735
    if (len < 0)
1736
        return len;
1737
    if (len == 0)
1738
        return AVERROR_EOF;
1739
    if (rt->transport == RTSP_TRANSPORT_RDT) {
1740
        ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
1741
    } else {
1742
        ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
1743
        if (ret < 0) {
1744
            /* Either bad packet, or a RTCP packet. Check if the
1745
             * first_rtcp_ntp_time field was initialized. */
1746
            RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1747
            if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
1748
                /* first_rtcp_ntp_time has been initialized for this stream,
1749
                 * copy the same value to all other uninitialized streams,
1750
                 * in order to map their timestamp origin to the same ntp time
1751
                 * as this one. */
1752
                int i;
1753
                for (i = 0; i < rt->nb_rtsp_streams; i++) {
1754
                    RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
1755
                    if (rtpctx2 &&
1756
                        rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
1757
                        rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
1758
                }
1759
            }
1760
            if (ret == -RTCP_BYE) {
1761
                rt->nb_byes++;
1762

    
1763
                av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
1764
                       rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
1765

    
1766
                if (rt->nb_byes == rt->nb_rtsp_streams)
1767
                    return AVERROR_EOF;
1768
            }
1769
        }
1770
    }
1771
end:
1772
    if (ret < 0)
1773
        goto redo;
1774
    if (ret == 1)
1775
        /* more packets may follow, so we save the RTP context */
1776
        rt->cur_transport_priv = rtsp_st->transport_priv;
1777

    
1778
    return ret;
1779
}
1780

    
1781
#if CONFIG_RTSP_DEMUXER
1782
static int rtsp_read_header(AVFormatContext *s,
1783
                            AVFormatParameters *ap)
1784
{
1785
    RTSPState *rt = s->priv_data;
1786
    int ret;
1787

    
1788
    ret = ff_rtsp_connect(s);
1789
    if (ret)
1790
        return ret;
1791

    
1792
    rt->real_setup_cache = av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
1793
    if (!rt->real_setup_cache)
1794
        return AVERROR(ENOMEM);
1795
    rt->real_setup = rt->real_setup_cache + s->nb_streams * sizeof(*rt->real_setup);
1796

    
1797
    if (ap->initial_pause) {
1798
         /* do not start immediately */
1799
    } else {
1800
         if (rtsp_read_play(s) < 0) {
1801
            ff_rtsp_close_streams(s);
1802
            ff_rtsp_close_connections(s);
1803
            return AVERROR_INVALIDDATA;
1804
        }
1805
    }
1806

    
1807
    return 0;
1808
}
1809

    
1810
static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1811
                           uint8_t *buf, int buf_size)
1812
{
1813
    RTSPState *rt = s->priv_data;
1814
    int id, len, i, ret;
1815
    RTSPStream *rtsp_st;
1816

    
1817
#ifdef DEBUG_RTP_TCP
1818
    dprintf(s, "tcp_read_packet:\n");
1819
#endif
1820
redo:
1821
    for (;;) {
1822
        RTSPMessageHeader reply;
1823

    
1824
        ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
1825
        if (ret < 0)
1826
            return ret;
1827
        if (ret == 1) /* received '$' */
1828
            break;
1829
        /* XXX: parse message */
1830
        if (rt->state != RTSP_STATE_STREAMING)
1831
            return 0;
1832
    }
1833
    ret = url_read_complete(rt->rtsp_hd, buf, 3);
1834
    if (ret != 3)
1835
        return -1;
1836
    id  = buf[0];
1837
    len = AV_RB16(buf + 1);
1838
#ifdef DEBUG_RTP_TCP
1839
    dprintf(s, "id=%d len=%d\n", id, len);
1840
#endif
1841
    if (len > buf_size || len < 12)
1842
        goto redo;
1843
    /* get the data */
1844
    ret = url_read_complete(rt->rtsp_hd, buf, len);
1845
    if (ret != len)
1846
        return -1;
1847
    if (rt->transport == RTSP_TRANSPORT_RDT &&
1848
        ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
1849
        return -1;
1850

    
1851
    /* find the matching stream */
1852
    for (i = 0; i < rt->nb_rtsp_streams; i++) {
1853
        rtsp_st = rt->rtsp_streams[i];
1854
        if (id >= rtsp_st->interleaved_min &&
1855
            id <= rtsp_st->interleaved_max)
1856
            goto found;
1857
    }
1858
    goto redo;
1859
found:
1860
    *prtsp_st = rtsp_st;
1861
    return len;
1862
}
1863
static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
1864
{
1865
    RTSPState *rt = s->priv_data;
1866
    int ret;
1867
    RTSPMessageHeader reply1, *reply = &reply1;
1868
    char cmd[1024];
1869

    
1870
    if (rt->server_type == RTSP_SERVER_REAL) {
1871
        int i;
1872

    
1873
        for (i = 0; i < s->nb_streams; i++)
1874
            rt->real_setup[i] = s->streams[i]->discard;
1875

    
1876
        if (!rt->need_subscription) {
1877
            if (memcmp (rt->real_setup, rt->real_setup_cache,
1878
                        sizeof(enum AVDiscard) * s->nb_streams)) {
1879
                snprintf(cmd, sizeof(cmd),
1880
                         "Unsubscribe: %s\r\n",
1881
                         rt->last_subscription);
1882
                ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1883
                                 cmd, reply, NULL);
1884
                if (reply->status_code != RTSP_STATUS_OK)
1885
                    return AVERROR_INVALIDDATA;
1886
                rt->need_subscription = 1;
1887
            }
1888
        }
1889

    
1890
        if (rt->need_subscription) {
1891
            int r, rule_nr, first = 1;
1892

    
1893
            memcpy(rt->real_setup_cache, rt->real_setup,
1894
                   sizeof(enum AVDiscard) * s->nb_streams);
1895
            rt->last_subscription[0] = 0;
1896

    
1897
            snprintf(cmd, sizeof(cmd),
1898
                     "Subscribe: ");
1899
            for (i = 0; i < rt->nb_rtsp_streams; i++) {
1900
                rule_nr = 0;
1901
                for (r = 0; r < s->nb_streams; r++) {
1902
                    if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
1903
                        if (s->streams[r]->discard != AVDISCARD_ALL) {
1904
                            if (!first)
1905
                                av_strlcat(rt->last_subscription, ",",
1906
                                           sizeof(rt->last_subscription));
1907
                            ff_rdt_subscribe_rule(
1908
                                rt->last_subscription,
1909
                                sizeof(rt->last_subscription), i, rule_nr);
1910
                            first = 0;
1911
                        }
1912
                        rule_nr++;
1913
                    }
1914
                }
1915
            }
1916
            av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
1917
            ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
1918
                             cmd, reply, NULL);
1919
            if (reply->status_code != RTSP_STATUS_OK)
1920
                return AVERROR_INVALIDDATA;
1921
            rt->need_subscription = 0;
1922

    
1923
            if (rt->state == RTSP_STATE_STREAMING)
1924
                rtsp_read_play (s);
1925
        }
1926
    }
1927

    
1928
    ret = rtsp_fetch_packet(s, pkt);
1929
    if (ret < 0)
1930
        return ret;
1931

    
1932
    /* send dummy request to keep TCP connection alive */
1933
    if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
1934
        if (rt->server_type == RTSP_SERVER_WMS) {
1935
            ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
1936
        } else {
1937
            ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
1938
        }
1939
    }
1940

    
1941
    return 0;
1942
}
1943

    
1944
/* pause the stream */
1945
static int rtsp_read_pause(AVFormatContext *s)
1946
{
1947
    RTSPState *rt = s->priv_data;
1948
    RTSPMessageHeader reply1, *reply = &reply1;
1949

    
1950
    if (rt->state != RTSP_STATE_STREAMING)
1951
        return 0;
1952
    else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
1953
        ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
1954
        if (reply->status_code != RTSP_STATUS_OK) {
1955
            return -1;
1956
        }
1957
    }
1958
    rt->state = RTSP_STATE_PAUSED;
1959
    return 0;
1960
}
1961

    
1962
static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1963
                          int64_t timestamp, int flags)
1964
{
1965
    RTSPState *rt = s->priv_data;
1966

    
1967
    rt->seek_timestamp = av_rescale_q(timestamp,
1968
                                      s->streams[stream_index]->time_base,
1969
                                      AV_TIME_BASE_Q);
1970
    switch(rt->state) {
1971
    default:
1972
    case RTSP_STATE_IDLE:
1973
        break;
1974
    case RTSP_STATE_STREAMING:
1975
        if (rtsp_read_pause(s) != 0)
1976
            return -1;
1977
        rt->state = RTSP_STATE_SEEKING;
1978
        if (rtsp_read_play(s) != 0)
1979
            return -1;
1980
        break;
1981
    case RTSP_STATE_PAUSED:
1982
        rt->state = RTSP_STATE_IDLE;
1983
        break;
1984
    }
1985
    return 0;
1986
}
1987

    
1988
static int rtsp_read_close(AVFormatContext *s)
1989
{
1990
    RTSPState *rt = s->priv_data;
1991

    
1992
#if 0
1993
    /* NOTE: it is valid to flush the buffer here */
1994
    if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1995
        url_fclose(&rt->rtsp_gb);
1996
    }
1997
#endif
1998
    ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
1999

    
2000
    ff_rtsp_close_streams(s);
2001
    ff_rtsp_close_connections(s);
2002
    ff_network_close();
2003
    rt->real_setup = NULL;
2004
    av_freep(&rt->real_setup_cache);
2005
    return 0;
2006
}
2007

    
2008
AVInputFormat rtsp_demuxer = {
2009
    "rtsp",
2010
    NULL_IF_CONFIG_SMALL("RTSP input format"),
2011
    sizeof(RTSPState),
2012
    rtsp_probe,
2013
    rtsp_read_header,
2014
    rtsp_read_packet,
2015
    rtsp_read_close,
2016
    rtsp_read_seek,
2017
    .flags = AVFMT_NOFILE,
2018
    .read_play = rtsp_read_play,
2019
    .read_pause = rtsp_read_pause,
2020
};
2021
#endif /* CONFIG_RTSP_DEMUXER */
2022

    
2023
static int sdp_probe(AVProbeData *p1)
2024
{
2025
    const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
2026

    
2027
    /* we look for a line beginning "c=IN IP" */
2028
    while (p < p_end && *p != '\0') {
2029
        if (p + sizeof("c=IN IP") - 1 < p_end &&
2030
            av_strstart(p, "c=IN IP", NULL))
2031
            return AVPROBE_SCORE_MAX / 2;
2032

    
2033
        while (p < p_end - 1 && *p != '\n') p++;
2034
        if (++p >= p_end)
2035
            break;
2036
        if (*p == '\r')
2037
            p++;
2038
    }
2039
    return 0;
2040
}
2041

    
2042
static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
2043
{
2044
    RTSPState *rt = s->priv_data;
2045
    RTSPStream *rtsp_st;
2046
    int size, i, err;
2047
    char *content;
2048
    char url[1024];
2049

    
2050
    if (!ff_network_init())
2051
        return AVERROR(EIO);
2052

    
2053
    /* read the whole sdp file */
2054
    /* XXX: better loading */
2055
    content = av_malloc(SDP_MAX_SIZE);
2056
    size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
2057
    if (size <= 0) {
2058
        av_free(content);
2059
        return AVERROR_INVALIDDATA;
2060
    }
2061
    content[size] ='\0';
2062

    
2063
    sdp_parse(s, content);
2064
    av_free(content);
2065

    
2066
    /* open each RTP stream */
2067
    for (i = 0; i < rt->nb_rtsp_streams; i++) {
2068
        char namebuf[50];
2069
        rtsp_st = rt->rtsp_streams[i];
2070

    
2071
        getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
2072
                    namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
2073
        ff_url_join(url, sizeof(url), "rtp", NULL,
2074
                    namebuf, rtsp_st->sdp_port,
2075
                    "?localport=%d&ttl=%d", rtsp_st->sdp_port,
2076
                    rtsp_st->sdp_ttl);
2077
        if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
2078
            err = AVERROR_INVALIDDATA;
2079
            goto fail;
2080
        }
2081
        if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
2082
            goto fail;
2083
    }
2084
    return 0;
2085
fail:
2086
    ff_rtsp_close_streams(s);
2087
    ff_network_close();
2088
    return err;
2089
}
2090

    
2091
static int sdp_read_close(AVFormatContext *s)
2092
{
2093
    ff_rtsp_close_streams(s);
2094
    ff_network_close();
2095
    return 0;
2096
}
2097

    
2098
AVInputFormat sdp_demuxer = {
2099
    "sdp",
2100
    NULL_IF_CONFIG_SMALL("SDP"),
2101
    sizeof(RTSPState),
2102
    sdp_probe,
2103
    sdp_read_header,
2104
    rtsp_fetch_packet,
2105
    sdp_read_close,
2106
};