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

/**
23
 * @file
24 25 26 27 28 29
 * @brief Realmedia RTSP protocol (RDT) support
 * @author Ronald S. Bultje <rbultje@ronald.bitfreak.net>
 */

#include "avformat.h"
#include "libavutil/avstring.h"
30
#include "rtpdec.h"
31 32 33 34 35
#include "rdt.h"
#include "libavutil/base64.h"
#include "libavutil/md5.h"
#include "rm.h"
#include "internal.h"
36
#include "avio_internal.h"
37
#include "libavcodec/get_bits.h"
38

39
struct RDTDemuxContext {
40
    AVFormatContext *ic; /**< the containing (RTSP) demux context */
41 42 43 44 45 46 47
    /** Each RDT stream-set (represented by one RTSPStream) can contain
     * multiple streams (of the same content, but with possibly different
     * codecs/bitrates). Each such stream is represented by one AVStream
     * in the AVFormatContext, and this variable points to the offset in
     * that array such that the first is the first stream of this set. */
    AVStream **streams;
    int n_streams; /**< streams with identifical content in this set */
48 49
    void *dynamic_protocol_context;
    DynamicPayloadPacketHandlerProc parse_packet;
50
    uint32_t prev_timestamp;
51
    int prev_set_id, prev_stream_id;
52 53 54
};

RDTDemuxContext *
55
ff_rdt_parse_open(AVFormatContext *ic, int first_stream_of_set_idx,
56 57 58 59 60 61 62
                  void *priv_data, RTPDynamicProtocolHandler *handler)
{
    RDTDemuxContext *s = av_mallocz(sizeof(RDTDemuxContext));
    if (!s)
        return NULL;

    s->ic = ic;
63 64 65 66
    s->streams = &ic->streams[first_stream_of_set_idx];
    do {
        s->n_streams++;
    } while (first_stream_of_set_idx + s->n_streams < ic->nb_streams &&
67
             s->streams[s->n_streams]->id == s->streams[0]->id);
68
    s->prev_set_id    = -1;
69
    s->prev_stream_id = -1;
70
    s->prev_timestamp = -1;
71
    s->parse_packet = handler ? handler->parse_packet : NULL;
72 73 74 75 76 77 78 79 80 81 82
    s->dynamic_protocol_context = priv_data;

    return s;
}

void
ff_rdt_parse_close(RDTDemuxContext *s)
{
    av_free(s);
}

83
struct PayloadContext {
84
    AVFormatContext *rmctx;
85 86
    int nb_rmst;
    RMStream **rmst;
87 88
    uint8_t *mlti_data;
    unsigned int mlti_data_size;
89
    char buffer[RTP_MAX_PACKET_LENGTH + FF_INPUT_BUFFER_PADDING_SIZE];
90
    int audio_pkt_cnt; /**< remaining audio packets in rmdec */
91
};
92

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
void
ff_rdt_calc_response_and_checksum(char response[41], char chksum[9],
                                  const char *challenge)
{
    int ch_len = strlen (challenge), i;
    unsigned char zres[16],
        buf[64] = { 0xa1, 0xe9, 0x14, 0x9d, 0x0e, 0x6b, 0x3b, 0x59 };
#define XOR_TABLE_SIZE 37
    const unsigned char xor_table[XOR_TABLE_SIZE] = {
        0x05, 0x18, 0x74, 0xd0, 0x0d, 0x09, 0x02, 0x53,
        0xc0, 0x01, 0x05, 0x05, 0x67, 0x03, 0x19, 0x70,
        0x08, 0x27, 0x66, 0x10, 0x10, 0x72, 0x08, 0x09,
        0x63, 0x11, 0x03, 0x71, 0x08, 0x08, 0x70, 0x02,
        0x10, 0x57, 0x05, 0x18, 0x54 };

    /* some (length) checks */
    if (ch_len == 40) /* what a hack... */
        ch_len = 32;
    else if (ch_len > 56)
        ch_len = 56;
    memcpy(buf + 8, challenge, ch_len);

    /* xor challenge bytewise with xor_table */
    for (i = 0; i < XOR_TABLE_SIZE; i++)
        buf[8 + i] ^= xor_table[i];

    av_md5_sum(zres, buf, 64);
120
    ff_data_to_hex(response, zres, 16, 1);
121 122 123 124 125 126 127 128 129

    /* add tail */
    strcpy (response + 32, "01d0a8e3");

    /* calculate checksum */
    for (i = 0; i < 8; i++)
        chksum[i] = response[i * 4];
    chksum[8] = 0;
}
130 131

