session.c 14.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
/**
 * @file session.c
 * @brief RTP session handling
 */
/*****************************************************************************
 * Copyright © 2008 Rémi Denis-Courmont
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2.0
 * of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 ****************************************************************************/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <stdlib.h>
#include <assert.h>
#include <errno.h>

#include <vlc/vlc.h>
#include <vlc_demux.h>

#include "rtp.h"

typedef struct rtp_source_t rtp_source_t;

/** State for a RTP session: */
struct rtp_session_t
{
    rtp_source_t **srcv;
    unsigned       srcc;
    uint8_t        ptc;
    rtp_pt_t      *ptv;
};

static rtp_source_t *
rtp_source_create (demux_t *, const rtp_session_t *, uint32_t, uint16_t);
static void
rtp_source_destroy (demux_t *, const rtp_session_t *, rtp_source_t *);

static void rtp_decode (demux_t *, const rtp_session_t *, rtp_source_t *);

/**
 * Creates a new RTP session.
 */
rtp_session_t *
rtp_session_create (demux_t *demux)
{
    rtp_session_t *session = malloc (sizeof (*session));
    if (session == NULL)
        return NULL;

    session->srcv = NULL;
    session->srcc = 0;
    session->ptc = 0;
    session->ptv = NULL;

    (void)demux;
    return session;
}


/**
 * Destroys an RTP session.
 */
void rtp_session_destroy (demux_t *demux, rtp_session_t *session)
{
    for (unsigned i = 0; i < session->srcc; i++)
        rtp_source_destroy (demux, session, session->srcv[i]);

    free (session->srcv);
    free (session->ptv);
    free (session);
    (void)demux;
}

static void *no_init (demux_t *demux)
{
90 91
    (void)demux;
    return NULL;
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 120 121 122 123 124 125 126 127
}

static void no_destroy (demux_t *demux, void *opaque)
{
    (void)demux; (void)opaque;
}

static void no_decode (demux_t *demux, void *opaque, block_t *block)
{
    (void)demux; (void)opaque;
    block_Release (block);
}

/**
 * Adds a payload type to an RTP session.
 */
int rtp_add_type (demux_t *demux, rtp_session_t *ses, const rtp_pt_t *pt)
{
    if (ses->srcc > 0)
    {
        msg_Err (demux, "cannot change RTP payload formats during session");
        return EINVAL;
    }

    rtp_pt_t *ppt = realloc (ses->ptv, (ses->ptc + 1) * sizeof (rtp_pt_t));
    if (ppt == NULL)
        return ENOMEM;

    ses->ptv = ppt;
    ppt += ses->ptc++;

    ppt->init = pt->init ? pt->init : no_init;
    ppt->destroy = pt->destroy ? pt->destroy : no_destroy;
    ppt->decode = pt->decode ? pt->decode : no_decode;
    ppt->frequency = pt->frequency;
    ppt->number = pt->number;
128 129
    msg_Dbg (demux, "added payload type %"PRIu8" (f = %"PRIu32" Hz)",
             ppt->number, ppt->frequency);
130 131 132 133 134 135 136 137 138 139

    assert (ppt->frequency > 0); /* SIGFPE! */
    (void)demux;
    return 0;
}

/** State for an RTP source */
struct rtp_source_t
{
    uint32_t ssrc;
140 141 142 143
    uint32_t jitter;  /* interarrival delay jitter estimate */
    mtime_t  last_rx; /* last received packet local timestamp */
    uint32_t last_ts; /* last received packet RTP timestamp */

144 145 146
    uint16_t bad_seq; /* tentatively next expected sequence for resync */
    uint16_t max_seq; /* next expected sequence */

147
    uint16_t last_seq; /* sequence of the last dequeued packet */
148
    block_t *blocks; /* re-ordered blocks queue */
149
    void    *opaque[0]; /* Per-source private payload data */
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
};

/**
 * Initializes a new RTP source within an RTP session.
 */
