2 * Farsight Voice+Video library
4 * Copyright 2007 Collabora Ltd,
5 * Copyright 2007 Nokia Corporation
6 * @author: Philippe Kalaf <philippe.kalaf@collabora.co.uk>.
7 * Copyright 2007 Wim Taymans <wim.taymans@gmail.com>
8 * Copyright 2015 Kurento (http://kurento.org/)
9 * @author: Miguel ParĂs <mparisdiaz@gmail.com>
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public
22 * License along with this library; if not, write to the
23 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
29 * SECTION:element-rtpjitterbuffer
31 * This element reorders and removes duplicate RTP packets as they are received
32 * from a network source.
34 * The element needs the clock-rate of the RTP payload in order to estimate the
35 * delay. This information is obtained either from the caps on the sink pad or,
36 * when no caps are present, from the #GstRtpJitterBuffer::request-pt-map signal.
37 * To clear the previous pt-map use the #GstRtpJitterBuffer::clear-pt-map signal.
39 * The rtpjitterbuffer will wait for missing packets up to a configurable time
40 * limit using the #GstRtpJitterBuffer:latency property. Packets arriving too
41 * late are considered to be lost packets. If the #GstRtpJitterBuffer:do-lost
42 * property is set, lost packets will result in a custom serialized downstream
43 * event of name GstRTPPacketLost. The lost packet events are usually used by a
44 * depayloader or other element to create concealment data or some other logic
45 * to gracefully handle the missing packets.
47 * The jitterbuffer will use the DTS (or PTS if no DTS is set) of the incomming
48 * buffer and the rtptime inside the RTP packet to create a PTS on the outgoing
51 * The jitterbuffer can also be configured to send early retransmission events
52 * upstream by setting the #GstRtpJitterBuffer:do-retransmission property. In
53 * this mode, the jitterbuffer tries to estimate when a packet should arrive and
54 * sends a custom upstream event named GstRTPRetransmissionRequest when the
55 * packet is considered late. The initial expected packet arrival time is
56 * calculated as follows:
58 * - If seqnum N arrived at time T, seqnum N+1 is expected to arrive at
59 * T + packet-spacing + #GstRtpJitterBuffer:rtx-delay. The packet spacing is
60 * calculated from the DTS (or PTS is no DTS) of two consecutive RTP
61 * packets with different rtptime.
63 * - If seqnum N0 arrived at time T0 and seqnum Nm arrived at time Tm,
64 * seqnum Ni is expected at time Ti = T0 + i*(Tm - T0)/(Nm - N0). Any
65 * previously scheduled timeout is overwritten.
67 * - If seqnum N arrived, all seqnum older than
68 * N - #GstRtpJitterBuffer:rtx-delay-reorder are considered late
69 * immediately. This is to request fast feedback for abonormally reorder
70 * packets before any of the previous timeouts is triggered.
72 * A late packet triggers the GstRTPRetransmissionRequest custom upstream
73 * event. After the initial timeout expires and the retransmission event is
74 * sent, the timeout is scheduled for
75 * T + #GstRtpJitterBuffer:rtx-retry-timeout. If the missing packet did not
76 * arrive after #GstRtpJitterBuffer:rtx-retry-timeout, a new
77 * GstRTPRetransmissionRequest is sent upstream and the timeout is rescheduled
78 * again for T + #GstRtpJitterBuffer:rtx-retry-timeout. This repeats until
79 * #GstRtpJitterBuffer:rtx-retry-period elapsed, at which point no further
80 * retransmission requests are sent and the regular logic is performed to
81 * schedule a lost packet as discussed above.
83 * This element acts as a live element and so adds #GstRtpJitterBuffer:latency
86 * This element will automatically be used inside rtpbin.
89 * <title>Example pipelines</title>
91 * gst-launch-1.0 rtspsrc location=rtsp://192.168.1.133:8554/mpeg1or2AudioVideoTest ! rtpjitterbuffer ! rtpmpvdepay ! mpeg2dec ! xvimagesink
92 * ]| Connect to a streaming server and decode the MPEG video. The jitterbuffer is
93 * inserted into the pipeline to smooth out network jitter and to reorder the
94 * out-of-order RTP packets.
104 #include <gst/rtp/gstrtpbuffer.h>
106 #include "gstrtpjitterbuffer.h"
107 #include "rtpjitterbuffer.h"
108 #include "rtpstats.h"
110 #include <gst/glib-compat-private.h>
112 GST_DEBUG_CATEGORY (rtpjitterbuffer_debug);
113 #define GST_CAT_DEFAULT (rtpjitterbuffer_debug)
115 /* RTPJitterBuffer signals and args */
118 SIGNAL_REQUEST_PT_MAP,
126 #define DEFAULT_LATENCY_MS 200
127 #define DEFAULT_DROP_ON_LATENCY FALSE
128 #define DEFAULT_TS_OFFSET 0
129 #define DEFAULT_DO_LOST FALSE
130 #define DEFAULT_MODE RTP_JITTER_BUFFER_MODE_SLAVE
131 #define DEFAULT_PERCENT 0
132 #define DEFAULT_DO_RETRANSMISSION FALSE
133 #define DEFAULT_RTX_NEXT_SEQNUM TRUE
134 #define DEFAULT_RTX_DELAY -1
135 #define DEFAULT_RTX_MIN_DELAY 0
136 #define DEFAULT_RTX_DELAY_REORDER 3
137 #define DEFAULT_RTX_RETRY_TIMEOUT -1
138 #define DEFAULT_RTX_MIN_RETRY_TIMEOUT -1
139 #define DEFAULT_RTX_RETRY_PERIOD -1
140 #define DEFAULT_RTX_MAX_RETRIES -1
141 #define DEFAULT_MAX_RTCP_RTP_TIME_DIFF 1000
142 #define DEFAULT_MAX_DROPOUT_TIME 60000
143 #define DEFAULT_MAX_MISORDER_TIME 2000
145 #define DEFAULT_AUTO_RTX_DELAY (20 * GST_MSECOND)
146 #define DEFAULT_AUTO_RTX_TIMEOUT (40 * GST_MSECOND)
152 PROP_DROP_ON_LATENCY,
157 PROP_DO_RETRANSMISSION,
158 PROP_RTX_NEXT_SEQNUM,
161 PROP_RTX_DELAY_REORDER,
162 PROP_RTX_RETRY_TIMEOUT,
163 PROP_RTX_MIN_RETRY_TIMEOUT,
164 PROP_RTX_RETRY_PERIOD,
165 PROP_RTX_MAX_RETRIES,
167 PROP_MAX_RTCP_RTP_TIME_DIFF,
168 PROP_MAX_DROPOUT_TIME,
169 PROP_MAX_MISORDER_TIME
172 #define JBUF_LOCK(priv) (g_mutex_lock (&(priv)->jbuf_lock))
174 #define JBUF_LOCK_CHECK(priv,label) G_STMT_START { \
176 if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK)) \
179 #define JBUF_UNLOCK(priv) (g_mutex_unlock (&(priv)->jbuf_lock))
181 #define JBUF_WAIT_TIMER(priv) G_STMT_START { \
182 GST_DEBUG ("waiting timer"); \
183 (priv)->waiting_timer = TRUE; \
184 g_cond_wait (&(priv)->jbuf_timer, &(priv)->jbuf_lock); \
185 (priv)->waiting_timer = FALSE; \
186 GST_DEBUG ("waiting timer done"); \
188 #define JBUF_SIGNAL_TIMER(priv) G_STMT_START { \
189 if (G_UNLIKELY ((priv)->waiting_timer)) { \
190 GST_DEBUG ("signal timer"); \
191 g_cond_signal (&(priv)->jbuf_timer); \
195 #define JBUF_WAIT_EVENT(priv,label) G_STMT_START { \
196 GST_DEBUG ("waiting event"); \
197 (priv)->waiting_event = TRUE; \
198 g_cond_wait (&(priv)->jbuf_event, &(priv)->jbuf_lock); \
199 (priv)->waiting_event = FALSE; \
200 GST_DEBUG ("waiting event done"); \
201 if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK)) \
204 #define JBUF_SIGNAL_EVENT(priv) G_STMT_START { \
205 if (G_UNLIKELY ((priv)->waiting_event)) { \
206 GST_DEBUG ("signal event"); \
207 g_cond_signal (&(priv)->jbuf_event); \
211 #define JBUF_WAIT_QUERY(priv,label) G_STMT_START { \
212 GST_DEBUG ("waiting query"); \
213 (priv)->waiting_query = TRUE; \
214 g_cond_wait (&(priv)->jbuf_query, &(priv)->jbuf_lock); \
215 (priv)->waiting_query = FALSE; \
216 GST_DEBUG ("waiting query done"); \
217 if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK)) \
220 #define JBUF_SIGNAL_QUERY(priv,res) G_STMT_START { \
221 (priv)->last_query = res; \
222 if (G_UNLIKELY ((priv)->waiting_query)) { \
223 GST_DEBUG ("signal query"); \
224 g_cond_signal (&(priv)->jbuf_query); \
229 struct _GstRtpJitterBufferPrivate
231 GstPad *sinkpad, *srcpad;
234 RTPJitterBuffer *jbuf;
236 gboolean waiting_timer;
238 gboolean waiting_event;
240 gboolean waiting_query;
248 gboolean timer_running;
249 GThread *timer_thread;
254 gboolean drop_on_latency;
257 gboolean do_retransmission;
258 gboolean rtx_next_seqnum;
261 gint rtx_delay_reorder;
262 gint rtx_retry_timeout;
263 gint rtx_min_retry_timeout;
264 gint rtx_retry_period;
265 gint rtx_max_retries;
266 gint max_rtcp_rtp_time_diff;
267 guint32 max_dropout_time;
268 guint32 max_misorder_time;
270 /* the last seqnum we pushed out */
271 guint32 last_popped_seqnum;
272 /* the next expected seqnum we push */
274 /* seqnum-base, if known */
276 /* last output time */
277 GstClockTime last_out_time;
278 /* last valid input timestamp and rtptime pair */
279 GstClockTime ips_dts;
281 GstClockTime packet_spacing;
285 /* the next expected seqnum we receive */
286 GstClockTime last_in_dts;
287 guint32 next_in_seqnum;
291 /* start and stop ranges */
292 GstClockTime npt_start;
293 GstClockTime npt_stop;
294 guint64 ext_timestamp;
295 guint64 last_elapsed;
296 guint64 estimated_eos;
303 /* clock rate and rtp timestamp offset */
307 gint64 prev_ts_offset;
309 /* when we are shutting down */
310 GstFlowReturn srcresult;
316 GstClockTime timer_timeout;
317 guint16 timer_seqnum;
318 /* the latency of the upstream peer, we have to take this into account when
319 * synchronizing the buffers. */
320 GstClockTime peer_latency;
324 /* some accounting */
326 guint64 num_duplicates;
327 guint64 num_rtx_requests;
328 guint64 num_rtx_success;
329 guint64 num_rtx_failed;
332 RTPPacketRateCtx packet_rate_ctx;
335 GstClockTime last_dts;
336 guint64 last_rtptime;
337 GstClockTime avg_jitter;
354 GstClockTime timeout;
355 GstClockTime duration;
356 GstClockTime rtx_base;
357 GstClockTime rtx_delay;
358 GstClockTime rtx_retry;
359 GstClockTime rtx_last;
363 #define GST_RTP_JITTER_BUFFER_GET_PRIVATE(o) \
364 (G_TYPE_INSTANCE_GET_PRIVATE ((o), GST_TYPE_RTP_JITTER_BUFFER, \
365 GstRtpJitterBufferPrivate))
367 static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_template =
368 GST_STATIC_PAD_TEMPLATE ("sink",
371 GST_STATIC_CAPS ("application/x-rtp"
372 /* "clock-rate = (int) [ 1, 2147483647 ], "
373 * "payload = (int) , "
374 * "encoding-name = (string) "
378 static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_rtcp_template =
379 GST_STATIC_PAD_TEMPLATE ("sink_rtcp",
382 GST_STATIC_CAPS ("application/x-rtcp")
385 static GstStaticPadTemplate gst_rtp_jitter_buffer_src_template =
386 GST_STATIC_PAD_TEMPLATE ("src",
389 GST_STATIC_CAPS ("application/x-rtp"
390 /* "payload = (int) , "
391 * "clock-rate = (int) , "
392 * "encoding-name = (string) "
396 static guint gst_rtp_jitter_buffer_signals[LAST_SIGNAL] = { 0 };
398 #define gst_rtp_jitter_buffer_parent_class parent_class
399 G_DEFINE_TYPE (GstRtpJitterBuffer, gst_rtp_jitter_buffer, GST_TYPE_ELEMENT);
401 /* object overrides */
402 static void gst_rtp_jitter_buffer_set_property (GObject * object,
403 guint prop_id, const GValue * value, GParamSpec * pspec);
404 static void gst_rtp_jitter_buffer_get_property (GObject * object,
405 guint prop_id, GValue * value, GParamSpec * pspec);
406 static void gst_rtp_jitter_buffer_finalize (GObject * object);
408 /* element overrides */
409 static GstStateChangeReturn gst_rtp_jitter_buffer_change_state (GstElement
410 * element, GstStateChange transition);
411 static GstPad *gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
412 GstPadTemplate * templ, const gchar * name, const GstCaps * filter);
413 static void gst_rtp_jitter_buffer_release_pad (GstElement * element,
415 static GstClock *gst_rtp_jitter_buffer_provide_clock (GstElement * element);
418 static GstCaps *gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter);
419 static GstIterator *gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad,
422 /* sinkpad overrides */
423 static gboolean gst_rtp_jitter_buffer_sink_event (GstPad * pad,
424 GstObject * parent, GstEvent * event);
425 static GstFlowReturn gst_rtp_jitter_buffer_chain (GstPad * pad,
426 GstObject * parent, GstBuffer * buffer);
428 static gboolean gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad,
429 GstObject * parent, GstEvent * event);
430 static GstFlowReturn gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad,
431 GstObject * parent, GstBuffer * buffer);
433 static gboolean gst_rtp_jitter_buffer_sink_query (GstPad * pad,
434 GstObject * parent, GstQuery * query);
436 /* srcpad overrides */
437 static gboolean gst_rtp_jitter_buffer_src_event (GstPad * pad,
438 GstObject * parent, GstEvent * event);
439 static gboolean gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad,
440 GstObject * parent, GstPadMode mode, gboolean active);
441 static void gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer);
442 static gboolean gst_rtp_jitter_buffer_src_query (GstPad * pad,
443 GstObject * parent, GstQuery * query);
446 gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer);
448 gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jitterbuffer,
449 gboolean active, guint64 base_time);
450 static void do_handle_sync (GstRtpJitterBuffer * jitterbuffer);
452 static void unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer);
453 static void remove_all_timers (GstRtpJitterBuffer * jitterbuffer);
455 static void wait_next_timeout (GstRtpJitterBuffer * jitterbuffer);
457 static GstStructure *gst_rtp_jitter_buffer_create_stats (GstRtpJitterBuffer *
461 gst_rtp_jitter_buffer_class_init (GstRtpJitterBufferClass * klass)
463 GObjectClass *gobject_class;
464 GstElementClass *gstelement_class;
466 gobject_class = (GObjectClass *) klass;
467 gstelement_class = (GstElementClass *) klass;
469 g_type_class_add_private (klass, sizeof (GstRtpJitterBufferPrivate));
471 gobject_class->finalize = gst_rtp_jitter_buffer_finalize;
473 gobject_class->set_property = gst_rtp_jitter_buffer_set_property;
474 gobject_class->get_property = gst_rtp_jitter_buffer_get_property;
477 * GstRtpJitterBuffer:latency:
479 * The maximum latency of the jitterbuffer. Packets will be kept in the buffer
480 * for at most this time.
482 g_object_class_install_property (gobject_class, PROP_LATENCY,
483 g_param_spec_uint ("latency", "Buffer latency in ms",
484 "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
485 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
487 * GstRtpJitterBuffer:drop-on-latency:
489 * Drop oldest buffers when the queue is completely filled.
491 g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
492 g_param_spec_boolean ("drop-on-latency",
493 "Drop buffers when maximum latency is reached",
494 "Tells the jitterbuffer to never exceed the given latency in size",
495 DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
497 * GstRtpJitterBuffer:ts-offset:
499 * Adjust GStreamer output buffer timestamps in the jitterbuffer with offset.
500 * This is mainly used to ensure interstream synchronisation.
502 g_object_class_install_property (gobject_class, PROP_TS_OFFSET,
503 g_param_spec_int64 ("ts-offset", "Timestamp Offset",
504 "Adjust buffer timestamps with offset in nanoseconds", G_MININT64,
505 G_MAXINT64, DEFAULT_TS_OFFSET,
506 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
509 * GstRtpJitterBuffer:do-lost:
511 * Send out a GstRTPPacketLost event downstream when a packet is considered
514 g_object_class_install_property (gobject_class, PROP_DO_LOST,
515 g_param_spec_boolean ("do-lost", "Do Lost",
516 "Send an event downstream when a packet is lost", DEFAULT_DO_LOST,
517 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
520 * GstRtpJitterBuffer:mode:
522 * Control the buffering and timestamping mode used by the jitterbuffer.
524 g_object_class_install_property (gobject_class, PROP_MODE,
525 g_param_spec_enum ("mode", "Mode",
526 "Control the buffering algorithm in use", RTP_TYPE_JITTER_BUFFER_MODE,
527 DEFAULT_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
529 * GstRtpJitterBuffer:percent:
531 * The percent of the jitterbuffer that is filled.
533 g_object_class_install_property (gobject_class, PROP_PERCENT,
534 g_param_spec_int ("percent", "percent",
535 "The buffer filled percent", 0, 100,
536 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
538 * GstRtpJitterBuffer:do-retransmission:
540 * Send out a GstRTPRetransmission event upstream when a packet is considered
541 * late and should be retransmitted.
545 g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
546 g_param_spec_boolean ("do-retransmission", "Do Retransmission",
547 "Send retransmission events upstream when a packet is late",
548 DEFAULT_DO_RETRANSMISSION,
549 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
552 * GstRtpJitterBuffer:rtx-next-seqnum
554 * Estimate when the next packet should arrive and schedule a retransmission
556 * This is, when packet N arrives, a GstRTPRetransmission event is schedule
557 * for packet N+1. So it will be requested if it does not arrive at the expected time.
558 * The expected time is calculated using the dts of N and the packet spacing.
562 g_object_class_install_property (gobject_class, PROP_RTX_NEXT_SEQNUM,
563 g_param_spec_boolean ("rtx-next-seqnum", "RTX next seqnum",
564 "Estimate when the next packet should arrive and schedule a "
565 "retransmission request for it.",
566 DEFAULT_RTX_NEXT_SEQNUM, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
569 * GstRtpJitterBuffer:rtx-delay:
571 * When a packet did not arrive at the expected time, wait this extra amount
572 * of time before sending a retransmission event.
574 * When -1 is used, the max jitter will be used as extra delay.
578 g_object_class_install_property (gobject_class, PROP_RTX_DELAY,
579 g_param_spec_int ("rtx-delay", "RTX Delay",
580 "Extra time in ms to wait before sending retransmission "
581 "event (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_DELAY,
582 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
585 * GstRtpJitterBuffer:rtx-min-delay:
587 * When a packet did not arrive at the expected time, wait at least this extra amount
588 * of time before sending a retransmission event.
592 g_object_class_install_property (gobject_class, PROP_RTX_MIN_DELAY,
593 g_param_spec_uint ("rtx-min-delay", "Minimum RTX Delay",
594 "Minimum time in ms to wait before sending retransmission "
595 "event", 0, G_MAXUINT, DEFAULT_RTX_MIN_DELAY,
596 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
598 * GstRtpJitterBuffer:rtx-delay-reorder:
600 * Assume that a retransmission event should be sent when we see
601 * this much packet reordering.
603 * When -1 is used, the value will be estimated based on observed packet
608 g_object_class_install_property (gobject_class, PROP_RTX_DELAY_REORDER,
609 g_param_spec_int ("rtx-delay-reorder", "RTX Delay Reorder",
610 "Sending retransmission event when this much reordering (-1 automatic)",
611 -1, G_MAXINT, DEFAULT_RTX_DELAY_REORDER,
612 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
614 * GstRtpJitterBuffer::rtx-retry-timeout:
616 * When no packet has been received after sending a retransmission event
617 * for this time, retry sending a retransmission event.
619 * When -1 is used, the value will be estimated based on observed round
624 g_object_class_install_property (gobject_class, PROP_RTX_RETRY_TIMEOUT,
625 g_param_spec_int ("rtx-retry-timeout", "RTX Retry Timeout",
626 "Retry sending a transmission event after this timeout in "
627 "ms (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_TIMEOUT,
628 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
630 * GstRtpJitterBuffer::rtx-min-retry-timeout:
632 * The minimum amount of time between retry timeouts. When
633 * GstRtpJitterBuffer::rtx-retry-timeout is -1, this value ensures a
634 * minimum interval between retry timeouts.
636 * When -1 is used, the value will be estimated based on the
641 g_object_class_install_property (gobject_class, PROP_RTX_MIN_RETRY_TIMEOUT,
642 g_param_spec_int ("rtx-min-retry-timeout", "RTX Min Retry Timeout",
643 "Minimum timeout between sending a transmission event in "
644 "ms (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_MIN_RETRY_TIMEOUT,
645 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
647 * GstRtpJitterBuffer:rtx-retry-period:
649 * The amount of time to try to get a retransmission.
651 * When -1 is used, the value will be estimated based on the jitterbuffer
652 * latency and the observed round trip time.
656 g_object_class_install_property (gobject_class, PROP_RTX_RETRY_PERIOD,
657 g_param_spec_int ("rtx-retry-period", "RTX Retry Period",
658 "Try to get a retransmission for this many ms "
659 "(-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_PERIOD,
660 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
662 * GstRtpJitterBuffer:rtx-max-retries:
664 * The maximum number of retries to request a retransmission.
666 * This implies that as maximum (rtx-max-retries + 1) retransmissions will be requested.
667 * When -1 is used, the number of retransmission request will not be limited.
671 g_object_class_install_property (gobject_class, PROP_RTX_MAX_RETRIES,
672 g_param_spec_int ("rtx-max-retries", "RTX Max Retries",
673 "The maximum number of retries to request a retransmission. "
674 "(-1 not limited)", -1, G_MAXINT, DEFAULT_RTX_MAX_RETRIES,
675 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
677 g_object_class_install_property (gobject_class, PROP_MAX_DROPOUT_TIME,
678 g_param_spec_uint ("max-dropout-time", "Max dropout time",
679 "The maximum time (milliseconds) of missing packets tolerated.",
680 0, G_MAXUINT, DEFAULT_MAX_DROPOUT_TIME,
681 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
683 g_object_class_install_property (gobject_class, PROP_MAX_MISORDER_TIME,
684 g_param_spec_uint ("max-misorder-time", "Max misorder time",
685 "The maximum time (milliseconds) of misordered packets tolerated.",
686 0, G_MAXUINT, DEFAULT_MAX_MISORDER_TIME,
687 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
689 * GstRtpJitterBuffer:stats:
691 * Various jitterbuffer statistics. This property returns a GstStructure
692 * with name application/x-rtp-jitterbuffer-stats with the following fields:
698 * <classname>"rtx-count"</classname>:
699 * the number of retransmissions requested.
705 * <classname>"rtx-success-count"</classname>:
706 * the number of successful retransmissions.
712 * <classname>"rtx-per-packet"</classname>:
713 * average number of RTX per packet.
719 * <classname>"rtx-rtt"</classname>:
720 * average round trip time per RTX.
727 g_object_class_install_property (gobject_class, PROP_STATS,
728 g_param_spec_boxed ("stats", "Statistics",
729 "Various statistics", GST_TYPE_STRUCTURE,
730 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
733 * GstRtpJitterBuffer:max-rtcp-rtp-time-diff
735 * The maximum amount of time in ms that the RTP time in the RTCP SRs
736 * is allowed to be ahead of the last RTP packet we received. Use
737 * -1 to disable ignoring of RTCP packets.
741 g_object_class_install_property (gobject_class, PROP_MAX_RTCP_RTP_TIME_DIFF,
742 g_param_spec_int ("max-rtcp-rtp-time-diff", "Max RTCP RTP Time Diff",
743 "Maximum amount of time in ms that the RTP time in RTCP SRs "
744 "is allowed to be ahead (-1 disabled)", -1, G_MAXINT,
745 DEFAULT_MAX_RTCP_RTP_TIME_DIFF,
746 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
749 * GstRtpJitterBuffer::request-pt-map:
750 * @buffer: the object which received the signal
753 * Request the payload type as #GstCaps for @pt.
755 gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP] =
756 g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
757 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
758 request_pt_map), NULL, NULL, g_cclosure_marshal_generic,
759 GST_TYPE_CAPS, 1, G_TYPE_UINT);
761 * GstRtpJitterBuffer::handle-sync:
762 * @buffer: the object which received the signal
763 * @struct: a GstStructure containing sync values.
765 * Be notified of new sync values.
767 gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC] =
768 g_signal_new ("handle-sync", G_TYPE_FROM_CLASS (klass),
769 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
770 handle_sync), NULL, NULL, g_cclosure_marshal_VOID__BOXED,
771 G_TYPE_NONE, 1, GST_TYPE_STRUCTURE | G_SIGNAL_TYPE_STATIC_SCOPE);
774 * GstRtpJitterBuffer::on-npt-stop:
775 * @buffer: the object which received the signal
777 * Signal that the jitterbufer has pushed the RTP packet that corresponds to
778 * the npt-stop position.
780 gst_rtp_jitter_buffer_signals[SIGNAL_ON_NPT_STOP] =
781 g_signal_new ("on-npt-stop", G_TYPE_FROM_CLASS (klass),
782 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
783 on_npt_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID,
784 G_TYPE_NONE, 0, G_TYPE_NONE);
787 * GstRtpJitterBuffer::clear-pt-map:
788 * @buffer: the object which received the signal
790 * Invalidate the clock-rate as obtained with the
791 * #GstRtpJitterBuffer::request-pt-map signal.
793 gst_rtp_jitter_buffer_signals[SIGNAL_CLEAR_PT_MAP] =
794 g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
795 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
796 G_STRUCT_OFFSET (GstRtpJitterBufferClass, clear_pt_map), NULL, NULL,
797 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
800 * GstRtpJitterBuffer::set-active:
801 * @buffer: the object which received the signal
803 * Start pushing out packets with the given base time. This signal is only
804 * useful in buffering mode.
806 * Returns: the time of the last pushed packet.
808 gst_rtp_jitter_buffer_signals[SIGNAL_SET_ACTIVE] =
809 g_signal_new ("set-active", G_TYPE_FROM_CLASS (klass),
810 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
811 G_STRUCT_OFFSET (GstRtpJitterBufferClass, set_active), NULL, NULL,
812 g_cclosure_marshal_generic, G_TYPE_UINT64, 2, G_TYPE_BOOLEAN,
815 gstelement_class->change_state =
816 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_change_state);
817 gstelement_class->request_new_pad =
818 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_request_new_pad);
819 gstelement_class->release_pad =
820 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_release_pad);
821 gstelement_class->provide_clock =
822 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_provide_clock);
824 gst_element_class_add_static_pad_template (gstelement_class,
825 &gst_rtp_jitter_buffer_src_template);
826 gst_element_class_add_static_pad_template (gstelement_class,
827 &gst_rtp_jitter_buffer_sink_template);
828 gst_element_class_add_static_pad_template (gstelement_class,
829 &gst_rtp_jitter_buffer_sink_rtcp_template);
831 gst_element_class_set_static_metadata (gstelement_class,
832 "RTP packet jitter-buffer", "Filter/Network/RTP",
833 "A buffer that deals with network jitter and other transmission faults",
834 "Philippe Kalaf <philippe.kalaf@collabora.co.uk>, "
835 "Wim Taymans <wim.taymans@gmail.com>");
837 klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_clear_pt_map);
838 klass->set_active = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_set_active);
840 GST_DEBUG_CATEGORY_INIT
841 (rtpjitterbuffer_debug, "rtpjitterbuffer", 0, "RTP Jitter Buffer");
845 gst_rtp_jitter_buffer_init (GstRtpJitterBuffer * jitterbuffer)
847 GstRtpJitterBufferPrivate *priv;
849 priv = GST_RTP_JITTER_BUFFER_GET_PRIVATE (jitterbuffer);
850 jitterbuffer->priv = priv;
852 priv->latency_ms = DEFAULT_LATENCY_MS;
853 priv->latency_ns = priv->latency_ms * GST_MSECOND;
854 priv->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
855 priv->do_lost = DEFAULT_DO_LOST;
856 priv->do_retransmission = DEFAULT_DO_RETRANSMISSION;
857 priv->rtx_next_seqnum = DEFAULT_RTX_NEXT_SEQNUM;
858 priv->rtx_delay = DEFAULT_RTX_DELAY;
859 priv->rtx_min_delay = DEFAULT_RTX_MIN_DELAY;
860 priv->rtx_delay_reorder = DEFAULT_RTX_DELAY_REORDER;
861 priv->rtx_retry_timeout = DEFAULT_RTX_RETRY_TIMEOUT;
862 priv->rtx_min_retry_timeout = DEFAULT_RTX_MIN_RETRY_TIMEOUT;
863 priv->rtx_retry_period = DEFAULT_RTX_RETRY_PERIOD;
864 priv->rtx_max_retries = DEFAULT_RTX_MAX_RETRIES;
865 priv->max_rtcp_rtp_time_diff = DEFAULT_MAX_RTCP_RTP_TIME_DIFF;
866 priv->max_dropout_time = DEFAULT_MAX_DROPOUT_TIME;
867 priv->max_misorder_time = DEFAULT_MAX_MISORDER_TIME;
870 priv->last_rtptime = -1;
871 priv->avg_jitter = 0;
872 priv->timers = g_array_new (FALSE, TRUE, sizeof (TimerData));
873 priv->jbuf = rtp_jitter_buffer_new ();
874 g_mutex_init (&priv->jbuf_lock);
875 g_cond_init (&priv->jbuf_timer);
876 g_cond_init (&priv->jbuf_event);
877 g_cond_init (&priv->jbuf_query);
878 g_queue_init (&priv->gap_packets);
880 /* reset skew detection initialy */
881 rtp_jitter_buffer_reset_skew (priv->jbuf);
882 rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
883 rtp_jitter_buffer_set_buffering (priv->jbuf, FALSE);
887 gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_src_template,
890 gst_pad_set_activatemode_function (priv->srcpad,
891 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_activate_mode));
892 gst_pad_set_query_function (priv->srcpad,
893 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_query));
894 gst_pad_set_event_function (priv->srcpad,
895 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_event));
898 gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_sink_template,
901 gst_pad_set_chain_function (priv->sinkpad,
902 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_chain));
903 gst_pad_set_event_function (priv->sinkpad,
904 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_event));
905 gst_pad_set_query_function (priv->sinkpad,
906 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_query));
908 gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->srcpad);
909 gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->sinkpad);
911 GST_OBJECT_FLAG_SET (jitterbuffer, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
914 #define IS_DROPABLE(it) (((it)->type == ITEM_TYPE_BUFFER) || ((it)->type == ITEM_TYPE_LOST))
916 #define ITEM_TYPE_BUFFER 0
917 #define ITEM_TYPE_LOST 1
918 #define ITEM_TYPE_EVENT 2
919 #define ITEM_TYPE_QUERY 3
921 static RTPJitterBufferItem *
922 alloc_item (gpointer data, guint type, GstClockTime dts, GstClockTime pts,
923 guint seqnum, guint count, guint rtptime)
925 RTPJitterBufferItem *item;
927 item = g_slice_new (RTPJitterBufferItem);
934 item->seqnum = seqnum;
936 item->rtptime = rtptime;
942 free_item (RTPJitterBufferItem * item)
944 g_return_if_fail (item != NULL);
946 if (item->data && item->type != ITEM_TYPE_QUERY)
947 gst_mini_object_unref (item->data);
948 g_slice_free (RTPJitterBufferItem, item);
952 free_item_and_retain_events (RTPJitterBufferItem * item, gpointer user_data)
954 GList **l = user_data;
956 if (item->data && item->type == ITEM_TYPE_EVENT
957 && GST_EVENT_IS_STICKY (item->data)) {
958 *l = g_list_prepend (*l, item->data);
959 } else if (item->data && item->type != ITEM_TYPE_QUERY) {
960 gst_mini_object_unref (item->data);
962 g_slice_free (RTPJitterBufferItem, item);
966 gst_rtp_jitter_buffer_finalize (GObject * object)
968 GstRtpJitterBuffer *jitterbuffer;
969 GstRtpJitterBufferPrivate *priv;
971 jitterbuffer = GST_RTP_JITTER_BUFFER (object);
972 priv = jitterbuffer->priv;
974 g_array_free (priv->timers, TRUE);
975 g_mutex_clear (&priv->jbuf_lock);
976 g_cond_clear (&priv->jbuf_timer);
977 g_cond_clear (&priv->jbuf_event);
978 g_cond_clear (&priv->jbuf_query);
980 rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
981 g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
982 g_queue_clear (&priv->gap_packets);
983 g_object_unref (priv->jbuf);
985 G_OBJECT_CLASS (parent_class)->finalize (object);
989 gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad, GstObject * parent)
991 GstRtpJitterBuffer *jitterbuffer;
992 GstPad *otherpad = NULL;
993 GstIterator *it = NULL;
996 jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
998 if (pad == jitterbuffer->priv->sinkpad) {
999 otherpad = jitterbuffer->priv->srcpad;
1000 } else if (pad == jitterbuffer->priv->srcpad) {
1001 otherpad = jitterbuffer->priv->sinkpad;
1002 } else if (pad == jitterbuffer->priv->rtcpsinkpad) {
1003 it = gst_iterator_new_single (GST_TYPE_PAD, NULL);
1007 g_value_init (&val, GST_TYPE_PAD);
1008 g_value_set_object (&val, otherpad);
1009 it = gst_iterator_new_single (GST_TYPE_PAD, &val);
1010 g_value_unset (&val);
1017 create_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
1019 GstRtpJitterBufferPrivate *priv;
1021 priv = jitterbuffer->priv;
1023 GST_DEBUG_OBJECT (jitterbuffer, "creating RTCP sink pad");
1026 gst_pad_new_from_static_template
1027 (&gst_rtp_jitter_buffer_sink_rtcp_template, "sink_rtcp");
1028 gst_pad_set_chain_function (priv->rtcpsinkpad,
1029 gst_rtp_jitter_buffer_chain_rtcp);
1030 gst_pad_set_event_function (priv->rtcpsinkpad,
1031 (GstPadEventFunction) gst_rtp_jitter_buffer_sink_rtcp_event);
1032 gst_pad_set_iterate_internal_links_function (priv->rtcpsinkpad,
1033 gst_rtp_jitter_buffer_iterate_internal_links);
1034 gst_pad_set_active (priv->rtcpsinkpad, TRUE);
1035 gst_element_add_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
1037 return priv->rtcpsinkpad;
1041 remove_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
1043 GstRtpJitterBufferPrivate *priv;
1045 priv = jitterbuffer->priv;
1047 GST_DEBUG_OBJECT (jitterbuffer, "removing RTCP sink pad");
1049 gst_pad_set_active (priv->rtcpsinkpad, FALSE);
1051 gst_element_remove_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
1052 priv->rtcpsinkpad = NULL;
1056 gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
1057 GstPadTemplate * templ, const gchar * name, const GstCaps * filter)
1059 GstRtpJitterBuffer *jitterbuffer;
1060 GstElementClass *klass;
1062 GstRtpJitterBufferPrivate *priv;
1064 g_return_val_if_fail (templ != NULL, NULL);
1065 g_return_val_if_fail (GST_IS_RTP_JITTER_BUFFER (element), NULL);
1067 jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (element);
1068 priv = jitterbuffer->priv;
1069 klass = GST_ELEMENT_GET_CLASS (element);
1071 GST_DEBUG_OBJECT (element, "requesting pad %s", GST_STR_NULL (name));
1073 /* figure out the template */
1074 if (templ == gst_element_class_get_pad_template (klass, "sink_rtcp")) {
1075 if (priv->rtcpsinkpad != NULL)
1078 result = create_rtcp_sink (jitterbuffer);
1080 goto wrong_template;
1087 g_warning ("rtpjitterbuffer: this is not our template");
1092 g_warning ("rtpjitterbuffer: pad already requested");
1098 gst_rtp_jitter_buffer_release_pad (GstElement * element, GstPad * pad)
1100 GstRtpJitterBuffer *jitterbuffer;
1101 GstRtpJitterBufferPrivate *priv;
1103 g_return_if_fail (GST_IS_RTP_JITTER_BUFFER (element));
1104 g_return_if_fail (GST_IS_PAD (pad));
1106 jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (element);
1107 priv = jitterbuffer->priv;
1109 GST_DEBUG_OBJECT (element, "releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1111 if (priv->rtcpsinkpad == pad) {
1112 remove_rtcp_sink (jitterbuffer);
1121 g_warning ("gstjitterbuffer: asked to release an unknown pad");
1127 gst_rtp_jitter_buffer_provide_clock (GstElement * element)
1129 return gst_system_clock_obtain ();
1133 gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer)
1135 GstRtpJitterBufferPrivate *priv;
1137 priv = jitterbuffer->priv;
1139 /* this will trigger a new pt-map request signal, FIXME, do something better. */
1142 priv->clock_rate = -1;
1143 /* do not clear current content, but refresh state for new arrival */
1144 GST_DEBUG_OBJECT (jitterbuffer, "reset jitterbuffer");
1145 rtp_jitter_buffer_reset_skew (priv->jbuf);
1150 gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jbuf, gboolean active,
1153 GstRtpJitterBufferPrivate *priv;
1154 GstClockTime last_out;
1155 RTPJitterBufferItem *item;
1160 GST_DEBUG_OBJECT (jbuf, "setting active %d with offset %" GST_TIME_FORMAT,
1161 active, GST_TIME_ARGS (offset));
1163 if (active != priv->active) {
1164 /* add the amount of time spent in paused to the output offset. All
1165 * outgoing buffers will have this offset applied to their timestamps in
1166 * order to make them arrive in time in the sink. */
1167 priv->out_offset = offset;
1168 GST_DEBUG_OBJECT (jbuf, "out offset %" GST_TIME_FORMAT,
1169 GST_TIME_ARGS (priv->out_offset));
1170 priv->active = active;
1171 JBUF_SIGNAL_EVENT (priv);
1174 rtp_jitter_buffer_set_buffering (priv->jbuf, TRUE);
1176 if ((item = rtp_jitter_buffer_peek (priv->jbuf))) {
1177 /* head buffer timestamp and offset gives our output time */
1178 last_out = item->dts + priv->ts_offset;
1180 /* use last known time when the buffer is empty */
1181 last_out = priv->last_out_time;
1189 gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter)
1191 GstRtpJitterBuffer *jitterbuffer;
1192 GstRtpJitterBufferPrivate *priv;
1197 jitterbuffer = GST_RTP_JITTER_BUFFER (gst_pad_get_parent (pad));
1198 priv = jitterbuffer->priv;
1200 other = (pad == priv->srcpad ? priv->sinkpad : priv->srcpad);
1202 caps = gst_pad_peer_query_caps (other, filter);
1204 templ = gst_pad_get_pad_template_caps (pad);
1206 GST_DEBUG_OBJECT (jitterbuffer, "use template");
1211 GST_DEBUG_OBJECT (jitterbuffer, "intersect with template");
1213 intersect = gst_caps_intersect (caps, templ);
1214 gst_caps_unref (caps);
1215 gst_caps_unref (templ);
1219 gst_object_unref (jitterbuffer);
1225 * Must be called with JBUF_LOCK held
1229 gst_jitter_buffer_sink_parse_caps (GstRtpJitterBuffer * jitterbuffer,
1232 GstRtpJitterBufferPrivate *priv;
1233 GstStructure *caps_struct;
1237 priv = jitterbuffer->priv;
1239 /* first parse the caps */
1240 caps_struct = gst_caps_get_structure (caps, 0);
1242 GST_DEBUG_OBJECT (jitterbuffer, "got caps");
1244 /* we need a clock-rate to convert the rtp timestamps to GStreamer time and to
1245 * measure the amount of data in the buffer */
1246 if (!gst_structure_get_int (caps_struct, "clock-rate", &priv->clock_rate))
1249 if (priv->clock_rate <= 0)
1252 GST_DEBUG_OBJECT (jitterbuffer, "got clock-rate %d", priv->clock_rate);
1254 rtp_jitter_buffer_set_clock_rate (priv->jbuf, priv->clock_rate);
1256 /* The clock base is the RTP timestamp corrsponding to the npt-start value. We
1257 * can use this to track the amount of time elapsed on the sender. */
1258 if (gst_structure_get_uint (caps_struct, "clock-base", &val))
1259 priv->clock_base = val;
1261 priv->clock_base = -1;
1263 priv->ext_timestamp = priv->clock_base;
1265 GST_DEBUG_OBJECT (jitterbuffer, "got clock-base %" G_GINT64_FORMAT,
1268 if (gst_structure_get_uint (caps_struct, "seqnum-base", &val)) {
1269 /* first expected seqnum, only update when we didn't have a previous base. */
1270 if (priv->next_in_seqnum == -1)
1271 priv->next_in_seqnum = val;
1272 if (priv->next_seqnum == -1) {
1273 priv->next_seqnum = val;
1274 JBUF_SIGNAL_EVENT (priv);
1276 priv->seqnum_base = val;
1278 priv->seqnum_base = -1;
1281 GST_DEBUG_OBJECT (jitterbuffer, "got seqnum-base %d", priv->next_in_seqnum);
1283 /* the start and stop times. The seqnum-base corresponds to the start time. We
1284 * will keep track of the seqnums on the output and when we reach the one
1285 * corresponding to npt-stop, we emit the npt-stop-reached signal */
1286 if (gst_structure_get_clock_time (caps_struct, "npt-start", &tval))
1287 priv->npt_start = tval;
1289 priv->npt_start = 0;
1291 if (gst_structure_get_clock_time (caps_struct, "npt-stop", &tval))
1292 priv->npt_stop = tval;
1294 priv->npt_stop = -1;
1296 GST_DEBUG_OBJECT (jitterbuffer,
1297 "npt start/stop: %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
1298 GST_TIME_ARGS (priv->npt_start), GST_TIME_ARGS (priv->npt_stop));
1305 GST_DEBUG_OBJECT (jitterbuffer, "No clock-rate in caps!");
1310 GST_DEBUG_OBJECT (jitterbuffer, "Invalid clock-rate %d", priv->clock_rate);
1316 gst_rtp_jitter_buffer_flush_start (GstRtpJitterBuffer * jitterbuffer)
1318 GstRtpJitterBufferPrivate *priv;
1320 priv = jitterbuffer->priv;
1323 /* mark ourselves as flushing */
1324 priv->srcresult = GST_FLOW_FLUSHING;
1325 GST_DEBUG_OBJECT (jitterbuffer, "Disabling pop on queue");
1326 /* this unblocks any waiting pops on the src pad task */
1327 JBUF_SIGNAL_EVENT (priv);
1328 JBUF_SIGNAL_QUERY (priv, FALSE);
1333 gst_rtp_jitter_buffer_flush_stop (GstRtpJitterBuffer * jitterbuffer)
1335 GstRtpJitterBufferPrivate *priv;
1337 priv = jitterbuffer->priv;
1340 GST_DEBUG_OBJECT (jitterbuffer, "Enabling pop on queue");
1341 /* Mark as non flushing */
1342 priv->srcresult = GST_FLOW_OK;
1343 gst_segment_init (&priv->segment, GST_FORMAT_TIME);
1344 priv->last_popped_seqnum = -1;
1345 priv->last_out_time = -1;
1346 priv->next_seqnum = -1;
1347 priv->seqnum_base = -1;
1348 priv->ips_rtptime = -1;
1349 priv->ips_dts = GST_CLOCK_TIME_NONE;
1350 priv->packet_spacing = 0;
1351 priv->next_in_seqnum = -1;
1352 priv->clock_rate = -1;
1355 priv->estimated_eos = -1;
1356 priv->last_elapsed = 0;
1357 priv->ext_timestamp = -1;
1358 priv->avg_jitter = 0;
1359 priv->last_dts = -1;
1360 priv->last_rtptime = -1;
1361 priv->last_in_dts = 0;
1362 GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
1363 rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
1364 rtp_jitter_buffer_disable_buffering (priv->jbuf, FALSE);
1365 rtp_jitter_buffer_reset_skew (priv->jbuf);
1366 remove_all_timers (jitterbuffer);
1367 g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
1368 g_queue_clear (&priv->gap_packets);
1373 gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad, GstObject * parent,
1374 GstPadMode mode, gboolean active)
1377 GstRtpJitterBuffer *jitterbuffer = NULL;
1379 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1382 case GST_PAD_MODE_PUSH:
1384 /* allow data processing */
1385 gst_rtp_jitter_buffer_flush_stop (jitterbuffer);
1387 /* start pushing out buffers */
1388 GST_DEBUG_OBJECT (jitterbuffer, "Starting task on srcpad");
1389 result = gst_pad_start_task (jitterbuffer->priv->srcpad,
1390 (GstTaskFunction) gst_rtp_jitter_buffer_loop, jitterbuffer, NULL);
1392 /* make sure all data processing stops ASAP */
1393 gst_rtp_jitter_buffer_flush_start (jitterbuffer);
1395 /* NOTE this will hardlock if the state change is called from the src pad
1396 * task thread because we will _join() the thread. */
1397 GST_DEBUG_OBJECT (jitterbuffer, "Stopping task on srcpad");
1398 result = gst_pad_stop_task (pad);
1408 static GstStateChangeReturn
1409 gst_rtp_jitter_buffer_change_state (GstElement * element,
1410 GstStateChange transition)
1412 GstRtpJitterBuffer *jitterbuffer;
1413 GstRtpJitterBufferPrivate *priv;
1414 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1416 jitterbuffer = GST_RTP_JITTER_BUFFER (element);
1417 priv = jitterbuffer->priv;
1419 switch (transition) {
1420 case GST_STATE_CHANGE_NULL_TO_READY:
1422 case GST_STATE_CHANGE_READY_TO_PAUSED:
1424 /* reset negotiated values */
1425 priv->clock_rate = -1;
1426 priv->clock_base = -1;
1427 priv->peer_latency = 0;
1429 /* block until we go to PLAYING */
1430 priv->blocked = TRUE;
1431 priv->timer_running = TRUE;
1432 priv->timer_thread =
1433 g_thread_new ("timer", (GThreadFunc) wait_next_timeout, jitterbuffer);
1436 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1438 /* unblock to allow streaming in PLAYING */
1439 priv->blocked = FALSE;
1440 JBUF_SIGNAL_EVENT (priv);
1441 JBUF_SIGNAL_TIMER (priv);
1448 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1450 switch (transition) {
1451 case GST_STATE_CHANGE_READY_TO_PAUSED:
1452 /* we are a live element because we sync to the clock, which we can only
1453 * do in the PLAYING state */
1454 if (ret != GST_STATE_CHANGE_FAILURE)
1455 ret = GST_STATE_CHANGE_NO_PREROLL;
1457 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1459 /* block to stop streaming when PAUSED */
1460 priv->blocked = TRUE;
1461 unschedule_current_timer (jitterbuffer);
1463 if (ret != GST_STATE_CHANGE_FAILURE)
1464 ret = GST_STATE_CHANGE_NO_PREROLL;
1466 case GST_STATE_CHANGE_PAUSED_TO_READY:
1468 gst_buffer_replace (&priv->last_sr, NULL);
1469 priv->timer_running = FALSE;
1470 unschedule_current_timer (jitterbuffer);
1471 JBUF_SIGNAL_TIMER (priv);
1472 JBUF_SIGNAL_QUERY (priv, FALSE);
1474 g_thread_join (priv->timer_thread);
1475 priv->timer_thread = NULL;
1477 case GST_STATE_CHANGE_READY_TO_NULL:
1487 gst_rtp_jitter_buffer_src_event (GstPad * pad, GstObject * parent,
1490 gboolean ret = TRUE;
1491 GstRtpJitterBuffer *jitterbuffer;
1492 GstRtpJitterBufferPrivate *priv;
1494 jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
1495 priv = jitterbuffer->priv;
1497 GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1499 switch (GST_EVENT_TYPE (event)) {
1500 case GST_EVENT_LATENCY:
1502 GstClockTime latency;
1504 gst_event_parse_latency (event, &latency);
1506 GST_DEBUG_OBJECT (jitterbuffer,
1507 "configuring latency of %" GST_TIME_FORMAT, GST_TIME_ARGS (latency));
1510 /* adjust the overall buffer delay to the total pipeline latency in
1511 * buffering mode because if downstream consumes too fast (because of
1512 * large latency or queues, we would start rebuffering again. */
1513 if (rtp_jitter_buffer_get_mode (priv->jbuf) ==
1514 RTP_JITTER_BUFFER_MODE_BUFFER) {
1515 rtp_jitter_buffer_set_delay (priv->jbuf, latency);
1519 ret = gst_pad_push_event (priv->sinkpad, event);
1523 ret = gst_pad_push_event (priv->sinkpad, event);
1530 /* handles and stores the event in the jitterbuffer, must be called with
1533 queue_event (GstRtpJitterBuffer * jitterbuffer, GstEvent * event)
1535 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1536 RTPJitterBufferItem *item;
1539 switch (GST_EVENT_TYPE (event)) {
1540 case GST_EVENT_CAPS:
1544 gst_event_parse_caps (event, &caps);
1545 gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1548 case GST_EVENT_SEGMENT:
1549 gst_event_copy_segment (event, &priv->segment);
1551 /* we need time for now */
1552 if (priv->segment.format != GST_FORMAT_TIME)
1553 goto newseg_wrong_format;
1555 GST_DEBUG_OBJECT (jitterbuffer,
1556 "segment: %" GST_SEGMENT_FORMAT, &priv->segment);
1560 rtp_jitter_buffer_disable_buffering (priv->jbuf, TRUE);
1567 GST_DEBUG_OBJECT (jitterbuffer, "adding event");
1568 item = alloc_item (event, ITEM_TYPE_EVENT, -1, -1, -1, 0, -1);
1569 rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
1571 JBUF_SIGNAL_EVENT (priv);
1576 newseg_wrong_format:
1578 GST_DEBUG_OBJECT (jitterbuffer, "received non TIME newsegment");
1579 gst_event_unref (event);
1585 gst_rtp_jitter_buffer_sink_event (GstPad * pad, GstObject * parent,
1588 gboolean ret = TRUE;
1589 GstRtpJitterBuffer *jitterbuffer;
1590 GstRtpJitterBufferPrivate *priv;
1592 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1593 priv = jitterbuffer->priv;
1595 GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1597 switch (GST_EVENT_TYPE (event)) {
1598 case GST_EVENT_FLUSH_START:
1599 ret = gst_pad_push_event (priv->srcpad, event);
1600 gst_rtp_jitter_buffer_flush_start (jitterbuffer);
1601 /* wait for the loop to go into PAUSED */
1602 gst_pad_pause_task (priv->srcpad);
1604 case GST_EVENT_FLUSH_STOP:
1605 ret = gst_pad_push_event (priv->srcpad, event);
1607 gst_rtp_jitter_buffer_src_activate_mode (priv->srcpad, parent,
1608 GST_PAD_MODE_PUSH, TRUE);
1611 if (GST_EVENT_IS_SERIALIZED (event)) {
1612 /* serialized events go in the queue */
1614 if (priv->srcresult != GST_FLOW_OK) {
1615 /* Errors in sticky event pushing are no problem and ignored here
1616 * as they will cause more meaningful errors during data flow.
1617 * For EOS events, that are not followed by data flow, we still
1618 * return FALSE here though.
1620 if (!GST_EVENT_IS_STICKY (event) ||
1621 GST_EVENT_TYPE (event) == GST_EVENT_EOS)
1622 goto out_flow_error;
1624 /* refuse more events on EOS */
1627 ret = queue_event (jitterbuffer, event);
1630 /* non-serialized events are forwarded downstream immediately */
1631 ret = gst_pad_push_event (priv->srcpad, event);
1640 GST_DEBUG_OBJECT (jitterbuffer,
1641 "refusing event, we have a downstream flow error: %s",
1642 gst_flow_get_name (priv->srcresult));
1644 gst_event_unref (event);
1649 GST_DEBUG_OBJECT (jitterbuffer, "refusing event, we are EOS");
1651 gst_event_unref (event);
1657 gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad, GstObject * parent,
1660 gboolean ret = TRUE;
1661 GstRtpJitterBuffer *jitterbuffer;
1663 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1665 GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1667 switch (GST_EVENT_TYPE (event)) {
1668 case GST_EVENT_FLUSH_START:
1669 gst_event_unref (event);
1671 case GST_EVENT_FLUSH_STOP:
1672 gst_event_unref (event);
1675 ret = gst_pad_event_default (pad, parent, event);
1683 * Must be called with JBUF_LOCK held, will release the LOCK when emiting the
1684 * signal. The function returns GST_FLOW_ERROR when a parsing error happened and
1685 * GST_FLOW_FLUSHING when the element is shutting down. On success
1686 * GST_FLOW_OK is returned.
1688 static GstFlowReturn
1689 gst_rtp_jitter_buffer_get_clock_rate (GstRtpJitterBuffer * jitterbuffer,
1693 GValue args[2] = { {0}, {0} };
1697 g_value_init (&args[0], GST_TYPE_ELEMENT);
1698 g_value_set_object (&args[0], jitterbuffer);
1699 g_value_init (&args[1], G_TYPE_UINT);
1700 g_value_set_uint (&args[1], pt);
1702 g_value_init (&ret, GST_TYPE_CAPS);
1703 g_value_set_boxed (&ret, NULL);
1705 JBUF_UNLOCK (jitterbuffer->priv);
1706 g_signal_emitv (args, gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP], 0,
1708 JBUF_LOCK_CHECK (jitterbuffer->priv, out_flushing);
1710 g_value_unset (&args[0]);
1711 g_value_unset (&args[1]);
1712 caps = (GstCaps *) g_value_dup_boxed (&ret);
1713 g_value_unset (&ret);
1717 res = gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1718 gst_caps_unref (caps);
1720 if (G_UNLIKELY (!res))
1728 GST_DEBUG_OBJECT (jitterbuffer, "could not get caps");
1729 return GST_FLOW_ERROR;
1733 GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
1734 return GST_FLOW_FLUSHING;
1738 GST_DEBUG_OBJECT (jitterbuffer, "parse failed");
1739 return GST_FLOW_ERROR;
1743 /* call with jbuf lock held */
1745 check_buffering_percent (GstRtpJitterBuffer * jitterbuffer, gint percent)
1747 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1748 GstMessage *message = NULL;
1753 /* Post a buffering message */
1754 if (priv->last_percent != percent) {
1755 priv->last_percent = percent;
1757 gst_message_new_buffering (GST_OBJECT_CAST (jitterbuffer), percent);
1758 gst_message_set_buffering_stats (message, GST_BUFFERING_LIVE, -1, -1, -1);
1765 apply_offset (GstRtpJitterBuffer * jitterbuffer, GstClockTime timestamp)
1767 GstRtpJitterBufferPrivate *priv;
1769 priv = jitterbuffer->priv;
1771 if (timestamp == -1)
1774 /* apply the timestamp offset, this is used for inter stream sync */
1775 timestamp += priv->ts_offset;
1776 /* add the offset, this is used when buffering */
1777 timestamp += priv->out_offset;
1783 find_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type, guint16 seqnum)
1785 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1786 TimerData *timer = NULL;
1789 len = priv->timers->len;
1790 for (i = 0; i < len; i++) {
1791 TimerData *test = &g_array_index (priv->timers, TimerData, i);
1792 if (test->seqnum == seqnum && test->type == type) {
1801 unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer)
1803 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1805 if (priv->clock_id) {
1806 GST_DEBUG_OBJECT (jitterbuffer, "unschedule current timer");
1807 gst_clock_id_unschedule (priv->clock_id);
1808 priv->clock_id = NULL;
1813 get_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1815 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1816 GstClockTime test_timeout;
1818 if ((test_timeout = timer->timeout) == -1)
1821 if (timer->type != TIMER_TYPE_EXPECTED) {
1822 /* add our latency and offset to get output times. */
1823 test_timeout = apply_offset (jitterbuffer, test_timeout);
1824 test_timeout += priv->latency_ns;
1826 return test_timeout;
1830 recalculate_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1832 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1834 if (priv->clock_id) {
1835 GstClockTime timeout = get_timeout (jitterbuffer, timer);
1837 GST_DEBUG ("%" GST_TIME_FORMAT " <> %" GST_TIME_FORMAT,
1838 GST_TIME_ARGS (timeout), GST_TIME_ARGS (priv->timer_timeout));
1840 if (timeout == -1 || timeout < priv->timer_timeout)
1841 unschedule_current_timer (jitterbuffer);
1846 add_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
1847 guint16 seqnum, guint num, GstClockTime timeout, GstClockTime delay,
1848 GstClockTime duration)
1850 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1854 GST_DEBUG_OBJECT (jitterbuffer,
1855 "add timer %d for seqnum %d to %" GST_TIME_FORMAT ", delay %"
1856 GST_TIME_FORMAT, type, seqnum, GST_TIME_ARGS (timeout),
1857 GST_TIME_ARGS (delay));
1859 len = priv->timers->len;
1860 g_array_set_size (priv->timers, len + 1);
1861 timer = &g_array_index (priv->timers, TimerData, len);
1864 timer->seqnum = seqnum;
1866 timer->timeout = timeout + delay;
1867 timer->duration = duration;
1868 if (type == TIMER_TYPE_EXPECTED) {
1869 timer->rtx_base = timeout;
1870 timer->rtx_delay = delay;
1871 timer->rtx_retry = 0;
1873 timer->num_rtx_retry = 0;
1874 recalculate_timer (jitterbuffer, timer);
1875 JBUF_SIGNAL_TIMER (priv);
1881 reschedule_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
1882 guint16 seqnum, GstClockTime timeout, GstClockTime delay, gboolean reset)
1884 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1885 gboolean seqchange, timechange;
1888 seqchange = timer->seqnum != seqnum;
1889 timechange = timer->timeout != timeout;
1891 if (!seqchange && !timechange)
1894 oldseq = timer->seqnum;
1896 GST_DEBUG_OBJECT (jitterbuffer,
1897 "replace timer for seqnum %d->%d to %" GST_TIME_FORMAT,
1898 oldseq, seqnum, GST_TIME_ARGS (timeout + delay));
1900 timer->timeout = timeout + delay;
1901 timer->seqnum = seqnum;
1903 timer->rtx_base = timeout;
1904 timer->rtx_delay = delay;
1905 timer->rtx_retry = 0;
1908 timer->num_rtx_retry = 0;
1910 if (priv->clock_id) {
1911 /* we changed the seqnum and there is a timer currently waiting with this
1912 * seqnum, unschedule it */
1913 if (seqchange && priv->timer_seqnum == oldseq)
1914 unschedule_current_timer (jitterbuffer);
1915 /* we changed the time, check if it is earlier than what we are waiting
1916 * for and unschedule if so */
1917 else if (timechange)
1918 recalculate_timer (jitterbuffer, timer);
1923 set_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
1924 guint16 seqnum, GstClockTime timeout)
1928 /* find the seqnum timer */
1929 timer = find_timer (jitterbuffer, type, seqnum);
1930 if (timer == NULL) {
1931 timer = add_timer (jitterbuffer, type, seqnum, 0, timeout, 0, -1);
1933 reschedule_timer (jitterbuffer, timer, seqnum, timeout, 0, FALSE);
1939 remove_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1941 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1944 if (priv->clock_id && priv->timer_seqnum == timer->seqnum)
1945 unschedule_current_timer (jitterbuffer);
1948 GST_DEBUG_OBJECT (jitterbuffer, "removed index %d", idx);
1949 g_array_remove_index_fast (priv->timers, idx);
1954 remove_all_timers (GstRtpJitterBuffer * jitterbuffer)
1956 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1957 GST_DEBUG_OBJECT (jitterbuffer, "removed all timers");
1958 g_array_set_size (priv->timers, 0);
1959 unschedule_current_timer (jitterbuffer);
1962 /* get the extra delay to wait before sending RTX */
1964 get_rtx_delay (GstRtpJitterBufferPrivate * priv)
1968 if (priv->rtx_delay == -1) {
1969 if (priv->avg_jitter == 0 && priv->packet_spacing == 0) {
1970 delay = DEFAULT_AUTO_RTX_DELAY;
1972 /* jitter is in nanoseconds, maximum of 2x jitter and half the
1973 * packet spacing is a good margin */
1974 delay = MAX (priv->avg_jitter * 2, priv->packet_spacing / 2);
1977 delay = priv->rtx_delay * GST_MSECOND;
1979 if (priv->rtx_min_delay > 0)
1980 delay = MAX (delay, priv->rtx_min_delay * GST_MSECOND);
1985 /* we just received a packet with seqnum and dts.
1987 * First check for old seqnum that we are still expecting. If the gap with the
1988 * current seqnum is too big, unschedule the timeouts.
1990 * If we have a valid packet spacing estimate we can set a timer for when we
1991 * should receive the next packet.
1992 * If we don't have a valid estimate, we remove any timer we might have
1993 * had for this packet.
1996 update_timers (GstRtpJitterBuffer * jitterbuffer, guint16 seqnum,
1997 GstClockTime dts, gboolean do_next_seqnum)
1999 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2000 TimerData *timer = NULL;
2003 /* go through all timers and unschedule the ones with a large gap, also find
2004 * the timer for the seqnum */
2005 len = priv->timers->len;
2006 for (i = 0; i < len; i++) {
2007 TimerData *test = &g_array_index (priv->timers, TimerData, i);
2010 gap = gst_rtp_buffer_compare_seqnum (test->seqnum, seqnum);
2012 GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, #%d<->#%d gap %d", i,
2013 test->type, test->seqnum, seqnum, gap);
2016 GST_DEBUG ("found timer for current seqnum");
2017 /* the timer for the current seqnum */
2019 /* when no retransmission, we can stop now, we only need to find the
2020 * timer for the current seqnum */
2021 if (!priv->do_retransmission)
2023 } else if (gap > priv->rtx_delay_reorder) {
2024 /* max gap, we exceeded the max reorder distance and we don't expect the
2025 * missing packet to be this reordered */
2026 if (test->num_rtx_retry == 0 && test->type == TIMER_TYPE_EXPECTED)
2027 reschedule_timer (jitterbuffer, test, test->seqnum, -1, 0, FALSE);
2031 do_next_seqnum = do_next_seqnum && priv->packet_spacing > 0
2032 && priv->do_retransmission && priv->rtx_next_seqnum;
2034 if (timer && timer->type != TIMER_TYPE_DEADLINE) {
2035 if (timer->num_rtx_retry > 0) {
2036 GstClockTime rtx_last, delay;
2038 /* we scheduled a retry for this packet and now we have it */
2039 priv->num_rtx_success++;
2040 /* all the previous retry attempts failed */
2041 priv->num_rtx_failed += timer->num_rtx_retry - 1;
2042 /* number of retries before receiving the packet */
2043 if (priv->avg_rtx_num == 0.0)
2044 priv->avg_rtx_num = timer->num_rtx_retry;
2046 priv->avg_rtx_num = (timer->num_rtx_retry + 7 * priv->avg_rtx_num) / 8;
2047 /* calculate the delay between retransmission request and receiving this
2048 * packet, start with when we scheduled this timeout last */
2049 rtx_last = timer->rtx_last;
2050 if (dts != GST_CLOCK_TIME_NONE && dts > rtx_last) {
2051 /* we have a valid delay if this packet arrived after we scheduled the
2053 delay = dts - rtx_last;
2054 if (priv->avg_rtx_rtt == 0)
2055 priv->avg_rtx_rtt = delay;
2057 priv->avg_rtx_rtt = (delay + 7 * priv->avg_rtx_rtt) / 8;
2061 GST_LOG_OBJECT (jitterbuffer,
2062 "RTX success %" G_GUINT64_FORMAT ", failed %" G_GUINT64_FORMAT
2063 ", requests %" G_GUINT64_FORMAT ", dups %" G_GUINT64_FORMAT
2064 ", avg-num %g, delay %" GST_TIME_FORMAT ", avg-rtt %" GST_TIME_FORMAT,
2065 priv->num_rtx_success, priv->num_rtx_failed, priv->num_rtx_requests,
2066 priv->num_duplicates, priv->avg_rtx_num, GST_TIME_ARGS (delay),
2067 GST_TIME_ARGS (priv->avg_rtx_rtt));
2069 /* don't try to estimate the next seqnum because this is a retransmitted
2070 * packet and it probably did not arrive with the expected packet
2072 do_next_seqnum = FALSE;
2076 if (do_next_seqnum && dts != GST_CLOCK_TIME_NONE) {
2077 GstClockTime expected, delay;
2079 /* calculate expected arrival time of the next seqnum */
2080 expected = dts + priv->packet_spacing;
2082 delay = get_rtx_delay (priv);
2084 /* and update/install timer for next seqnum */
2086 reschedule_timer (jitterbuffer, timer, priv->next_in_seqnum, expected,
2089 add_timer (jitterbuffer, TIMER_TYPE_EXPECTED, priv->next_in_seqnum, 0,
2090 expected, delay, priv->packet_spacing);
2092 } else if (timer && timer->type != TIMER_TYPE_DEADLINE) {
2093 /* if we had a timer, remove it, we don't know when to expect the next
2095 remove_timer (jitterbuffer, timer);
2100 calculate_packet_spacing (GstRtpJitterBuffer * jitterbuffer, guint32 rtptime,
2103 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2105 /* we need consecutive seqnums with a different
2106 * rtptime to estimate the packet spacing. */
2107 if (priv->ips_rtptime != rtptime) {
2108 /* rtptime changed, check dts diff */
2109 if (priv->ips_dts != -1 && dts != -1 && dts > priv->ips_dts) {
2110 GstClockTime new_packet_spacing = dts - priv->ips_dts;
2111 GstClockTime old_packet_spacing = priv->packet_spacing;
2113 /* Biased towards bigger packet spacings to prevent
2114 * too many unneeded retransmission requests for next
2115 * packets that just arrive a little later than we would
2117 if (old_packet_spacing > new_packet_spacing)
2118 priv->packet_spacing =
2119 (new_packet_spacing + 3 * old_packet_spacing) / 4;
2120 else if (old_packet_spacing > 0)
2121 priv->packet_spacing =
2122 (3 * new_packet_spacing + old_packet_spacing) / 4;
2124 priv->packet_spacing = new_packet_spacing;
2126 GST_DEBUG_OBJECT (jitterbuffer,
2127 "new packet spacing %" GST_TIME_FORMAT
2128 " old packet spacing %" GST_TIME_FORMAT
2129 " combined to %" GST_TIME_FORMAT,
2130 GST_TIME_ARGS (new_packet_spacing),
2131 GST_TIME_ARGS (old_packet_spacing),
2132 GST_TIME_ARGS (priv->packet_spacing));
2134 priv->ips_rtptime = rtptime;
2135 priv->ips_dts = dts;
2140 calculate_expected (GstRtpJitterBuffer * jitterbuffer, guint32 expected,
2141 guint16 seqnum, GstClockTime dts, gint gap)
2143 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2144 GstClockTime total_duration, duration, expected_dts;
2147 GST_DEBUG_OBJECT (jitterbuffer,
2148 "dts %" GST_TIME_FORMAT ", last %" GST_TIME_FORMAT,
2149 GST_TIME_ARGS (dts), GST_TIME_ARGS (priv->last_in_dts));
2151 if (dts == GST_CLOCK_TIME_NONE) {
2152 GST_WARNING_OBJECT (jitterbuffer, "Have no DTS");
2156 /* the total duration spanned by the missing packets */
2157 if (dts >= priv->last_in_dts)
2158 total_duration = dts - priv->last_in_dts;
2162 /* interpolate between the current time and the last time based on
2163 * number of packets we are missing, this is the estimated duration
2164 * for the missing packet based on equidistant packet spacing. */
2165 duration = total_duration / (gap + 1);
2167 GST_DEBUG_OBJECT (jitterbuffer, "duration %" GST_TIME_FORMAT,
2168 GST_TIME_ARGS (duration));
2170 if (total_duration > priv->latency_ns) {
2171 GstClockTime gap_time;
2175 GstClockTime gap_dur = gap * duration;
2176 if (gap_dur > priv->latency_ns)
2177 gap_time = gap_dur - priv->latency_ns;
2180 lost_packets = gap_time / duration;
2182 gap_time = total_duration - priv->latency_ns;
2186 /* too many lost packets, some of the missing packets are already
2187 * too late and we can generate lost packet events for them. */
2188 GST_DEBUG_OBJECT (jitterbuffer,
2189 "lost packets (%d, #%d->#%d) duration too large %" GST_TIME_FORMAT
2190 " > %" GST_TIME_FORMAT ", consider %u lost (%" GST_TIME_FORMAT ")",
2191 gap, expected, seqnum, GST_TIME_ARGS (total_duration),
2192 GST_TIME_ARGS (priv->latency_ns), lost_packets,
2193 GST_TIME_ARGS (gap_time));
2195 /* this timer will fire immediately and the lost event will be pushed from
2196 * the timer thread */
2197 if (lost_packets > 0) {
2198 add_timer (jitterbuffer, TIMER_TYPE_LOST, expected, lost_packets,
2199 priv->last_in_dts + duration, 0, gap_time);
2200 expected += lost_packets;
2201 priv->last_in_dts += gap_time;
2205 expected_dts = priv->last_in_dts + duration;
2207 if (priv->do_retransmission) {
2210 type = TIMER_TYPE_EXPECTED;
2211 /* if we had a timer for the first missing packet, update it. */
2212 if ((timer = find_timer (jitterbuffer, type, expected))) {
2213 GstClockTime timeout = timer->timeout;
2215 timer->duration = duration;
2216 if (timeout > (expected_dts + timer->rtx_retry)) {
2217 GstClockTime delay = timeout - expected_dts - timer->rtx_retry;
2218 reschedule_timer (jitterbuffer, timer, timer->seqnum, expected_dts,
2222 expected_dts += duration;
2225 type = TIMER_TYPE_LOST;
2228 while (gst_rtp_buffer_compare_seqnum (expected, seqnum) > 0) {
2229 add_timer (jitterbuffer, type, expected, 0, expected_dts, 0, duration);
2230 expected_dts += duration;
2236 calculate_jitter (GstRtpJitterBuffer * jitterbuffer, GstClockTime dts,
2240 GstClockTimeDiff dtsdiff, rtpdiffns, diff;
2241 GstRtpJitterBufferPrivate *priv;
2243 priv = jitterbuffer->priv;
2245 if (G_UNLIKELY (dts == GST_CLOCK_TIME_NONE) || priv->clock_rate <= 0)
2248 if (priv->last_dts != -1)
2249 dtsdiff = dts - priv->last_dts;
2253 if (priv->last_rtptime != -1)
2254 rtpdiff = rtptime - (guint32) priv->last_rtptime;
2258 priv->last_dts = dts;
2259 priv->last_rtptime = rtptime;
2263 gst_util_uint64_scale_int (rtpdiff, GST_SECOND, priv->clock_rate);
2266 -gst_util_uint64_scale_int (-rtpdiff, GST_SECOND, priv->clock_rate);
2268 diff = ABS (dtsdiff - rtpdiffns);
2270 /* jitter is stored in nanoseconds */
2271 priv->avg_jitter = (diff + (15 * priv->avg_jitter)) >> 4;
2273 GST_LOG_OBJECT (jitterbuffer,
2274 "dtsdiff %" GST_TIME_FORMAT " rtptime %" GST_TIME_FORMAT
2275 ", clock-rate %d, diff %" GST_TIME_FORMAT ", jitter: %" GST_TIME_FORMAT,
2276 GST_TIME_ARGS (dtsdiff), GST_TIME_ARGS (rtpdiffns), priv->clock_rate,
2277 GST_TIME_ARGS (diff), GST_TIME_ARGS (priv->avg_jitter));
2284 GST_DEBUG_OBJECT (jitterbuffer,
2285 "no dts or no clock-rate, can't calculate jitter");
2291 compare_buffer_seqnum (GstBuffer * a, GstBuffer * b, gpointer user_data)
2293 GstRTPBuffer rtp_a = GST_RTP_BUFFER_INIT;
2294 GstRTPBuffer rtp_b = GST_RTP_BUFFER_INIT;
2297 gst_rtp_buffer_map (a, GST_MAP_READ, &rtp_a);
2298 seq_a = gst_rtp_buffer_get_seq (&rtp_a);
2299 gst_rtp_buffer_unmap (&rtp_a);
2301 gst_rtp_buffer_map (b, GST_MAP_READ, &rtp_b);
2302 seq_b = gst_rtp_buffer_get_seq (&rtp_b);
2303 gst_rtp_buffer_unmap (&rtp_b);
2305 return gst_rtp_buffer_compare_seqnum (seq_b, seq_a);
2309 handle_big_gap_buffer (GstRtpJitterBuffer * jitterbuffer, gboolean future,
2310 GstBuffer * buffer, guint8 pt, guint16 seqnum, gint gap, guint max_dropout,
2313 GstRtpJitterBufferPrivate *priv;
2314 guint gap_packets_length;
2315 gboolean reset = FALSE;
2317 priv = jitterbuffer->priv;
2319 if ((gap_packets_length = g_queue_get_length (&priv->gap_packets)) > 0) {
2321 guint32 prev_gap_seq = -1;
2322 gboolean all_consecutive = TRUE;
2324 g_queue_insert_sorted (&priv->gap_packets, buffer,
2325 (GCompareDataFunc) compare_buffer_seqnum, NULL);
2327 for (l = priv->gap_packets.head; l; l = l->next) {
2328 GstBuffer *gap_buffer = l->data;
2329 GstRTPBuffer gap_rtp = GST_RTP_BUFFER_INIT;
2332 gst_rtp_buffer_map (gap_buffer, GST_MAP_READ, &gap_rtp);
2334 all_consecutive = (gst_rtp_buffer_get_payload_type (&gap_rtp) == pt);
2336 gap_seq = gst_rtp_buffer_get_seq (&gap_rtp);
2337 if (prev_gap_seq == -1)
2338 prev_gap_seq = gap_seq;
2339 else if (gst_rtp_buffer_compare_seqnum (gap_seq, prev_gap_seq) != -1)
2340 all_consecutive = FALSE;
2342 prev_gap_seq = gap_seq;
2344 gst_rtp_buffer_unmap (&gap_rtp);
2345 if (!all_consecutive)
2349 if (all_consecutive && gap_packets_length > 3) {
2350 GST_DEBUG_OBJECT (jitterbuffer,
2351 "buffer too %s %d < %d, got 5 consecutive ones - reset",
2352 (future ? "new" : "old"), gap,
2353 (future ? max_dropout : -max_misorder));
2355 } else if (!all_consecutive) {
2356 g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
2357 g_queue_clear (&priv->gap_packets);
2358 GST_DEBUG_OBJECT (jitterbuffer,
2359 "buffer too %s %d < %d, got no 5 consecutive ones - dropping",
2360 (future ? "new" : "old"), gap,
2361 (future ? max_dropout : -max_misorder));
2364 GST_DEBUG_OBJECT (jitterbuffer,
2365 "buffer too %s %d < %d, got %u consecutive ones - waiting",
2366 (future ? "new" : "old"), gap,
2367 (future ? max_dropout : -max_misorder), gap_packets_length + 1);
2371 GST_DEBUG_OBJECT (jitterbuffer,
2372 "buffer too %s %d < %d, first one - waiting", (future ? "new" : "old"),
2373 gap, -max_misorder);
2374 g_queue_push_tail (&priv->gap_packets, buffer);
2382 get_current_running_time (GstRtpJitterBuffer * jitterbuffer)
2384 GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (jitterbuffer));
2385 GstClockTime running_time = GST_CLOCK_TIME_NONE;
2388 GstClockTime base_time =
2389 gst_element_get_base_time (GST_ELEMENT_CAST (jitterbuffer));
2390 GstClockTime clock_time = gst_clock_get_time (clock);
2392 if (clock_time > base_time)
2393 running_time = clock_time - base_time;
2397 gst_object_unref (clock);
2400 return running_time;
2403 static GstFlowReturn
2404 gst_rtp_jitter_buffer_chain (GstPad * pad, GstObject * parent,
2407 GstRtpJitterBuffer *jitterbuffer;
2408 GstRtpJitterBufferPrivate *priv;
2410 guint32 expected, rtptime;
2411 GstFlowReturn ret = GST_FLOW_OK;
2412 GstClockTime dts, pts;
2417 GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
2418 gboolean do_next_seqnum = FALSE;
2419 RTPJitterBufferItem *item;
2420 GstMessage *msg = NULL;
2421 gboolean estimated_dts = FALSE;
2422 guint32 packet_rate, max_dropout, max_misorder;
2424 jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
2426 priv = jitterbuffer->priv;
2428 if (G_UNLIKELY (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)))
2429 goto invalid_buffer;
2431 pt = gst_rtp_buffer_get_payload_type (&rtp);
2432 seqnum = gst_rtp_buffer_get_seq (&rtp);
2433 rtptime = gst_rtp_buffer_get_timestamp (&rtp);
2434 gst_rtp_buffer_unmap (&rtp);
2436 /* make sure we have PTS and DTS set */
2437 pts = GST_BUFFER_PTS (buffer);
2438 dts = GST_BUFFER_DTS (buffer);
2445 /* If we have no DTS here, i.e. no capture time, get one from the
2446 * clock now to have something to calculate with in the future. */
2447 dts = get_current_running_time (jitterbuffer);
2450 /* Remember that we estimated the DTS if we are running already
2451 * and this is not our first packet (or first packet after a reset).
2452 * If it's the first packet, we somehow must generate a timestamp for
2453 * everything, otherwise we can't calculate any times
2455 estimated_dts = (priv->next_in_seqnum != -1);
2457 /* take the DTS of the buffer. This is the time when the packet was
2458 * received and is used to calculate jitter and clock skew. We will adjust
2459 * this DTS with the smoothed value after processing it in the
2460 * jitterbuffer and assign it as the PTS. */
2461 /* bring to running time */
2462 dts = gst_segment_to_running_time (&priv->segment, GST_FORMAT_TIME, dts);
2465 GST_DEBUG_OBJECT (jitterbuffer,
2466 "Received packet #%d at time %" GST_TIME_FORMAT ", discont %d", seqnum,
2467 GST_TIME_ARGS (dts), GST_BUFFER_IS_DISCONT (buffer));
2469 JBUF_LOCK_CHECK (priv, out_flushing);
2471 if (G_UNLIKELY (priv->last_pt != pt)) {
2474 GST_DEBUG_OBJECT (jitterbuffer, "pt changed from %u to %u", priv->last_pt,
2478 /* reset clock-rate so that we get a new one */
2479 priv->clock_rate = -1;
2481 /* Try to get the clock-rate from the caps first if we can. If there are no
2482 * caps we must fire the signal to get the clock-rate. */
2483 if ((caps = gst_pad_get_current_caps (pad))) {
2484 gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
2485 gst_caps_unref (caps);
2489 if (G_UNLIKELY (priv->clock_rate == -1)) {
2490 /* no clock rate given on the caps, try to get one with the signal */
2491 if (gst_rtp_jitter_buffer_get_clock_rate (jitterbuffer,
2492 pt) == GST_FLOW_FLUSHING)
2495 if (G_UNLIKELY (priv->clock_rate == -1))
2499 /* don't accept more data on EOS */
2500 if (G_UNLIKELY (priv->eos))
2503 calculate_jitter (jitterbuffer, dts, rtptime);
2505 if (priv->seqnum_base != -1) {
2508 gap = gst_rtp_buffer_compare_seqnum (priv->seqnum_base, seqnum);
2511 GST_DEBUG_OBJECT (jitterbuffer,
2512 "packet seqnum #%d before seqnum-base #%d", seqnum,
2514 gst_buffer_unref (buffer);
2517 } else if (gap > 16384) {
2518 /* From now on don't compare against the seqnum base anymore as
2519 * at some point in the future we will wrap around and also that
2520 * much reordering is very unlikely */
2521 priv->seqnum_base = -1;
2525 expected = priv->next_in_seqnum;
2528 gst_rtp_packet_rate_ctx_update (&priv->packet_rate_ctx, seqnum, rtptime);
2530 gst_rtp_packet_rate_ctx_get_max_dropout (&priv->packet_rate_ctx,
2531 priv->max_dropout_time);
2533 gst_rtp_packet_rate_ctx_get_max_misorder (&priv->packet_rate_ctx,
2534 priv->max_misorder_time);
2535 GST_TRACE_OBJECT (jitterbuffer,
2536 "packet_rate: %d, max_dropout: %d, max_misorder: %d", packet_rate,
2537 max_dropout, max_misorder);
2539 /* now check against our expected seqnum */
2540 if (G_LIKELY (expected != -1)) {
2543 /* now calculate gap */
2544 gap = gst_rtp_buffer_compare_seqnum (expected, seqnum);
2546 GST_DEBUG_OBJECT (jitterbuffer, "expected #%d, got #%d, gap of %d",
2547 expected, seqnum, gap);
2549 if (G_LIKELY (gap == 0)) {
2550 /* packet is expected */
2551 calculate_packet_spacing (jitterbuffer, rtptime, dts);
2552 do_next_seqnum = TRUE;
2554 gboolean reset = FALSE;
2557 /* we received an old packet */
2558 if (G_UNLIKELY (gap != -1 && gap < -max_misorder)) {
2560 handle_big_gap_buffer (jitterbuffer, FALSE, buffer, pt, seqnum,
2561 gap, max_dropout, max_misorder);
2564 GST_DEBUG_OBJECT (jitterbuffer, "old packet received");
2567 /* new packet, we are missing some packets */
2568 if (G_UNLIKELY (priv->timers->len >= max_dropout)) {
2569 /* If we have timers for more than RTP_MAX_DROPOUT packets
2570 * pending this means that we have a huge gap overall. We can
2571 * reset the jitterbuffer at this point because there's
2572 * just too much data missing to be able to do anything
2573 * sensible with the past data. Just try again from the
2575 GST_WARNING_OBJECT (jitterbuffer,
2576 "%d pending timers > %d - resetting", priv->timers->len,
2579 gst_buffer_unref (buffer);
2581 } else if (G_UNLIKELY (gap >= max_dropout)) {
2583 handle_big_gap_buffer (jitterbuffer, TRUE, buffer, pt, seqnum,
2584 gap, max_dropout, max_misorder);
2587 GST_DEBUG_OBJECT (jitterbuffer, "%d missing packets", gap);
2588 /* fill in the gap with EXPECTED timers */
2589 calculate_expected (jitterbuffer, expected, seqnum, dts, gap);
2591 do_next_seqnum = TRUE;
2594 if (G_UNLIKELY (reset)) {
2595 GList *events = NULL, *l;
2598 GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
2599 rtp_jitter_buffer_flush (priv->jbuf,
2600 (GFunc) free_item_and_retain_events, &events);
2601 rtp_jitter_buffer_reset_skew (priv->jbuf);
2602 remove_all_timers (jitterbuffer);
2603 priv->discont = TRUE;
2604 priv->last_popped_seqnum = -1;
2606 if (priv->gap_packets.head) {
2607 GstBuffer *gap_buffer = priv->gap_packets.head->data;
2608 GstRTPBuffer gap_rtp = GST_RTP_BUFFER_INIT;
2610 gst_rtp_buffer_map (gap_buffer, GST_MAP_READ, &gap_rtp);
2611 priv->next_seqnum = gst_rtp_buffer_get_seq (&gap_rtp);
2612 gst_rtp_buffer_unmap (&gap_rtp);
2614 priv->next_seqnum = seqnum;
2617 priv->last_in_dts = -1;
2618 priv->next_in_seqnum = -1;
2620 /* Insert all sticky events again in order, otherwise we would
2621 * potentially loose STREAM_START, CAPS or SEGMENT events
2623 events = g_list_reverse (events);
2624 for (l = events; l; l = l->next) {
2625 RTPJitterBufferItem *item;
2627 item = alloc_item (l->data, ITEM_TYPE_EVENT, -1, -1, -1, 0, -1);
2628 rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
2630 g_list_free (events);
2632 JBUF_SIGNAL_EVENT (priv);
2634 /* reset spacing estimation when gap */
2635 priv->ips_rtptime = -1;
2636 priv->ips_dts = GST_CLOCK_TIME_NONE;
2638 buffers = g_list_copy (priv->gap_packets.head);
2639 g_queue_clear (&priv->gap_packets);
2641 priv->ips_rtptime = -1;
2642 priv->ips_dts = GST_CLOCK_TIME_NONE;
2643 JBUF_UNLOCK (jitterbuffer->priv);
2645 for (l = buffers; l; l = l->next) {
2646 ret = gst_rtp_jitter_buffer_chain (pad, parent, l->data);
2648 if (ret != GST_FLOW_OK)
2651 for (; l; l = l->next)
2652 gst_buffer_unref (l->data);
2653 g_list_free (buffers);
2657 /* reset spacing estimation when gap */
2658 priv->ips_rtptime = -1;
2659 priv->ips_dts = GST_CLOCK_TIME_NONE;
2662 GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
2664 /* we don't know what the next_in_seqnum should be, wait for the last
2665 * possible moment to push this buffer, maybe we get an earlier seqnum
2667 set_timer (jitterbuffer, TIMER_TYPE_DEADLINE, seqnum, dts);
2668 do_next_seqnum = TRUE;
2669 /* take rtptime and dts to calculate packet spacing */
2670 priv->ips_rtptime = rtptime;
2671 priv->ips_dts = dts;
2674 /* We had no huge gap, let's drop all the gap packets */
2675 if (buffer != NULL) {
2676 GST_DEBUG_OBJECT (jitterbuffer, "Clearing gap packets");
2677 g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
2678 g_queue_clear (&priv->gap_packets);
2680 GST_DEBUG_OBJECT (jitterbuffer,
2681 "Had big gap, waiting for more consecutive packets");
2682 JBUF_UNLOCK (jitterbuffer->priv);
2686 if (do_next_seqnum) {
2687 priv->last_in_dts = dts;
2688 priv->next_in_seqnum = (seqnum + 1) & 0xffff;
2691 /* let's check if this buffer is too late, we can only accept packets with
2692 * bigger seqnum than the one we last pushed. */
2693 if (G_LIKELY (priv->last_popped_seqnum != -1)) {
2696 gap = gst_rtp_buffer_compare_seqnum (priv->last_popped_seqnum, seqnum);
2698 /* priv->last_popped_seqnum >= seqnum, we're too late. */
2699 if (G_UNLIKELY (gap <= 0))
2703 /* let's drop oldest packet if the queue is already full and drop-on-latency
2704 * is set. We can only do this when there actually is a latency. When no
2705 * latency is set, we just pump it in the queue and let the other end push it
2706 * out as fast as possible. */
2707 if (priv->latency_ms && priv->drop_on_latency) {
2709 gst_util_uint64_scale_int (priv->latency_ms, priv->clock_rate, 1000);
2711 if (G_UNLIKELY (rtp_jitter_buffer_get_ts_diff (priv->jbuf) >= latency_ts)) {
2712 RTPJitterBufferItem *old_item;
2714 old_item = rtp_jitter_buffer_peek (priv->jbuf);
2716 if (IS_DROPABLE (old_item)) {
2717 old_item = rtp_jitter_buffer_pop (priv->jbuf, &percent);
2718 GST_DEBUG_OBJECT (jitterbuffer, "Queue full, dropping old packet %p",
2720 priv->next_seqnum = (old_item->seqnum + 1) & 0xffff;
2721 free_item (old_item);
2723 /* we might have removed some head buffers, signal the pushing thread to
2724 * see if it can push now */
2725 JBUF_SIGNAL_EVENT (priv);
2729 /* If we estimated the DTS, don't consider it in the clock skew calculations
2730 * later. The code above always sets dts to pts or the other way around if
2731 * any of those is valid in the buffer, so we know that if we estimated the
2732 * dts that both are unknown */
2735 alloc_item (buffer, ITEM_TYPE_BUFFER, GST_CLOCK_TIME_NONE,
2736 GST_CLOCK_TIME_NONE, seqnum, 1, rtptime);
2738 item = alloc_item (buffer, ITEM_TYPE_BUFFER, dts, pts, seqnum, 1, rtptime);
2740 /* now insert the packet into the queue in sorted order. This function returns
2741 * FALSE if a packet with the same seqnum was already in the queue, meaning we
2742 * have a duplicate. */
2743 if (G_UNLIKELY (!rtp_jitter_buffer_insert (priv->jbuf, item,
2748 update_timers (jitterbuffer, seqnum, dts, do_next_seqnum);
2750 /* we had an unhandled SR, handle it now */
2752 do_handle_sync (jitterbuffer);
2754 if (G_UNLIKELY (head)) {
2755 /* signal addition of new buffer when the _loop is waiting. */
2756 if (G_LIKELY (priv->active))
2757 JBUF_SIGNAL_EVENT (priv);
2759 /* let's unschedule and unblock any waiting buffers. We only want to do this
2760 * when the head buffer changed */
2761 if (G_UNLIKELY (priv->clock_id)) {
2762 GST_DEBUG_OBJECT (jitterbuffer, "Unscheduling waiting new buffer");
2763 unschedule_current_timer (jitterbuffer);
2767 GST_DEBUG_OBJECT (jitterbuffer,
2768 "Pushed packet #%d, now %d packets, head: %d, " "percent %d", seqnum,
2769 rtp_jitter_buffer_num_packets (priv->jbuf), head, percent);
2771 msg = check_buffering_percent (jitterbuffer, percent);
2777 gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), msg);
2784 /* this is not fatal but should be filtered earlier */
2785 GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
2786 ("Received invalid RTP payload, dropping"));
2787 gst_buffer_unref (buffer);
2792 GST_WARNING_OBJECT (jitterbuffer,
2793 "No clock-rate in caps!, dropping buffer");
2794 gst_buffer_unref (buffer);
2799 ret = priv->srcresult;
2800 GST_DEBUG_OBJECT (jitterbuffer, "flushing %s", gst_flow_get_name (ret));
2801 gst_buffer_unref (buffer);
2807 GST_WARNING_OBJECT (jitterbuffer, "we are EOS, refusing buffer");
2808 gst_buffer_unref (buffer);
2813 GST_DEBUG_OBJECT (jitterbuffer, "Packet #%d too late as #%d was already"
2814 " popped, dropping", seqnum, priv->last_popped_seqnum);
2816 gst_buffer_unref (buffer);
2821 GST_DEBUG_OBJECT (jitterbuffer, "Duplicate packet #%d detected, dropping",
2823 priv->num_duplicates++;
2830 compute_elapsed (GstRtpJitterBuffer * jitterbuffer, RTPJitterBufferItem * item)
2832 guint64 ext_time, elapsed;
2834 GstRtpJitterBufferPrivate *priv;
2836 priv = jitterbuffer->priv;
2837 rtp_time = item->rtptime;
2839 GST_LOG_OBJECT (jitterbuffer, "rtp %" G_GUINT32_FORMAT ", ext %"
2840 G_GUINT64_FORMAT, rtp_time, priv->ext_timestamp);
2842 ext_time = priv->ext_timestamp;
2843 ext_time = gst_rtp_buffer_ext_timestamp (&ext_time, rtp_time);
2844 if (ext_time < priv->ext_timestamp) {
2845 ext_time = priv->ext_timestamp;
2847 priv->ext_timestamp = ext_time;
2850 if (ext_time > priv->clock_base)
2851 elapsed = ext_time - priv->clock_base;
2855 elapsed = gst_util_uint64_scale_int (elapsed, GST_SECOND, priv->clock_rate);
2860 update_estimated_eos (GstRtpJitterBuffer * jitterbuffer,
2861 RTPJitterBufferItem * item)
2863 guint64 total, elapsed, left, estimated;
2864 GstClockTime out_time;
2865 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2867 if (priv->npt_stop == -1 || priv->ext_timestamp == -1
2868 || priv->clock_base == -1 || priv->clock_rate <= 0)
2871 /* compute the elapsed time */
2872 elapsed = compute_elapsed (jitterbuffer, item);
2874 /* do nothing if elapsed time doesn't increment */
2875 if (priv->last_elapsed && elapsed <= priv->last_elapsed)
2878 priv->last_elapsed = elapsed;
2880 /* this is the total time we need to play */
2881 total = priv->npt_stop - priv->npt_start;
2882 GST_LOG_OBJECT (jitterbuffer, "total %" GST_TIME_FORMAT,
2883 GST_TIME_ARGS (total));
2885 /* this is how much time there is left */
2886 if (total > elapsed)
2887 left = total - elapsed;
2891 /* if we have less time left that the size of the buffer, we will not
2892 * be able to keep it filled, disabled buffering then */
2893 if (left < rtp_jitter_buffer_get_delay (priv->jbuf)) {
2894 GST_DEBUG_OBJECT (jitterbuffer, "left %" GST_TIME_FORMAT
2895 ", disable buffering close to EOS", GST_TIME_ARGS (left));
2896 rtp_jitter_buffer_disable_buffering (priv->jbuf, TRUE);
2899 /* this is the current time as running-time */
2900 out_time = item->dts;
2903 estimated = gst_util_uint64_scale (out_time, total, elapsed);
2905 /* if there is almost nothing left,
2906 * we may never advance enough to end up in the above case */
2907 if (total < GST_SECOND)
2908 estimated = GST_SECOND;
2912 GST_LOG_OBJECT (jitterbuffer, "elapsed %" GST_TIME_FORMAT ", estimated %"
2913 GST_TIME_FORMAT, GST_TIME_ARGS (elapsed), GST_TIME_ARGS (estimated));
2915 if (estimated != -1 && priv->estimated_eos != estimated) {
2916 set_timer (jitterbuffer, TIMER_TYPE_EOS, -1, estimated);
2917 priv->estimated_eos = estimated;
2921 /* take a buffer from the queue and push it */
2922 static GstFlowReturn
2923 pop_and_push_next (GstRtpJitterBuffer * jitterbuffer, guint seqnum)
2925 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2926 GstFlowReturn result = GST_FLOW_OK;
2927 RTPJitterBufferItem *item;
2928 GstBuffer *outbuf = NULL;
2929 GstEvent *outevent = NULL;
2930 GstQuery *outquery = NULL;
2931 GstClockTime dts, pts;
2933 gboolean do_push = TRUE;
2937 /* when we get here we are ready to pop and push the buffer */
2938 item = rtp_jitter_buffer_pop (priv->jbuf, &percent);
2942 case ITEM_TYPE_BUFFER:
2944 /* we need to make writable to change the flags and timestamps */
2945 outbuf = gst_buffer_make_writable (item->data);
2947 if (G_UNLIKELY (priv->discont)) {
2948 /* set DISCONT flag when we missed a packet. We pushed the buffer writable
2949 * into the jitterbuffer so we can modify now. */
2950 GST_DEBUG_OBJECT (jitterbuffer, "mark output buffer discont");
2951 GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
2952 priv->discont = FALSE;
2954 if (G_UNLIKELY (priv->ts_discont)) {
2955 GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_RESYNC);
2956 priv->ts_discont = FALSE;
2960 gst_segment_position_from_running_time (&priv->segment,
2961 GST_FORMAT_TIME, item->dts);
2963 gst_segment_position_from_running_time (&priv->segment,
2964 GST_FORMAT_TIME, item->pts);
2966 /* apply timestamp with offset to buffer now */
2967 GST_BUFFER_DTS (outbuf) = apply_offset (jitterbuffer, dts);
2968 GST_BUFFER_PTS (outbuf) = apply_offset (jitterbuffer, pts);
2970 /* update the elapsed time when we need to check against the npt stop time. */
2971 update_estimated_eos (jitterbuffer, item);
2973 priv->last_out_time = GST_BUFFER_PTS (outbuf);
2975 case ITEM_TYPE_LOST:
2976 priv->discont = TRUE;
2980 case ITEM_TYPE_EVENT:
2981 outevent = item->data;
2983 case ITEM_TYPE_QUERY:
2984 outquery = item->data;
2988 /* now we are ready to push the buffer. Save the seqnum and release the lock
2989 * so the other end can push stuff in the queue again. */
2991 priv->last_popped_seqnum = seqnum;
2992 priv->next_seqnum = (seqnum + item->count) & 0xffff;
2994 msg = check_buffering_percent (jitterbuffer, percent);
3001 gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), msg);
3004 case ITEM_TYPE_BUFFER:
3006 GST_DEBUG_OBJECT (jitterbuffer,
3007 "Pushing buffer %d, dts %" GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT,
3008 seqnum, GST_TIME_ARGS (GST_BUFFER_DTS (outbuf)),
3009 GST_TIME_ARGS (GST_BUFFER_PTS (outbuf)));
3010 result = gst_pad_push (priv->srcpad, outbuf);
3012 JBUF_LOCK_CHECK (priv, out_flushing);
3014 case ITEM_TYPE_LOST:
3015 case ITEM_TYPE_EVENT:
3016 /* We got not enough consecutive packets with a huge gap, we can
3017 * as well just drop them here now on EOS */
3018 if (GST_EVENT_TYPE (outevent) == GST_EVENT_EOS) {
3019 GST_DEBUG_OBJECT (jitterbuffer, "Clearing gap packets on EOS");
3020 g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
3021 g_queue_clear (&priv->gap_packets);
3024 GST_DEBUG_OBJECT (jitterbuffer, "%sPushing event %" GST_PTR_FORMAT
3025 ", seqnum %d", do_push ? "" : "NOT ", outevent, seqnum);
3028 gst_pad_push_event (priv->srcpad, outevent);
3030 gst_event_unref (outevent);
3032 result = GST_FLOW_OK;
3034 JBUF_LOCK_CHECK (priv, out_flushing);
3036 case ITEM_TYPE_QUERY:
3040 res = gst_pad_peer_query (priv->srcpad, outquery);
3042 JBUF_LOCK_CHECK (priv, out_flushing);
3043 result = GST_FLOW_OK;
3044 GST_LOG_OBJECT (jitterbuffer, "did query %p, return %d", outquery, res);
3045 JBUF_SIGNAL_QUERY (priv, res);
3054 return priv->srcresult;
3058 #define GST_FLOW_WAIT GST_FLOW_CUSTOM_SUCCESS
3060 /* Peek a buffer and compare the seqnum to the expected seqnum.
3061 * If all is fine, the buffer is pushed.
3062 * If something is wrong, we wait for some event
3064 static GstFlowReturn
3065 handle_next_buffer (GstRtpJitterBuffer * jitterbuffer)
3067 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3068 GstFlowReturn result;
3069 RTPJitterBufferItem *item;
3071 guint32 next_seqnum;
3073 /* only push buffers when PLAYING and active and not buffering */
3074 if (priv->blocked || !priv->active ||
3075 rtp_jitter_buffer_is_buffering (priv->jbuf)) {
3076 return GST_FLOW_WAIT;
3079 /* peek a buffer, we're just looking at the sequence number.
3080 * If all is fine, we'll pop and push it. If the sequence number is wrong we
3081 * wait for a timeout or something to change.
3082 * The peeked buffer is valid for as long as we hold the jitterbuffer lock. */
3083 item = rtp_jitter_buffer_peek (priv->jbuf);
3088 /* get the seqnum and the next expected seqnum */
3089 seqnum = item->seqnum;
3091 return pop_and_push_next (jitterbuffer, seqnum);
3094 next_seqnum = priv->next_seqnum;
3096 /* get the gap between this and the previous packet. If we don't know the
3097 * previous packet seqnum assume no gap. */
3098 if (G_UNLIKELY (next_seqnum == -1)) {
3099 GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
3100 /* we don't know what the next_seqnum should be, the chain function should
3101 * have scheduled a DEADLINE timer that will increment next_seqnum when it
3102 * fires, so wait for that */
3103 result = GST_FLOW_WAIT;
3105 gint gap = gst_rtp_buffer_compare_seqnum (next_seqnum, seqnum);
3107 if (G_LIKELY (gap == 0)) {
3108 /* no missing packet, pop and push */
3109 result = pop_and_push_next (jitterbuffer, seqnum);
3110 } else if (G_UNLIKELY (gap < 0)) {
3111 /* if we have a packet that we already pushed or considered dropped, pop it
3112 * off and get the next packet */
3113 GST_DEBUG_OBJECT (jitterbuffer, "Old packet #%d, next #%d dropping",
3114 seqnum, next_seqnum);
3115 item = rtp_jitter_buffer_pop (priv->jbuf, NULL);
3117 result = GST_FLOW_OK;
3119 /* the chain function has scheduled timers to request retransmission or
3120 * when to consider the packet lost, wait for that */
3121 GST_DEBUG_OBJECT (jitterbuffer,
3122 "Sequence number GAP detected: expected %d instead of %d (%d missing)",
3123 next_seqnum, seqnum, gap);
3124 result = GST_FLOW_WAIT;
3132 GST_DEBUG_OBJECT (jitterbuffer, "no buffer, going to wait");
3134 return GST_FLOW_EOS;
3136 return GST_FLOW_WAIT;
3142 get_rtx_retry_timeout (GstRtpJitterBufferPrivate * priv)
3144 GstClockTime rtx_retry_timeout;
3145 GstClockTime rtx_min_retry_timeout;
3147 if (priv->rtx_retry_timeout == -1) {
3148 if (priv->avg_rtx_rtt == 0)
3149 rtx_retry_timeout = DEFAULT_AUTO_RTX_TIMEOUT;
3151 /* we want to ask for a retransmission after we waited for a
3152 * complete RTT and the additional jitter */
3153 rtx_retry_timeout = priv->avg_rtx_rtt + priv->avg_jitter * 2;
3155 rtx_retry_timeout = priv->rtx_retry_timeout * GST_MSECOND;
3157 /* make sure we don't retry too often. On very low latency networks,
3158 * the RTT and jitter can be very low. */
3159 if (priv->rtx_min_retry_timeout == -1) {
3160 rtx_min_retry_timeout = priv->packet_spacing;
3162 rtx_min_retry_timeout = priv->rtx_min_retry_timeout * GST_MSECOND;
3164 rtx_retry_timeout = MAX (rtx_retry_timeout, rtx_min_retry_timeout);
3166 return rtx_retry_timeout;
3170 get_rtx_retry_period (GstRtpJitterBufferPrivate * priv,
3171 GstClockTime rtx_retry_timeout)
3173 GstClockTime rtx_retry_period;
3175 if (priv->rtx_retry_period == -1) {
3176 /* we retry up to the configured jitterbuffer size but leaving some
3177 * room for the retransmission to arrive in time */
3178 if (rtx_retry_timeout > priv->latency_ns) {
3179 rtx_retry_period = 0;
3181 rtx_retry_period = priv->latency_ns - rtx_retry_timeout;
3184 rtx_retry_period = priv->rtx_retry_period * GST_MSECOND;
3186 return rtx_retry_period;
3189 /* the timeout for when we expected a packet expired */
3191 do_expected_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3194 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3196 guint delay, delay_ms, avg_rtx_rtt_ms;
3197 guint rtx_retry_timeout_ms, rtx_retry_period_ms;
3198 GstClockTime rtx_retry_period;
3199 GstClockTime rtx_retry_timeout;
3202 GST_DEBUG_OBJECT (jitterbuffer, "expected %d didn't arrive, now %"
3203 GST_TIME_FORMAT, timer->seqnum, GST_TIME_ARGS (now));
3205 rtx_retry_timeout = get_rtx_retry_timeout (priv);
3206 rtx_retry_period = get_rtx_retry_period (priv, rtx_retry_timeout);
3208 GST_DEBUG_OBJECT (jitterbuffer, "timeout %" GST_TIME_FORMAT ", period %"
3209 GST_TIME_FORMAT, GST_TIME_ARGS (rtx_retry_timeout),
3210 GST_TIME_ARGS (rtx_retry_period));
3212 delay = timer->rtx_delay + timer->rtx_retry;
3214 delay_ms = GST_TIME_AS_MSECONDS (delay);
3215 rtx_retry_timeout_ms = GST_TIME_AS_MSECONDS (rtx_retry_timeout);
3216 rtx_retry_period_ms = GST_TIME_AS_MSECONDS (rtx_retry_period);
3217 avg_rtx_rtt_ms = GST_TIME_AS_MSECONDS (priv->avg_rtx_rtt);
3219 event = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
3220 gst_structure_new ("GstRTPRetransmissionRequest",
3221 "seqnum", G_TYPE_UINT, (guint) timer->seqnum,
3222 "running-time", G_TYPE_UINT64, timer->rtx_base,
3223 "delay", G_TYPE_UINT, delay_ms,
3224 "retry", G_TYPE_UINT, timer->num_rtx_retry,
3225 "frequency", G_TYPE_UINT, rtx_retry_timeout_ms,
3226 "period", G_TYPE_UINT, rtx_retry_period_ms,
3227 "deadline", G_TYPE_UINT, priv->latency_ms,
3228 "packet-spacing", G_TYPE_UINT64, priv->packet_spacing,
3229 "avg-rtt", G_TYPE_UINT, avg_rtx_rtt_ms, NULL));
3231 priv->num_rtx_requests++;
3232 timer->num_rtx_retry++;
3234 GST_OBJECT_LOCK (jitterbuffer);
3235 if ((clock = GST_ELEMENT_CLOCK (jitterbuffer))) {
3236 timer->rtx_last = gst_clock_get_time (clock);
3237 timer->rtx_last -= GST_ELEMENT_CAST (jitterbuffer)->base_time;
3239 timer->rtx_last = now;
3241 GST_OBJECT_UNLOCK (jitterbuffer);
3243 /* calculate the timeout for the next retransmission attempt */
3244 timer->rtx_retry += rtx_retry_timeout;
3245 GST_DEBUG_OBJECT (jitterbuffer, "base %" GST_TIME_FORMAT ", delay %"
3246 GST_TIME_FORMAT ", retry %" GST_TIME_FORMAT ", num_retry %u",
3247 GST_TIME_ARGS (timer->rtx_base), GST_TIME_ARGS (timer->rtx_delay),
3248 GST_TIME_ARGS (timer->rtx_retry), timer->num_rtx_retry);
3249 if ((priv->rtx_max_retries != -1
3250 && timer->num_rtx_retry >= priv->rtx_max_retries)
3251 || (timer->rtx_retry + timer->rtx_delay > rtx_retry_period)) {
3252 GST_DEBUG_OBJECT (jitterbuffer, "reschedule as LOST timer");
3253 /* too many retransmission request, we now convert the timer
3254 * to a lost timer, leave the num_rtx_retry as it is for stats */
3255 timer->type = TIMER_TYPE_LOST;
3256 timer->rtx_delay = 0;
3257 timer->rtx_retry = 0;
3259 reschedule_timer (jitterbuffer, timer, timer->seqnum,
3260 timer->rtx_base + timer->rtx_retry, timer->rtx_delay, FALSE);
3263 gst_pad_push_event (priv->sinkpad, event);
3269 /* a packet is lost */
3271 do_lost_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3274 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3275 GstClockTime duration, timestamp;
3276 guint seqnum, lost_packets, num_rtx_retry, next_in_seqnum;
3279 RTPJitterBufferItem *item;
3281 seqnum = timer->seqnum;
3282 timestamp = apply_offset (jitterbuffer, timer->timeout);
3283 duration = timer->duration;
3284 if (duration == GST_CLOCK_TIME_NONE && priv->packet_spacing > 0)
3285 duration = priv->packet_spacing;
3286 lost_packets = MAX (timer->num, 1);
3287 num_rtx_retry = timer->num_rtx_retry;
3289 /* we had a gap and thus we lost some packets. Create an event for this. */
3290 if (lost_packets > 1)
3291 GST_DEBUG_OBJECT (jitterbuffer, "Packets #%d -> #%d lost", seqnum,
3292 seqnum + lost_packets - 1);
3294 GST_DEBUG_OBJECT (jitterbuffer, "Packet #%d lost", seqnum);
3296 priv->num_late += lost_packets;
3297 priv->num_rtx_failed += num_rtx_retry;
3299 next_in_seqnum = (seqnum + lost_packets) & 0xffff;
3301 /* we now only accept seqnum bigger than this */
3302 if (gst_rtp_buffer_compare_seqnum (priv->next_in_seqnum, next_in_seqnum) > 0)
3303 priv->next_in_seqnum = next_in_seqnum;
3305 /* create paket lost event */
3306 event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM,
3307 gst_structure_new ("GstRTPPacketLost",
3308 "seqnum", G_TYPE_UINT, (guint) seqnum,
3309 "timestamp", G_TYPE_UINT64, timestamp,
3310 "duration", G_TYPE_UINT64, duration,
3311 "retry", G_TYPE_UINT, num_rtx_retry, NULL));
3313 item = alloc_item (event, ITEM_TYPE_LOST, -1, -1, seqnum, lost_packets, -1);
3314 rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
3316 /* remove timer now */
3317 remove_timer (jitterbuffer, timer);
3319 JBUF_SIGNAL_EVENT (priv);
3325 do_eos_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3328 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3330 GST_INFO_OBJECT (jitterbuffer, "got the NPT timeout");
3331 remove_timer (jitterbuffer, timer);
3333 /* there was no EOS in the buffer, put one in there now */
3334 queue_event (jitterbuffer, gst_event_new_eos ());
3336 JBUF_SIGNAL_EVENT (priv);
3342 do_deadline_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3345 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3347 GST_INFO_OBJECT (jitterbuffer, "got deadline timeout");
3349 /* timer seqnum might have been obsoleted by caps seqnum-base,
3350 * only mess with current ongoing seqnum if still unknown */
3351 if (priv->next_seqnum == -1)
3352 priv->next_seqnum = timer->seqnum;
3353 remove_timer (jitterbuffer, timer);
3354 JBUF_SIGNAL_EVENT (priv);
3360 do_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3363 gboolean removed = FALSE;
3365 switch (timer->type) {
3366 case TIMER_TYPE_EXPECTED:
3367 removed = do_expected_timeout (jitterbuffer, timer, now);
3369 case TIMER_TYPE_LOST:
3370 removed = do_lost_timeout (jitterbuffer, timer, now);
3372 case TIMER_TYPE_DEADLINE:
3373 removed = do_deadline_timeout (jitterbuffer, timer, now);
3375 case TIMER_TYPE_EOS:
3376 removed = do_eos_timeout (jitterbuffer, timer, now);
3382 /* called when we need to wait for the next timeout.
3384 * We loop over the array of recorded timeouts and wait for the earliest one.
3385 * When it timed out, do the logic associated with the timer.
3387 * If there are no timers, we wait on a gcond until something new happens.
3390 wait_next_timeout (GstRtpJitterBuffer * jitterbuffer)
3392 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3393 GstClockTime now = 0;
3396 while (priv->timer_running) {
3397 TimerData *timer = NULL;
3398 GstClockTime timer_timeout = -1;
3401 /* If we have a clock, update "now" now with the very
3402 * latest running time we have. If timers are unscheduled below we
3403 * otherwise wouldn't update now (it's only updated when timers
3404 * expire), and also for the very first loop iteration now would
3405 * otherwise always be 0
3407 GST_OBJECT_LOCK (jitterbuffer);
3408 if (GST_ELEMENT_CLOCK (jitterbuffer)) {
3410 gst_clock_get_time (GST_ELEMENT_CLOCK (jitterbuffer)) -
3411 GST_ELEMENT_CAST (jitterbuffer)->base_time;
3413 GST_OBJECT_UNLOCK (jitterbuffer);
3415 GST_DEBUG_OBJECT (jitterbuffer, "now %" GST_TIME_FORMAT,
3416 GST_TIME_ARGS (now));
3418 len = priv->timers->len;
3419 for (i = 0; i < len; i++) {
3420 TimerData *test = &g_array_index (priv->timers, TimerData, i);
3421 GstClockTime test_timeout = get_timeout (jitterbuffer, test);
3422 gboolean save_best = FALSE;
3424 GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, %d, %" GST_TIME_FORMAT,
3425 i, test->type, test->seqnum, GST_TIME_ARGS (test_timeout));
3427 /* find the smallest timeout */
3428 if (timer == NULL) {
3430 } else if (timer_timeout == -1) {
3431 /* we already have an immediate timeout, the new timer must be an
3432 * immediate timer with smaller seqnum to become the best */
3433 if (test_timeout == -1
3434 && (gst_rtp_buffer_compare_seqnum (test->seqnum,
3435 timer->seqnum) > 0))
3437 } else if (test_timeout == -1) {
3438 /* first immediate timer */
3440 } else if (test_timeout < timer_timeout) {
3443 } else if (test_timeout == timer_timeout
3444 && (gst_rtp_buffer_compare_seqnum (test->seqnum,
3445 timer->seqnum) > 0)) {
3446 /* same timer, smaller seqnum */
3450 GST_DEBUG_OBJECT (jitterbuffer, "new best %d", i);
3452 timer_timeout = test_timeout;
3455 if (timer && !priv->blocked) {
3457 GstClockTime sync_time;
3460 GstClockTimeDiff clock_jitter;
3462 if (timer_timeout == -1 || timer_timeout <= now) {
3463 do_timeout (jitterbuffer, timer, now);
3464 /* check here, do_timeout could have released the lock */
3465 if (!priv->timer_running)
3470 GST_OBJECT_LOCK (jitterbuffer);
3471 clock = GST_ELEMENT_CLOCK (jitterbuffer);
3473 GST_OBJECT_UNLOCK (jitterbuffer);
3474 /* let's just push if there is no clock */
3475 GST_DEBUG_OBJECT (jitterbuffer, "No clock, timeout right away");
3476 now = timer_timeout;
3480 /* prepare for sync against clock */
3481 sync_time = timer_timeout + GST_ELEMENT_CAST (jitterbuffer)->base_time;
3482 /* add latency of peer to get input time */
3483 sync_time += priv->peer_latency;
3485 GST_DEBUG_OBJECT (jitterbuffer, "sync to timestamp %" GST_TIME_FORMAT
3486 " with sync time %" GST_TIME_FORMAT,
3487 GST_TIME_ARGS (timer_timeout), GST_TIME_ARGS (sync_time));
3489 /* create an entry for the clock */
3490 id = priv->clock_id = gst_clock_new_single_shot_id (clock, sync_time);
3491 priv->timer_timeout = timer_timeout;
3492 priv->timer_seqnum = timer->seqnum;
3493 GST_OBJECT_UNLOCK (jitterbuffer);
3495 /* release the lock so that the other end can push stuff or unlock */
3498 ret = gst_clock_id_wait (id, &clock_jitter);
3501 if (!priv->timer_running) {
3502 gst_clock_id_unref (id);
3503 priv->clock_id = NULL;
3507 if (ret != GST_CLOCK_UNSCHEDULED) {
3508 now = timer_timeout + MAX (clock_jitter, 0);
3509 GST_DEBUG_OBJECT (jitterbuffer,
3510 "sync done, %d, #%d, %" GST_STIME_FORMAT, ret, priv->timer_seqnum,
3511 GST_STIME_ARGS (clock_jitter));
3513 GST_DEBUG_OBJECT (jitterbuffer, "sync unscheduled");
3515 /* and free the entry */
3516 gst_clock_id_unref (id);
3517 priv->clock_id = NULL;
3519 /* no timers, wait for activity */
3520 JBUF_WAIT_TIMER (priv);
3525 GST_DEBUG_OBJECT (jitterbuffer, "we are stopping");
3530 * This funcion implements the main pushing loop on the source pad.
3532 * It first tries to push as many buffers as possible. If there is a seqnum
3533 * mismatch, we wait for the next timeouts.
3536 gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer)
3538 GstRtpJitterBufferPrivate *priv;
3539 GstFlowReturn result = GST_FLOW_OK;
3541 priv = jitterbuffer->priv;
3543 JBUF_LOCK_CHECK (priv, flushing);
3545 result = handle_next_buffer (jitterbuffer);
3546 if (G_LIKELY (result == GST_FLOW_WAIT)) {
3547 /* now wait for the next event */
3548 JBUF_WAIT_EVENT (priv, flushing);
3549 result = GST_FLOW_OK;
3551 } while (result == GST_FLOW_OK);
3552 /* store result for upstream */
3553 priv->srcresult = result;
3554 /* if we get here we need to pause */
3560 result = priv->srcresult;
3567 JBUF_SIGNAL_QUERY (priv, FALSE);
3570 GST_DEBUG_OBJECT (jitterbuffer, "pausing task, reason %s",
3571 gst_flow_get_name (result));
3572 gst_pad_pause_task (priv->srcpad);
3573 if (result == GST_FLOW_EOS) {
3574 event = gst_event_new_eos ();
3575 gst_pad_push_event (priv->srcpad, event);
3581 /* collect the info from the lastest RTCP packet and the jitterbuffer sync, do
3582 * some sanity checks and then emit the handle-sync signal with the parameters.
3583 * This function must be called with the LOCK */
3585 do_handle_sync (GstRtpJitterBuffer * jitterbuffer)
3587 GstRtpJitterBufferPrivate *priv;
3588 guint64 base_rtptime, base_time;
3590 guint64 last_rtptime;
3592 guint64 ext_rtptime, diff;
3593 gboolean valid = TRUE, keep = FALSE;
3595 priv = jitterbuffer->priv;
3597 /* get the last values from the jitterbuffer */
3598 rtp_jitter_buffer_get_sync (priv->jbuf, &base_rtptime, &base_time,
3599 &clock_rate, &last_rtptime);
3601 clock_base = priv->clock_base;
3602 ext_rtptime = priv->ext_rtptime;
3604 GST_DEBUG_OBJECT (jitterbuffer, "ext SR %" G_GUINT64_FORMAT ", base %"
3605 G_GUINT64_FORMAT ", clock-rate %" G_GUINT32_FORMAT
3606 ", clock-base %" G_GUINT64_FORMAT ", last-rtptime %" G_GUINT64_FORMAT,
3607 ext_rtptime, base_rtptime, clock_rate, clock_base, last_rtptime);
3609 if (base_rtptime == -1 || clock_rate == -1 || base_time == -1) {
3610 /* we keep this SR packet for later. When we get a valid RTP packet the
3611 * above values will be set and we can try to use the SR packet */
3612 GST_DEBUG_OBJECT (jitterbuffer, "keeping for later, no RTP values");
3615 /* we can't accept anything that happened before we did the last resync */
3616 if (base_rtptime > ext_rtptime) {
3617 GST_DEBUG_OBJECT (jitterbuffer, "dropping, older than base time");
3620 /* the SR RTP timestamp must be something close to what we last observed
3621 * in the jitterbuffer */
3622 if (ext_rtptime > last_rtptime) {
3623 /* check how far ahead it is to our RTP timestamps */
3624 diff = ext_rtptime - last_rtptime;
3625 /* if bigger than 1 second, we drop it */
3626 if (jitterbuffer->priv->max_rtcp_rtp_time_diff != -1 &&
3628 gst_util_uint64_scale (jitterbuffer->priv->max_rtcp_rtp_time_diff,
3629 clock_rate, 1000)) {
3630 GST_DEBUG_OBJECT (jitterbuffer, "too far ahead");
3631 /* should drop this, but some RTSP servers end up with bogus
3632 * way too ahead RTCP packet when repeated PAUSE/PLAY,
3633 * so still trigger rptbin sync but invalidate RTCP data
3634 * (sync might use other methods) */
3637 GST_DEBUG_OBJECT (jitterbuffer, "ext last %" G_GUINT64_FORMAT ", diff %"
3638 G_GUINT64_FORMAT, last_rtptime, diff);
3644 GST_DEBUG_OBJECT (jitterbuffer, "keeping RTCP packet for later");
3648 s = gst_structure_new ("application/x-rtp-sync",
3649 "base-rtptime", G_TYPE_UINT64, base_rtptime,
3650 "base-time", G_TYPE_UINT64, base_time,
3651 "clock-rate", G_TYPE_UINT, clock_rate,
3652 "clock-base", G_TYPE_UINT64, clock_base,
3653 "sr-ext-rtptime", G_TYPE_UINT64, ext_rtptime,
3654 "sr-buffer", GST_TYPE_BUFFER, priv->last_sr, NULL);
3656 GST_DEBUG_OBJECT (jitterbuffer, "signaling sync");
3657 gst_buffer_replace (&priv->last_sr, NULL);
3659 g_signal_emit (jitterbuffer,
3660 gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC], 0, s);
3662 gst_structure_free (s);
3664 GST_DEBUG_OBJECT (jitterbuffer, "dropping RTCP packet");
3665 gst_buffer_replace (&priv->last_sr, NULL);
3669 static GstFlowReturn
3670 gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad, GstObject * parent,
3673 GstRtpJitterBuffer *jitterbuffer;
3674 GstRtpJitterBufferPrivate *priv;
3675 GstFlowReturn ret = GST_FLOW_OK;
3677 GstRTCPPacket packet;
3678 guint64 ext_rtptime;
3680 GstRTCPBuffer rtcp = { NULL, };
3682 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3684 if (G_UNLIKELY (!gst_rtcp_buffer_validate_reduced (buffer)))
3685 goto invalid_buffer;
3687 priv = jitterbuffer->priv;
3689 gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
3691 if (!gst_rtcp_buffer_get_first_packet (&rtcp, &packet))
3694 /* first packet must be SR or RR or else the validate would have failed */
3695 switch (gst_rtcp_packet_get_type (&packet)) {
3696 case GST_RTCP_TYPE_SR:
3697 gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, NULL, &rtptime,
3703 gst_rtcp_buffer_unmap (&rtcp);
3705 GST_DEBUG_OBJECT (jitterbuffer, "received RTCP of SSRC %08x", ssrc);
3708 /* convert the RTP timestamp to our extended timestamp, using the same offset
3709 * we used in the jitterbuffer */
3710 ext_rtptime = priv->jbuf->ext_rtptime;
3711 ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
3713 priv->ext_rtptime = ext_rtptime;
3714 gst_buffer_replace (&priv->last_sr, buffer);
3716 do_handle_sync (jitterbuffer);
3720 gst_buffer_unref (buffer);
3726 /* this is not fatal but should be filtered earlier */
3727 GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
3728 ("Received invalid RTCP payload, dropping"));
3734 /* this is not fatal but should be filtered earlier */
3735 GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
3736 ("Received empty RTCP payload, dropping"));
3737 gst_rtcp_buffer_unmap (&rtcp);
3743 GST_DEBUG_OBJECT (jitterbuffer, "ignoring RTCP packet");
3744 gst_rtcp_buffer_unmap (&rtcp);
3751 gst_rtp_jitter_buffer_sink_query (GstPad * pad, GstObject * parent,
3754 gboolean res = FALSE;
3755 GstRtpJitterBuffer *jitterbuffer;
3756 GstRtpJitterBufferPrivate *priv;
3758 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3759 priv = jitterbuffer->priv;
3761 switch (GST_QUERY_TYPE (query)) {
3762 case GST_QUERY_CAPS:
3764 GstCaps *filter, *caps;
3766 gst_query_parse_caps (query, &filter);
3767 caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
3768 gst_query_set_caps_result (query, caps);
3769 gst_caps_unref (caps);
3774 if (GST_QUERY_IS_SERIALIZED (query)) {
3775 RTPJitterBufferItem *item;
3778 JBUF_LOCK_CHECK (priv, out_flushing);
3779 if (rtp_jitter_buffer_get_mode (priv->jbuf) !=
3780 RTP_JITTER_BUFFER_MODE_BUFFER) {
3781 GST_DEBUG_OBJECT (jitterbuffer, "adding serialized query");
3782 item = alloc_item (query, ITEM_TYPE_QUERY, -1, -1, -1, 0, -1);
3783 rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
3785 JBUF_SIGNAL_EVENT (priv);
3786 JBUF_WAIT_QUERY (priv, out_flushing);
3787 res = priv->last_query;
3789 GST_DEBUG_OBJECT (jitterbuffer, "refusing query, we are buffering");
3794 res = gst_pad_query_default (pad, parent, query);
3802 GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
3810 gst_rtp_jitter_buffer_src_query (GstPad * pad, GstObject * parent,
3813 GstRtpJitterBuffer *jitterbuffer;
3814 GstRtpJitterBufferPrivate *priv;
3815 gboolean res = FALSE;
3817 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3818 priv = jitterbuffer->priv;
3820 switch (GST_QUERY_TYPE (query)) {
3821 case GST_QUERY_LATENCY:
3823 /* We need to send the query upstream and add the returned latency to our
3825 GstClockTime min_latency, max_latency;
3827 GstClockTime our_latency;
3829 if ((res = gst_pad_peer_query (priv->sinkpad, query))) {
3830 gst_query_parse_latency (query, &us_live, &min_latency, &max_latency);
3832 GST_DEBUG_OBJECT (jitterbuffer, "Peer latency: min %"
3833 GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
3834 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3836 /* store this so that we can safely sync on the peer buffers. */
3838 priv->peer_latency = min_latency;
3839 our_latency = priv->latency_ns;
3842 GST_DEBUG_OBJECT (jitterbuffer, "Our latency: %" GST_TIME_FORMAT,
3843 GST_TIME_ARGS (our_latency));
3845 /* we add some latency but can buffer an infinite amount of time */
3846 min_latency += our_latency;
3849 GST_DEBUG_OBJECT (jitterbuffer, "Calculated total latency : min %"
3850 GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
3851 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3853 gst_query_set_latency (query, TRUE, min_latency, max_latency);
3857 case GST_QUERY_POSITION:
3859 GstClockTime start, last_out;
3862 gst_query_parse_position (query, &fmt, NULL);
3863 if (fmt != GST_FORMAT_TIME) {
3864 res = gst_pad_query_default (pad, parent, query);
3869 start = priv->npt_start;
3870 last_out = priv->last_out_time;
3873 GST_DEBUG_OBJECT (jitterbuffer, "npt start %" GST_TIME_FORMAT
3874 ", last out %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
3875 GST_TIME_ARGS (last_out));
3877 if (GST_CLOCK_TIME_IS_VALID (start) && GST_CLOCK_TIME_IS_VALID (last_out)) {
3878 /* bring 0-based outgoing time to stream time */
3879 gst_query_set_position (query, GST_FORMAT_TIME, start + last_out);
3882 res = gst_pad_query_default (pad, parent, query);
3886 case GST_QUERY_CAPS:
3888 GstCaps *filter, *caps;
3890 gst_query_parse_caps (query, &filter);
3891 caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
3892 gst_query_set_caps_result (query, caps);
3893 gst_caps_unref (caps);
3898 res = gst_pad_query_default (pad, parent, query);
3906 gst_rtp_jitter_buffer_set_property (GObject * object,
3907 guint prop_id, const GValue * value, GParamSpec * pspec)
3909 GstRtpJitterBuffer *jitterbuffer;
3910 GstRtpJitterBufferPrivate *priv;
3912 jitterbuffer = GST_RTP_JITTER_BUFFER (object);
3913 priv = jitterbuffer->priv;
3918 guint new_latency, old_latency;
3920 new_latency = g_value_get_uint (value);
3923 old_latency = priv->latency_ms;
3924 priv->latency_ms = new_latency;
3925 priv->latency_ns = priv->latency_ms * GST_MSECOND;
3926 rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
3929 /* post message if latency changed, this will inform the parent pipeline
3930 * that a latency reconfiguration is possible/needed. */
3931 if (new_latency != old_latency) {
3932 GST_DEBUG_OBJECT (jitterbuffer, "latency changed to: %" GST_TIME_FORMAT,
3933 GST_TIME_ARGS (new_latency * GST_MSECOND));
3935 gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer),
3936 gst_message_new_latency (GST_OBJECT_CAST (jitterbuffer)));
3940 case PROP_DROP_ON_LATENCY:
3942 priv->drop_on_latency = g_value_get_boolean (value);
3945 case PROP_TS_OFFSET:
3947 priv->ts_offset = g_value_get_int64 (value);
3948 priv->ts_discont = TRUE;
3953 priv->do_lost = g_value_get_boolean (value);
3958 rtp_jitter_buffer_set_mode (priv->jbuf, g_value_get_enum (value));
3961 case PROP_DO_RETRANSMISSION:
3963 priv->do_retransmission = g_value_get_boolean (value);
3966 case PROP_RTX_NEXT_SEQNUM:
3968 priv->rtx_next_seqnum = g_value_get_boolean (value);
3971 case PROP_RTX_DELAY:
3973 priv->rtx_delay = g_value_get_int (value);
3976 case PROP_RTX_MIN_DELAY:
3978 priv->rtx_min_delay = g_value_get_uint (value);
3981 case PROP_RTX_DELAY_REORDER:
3983 priv->rtx_delay_reorder = g_value_get_int (value);
3986 case PROP_RTX_RETRY_TIMEOUT:
3988 priv->rtx_retry_timeout = g_value_get_int (value);
3991 case PROP_RTX_MIN_RETRY_TIMEOUT:
3993 priv->rtx_min_retry_timeout = g_value_get_int (value);
3996 case PROP_RTX_RETRY_PERIOD:
3998 priv->rtx_retry_period = g_value_get_int (value);
4001 case PROP_RTX_MAX_RETRIES:
4003 priv->rtx_max_retries = g_value_get_int (value);
4006 case PROP_MAX_RTCP_RTP_TIME_DIFF:
4008 priv->max_rtcp_rtp_time_diff = g_value_get_int (value);
4011 case PROP_MAX_DROPOUT_TIME:
4013 priv->max_dropout_time = g_value_get_uint (value);
4016 case PROP_MAX_MISORDER_TIME:
4018 priv->max_misorder_time = g_value_get_uint (value);
4022 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4028 gst_rtp_jitter_buffer_get_property (GObject * object,
4029 guint prop_id, GValue * value, GParamSpec * pspec)
4031 GstRtpJitterBuffer *jitterbuffer;
4032 GstRtpJitterBufferPrivate *priv;
4034 jitterbuffer = GST_RTP_JITTER_BUFFER (object);
4035 priv = jitterbuffer->priv;
4040 g_value_set_uint (value, priv->latency_ms);
4043 case PROP_DROP_ON_LATENCY:
4045 g_value_set_boolean (value, priv->drop_on_latency);
4048 case PROP_TS_OFFSET:
4050 g_value_set_int64 (value, priv->ts_offset);
4055 g_value_set_boolean (value, priv->do_lost);
4060 g_value_set_enum (value, rtp_jitter_buffer_get_mode (priv->jbuf));
4068 if (priv->srcresult != GST_FLOW_OK)
4071 percent = rtp_jitter_buffer_get_percent (priv->jbuf);
4073 g_value_set_int (value, percent);
4077 case PROP_DO_RETRANSMISSION:
4079 g_value_set_boolean (value, priv->do_retransmission);
4082 case PROP_RTX_NEXT_SEQNUM:
4084 g_value_set_boolean (value, priv->rtx_next_seqnum);
4087 case PROP_RTX_DELAY:
4089 g_value_set_int (value, priv->rtx_delay);
4092 case PROP_RTX_MIN_DELAY:
4094 g_value_set_uint (value, priv->rtx_min_delay);
4097 case PROP_RTX_DELAY_REORDER:
4099 g_value_set_int (value, priv->rtx_delay_reorder);
4102 case PROP_RTX_RETRY_TIMEOUT:
4104 g_value_set_int (value, priv->rtx_retry_timeout);
4107 case PROP_RTX_MIN_RETRY_TIMEOUT:
4109 g_value_set_int (value, priv->rtx_min_retry_timeout);
4112 case PROP_RTX_RETRY_PERIOD:
4114 g_value_set_int (value, priv->rtx_retry_period);
4117 case PROP_RTX_MAX_RETRIES:
4119 g_value_set_int (value, priv->rtx_max_retries);
4123 g_value_take_boxed (value,
4124 gst_rtp_jitter_buffer_create_stats (jitterbuffer));
4126 case PROP_MAX_RTCP_RTP_TIME_DIFF:
4128 g_value_set_int (value, priv->max_rtcp_rtp_time_diff);
4131 case PROP_MAX_DROPOUT_TIME:
4133 g_value_set_uint (value, priv->max_dropout_time);
4136 case PROP_MAX_MISORDER_TIME:
4138 g_value_set_uint (value, priv->max_misorder_time);
4142 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4147 static GstStructure *
4148 gst_rtp_jitter_buffer_create_stats (GstRtpJitterBuffer * jbuf)
4152 JBUF_LOCK (jbuf->priv);
4153 s = gst_structure_new ("application/x-rtp-jitterbuffer-stats",
4154 "rtx-count", G_TYPE_UINT64, jbuf->priv->num_rtx_requests,
4155 "rtx-success-count", G_TYPE_UINT64, jbuf->priv->num_rtx_success,
4156 "rtx-per-packet", G_TYPE_DOUBLE, jbuf->priv->avg_rtx_num,
4157 "rtx-rtt", G_TYPE_UINT64, jbuf->priv->avg_rtx_rtt, NULL);
4158 JBUF_UNLOCK (jbuf->priv);