static int
132
rdt_load_mdpr (PayloadContext *rdt, AVStream *st, int rule_nr)
133
{
134
    AVIOContext pb;
135 136 137 138 139
    int size;
    uint32_t tag;

    /**
     * Layout of the MLTI chunk:
140 141
     * 4: MLTI
     * 2: number of streams
142
     * Then for each stream ([number_of_streams] times):
143 144
     *     2: mdpr index
     * 2: number of mdpr chunks
145
     * Then for each mdpr chunk ([number_of_mdpr_chunks] times):
146 147
     *     4: size
     *     [size]: data
148 149 150 151 152 153
     * we skip MDPR chunks until we reach the one of the stream
     * we're interested in, and forward that ([size]+[data]) to
     * the RM demuxer to parse the stream-specific header data.
     */
    if (!rdt->mlti_data)
        return -1;
154
    ffio_init_context(&pb, rdt->mlti_data, rdt->mlti_data_size, 0,
155
                  NULL, NULL, NULL, NULL);
156
    tag = avio_rl32(&pb);
157 158 159 160
    if (tag == MKTAG('M', 'L', 'T', 'I')) {
        int num, chunk_nr;

        /* read index of MDPR chunk numbers */
161
        num = avio_rb16(&pb);
162 163
        if (rule_nr < 0 || rule_nr >= num)
            return -1;
164
        avio_skip(&pb, rule_nr * 2);
165
        chunk_nr = avio_rb16(&pb);
166
        avio_skip(&pb, (num - 1 - rule_nr) * 2);
167 168

        /* read MDPR chunks */
169
        num = avio_rb16(&pb);
170 171 172
        if (chunk_nr >= num)
            return -1;
        while (chunk_nr--)
173
            avio_skip(&pb, avio_rb32(&pb));
174
        size = avio_rb32(&pb);
175 176
    } else {
        size = rdt->mlti_data_size;
A
Anton Khirnov 已提交
177
        avio_seek(&pb, 0, SEEK_SET);
178
    }
179
    if (ff_rm_read_mdpr_codecdata(rdt->rmctx, &pb, st, rdt->rmst[st->index], size) < 0)
180 181 182 183 184
        return -1;

    return 0;
}

185 186 187 188
/**
 * Actual data handling.
 */

189 190
int
ff_rdt_parse_header(const uint8_t *buf, int len,
191 192
                    int *pset_id, int *pseq_no, int *pstream_id,
                    int *pis_keyframe, uint32_t *ptimestamp)
