]> git.sesse.net Git - vlc/blob - modules/access/rtp/session.c
Revert "Fixed deadlock when no data are received in rtp."
[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 last dequeued packet */
148     block_t *blocks; /* re-ordered blocks queue */
149     void    *opaque[0]; /* Per-source private payload data */
150 };
151
152 /**
153  * Initializes a new RTP source within an RTP session.
154  */
155 static rtp_source_t *
156 rtp_source_create (demux_t *demux, const rtp_session_t *session,
157                    uint32_t ssrc, uint16_t init_seq)
158 {
159     rtp_source_t *source;
160
161     source = malloc (sizeof (*source) + (sizeof (void *) * session->ptc));
162     if (source == NULL)
163         return NULL;
164
165     source->ssrc = ssrc;
166     source->jitter = 0;
167     source->max_seq = source->bad_seq = init_seq;
168     source->last_seq = init_seq - 1;
169     source->blocks = NULL;
170
171     /* Initializes all payload */
172     for (unsigned i = 0; i < session->ptc; i++)
173         source->opaque[i] = session->ptv[i].init (demux);
174
175     msg_Dbg (demux, "added RTP source (%08x)", ssrc);
176     return source;
177 }
178
179
180 /**
181  * Destroys an RTP source and its associated streams.
182  */
183 static void
184 rtp_source_destroy (demux_t *demux, const rtp_session_t *session,
185                     rtp_source_t *source)
186 {
187     msg_Dbg (demux, "removing RTP source (%08x)", source->ssrc);
188
189     for (unsigned i = 0; i < session->ptc; i++)
190         session->ptv[i].destroy (demux, source->opaque[i]);
191     block_ChainRelease (source->blocks);
192     free (source);
193 }
194
195 static inline uint16_t rtp_seq (const block_t *block)
196 {
197     assert (block->i_buffer >= 4);
198     return GetWBE (block->p_buffer + 2);
199 }
200
201 static inline uint32_t rtp_timestamp (const block_t *block)
202 {
203     assert (block->i_buffer >= 12);
204     return GetDWBE (block->p_buffer + 4);
205 }
206
207 static const struct rtp_pt_t *
208 rtp_find_ptype (const rtp_session_t *session, rtp_source_t *source,
209                 const block_t *block, void **pt_data)
210 {
211     uint8_t ptype = rtp_ptype (block);
212
213     for (unsigned i = 0; i < session->ptc; i++)
214     {
215         if (session->ptv[i].number == ptype)
216         {
217             if (pt_data != NULL)
218                 *pt_data = source->opaque[i];
219             return &session->ptv[i];
220         }
221     }
222     return NULL;
223 }
224
225 /**
226  * Receives an RTP packet and queues it. Not a cancellation point.
227  *
228  * @param demux VLC demux object
229  * @param session RTP session receiving the packet
230  * @param block RTP packet including the RTP header
231  */
232 void
233 rtp_queue (demux_t *demux, rtp_session_t *session, block_t *block)
234 {
235     demux_sys_t *p_sys = demux->p_sys;
236
237     /* RTP header sanity checks (see RFC 3550) */
238     if (block->i_buffer < 12)
239         goto drop;
240     if ((block->p_buffer[0] >> 6 ) != 2) /* RTP version number */
241         goto drop;
242
243     /* Remove padding if present */
244     if (block->p_buffer[0] & 0x20)
245     {
246         uint8_t padding = block->p_buffer[block->i_buffer - 1];
247         if ((padding == 0) || (block->i_buffer < (12u + padding)))
248             goto drop; /* illegal value */
249
250         block->i_buffer -= padding;
251     }
252
253     mtime_t        now = mdate ();
254     rtp_source_t  *src  = NULL;
255     const uint16_t seq  = GetWBE (block->p_buffer + 2);
256     const uint32_t ssrc = GetDWBE (block->p_buffer + 8);
257
258     /* In most case, we know this source already */
259     for (unsigned i = 0, max = session->srcc; i < max; i++)
260     {
261         rtp_source_t *tmp = session->srcv[i];
262         if (tmp->ssrc == ssrc)
263         {
264             src = tmp;
265             break;
266         }
267
268         /* RTP source garbage collection */
269         if ((tmp->last_rx + (p_sys->timeout * CLOCK_FREQ)) < now)
270         {
271             rtp_source_destroy (demux, session, tmp);
272             if (--session->srcc > 0)
273                 session->srcv[i] = session->srcv[session->srcc - 1];
274         }
275     }
276
277     if (src == NULL)
278     {
279         /* New source */
280         if (session->srcc >= p_sys->max_src)
281         {
282             msg_Warn (demux, "too many RTP sessions");
283             goto drop;
284         }
285
286         rtp_source_t **tab;
287         tab = realloc (session->srcv, (session->srcc + 1) * sizeof (*tab));
288         if (tab == NULL)
289             goto drop;
290         session->srcv = tab;
291
292         src = rtp_source_create (demux, session, ssrc, seq);
293         if (src == NULL)
294             goto drop;
295
296         tab[session->srcc++] = src;
297         /* Cannot compute jitter yet */
298     }
299     else
300     {
301         const rtp_pt_t *pt = rtp_find_ptype (session, src, block, NULL);
302
303         if (pt != NULL)
304         {
305             /* Recompute jitter estimate.
306              * That is computed from the RTP timestamps and the system clock.
307              * It is independent of RTP sequence. */
308             uint32_t freq = pt->frequency;
309             uint32_t ts = rtp_timestamp (block);
310             int64_t d = ((now - src->last_rx) * freq) / CLOCK_FREQ;
311             d        -=    ts - src->last_ts;
312             if (d < 0) d = -d;
313             src->jitter += ((d - src->jitter) + 8) >> 4;
314         }
315     }
316     src->last_rx = now;
317     src->last_ts = rtp_timestamp (block);
318
319     /* Be optimistic for the first packet. Certain codec, such as Vorbis
320      * do not like loosing the first packet(s), so we cannot just wait
321      * for proper sequence synchronization. And we don't want to assume that
322      * the sender starts at seq=0 either. */
323     if (src->blocks == NULL)
324         src->max_seq = seq - p_sys->max_dropout;
325
326     /* Check sequence number */
327     /* NOTE: the sequence number is per-source,
328      * but is independent from the payload type. */
329     uint16_t delta_seq = seq - (src->max_seq + 1);
330     if ((delta_seq < 0x8000) ? (delta_seq > p_sys->max_dropout)
331                              : ((65535 - delta_seq) > p_sys->max_misorder))
332     {
333         msg_Dbg (demux, "sequence discontinuity (got: %u, expected: %u)",
334                  seq, (src->max_seq + 1) & 0xffff);
335         if (seq == ((src->bad_seq + 1) & 0xffff))
336         {
337             src->max_seq = src->bad_seq = seq;
338             msg_Warn (demux, "sequence resynchronized");
339             block_ChainRelease (src->blocks);
340             src->blocks = NULL;
341         }
342         else
343         {
344             src->bad_seq = seq;
345             goto drop;
346         }
347     }
348     else
349     if (delta_seq < 0x8000)
350         src->max_seq = seq;
351
352     /* Queues the block in sequence order,
353      * hence there is a single queue for all payload types. */
354     block_t **pp = &src->blocks;
355     for (block_t *prev = *pp; prev != NULL; prev = *pp)
356     {
357         int16_t delta_seq = seq - rtp_seq (prev);
358         if (delta_seq < 0)
359             break;
360         if (delta_seq == 0)
361             goto drop; /* duplicate */
362         pp = &prev->p_next;
363     }
364     block->p_next = *pp;
365     *pp = block;
366
367     /*rtp_decode (demux, session, src);*/
368     return;
369
370 drop:
371     block_Release (block);
372 }
373
374
375 static void
376 rtp_decode (demux_t *demux, const rtp_session_t *session, rtp_source_t *src)
377 {
378     block_t *block = src->blocks;
379
380     assert (block);
381     src->blocks = block->p_next;
382     block->p_next = NULL;
383
384     /* Discontinuity detection */
385     uint16_t delta_seq = rtp_seq (block) - (src->last_seq + 1);
386     if (delta_seq != 0)
387     {
388         if (delta_seq >= 0x8000)
389         {   /* Unrecoverable if later packets have already been dequeued */
390             msg_Warn (demux, "ignoring late packet (sequence: %u)",
391                       rtp_seq (block));
392             goto drop;
393         }
394         block->i_flags |= BLOCK_FLAG_DISCONTINUITY;
395     }
396     src->last_seq = rtp_seq (block);
397
398     /* Match the payload type */
399     void *pt_data;
400     const rtp_pt_t *pt = rtp_find_ptype (session, src, block, &pt_data);
401     if (pt == NULL)
402     {
403         msg_Dbg (demux, "ignoring unknown payload (%"PRIu8")",
404                  rtp_ptype (block));
405         goto drop;
406     }
407
408     /* Computes the PTS from the RTP timestamp and payload RTP frequency.
409      * DTS is unknown. Also, while the clock frequency depends on the payload
410      * format, a single source MUST only use payloads of a chosen frequency.
411      * Otherwise it would be impossible to compute consistent timestamps. */
412     /* 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     /* 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     for (unsigned i = 0, max = session->srcc; i < max; i++)
460     {
461         rtp_source_t *src = session->srcv[i];
462         block_t *block;
463
464         /* Because of IP packet delay variation (IPDV), we need to guesstimate
465          * how long to wait for a missing packet in the RTP sequence
466          * (see RFC3393 for background on IPDV).
467          *
468          * This situation occurs if a packet got lost, or if the network has
469          * re-ordered packets. Unfortunately, the MSL is 2 minutes, orders of
470          * magnitude too long for multimedia. We need a tradeoff.
471          * If we underestimated IPDV, we may have to discard valid but late
472          * packets. If we overestimate it, we will either cause too much
473          * delay, or worse, underflow our downstream buffers, as we wait for
474          * definitely a lost packets.
475          *
476          * The rest of the "de-jitter buffer" work is done by the interval
477          * LibVLC E/S-out clock synchronization. Here, we need to bother about
478          * re-ordering packets, as decoders can't cope with mis-ordered data.
479          */
480         while (((block = src->blocks)) != NULL)
481         {
482 #if 0
483             if (rtp_seq (block) == ((src->last_seq + 1) & 0xffff))
484             {   /* Next block ready, no need to wait */
485                 rtp_decode (demux, session, src);
486                 continue;
487             }
488 #endif
489             /* Wait for 3 times the inter-arrival delay variance (about 99.7%
490              * match for random gaussian jitter). Additionnaly, we implicitly
491              * wait for misordering times the packetization time.
492              */
493             mtime_t deadline = src->last_rx;
494             const rtp_pt_t *pt = rtp_find_ptype (session, src, block, NULL);
495             if (pt)
496                 deadline += UINT64_C(3) * CLOCK_FREQ * src->jitter
497                             / pt->frequency;
498
499             if (now >= deadline)
500             {
501                 rtp_decode (demux, session, src);
502                 continue;
503             }
504             if (*deadlinep > deadline)
505                 *deadlinep = deadline;
506             pending = true; /* packet pending in buffer */
507             break;
508         }
509     }
510     return pending;
511 }