static rtp_source_t *
rtp_source_create (demux_t *demux, const rtp_session_t *session,
                   uint32_t ssrc, uint16_t init_seq)
{
    rtp_source_t *source;

    source = malloc (sizeof (*source) + (sizeof (void *) * session->ptc));
    if (source == NULL)
        return NULL;

    source->ssrc = ssrc;
166
    source->jitter = 0;
167
    source->max_seq = source->bad_seq = init_seq;
168
    source->last_seq = init_seq - 1;
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    source->blocks = NULL;

    /* Initializes all payload */
    for (unsigned i = 0; i < session->ptc; i++)
        source->opaque[i] = session->ptv[i].init (demux);

    msg_Dbg (demux, "added RTP source (%08x)", ssrc);
    return source;
}


/**
 * Destroys an RTP source and its associated streams.
 */
static void
rtp_source_destroy (demux_t *demux, const rtp_session_t *session,
                    rtp_source_t *source)
{
    msg_Dbg (demux, "removing RTP source (%08x)", source->ssrc);

    for (unsigned i = 0; i < session->ptc; i++)
        session->ptv[i].destroy (demux, source->opaque[i]);
    block_ChainRelease (source->blocks);
    free (source);
}

static inline uint16_t rtp_seq (const block_t *block)
{
    assert (block->i_buffer >= 4);
    return GetWBE (block->p_buffer + 2);
}

201 202 203 204 205 206
static inline uint32_t rtp_timestamp (const block_t *block)
{
    assert (block->i_buffer >= 12);
    return GetDWBE (block->p_buffer + 4);
}

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
static const struct rtp_pt_t *
rtp_find_ptype (const rtp_session_t *session, rtp_source_t *source,
                const block_t *block, void **pt_data)
{
    uint8_t ptype = rtp_ptype (block);

    for (unsigned i = 0; i < session->ptc; i++)
    {
        if (session->ptv[i].number == ptype)
        {
            if (pt_data != NULL)
                *pt_data = source->opaque[i];
            return &session->ptv[i];
        }
    }
    return NULL;
}

225
/**
226 227
 * Receives an RTP packet and queues it. Not a cancellation point.
 *
228 229 230 231 232
 * @param demux VLC demux object
 * @param session RTP session receiving the packet
 * @param block RTP packet including the RTP header
 */