193
{
194
    GetBitContext gb;
195 196
    int consumed = 0, set_id, seq_no, stream_id, is_keyframe,
        len_included, need_reliable;
197
    uint32_t timestamp;
198

199 200 201 202 203 204 205 206 207 208 209
    /* skip status packets */
    while (len >= 5 && buf[1] == 0xFF /* status packet */) {
        int pkt_len;

        if (!(buf[0] & 0x80))
            return -1; /* not followed by a data packet */

        pkt_len = AV_RB16(buf+3);
        buf += pkt_len;
        len -= pkt_len;
        consumed += pkt_len;
210
    }
211
    if (len < 16)
212
        return -1;
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    /**
     * Layout of the header (in bits):
     * 1:  len_included
     *     Flag indicating whether this header includes a length field;
     *     this can be used to concatenate multiple RDT packets in a
     *     single UDP/TCP data frame and is used to precede RDT data
     *     by stream status packets
     * 1:  need_reliable
     *     Flag indicating whether this header includes a "reliable
     *     sequence number"; these are apparently sequence numbers of
     *     data packets alone. For data packets, this flag is always
     *     set, according to the Real documentation [1]
     * 5:  set_id
     *     ID of a set of streams of identical content, possibly with
     *     different codecs or bitrates
     * 1:  is_reliable
     *     Flag set for certain streams deemed less tolerable for packet
     *     loss
     * 16: seq_no
     *     Packet sequence number; if >=0xFF00, this is a non-data packet
     *     containing stream status info, the second byte indicates the
     *     type of status packet (see wireshark docs / source code [2])
     * if (len_included) {
     *     16: packet_len
     * } else {
     *     packet_len = remainder of UDP/TCP frame
     * }
     * 1:  is_back_to_back
     *     Back-to-Back flag; used for timing, set for one in every 10
     *     packets, according to the Real documentation [1]
     * 1:  is_slow_data
     *     Slow-data flag; currently unused, according to Real docs [1]
     * 5:  stream_id
     *     ID of the stream within this particular set of streams
     * 1:  is_no_keyframe
     *     Non-keyframe flag (unset if packet belongs to a keyframe)
     * 32: timestamp (PTS)
     * if (set_id == 0x1F) {
     *     16: set_id (extended set-of-streams ID; see set_id)
     * }
     * if (need_reliable) {
     *     16: reliable_seq_no
     *         Reliable sequence number (see need_reliable)
     * }
     * if (stream_id == 0x3F) {
     *     16: stream_id (extended stream ID; see stream_id)
     * }
     * [1] https://protocol.helixcommunity.org/files/2005/devdocs/RDT_Feature_Level_20.txt
     * [2] http://www.wireshark.org/docs/dfref/r/rdt.html and
     *     http://anonsvn.wireshark.org/viewvc/trunk/epan/dissectors/packet-rdt.c
     */
264
    init_get_bits(&gb, buf, len << 3);
265 266
    len_included  = get_bits1(&gb);
    need_reliable = get_bits1(&gb);
267 268 269
    set_id        = get_bits(&gb, 5);
    skip_bits(&gb, 1);
    seq_no        = get_bits(&gb, 16);
270 271
    if (len_included)
        skip_bits(&gb, 16);
272 273 274 275
    skip_bits(&gb, 2);
    stream_id     = get_bits(&gb, 5);
    is_keyframe   = !get_bits1(&gb);
    timestamp     = get_bits_long(&gb, 32);
276 277 278
    if (set_id == 0x1f)
        set_id    = get_bits(&gb, 16);
    if (need_reliable)
R
Ronald S. Bultje 已提交
279
        skip_bits(&gb, 16);
280 281
    if (stream_id == 0x1f)
        stream_id = get_bits(&gb, 16);
282

283 284 285 286 287 288 289
    if (pset_id)      *pset_id      = set_id;
    if (pseq_no)      *pseq_no      = seq_no;
    if (pstream_id)   *pstream_id   = stream_id;
    if (pis_keyframe) *pis_keyframe = is_keyframe;
    if (ptimestamp)   *ptimestamp   = timestamp;

    return consumed + (get_bits_count(&gb) >> 3);
290 291 292 293
}

/**< return 0 on packet, no more left, 1 on packet, 1 on partial packet... */
static int
294
rdt_parse_packet (AVFormatContext *ctx, PayloadContext *rdt, AVStream *st,
295
                  AVPacket *pkt, uint32_t *timestamp,
296
                  const uint8_t *buf, int len, uint16_t rtp_seq, int flags)
297 298
{
    int seq = 1, res;
299
    AVIOContext pb;
300

301
    if (rdt->audio_pkt_cnt == 0) {
302 303
        int pos;

304
        ffio_init_context(&pb, buf, len, 0, NULL, NULL, NULL, NULL);
305
        flags = (flags & RTP_FLAG_KEY) ? 2 : 0;
306
        res = ff_rm_parse_packet (rdt->rmctx, &pb, st, rdt->rmst[st->index], len, pkt,
307
                                  &seq, flags, *timestamp);
308
        pos = avio_tell(&pb);
309 310
        if (res < 0)
            return res;
311
        if (res > 0) {
312
            if (st->codec->codec_id == AV_CODEC_ID_AAC) {
R
Ronald S. Bultje 已提交
313
                memcpy (rdt->buffer, buf + pos, len - pos);
314
                rdt->rmctx->pb = avio_alloc_context (rdt->buffer, len - pos, 0,
R
Ronald S. Bultje 已提交
315
                                                    NULL, NULL, NULL, NULL);
316 317
            }
            goto get_cache;
318 319
        }
    } else {
320
get_cache:
321
        rdt->audio_pkt_cnt =
R
Ronald S. Bultje 已提交
322
            ff_rm_retrieve_cache (rdt->rmctx, rdt->rmctx->pb,
323
                                  st, rdt->rmst[st->index], pkt);
324
        if (rdt->audio_pkt_cnt == 0 &&
325
            st->codec->codec_id == AV_CODEC_ID_AAC)
326
            av_freep(&rdt->rmctx->pb);
327 328 329 330
    }
    pkt->stream_index = st->index;
    pkt->pts = *timestamp;

331
    return rdt->audio_pkt_cnt > 0;
332 333 334
}

int
335
ff_rdt_parse_packet(RDTDemuxContext *s, AVPacket *pkt,
336
                    uint8_t **bufptr, int len)
