]> git.sesse.net Git - vlc/blob - modules/access/rtp/session.c
RTP: compute deadline for reordering from the current time
[vlc] / modules / access / rtp / session.c
1 /**
2  * @file session.c
3  * @brief RTP session handling
4  */
5 /*****************************************************************************
6  * Copyright © 2008 Rémi Denis-Courmont
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2.0
11  * of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  ****************************************************************************/
22
23 #ifdef HAVE_CONFIG_H
24 # include <config.h>
25 #endif
26
27 #include <stdlib.h>
28 #include <assert.h>
29 #include <errno.h>
30
31 #include <vlc/vlc.h>
32 #include <vlc_demux.h>
33
34 #include "rtp.h"
35
36 typedef struct rtp_source_t rtp_source_t;
37
38 /** State for a RTP session: */
39 struct rtp_session_t
40 {
41     rtp_source_t **srcv;
42     unsigned       srcc;
43     uint8_t        ptc;
44     rtp_pt_t      *ptv;
45 };
46
47 static rtp_source_t *
48 rtp_source_create (demux_t *, const rtp_session_t *, uint32_t, uint16_t);
49 static void
50 rtp_source_destroy (demux_t *, const rtp_session_t *, rtp_source_t *);
51
52 static void rtp_decode (demux_t *, const rtp_session_t *, rtp_source_t *);
53
54 /**
55  * Creates a new RTP session.
56  */
57 rtp_session_t *
58 rtp_session_create (demux_t *demux)
59 {
60     rtp_session_t *session = malloc (sizeof (*session));
61     if (session == NULL)
62         return NULL;
63
64     session->srcv = NULL;
65     session->srcc = 0;
66     session->ptc = 0;
67     session->ptv = NULL;
68
69     (void)demux;
70     return session;
71 }
72
73
74 /**
75  * Destroys an RTP session.
76  */
77 void rtp_session_destroy (demux_t *demux, rtp_session_t *session)
78 {
79     for (unsigned i = 0; i < session->srcc; i++)
80         rtp_source_destroy (demux, session, session->srcv[i]);
81
82     free (session->srcv);
83     free (session->ptv);
84     free (session);
85     (void)demux;
86 }
87
88 static void *no_init (demux_t *demux)
89 {
90     (void)demux;
91     return NULL;
92 }
93
94 static void no_destroy (demux_t *demux, void *opaque)
95 {
96     (void)demux; (void)opaque;
97 }
98
99 static void no_decode (demux_t *demux, void *opaque, block_t *block)
100 {
101     (void)demux; (void)opaque;
102     block_Release (block);
103 }
104
105 /**
106  * Adds a payload type to an RTP session.
107  */
108 int rtp_add_type (demux_t *demux, rtp_session_t *ses, const rtp_pt_t *pt)
109 {
110     if (ses->srcc > 0)
111     {
112         msg_Err (demux, "cannot change RTP payload formats during session");
113         return EINVAL;
114     }
115
116     rtp_pt_t *ppt = realloc (ses->ptv, (ses->ptc + 1) * sizeof (rtp_pt_t));
117     if (ppt == NULL)
118         return ENOMEM;
119
120     ses->ptv = ppt;
121     ppt += ses->ptc++;
122
123     ppt->init = pt->init ? pt->init : no_init;
124     ppt->destroy = pt->destroy ? pt->destroy : no_destroy;
125     ppt->decode = pt->decode ? pt->decode : no_decode;
126     ppt->frequency = pt->frequency;
127     ppt->number = pt->number;
128     msg_Dbg (demux, "added payload type %"PRIu8" (f = %"PRIu32" Hz)",
129              ppt->number, ppt->frequency);
130
131     assert (ppt->frequency > 0); /* SIGFPE! */
132     (void)demux;
133     return 0;
134 }
135
136 /** State for an RTP source */
137 struct rtp_source_t
138 {
139     uint32_t ssrc;
140     uint32_t jitter;  /* interarrival delay jitter estimate */
141     mtime_t  last_rx; /* last received packet local timestamp */
142     uint32_t last_ts; /* last received packet RTP timestamp */
143
144     uint16_t bad_seq; /* tentatively next expected sequence for resync */
145     uint16_t max_seq; /* next expected sequence */
146
147     uint16_t last_seq; /* sequence of the next dequeued packet */
148     block_t *blocks; /* re-ordered blocks queue */
149     mtime_t  ref_ts; /* reference timestamp for reordering */
150     void    *opaque[0]; /* Per-source private payload data */
151 };
152
153 /**
154  * Initializes a new RTP source within an RTP session.
155  */
156 static rtp_source_t *
157 rtp_source_create (demux_t *demux, const rtp_session_t *session,
158                    uint32_t ssrc, uint16_t init_seq)
159 {
160     rtp_source_t *source;
161
162     source = malloc (sizeof (*source) + (sizeof (void *) * session->ptc));
163     if (source == NULL)
164         return NULL;
165
166     source->ssrc = ssrc;
167     source->jitter = 0;
168     source->max_seq = source->bad_seq = init_seq;
169     source->last_seq = init_seq - 1;
170     source->blocks = NULL;
171
172     /* Initializes all payload */
173     for (unsigned i = 0; i < session->ptc; i++)
174         source->opaque[i] = session->ptv[i].init (demux);
175
176     msg_Dbg (demux, "added RTP source (%08x)", ssrc);
177     return source;
178 }
179
180
181 /**
182  * Destroys an RTP source and its associated streams.
183  */
184 static void
185 rtp_source_destroy (demux_t *demux, const rtp_session_t *session,
186                     rtp_source_t *source)
187 {
188     msg_Dbg (demux, "removing RTP source (%08x)", source->ssrc);
189
190     for (unsigned i = 0; i < session->ptc; i++)
191         session->ptv[i].destroy (demux, source->opaque[i]);
192     block_ChainRelease (source->blocks);
193     free (source);
194 }
195
196 static inline uint16_t rtp_seq (const block_t *block)
197 {
198     assert (block->i_buffer >= 4);
199     return GetWBE (block->p_buffer + 2);
200 }
201
202 static inline uint32_t rtp_timestamp (const block_t *block)
203 {
204     assert (block->i_buffer >= 12);
205     return GetDWBE (block->p_buffer + 4);
206 }
207
208 static const struct rtp_pt_t *
209 rtp_find_ptype (const rtp_session_t *session, rtp_source_t *source,
210                 const block_t *block, void **pt_data)
211 {
212     uint8_t ptype = rtp_ptype (block);
213
214     for (unsigned i = 0; i < session->ptc; i++)
215     {
216         if (session->ptv[i].number == ptype)
217         {
218             if (pt_data != NULL)
219                 *pt_data = source->opaque[i];
220             return &session->ptv[i];
221         }
222     }
223     return NULL;
224 }
225
226 /**
227  * Receives an RTP packet and queues it. Not a cancellation point.
228  *
229  * @param demux VLC demux object
230  * @param session RTP session receiving the packet
231  * @param block RTP packet including the RTP header
232  */
233 void
234 rtp_queue (demux_t *demux, rtp_session_t *session, block_t *block)
235 {
236     demux_sys_t *p_sys = demux->p_sys;
237
238     /* RTP header sanity checks (see RFC 3550) */
239     if (block->i_buffer < 12)
240         goto drop;
241     if ((block->p_buffer[0] >> 6 ) != 2) /* RTP version number */
242         goto drop;
243
244     /* Remove padding if present */
245     if (block->p_buffer[0] & 0x20)
246     {
247         uint8_t padding = block->p_buffer[block->i_buffer - 1];
248         if ((padding == 0) || (block->i_buffer < (12u + padding)))
249             goto drop; /* illegal value */
250
251         block->i_buffer -= padding;
252     }
253
254     mtime_t        now = mdate ();
255     rtp_source_t  *src  = NULL;
256     const uint16_t seq  = rtp_seq (block);
257     const uint32_t ssrc = GetDWBE (block->p_buffer + 8);
258
259     /* In most case, we know this source already */
260     for (unsigned i = 0, max = session->srcc; i < max; i++)
261     {
262         rtp_source_t *tmp = session->srcv[i];
263         if (tmp->ssrc == ssrc)
264         {
265             src = tmp;
266             break;
267         }
268
269         /* RTP source garbage collection */
270         if ((tmp->last_rx + (p_sys->timeout * CLOCK_FREQ)) < now)
271         {
272             rtp_source_destroy (demux, session, tmp);
273             if (--session->srcc > 0)
274                 session->srcv[i] = session->srcv[session->srcc - 1];
275         }
276     }
277
278     if (src == NULL)
279     {
280         /* New source */
281         if (session->srcc >= p_sys->max_src)
282         {
283             msg_Warn (demux, "too many RTP sessions");
284             goto drop;
285         }
286
287         rtp_source_t **tab;
288         tab = realloc (session->srcv, (session->srcc + 1) * sizeof (*tab));
289         if (tab == NULL)
290             goto drop;
291         session->srcv = tab;
292
293         src = rtp_source_create (demux, session, ssrc, seq);
294         if (src == NULL)
295             goto drop;
296
297         tab[session->srcc++] = src;
298         /* Cannot compute jitter yet */
299     }
300     else
301     {
302         const rtp_pt_t *pt = rtp_find_ptype (session, src, block, NULL);
303
304         if (pt != NULL)
305         {
306             /* Recompute jitter estimate.
307              * That is computed from the RTP timestamps and the system clock.
308              * It is independent of RTP sequence. */
309             uint32_t freq = pt->frequency;
310             int64_t ts = rtp_timestamp (block);
311             int64_t d = ((now - src->last_rx) * freq) / CLOCK_FREQ;
312             d        -=    ts - src->last_ts;
313             if (d < 0) d = -d;
314             src->jitter += ((d - src->jitter) + 8) >> 4;
315         }
316     }
317     src->last_rx = now;
318     src->last_ts = rtp_timestamp (block);
319
320     /* Check sequence number */
321     /* NOTE: the sequence number is per-source,
322      * but is independent from the payload type. */
323     int16_t delta_seq = seq - src->max_seq;
324     if ((delta_seq > 0) ? (delta_seq > p_sys->max_dropout)
325                         : (-delta_seq > p_sys->max_misorder))
326     {
327         msg_Dbg (demux, "sequence discontinuity"
328                  " (got: %"PRIu16", expected: %"PRIu16")", seq, src->max_seq);
329         if (seq == src->bad_seq)
330         {
331             src->max_seq = src->bad_seq = seq + 1;
332             src->last_seq = seq - 0x7fffe; /* hack for rtp_decode() */
333             msg_Warn (demux, "sequence resynchronized");
334             block_ChainRelease (src->blocks);
335             src->blocks = NULL;
336         }
337         else
338         {
339             src->bad_seq = seq + 1;
340             goto drop;
341         }
342     }
343     else
344     if (delta_seq >= 0)
345         src->max_seq = seq + 1;
346
347     /* Queues the block in sequence order,
348      * hence there is a single queue for all payload types. */
349     block_t **pp = &src->blocks;
350     for (block_t *prev = *pp; prev != NULL; prev = *pp)
351     {
352         int16_t delta_seq = seq - rtp_seq (prev);
353         if (delta_seq < 0)
354             break;
355         if (delta_seq == 0)
356         {
357             msg_Dbg (demux, "duplicate packet (sequence: %"PRIu16")", seq);
358             goto drop; /* duplicate */
359         }
360         pp = &prev->p_next;
361     }
362     block->p_next = *pp;
363     *pp = block;
364
365     /*rtp_decode (demux, session, src);*/
366     return;
367
368 drop:
369     block_Release (block);
370 }
371
372
373 static void
374 rtp_decode (demux_t *demux, const rtp_session_t *session, rtp_source_t *src)
375 {
376     block_t *block = src->blocks;
377
378     assert (block);
379     src->blocks = block->p_next;
380     block->p_next = NULL;
381
382     /* Discontinuity detection */
383     uint16_t delta_seq = rtp_seq (block) - (src->last_seq + 1);
384     if (delta_seq != 0)
385     {
386         if (delta_seq >= 0x8000)
387         {   /* Trash too late packets (and PIM Assert duplicates) */
388             msg_Dbg (demux, "ignoring late packet (sequence: %"PRIu16")",
389                       rtp_seq (block));
390             goto drop;
391         }
392         msg_Warn (demux, "%"PRIu16" packet(s) lost", delta_seq);
393         block->i_flags |= BLOCK_FLAG_DISCONTINUITY;
394     }
395     src->last_seq = rtp_seq (block);
396
397     /* Match the payload type */
398     void *pt_data;
399     const rtp_pt_t *pt = rtp_find_ptype (session, src, block, &pt_data);
400     if (pt == NULL)
401     {
402         msg_Dbg (demux, "unknown payload (%"PRIu8")",
403                  rtp_ptype (block));
404         goto drop;
405     }
406
407     /* Computes the PTS from the RTP timestamp and payload RTP frequency.
408      * DTS is unknown. Also, while the clock frequency depends on the payload
409      * format, a single source MUST only use payloads of a chosen frequency.
410      * Otherwise it would be impossible to compute consistent timestamps. */
411     /* FIXME: handle timestamp wrap properly */
412     /* TODO: inter-medias/sessions sync (using RTCP-SR) */
413     const uint32_t timestamp = rtp_timestamp (block);
414     src->ref_ts = 0;
415     block->i_pts = CLOCK_FREQ * timestamp / pt->frequency;
416
417     /* CSRC count */
418     size_t skip = 12u + (block->p_buffer[0] & 0x0F) * 4;
419
420     /* Extension header (ignored for now) */
421     if (block->p_buffer[0] & 0x10)
422     {
423         skip += 4;
424         if (block->i_buffer < skip)
425             goto drop;
426
427         skip += 4 * GetWBE (block->p_buffer + skip - 2);
428     }
429
430     if (block->i_buffer < skip)
431         goto drop;
432
433     block->p_buffer += skip;
434     block->i_buffer -= skip;
435
436     pt->decode (demux, pt_data, block);
437     return;
438
439 drop:
440     block_Release (block);
441 }
442
443
444 /**
445  * Dequeues an RTP packet and pass it to decoder. Not cancellation-safe(?).
446  *
447  * @param demux VLC demux object
448  * @param session RTP session receiving the packet
449  * @param deadlinep pointer to deadline to call rtp_dequeue() again
450  * @return true if the buffer is not empty, false otherwise.
451  * In the later case, *deadlinep is undefined.
452  */
453 bool rtp_dequeue (demux_t *demux, const rtp_session_t *session,
454                   mtime_t *restrict deadlinep)
455 {
456     mtime_t now = mdate ();
457     bool pending = false;
458
459     *deadlinep = INT64_MAX;
460
461     for (unsigned i = 0, max = session->srcc; i < max; i++)
462     {
463         rtp_source_t *src = session->srcv[i];
464         block_t *block;
465
466         /* Because of IP packet delay variation (IPDV), we need to guesstimate
467          * how long to wait for a missing packet in the RTP sequence
468          * (see RFC3393 for background on IPDV).
469          *
470          * This situation occurs if a packet got lost, or if the network has
471          * re-ordered packets. Unfortunately, the MSL is 2 minutes, orders of
472          * magnitude too long for multimedia. We need a tradeoff.
473          * If we underestimated IPDV, we may have to discard valid but late
474          * packets. If we overestimate it, we will either cause too much
475          * delay, or worse, underflow our downstream buffers, as we wait for
476          * definitely a lost packets.
477          *
478          * The rest of the "de-jitter buffer" work is done by the interval
479          * LibVLC E/S-out clock synchronization. Here, we need to bother about
480          * re-ordering packets, as decoders can't cope with mis-ordered data.
481          */
482         while (((block = src->blocks)) != NULL)
483         {
484             if ((int16_t)(rtp_seq (block) - (src->last_seq + 1)) <= 0)
485             {   /* Next (or earlier) block ready, no need to wait */
486                 rtp_decode (demux, session, src);
487                 continue;
488             }
489
490             /* Wait for 3 times the inter-arrival delay variance (about 99.7%
491              * match for random gaussian jitter). Additionnaly, we implicitly
492              * wait for misordering times the packetization time.
493              */
494             mtime_t deadline = src->ref_ts;
495             const rtp_pt_t *pt = rtp_find_ptype (session, src, block, NULL);
496             if (!deadline)
497                 deadline = src->ref_ts = now;
498             if (pt)
499                 deadline += CLOCK_FREQ * 3 * src->jitter / pt->frequency;
500
501             if (now >= deadline)
502             {
503                 rtp_decode (demux, session, src);
504                 continue;
505             }
506             if (*deadlinep > deadline)
507                 *deadlinep = deadline;
508             pending = true; /* packet pending in buffer */
509             break;
510         }
511     }
512     return pending;
513 }