void
233
rtp_queue (demux_t *demux, rtp_session_t *session, block_t *block)
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
{
    demux_sys_t *p_sys = demux->p_sys;

    /* RTP header sanity checks (see RFC 3550) */
    if (block->i_buffer < 12)
        goto drop;
    if ((block->p_buffer[0] >> 6 ) != 2) /* RTP version number */
        goto drop;

    /* Remove padding if present */
    if (block->p_buffer[0] & 0x20)
    {
        uint8_t padding = block->p_buffer[block->i_buffer - 1];
        if ((padding == 0) || (block->i_buffer < (12u + padding)))
            goto drop; /* illegal value */

        block->i_buffer -= padding;
    }

    mtime_t        now = mdate ();
    rtp_source_t  *src  = NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
255
    const uint16_t seq  = rtp_seq (block);
256 257 258 259 260 261 262 263 264 265 266 267 268
    const uint32_t ssrc = GetDWBE (block->p_buffer + 8);

    /* In most case, we know this source already */
    for (unsigned i = 0, max = session->srcc; i < max; i++)
    {
        rtp_source_t *tmp = session->srcv[i];
        if (tmp->ssrc == ssrc)
        {
            src = tmp;
            break;
        }

        /* RTP source garbage collection */
269
        if ((tmp->last_rx + (p_sys->timeout * CLOCK_FREQ)) < now)
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
        {
            rtp_source_destroy (demux, session, tmp);
            if (--session->srcc > 0)
                session->srcv[i] = session->srcv[session->srcc - 1];
        }
    }

    if (src == NULL)
    {
        /* New source */
        if (session->srcc >= p_sys->max_src)
        {
            msg_Warn (demux, "too many RTP sessions");
            goto drop;
        }

        rtp_source_t **tab;
        tab = realloc (session->srcv, (session->srcc + 1) * sizeof (*tab));
        if (tab == NULL)
            goto drop;
        session->srcv = tab;

        src = rtp_source_create (demux, session, ssrc, seq);
        if (src == NULL)
            goto drop;

        tab[session->srcc++] = src;
297 298
        /* Cannot compute jitter yet */
    }
299
    else
300
    {
301 302 303 304 305 306 307 308 309 310 311 312 313 314
        const rtp_pt_t *pt = rtp_find_ptype (session, src, block, NULL);

        if (pt != NULL)
        {
            /* Recompute jitter estimate.
             * That is computed from the RTP timestamps and the system clock.
             * It is independent of RTP sequence. */
            uint32_t freq = pt->frequency;
            uint32_t ts = rtp_timestamp (block);
            int64_t d = ((now - src->last_rx) * freq) / CLOCK_FREQ;
            d        -=    ts - src->last_ts;
            if (d < 0) d = -d;
            src->jitter += ((d - src->jitter) + 8) >> 4;
        }
315
    }
316 317
    src->last_rx = now;
    src->last_ts = rtp_timestamp (block);
318

319 320 321 322 323 324 325
    /* Be optimistic for the first packet. Certain codec, such as Vorbis
     * do not like loosing the first packet(s), so we cannot just wait
     * for proper sequence synchronization. And we don't want to assume that
     * the sender starts at seq=0 either. */
    if (src->blocks == NULL)
        src->max_seq = seq - p_sys->max_dropout;

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    /* Check sequence number */
    /* NOTE: the sequence number is per-source,
     * but is independent from the payload type. */
    uint16_t delta_seq = seq - (src->max_seq + 1);
    if ((delta_seq < 0x8000) ? (delta_seq > p_sys->max_dropout)
                             : ((65535 - delta_seq) > p_sys->max_misorder))
    {
        msg_Dbg (demux, "sequence discontinuity (got: %u, expected: %u)",
                 seq, (src->max_seq + 1) & 0xffff);
        if (seq == ((src->bad_seq + 1) & 0xffff))
        {
            src->max_seq = src->bad_seq = seq;
            msg_Warn (demux, "sequence resynchronized");
            block_ChainRelease (src->blocks);
            src->blocks = NULL;
        }
        else
        {
            src->bad_seq = seq;
            goto drop;
        }
    }
348 349 350
    else
    if (delta_seq < 0x8000)
        src->max_seq = seq;
351 352 353 354 355 356

    /* Queues the block in sequence order,
     * hence there is a single queue for all payload types. */
    block_t **pp = &src->blocks;
    for (block_t *prev = *pp; prev != NULL; prev = *pp)
    {
357 358
        int16_t delta_seq = seq - rtp_seq (prev);
        if (delta_seq < 0)
359
            break;
360 361
        if (delta_seq == 0)
            goto drop; /* duplicate */
362 363 364 365 366
        pp = &prev->p_next;
    }
    block->p_next = *pp;
    *pp = block;

367
    /*rtp_decode (demux, session, src);*/
368 369 370 371 372 373 374 375 376 377 378 379
    return;

drop:
    block_Release (block);
}