337
{
338
    uint8_t *buf = bufptr ? *bufptr : NULL;
339
    int seq_no, flags = 0, stream_id, set_id, is_keyframe;
340 341 342
    uint32_t timestamp;
    int rv= 0;

343 344 345
    if (!s->parse_packet)
        return -1;

346
    if (!buf && s->prev_stream_id != -1) {
347 348
        /* return the next packets, if any */
        timestamp= 0; ///< Should not be used if buf is NULL, but should be set to the timestamp of the packet returned....
349
        rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
350
                            s->streams[s->prev_stream_id],
351
                            pkt, &timestamp, NULL, 0, 0, flags);
352 353 354 355 356
        return rv;
    }

    if (len < 12)
        return -1;
357
    rv = ff_rdt_parse_header(buf, len, &set_id, &seq_no, &stream_id, &is_keyframe, &timestamp);
358 359
    if (rv < 0)
        return rv;
360 361 362
    if (is_keyframe &&
        (set_id != s->prev_set_id || timestamp != s->prev_timestamp ||
         stream_id != s->prev_stream_id)) {
363
        flags |= RTP_FLAG_KEY;
364 365
        s->prev_set_id    = set_id;
        s->prev_timestamp = timestamp;
366
    }
367
    s->prev_stream_id = stream_id;
368 369 370
    buf += rv;
    len -= rv;

371 372 373 374 375
     if (s->prev_stream_id >= s->n_streams) {
         s->prev_stream_id = -1;
         return -1;
     }

376
    rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
377
                         s->streams[s->prev_stream_id],
378
                         pkt, &timestamp, buf, len, 0, flags);
379 380 381 382

    return rv;
}

383
void
384
ff_rdt_subscribe_rule (char *cmd, int size,
385 386 387
                       int stream_nr, int rule_nr)
{
    av_strlcatf(cmd, size, "stream=%d;rule=%d,stream=%d;rule=%d",
388 389 390
                stream_nr, rule_nr * 2, stream_nr, rule_nr * 2 + 1);
}

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
static unsigned char *
rdt_parse_b64buf (unsigned int *target_len, const char *p)
{
    unsigned char *target;
    int len = strlen(p);
    if (*p == '\"') {
        p++;
        len -= 2; /* skip embracing " at start/end */
    }
    *target_len = len * 3 / 4;
    target = av_mallocz(*target_len + FF_INPUT_BUFFER_PADDING_SIZE);
    av_base64_decode(target, p, *target_len);
    return target;
}

static int
407 408
rdt_parse_sdp_line (AVFormatContext *s, int st_index,
                    PayloadContext *rdt, const char *line)
409
{
410
    AVStream *stream = s->streams[st_index];
411 412 413 414 415 416
    const char *p = line;

    if (av_strstart(p, "OpaqueData:buffer;", &p)) {
        rdt->mlti_data = rdt_parse_b64buf(&rdt->mlti_data_size, p);
    } else if (av_strstart(p, "StartTime:integer;", &p))
        stream->first_dts = atoi(p);
417
    else if (av_strstart(p, "ASMRuleBook:string;", &p)) {
R
Ronald S. Bultje 已提交
418
        int n, first = -1;
419 420

        for (n = 0; n < s->nb_streams; n++)
421
            if (s->streams[n]->id == stream->id) {
422
                int count = s->streams[n]->index + 1, err;
423
                if (first == -1) first = n;
424
                if (rdt->nb_rmst < count) {
425
                    if ((err = av_reallocp(&rdt->rmst,
426 427
                                           count * sizeof(*rdt->rmst))) < 0) {
                        rdt->nb_rmst = 0;
428
                        return err;
429
                    }
430 431
                    memset(rdt->rmst + rdt->nb_rmst, 0,
                           (count - rdt->nb_rmst) * sizeof(*rdt->rmst));
432 433
                    rdt->nb_rmst = count;
                }
434 435 436 437
                rdt->rmst[s->streams[n]->index] = ff_rm_alloc_rmstream();
                rdt_load_mdpr(rdt, s->streams[n], (n - first) * 2);
           }
    }
438 439 440 441

    return 0;
}

442 443 444 445 446 447 448 449 450 451 452 453 454
static void
real_parse_asm_rule(AVStream *st, const char *p, const char *end)
{
    do {
        /* can be either averagebandwidth= or AverageBandwidth= */
        if (sscanf(p, " %*1[Aa]verage%*1[Bb]andwidth=%d", &st->codec->bit_rate) == 1)
            break;
        if (!(p = strchr(p, ',')) || p > end)
            p = end;
        p++;
    } while (p < end);
}

455 456 457 458 459
static AVStream *
add_dstream(AVFormatContext *s, AVStream *orig_st)
{
    AVStream *st;

460
    if (!(st = avformat_new_stream(s, NULL)))
461
        return NULL;
462
    st->id = orig_st->id;
463 464 465 466 467 468 469 470 471 472 473
    st->codec->codec_type = orig_st->codec->codec_type;
    st->first_dts         = orig_st->first_dts;

    return st;
}

static void
real_parse_asm_rulebook(AVFormatContext *s, AVStream *orig_st,
                        const char *p)
{
    const char *end;
474
    int n_rules = 0, odd = 0;
475 476 477 478 479 480 481 482 483 484
    AVStream *st;

    /**
     * The ASMRuleBook contains a list of comma-separated strings per rule,
     * and each rule is separated by a ;. The last one also has a ; at the
     * end so we can use it as delimiter.
     * Every rule occurs twice, once for when the RTSP packet header marker
     * is set and once for if it isn't. We only read the first because we
     * don't care much (that's what the "odd" variable is for).
     * Each rule contains a set of one or more statements, optionally
D
Diego Biurrun 已提交
485
     * preceded by a single condition. If there's a condition, the rule
486 487 488 489 490 491
     * starts with a '#'. Multiple conditions are merged between brackets,
     * so there are never multiple conditions spread out over separate
     * statements. Generally, these conditions are bitrate limits (min/max)
     * for multi-bitrate streams.
     */
    if (*p == '\"') p++;
492
    while (1) {
493 494 495 496 497 498 499
        if (!(end = strchr(p, ';')))
            break;
        if (!odd && end != p) {
            if (n_rules > 0)
                st = add_dstream(s, orig_st);
            else
                st = orig_st;
500 501
            if (!st)
                break;
502
            real_parse_asm_rule(st, p, end);
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
            n_rules++;
        }
        p = end + 1;
        odd ^= 1;
    }
}

void
ff_real_parse_sdp_a_line (AVFormatContext *s, int stream_index,
                          const char *line)
{
    const char *p = line;

    if (av_strstart(p, "ASMRuleBook:string;", &p))
        real_parse_asm_rulebook(s, s->streams[stream_index], p);
}

520
static PayloadContext *
521
rdt_new_context (void)
522
{
523
    PayloadContext *rdt = av_mallocz(sizeof(PayloadContext));
524

525 526 527 528 529
    int ret = avformat_open_input(&rdt->rmctx, "", &ff_rdt_demuxer, NULL);
    if (ret < 0) {
        av_free(rdt);
        return NULL;
    }
530 531 532 533 534

    return rdt;
}

static void
535
rdt_free_context (PayloadContext *rdt)
536
{
537 538
    int i;

539
    for (i = 0; i < rdt->nb_rmst; i++)
540 541 542 543
        if (rdt->rmst[i]) {
            ff_rm_free_rmstream(rdt->rmst[i]);
            av_freep(&rdt->rmst[i]);
        }
544
    if (rdt->rmctx)
545
        avformat_close_input(&rdt->rmctx);
546
    av_freep(&rdt->mlti_data);
547
    av_freep(&rdt->rmst);
548 549 550 551
    av_free(rdt);
}

#define RDT_HANDLER(n, s, t) \
552
static RTPDynamicProtocolHandler rdt_ ## n ## _handler = { \
553 554
    .enc_name         = s, \
    .codec_type       = t, \
555
    .codec_id         = AV_CODEC_ID_NONE, \
556
    .parse_sdp_a_line = rdt_parse_sdp_line, \
557 558
    .alloc            = rdt_new_context, \
    .free             = rdt_free_context, \
559
    .parse_packet     = rdt_parse_packet \
560
}
561

562 563 564 565
RDT_HANDLER(live_video, "x-pn-multirate-realvideo-live", AVMEDIA_TYPE_VIDEO);
RDT_HANDLER(live_audio, "x-pn-multirate-realaudio-live", AVMEDIA_TYPE_AUDIO);
RDT_HANDLER(video,      "x-pn-realvideo",                AVMEDIA_TYPE_VIDEO);
RDT_HANDLER(audio,      "x-pn-realaudio",                AVMEDIA_TYPE_AUDIO);
566 567 568

void av_register_rdt_dynamic_payload_handlers(void)
{
569 570 571 572
    ff_register_dynamic_payload_handler(&rdt_video_handler);
    ff_register_dynamic_payload_handler(&rdt_audio_handler);
    ff_register_dynamic_payload_handler(&rdt_live_video_handler);
    ff_register_dynamic_payload_handler(&rdt_live_audio_handler);
573
}