static void
rtp_decode (demux_t *demux, const rtp_session_t *session, rtp_source_t *src)
{
    block_t *block = src->blocks;

380
    assert (block);
381 382 383
    src->blocks = block->p_next;
    block->p_next = NULL;

384
    /* Discontinuity detection */
385 386 387 388 389 390 391 392 393
    uint16_t delta_seq = rtp_seq (block) - (src->last_seq + 1);
    if (delta_seq != 0)
    {
        if (delta_seq >= 0x8000)
        {   /* Unrecoverable if later packets have already been dequeued */
            msg_Warn (demux, "ignoring late packet (sequence: %u)",
                      rtp_seq (block));
            goto drop;
        }
394
        block->i_flags |= BLOCK_FLAG_DISCONTINUITY;
395
    }
396 397
    src->last_seq = rtp_seq (block);

398
    /* Match the payload type */
399 400
    void *pt_data;
    const rtp_pt_t *pt = rtp_find_ptype (session, src, block, &pt_data);
401 402
    if (pt == NULL)
    {
403 404
        msg_Dbg (demux, "ignoring unknown payload (%"PRIu8")",
                 rtp_ptype (block));
405 406 407 408 409 410 411 412
        goto drop;
    }

    /* Computes the PTS from the RTP timestamp and payload RTP frequency.
     * DTS is unknown. Also, while the clock frequency depends on the payload
     * format, a single source MUST only use payloads of a chosen frequency.
     * Otherwise it would be impossible to compute consistent timestamps. */
    /* FIXME: handle timestamp wrap properly */
413
    /* TODO: inter-medias/sessions sync (using RTCP-SR) */
414
    const uint32_t timestamp = rtp_timestamp (block);
415
    block->i_pts = UINT64_C(1) * CLOCK_FREQ * timestamp / pt->frequency;
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

    /* CSRC count */
    size_t skip = 12u + (block->p_buffer[0] & 0x0F) * 4;

    /* Extension header (ignored for now) */
    if (block->p_buffer[0] & 0x10)
    {
        skip += 4;
        if (block->i_buffer < skip)
            goto drop;

        skip += 4 * GetWBE (block->p_buffer + skip - 2);
    }

    if (block->i_buffer < skip)
        goto drop;

    block->p_buffer += skip;
    block->i_buffer -= skip;

    pt->decode (demux, pt_data, block);
    return;

drop:
    block_Release (block);
}
442 443


444 445 446 447 448 449 450 451 452
/**
 * Dequeues an RTP packet and pass it to decoder. Not cancellation-safe(?).
 *
 * @param demux VLC demux object
 * @param session RTP session receiving the packet
 * @param deadlinep pointer to deadline to call rtp_dequeue() again
 * @return true if the buffer is not empty, false otherwise.
 * In the later case, *deadlinep is undefined.
 */
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
bool rtp_dequeue (demux_t *demux, const rtp_session_t *session,
                  mtime_t *restrict deadlinep)
{
    mtime_t now = mdate ();
    bool pending = false;

    for (unsigned i = 0, max = session->srcc; i < max; i++)
    {
        rtp_source_t *src = session->srcv[i];
        block_t *block;

        /* Because of IP packet delay variation (IPDV), we need to guesstimate
         * how long to wait for a missing packet in the RTP sequence
         * (see RFC3393 for background on IPDV).
         *
         * This situation occurs if a packet got lost, or if the network has
         * re-ordered packets. Unfortunately, the MSL is 2 minutes, orders of
         * magnitude too long for multimedia. We need a tradeoff.
         * If we underestimated IPDV, we may have to discard valid but late
         * packets. If we overestimate it, we will either cause too much
         * delay, or worse, underflow our downstream buffers, as we wait for
         * definitely a lost packets.
         *
         * The rest of the "de-jitter buffer" work is done by the interval
         * LibVLC E/S-out clock synchronization. Here, we need to bother about
         * re-ordering packets, as decoders can't cope with mis-ordered data.
         */
        while (((block = src->blocks)) != NULL)
        {
482 483
            if ((int16_t)(rtp_seq (block) - (src->last_seq + 1)) <= 0)
            {   /* Next (or earlier) block ready, no need to wait */
484 485 486
                rtp_decode (demux, session, src);
                continue;
            }
487

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
            /* Wait for 3 times the inter-arrival delay variance (about 99.7%
             * match for random gaussian jitter). Additionnaly, we implicitly
             * wait for misordering times the packetization time.
             */
            mtime_t deadline = src->last_rx;
            const rtp_pt_t *pt = rtp_find_ptype (session, src, block, NULL);
            if (pt)
                deadline += UINT64_C(3) * CLOCK_FREQ * src->jitter
                            / pt->frequency;

            if (now >= deadline)
            {
                rtp_decode (demux, session, src);
                continue;
            }
            if (*deadlinep > deadline)
                *deadlinep = deadline;
            pending = true; /* packet pending in buffer */
            break;
        }
    }
    return pending;
}