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>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public
20 * License along with this library; if not, write to the
21 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
27 * SECTION:element-rtpjitterbuffer
29 * This element reorders and removes duplicate RTP packets as they are received
30 * from a network source.
32 * The element needs the clock-rate of the RTP payload in order to estimate the
33 * delay. This information is obtained either from the caps on the sink pad or,
34 * when no caps are present, from the #GstRtpJitterBuffer::request-pt-map signal.
35 * To clear the previous pt-map use the #GstRtpJitterBuffer::clear-pt-map signal.
37 * The rtpjitterbuffer will wait for missing packets up to a configurable time
38 * limit using the #GstRtpJitterBuffer:latency property. Packets arriving too
39 * late are considered to be lost packets. If the #GstRtpJitterBuffer:do-lost
40 * property is set, lost packets will result in a custom serialized downstream
41 * event of name GstRTPPacketLost. The lost packet events are usually used by a
42 * depayloader or other element to create concealment data or some other logic
43 * to gracefully handle the missing packets.
45 * The jitterbuffer will use the DTS (or PTS if no DTS is set) of the incomming
46 * buffer and the rtptime inside the RTP packet to create a PTS on the outgoing
49 * The jitterbuffer can also be configured to send early retransmission events
50 * upstream by setting the #GstRtpJitterBuffer:do-retransmission property. In
51 * this mode, the jitterbuffer tries to estimate when a packet should arrive and
52 * sends a custom upstream event named GstRTPRetransmissionRequest when the
53 * packet is considered late. The initial expected packet arrival time is
54 * calculated as follows:
56 * - If seqnum N arrived at time T, seqnum N+1 is expected to arrive at
57 * T + packet-spacing + #GstRtpJitterBuffer:rtx-delay. The packet spacing is
58 * calculated from the DTS (or PTS is no DTS) of two consecutive RTP
59 * packets with different rtptime.
61 * - If seqnum N0 arrived at time T0 and seqnum Nm arrived at time Tm,
62 * seqnum Ni is expected at time Ti = T0 + i*(Tm - T0)/(Nm - N0). Any
63 * previously scheduled timeout is overwritten.
65 * - If seqnum N arrived, all seqnum older than
66 * N - #GstRtpJitterBuffer:rtx-delay-reorder are considered late
67 * immediately. This is to request fast feedback for abonormally reorder
68 * packets before any of the previous timeouts is triggered.
70 * A late packet triggers the GstRTPRetransmissionRequest custom upstream
71 * event. After the initial timeout expires and the retransmission event is
72 * sent, the timeout is scheduled for
73 * T + #GstRtpJitterBuffer:rtx-retry-timeout. If the missing packet did not
74 * arrive after #GstRtpJitterBuffer:rtx-retry-timeout, a new
75 * GstRTPRetransmissionRequest is sent upstream and the timeout is rescheduled
76 * again for T + #GstRtpJitterBuffer:rtx-retry-timeout. This repeats until
77 * #GstRtpJitterBuffer:rtx-retry-period elapsed, at which point no further
78 * retransmission requests are sent and the regular logic is performed to
79 * schedule a lost packet as discussed above.
81 * This element acts as a live element and so adds #GstRtpJitterBuffer:latency
84 * This element will automatically be used inside rtpbin.
87 * <title>Example pipelines</title>
89 * gst-launch-1.0 rtspsrc location=rtsp://192.168.1.133:8554/mpeg1or2AudioVideoTest ! rtpjitterbuffer ! rtpmpvdepay ! mpeg2dec ! xvimagesink
90 * ]| Connect to a streaming server and decode the MPEG video. The jitterbuffer is
91 * inserted into the pipeline to smooth out network jitter and to reorder the
92 * out-of-order RTP packets.
102 #include <gst/rtp/gstrtpbuffer.h>
104 #include "gstrtpjitterbuffer.h"
105 #include "rtpjitterbuffer.h"
106 #include "rtpstats.h"
108 #include <gst/glib-compat-private.h>
110 GST_DEBUG_CATEGORY (rtpjitterbuffer_debug);
111 #define GST_CAT_DEFAULT (rtpjitterbuffer_debug)
113 /* RTPJitterBuffer signals and args */
116 SIGNAL_REQUEST_PT_MAP,
124 #define DEFAULT_LATENCY_MS 200
125 #define DEFAULT_DROP_ON_LATENCY FALSE
126 #define DEFAULT_TS_OFFSET 0
127 #define DEFAULT_DO_LOST FALSE
128 #define DEFAULT_MODE RTP_JITTER_BUFFER_MODE_SLAVE
129 #define DEFAULT_PERCENT 0
130 #define DEFAULT_DO_RETRANSMISSION FALSE
131 #define DEFAULT_RTX_NEXT_SEQNUM TRUE
132 #define DEFAULT_RTX_DELAY -1
133 #define DEFAULT_RTX_MIN_DELAY 0
134 #define DEFAULT_RTX_DELAY_REORDER 3
135 #define DEFAULT_RTX_RETRY_TIMEOUT -1
136 #define DEFAULT_RTX_MIN_RETRY_TIMEOUT -1
137 #define DEFAULT_RTX_RETRY_PERIOD -1
138 #define DEFAULT_RTX_MAX_RETRIES -1
140 #define DEFAULT_AUTO_RTX_DELAY (20 * GST_MSECOND)
141 #define DEFAULT_AUTO_RTX_TIMEOUT (40 * GST_MSECOND)
147 PROP_DROP_ON_LATENCY,
152 PROP_DO_RETRANSMISSION,
153 PROP_RTX_NEXT_SEQNUM,
156 PROP_RTX_DELAY_REORDER,
157 PROP_RTX_RETRY_TIMEOUT,
158 PROP_RTX_MIN_RETRY_TIMEOUT,
159 PROP_RTX_RETRY_PERIOD,
160 PROP_RTX_MAX_RETRIES,
164 #define JBUF_LOCK(priv) (g_mutex_lock (&(priv)->jbuf_lock))
166 #define JBUF_LOCK_CHECK(priv,label) G_STMT_START { \
168 if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK)) \
171 #define JBUF_UNLOCK(priv) (g_mutex_unlock (&(priv)->jbuf_lock))
173 #define JBUF_WAIT_TIMER(priv) G_STMT_START { \
174 GST_DEBUG ("waiting timer"); \
175 (priv)->waiting_timer = TRUE; \
176 g_cond_wait (&(priv)->jbuf_timer, &(priv)->jbuf_lock); \
177 (priv)->waiting_timer = FALSE; \
178 GST_DEBUG ("waiting timer done"); \
180 #define JBUF_SIGNAL_TIMER(priv) G_STMT_START { \
181 if (G_UNLIKELY ((priv)->waiting_timer)) { \
182 GST_DEBUG ("signal timer"); \
183 g_cond_signal (&(priv)->jbuf_timer); \
187 #define JBUF_WAIT_EVENT(priv,label) G_STMT_START { \
188 GST_DEBUG ("waiting event"); \
189 (priv)->waiting_event = TRUE; \
190 g_cond_wait (&(priv)->jbuf_event, &(priv)->jbuf_lock); \
191 (priv)->waiting_event = FALSE; \
192 GST_DEBUG ("waiting event done"); \
193 if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK)) \
196 #define JBUF_SIGNAL_EVENT(priv) G_STMT_START { \
197 if (G_UNLIKELY ((priv)->waiting_event)) { \
198 GST_DEBUG ("signal event"); \
199 g_cond_signal (&(priv)->jbuf_event); \
203 #define JBUF_WAIT_QUERY(priv,label) G_STMT_START { \
204 GST_DEBUG ("waiting query"); \
205 (priv)->waiting_query = TRUE; \
206 g_cond_wait (&(priv)->jbuf_query, &(priv)->jbuf_lock); \
207 (priv)->waiting_query = FALSE; \
208 GST_DEBUG ("waiting query done"); \
209 if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK)) \
212 #define JBUF_SIGNAL_QUERY(priv,res) G_STMT_START { \
213 (priv)->last_query = res; \
214 if (G_UNLIKELY ((priv)->waiting_query)) { \
215 GST_DEBUG ("signal query"); \
216 g_cond_signal (&(priv)->jbuf_query); \
221 struct _GstRtpJitterBufferPrivate
223 GstPad *sinkpad, *srcpad;
226 RTPJitterBuffer *jbuf;
228 gboolean waiting_timer;
230 gboolean waiting_event;
232 gboolean waiting_query;
240 gboolean timer_running;
241 GThread *timer_thread;
246 gboolean drop_on_latency;
249 gboolean do_retransmission;
250 gboolean rtx_next_seqnum;
253 gint rtx_delay_reorder;
254 gint rtx_retry_timeout;
255 gint rtx_min_retry_timeout;
256 gint rtx_retry_period;
257 gint rtx_max_retries;
259 /* the last seqnum we pushed out */
260 guint32 last_popped_seqnum;
261 /* the next expected seqnum we push */
263 /* seqnum-base, if known */
265 /* last output time */
266 GstClockTime last_out_time;
267 /* last valid input timestamp and rtptime pair */
268 GstClockTime ips_dts;
270 GstClockTime packet_spacing;
274 /* the next expected seqnum we receive */
275 GstClockTime last_in_dts;
276 guint32 last_in_seqnum;
277 guint32 next_in_seqnum;
281 /* start and stop ranges */
282 GstClockTime npt_start;
283 GstClockTime npt_stop;
284 guint64 ext_timestamp;
285 guint64 last_elapsed;
286 guint64 estimated_eos;
293 /* clock rate and rtp timestamp offset */
297 gint64 prev_ts_offset;
299 /* when we are shutting down */
300 GstFlowReturn srcresult;
306 GstClockTime timer_timeout;
307 guint16 timer_seqnum;
308 /* the latency of the upstream peer, we have to take this into account when
309 * synchronizing the buffers. */
310 GstClockTime peer_latency;
314 /* some accounting */
316 guint64 num_duplicates;
317 guint64 num_rtx_requests;
318 guint64 num_rtx_success;
319 guint64 num_rtx_failed;
324 GstClockTime last_dts;
325 guint64 last_rtptime;
326 GstClockTime avg_jitter;
343 GstClockTime timeout;
344 GstClockTime duration;
345 GstClockTime rtx_base;
346 GstClockTime rtx_delay;
347 GstClockTime rtx_retry;
348 GstClockTime rtx_last;
352 #define GST_RTP_JITTER_BUFFER_GET_PRIVATE(o) \
353 (G_TYPE_INSTANCE_GET_PRIVATE ((o), GST_TYPE_RTP_JITTER_BUFFER, \
354 GstRtpJitterBufferPrivate))
356 static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_template =
357 GST_STATIC_PAD_TEMPLATE ("sink",
360 GST_STATIC_CAPS ("application/x-rtp"
361 /* "clock-rate = (int) [ 1, 2147483647 ], "
362 * "payload = (int) , "
363 * "encoding-name = (string) "
367 static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_rtcp_template =
368 GST_STATIC_PAD_TEMPLATE ("sink_rtcp",
371 GST_STATIC_CAPS ("application/x-rtcp")
374 static GstStaticPadTemplate gst_rtp_jitter_buffer_src_template =
375 GST_STATIC_PAD_TEMPLATE ("src",
378 GST_STATIC_CAPS ("application/x-rtp"
379 /* "payload = (int) , "
380 * "clock-rate = (int) , "
381 * "encoding-name = (string) "
385 static guint gst_rtp_jitter_buffer_signals[LAST_SIGNAL] = { 0 };
387 #define gst_rtp_jitter_buffer_parent_class parent_class
388 G_DEFINE_TYPE (GstRtpJitterBuffer, gst_rtp_jitter_buffer, GST_TYPE_ELEMENT);
390 /* object overrides */
391 static void gst_rtp_jitter_buffer_set_property (GObject * object,
392 guint prop_id, const GValue * value, GParamSpec * pspec);
393 static void gst_rtp_jitter_buffer_get_property (GObject * object,
394 guint prop_id, GValue * value, GParamSpec * pspec);
395 static void gst_rtp_jitter_buffer_finalize (GObject * object);
397 /* element overrides */
398 static GstStateChangeReturn gst_rtp_jitter_buffer_change_state (GstElement
399 * element, GstStateChange transition);
400 static GstPad *gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
401 GstPadTemplate * templ, const gchar * name, const GstCaps * filter);
402 static void gst_rtp_jitter_buffer_release_pad (GstElement * element,
404 static GstClock *gst_rtp_jitter_buffer_provide_clock (GstElement * element);
407 static GstCaps *gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter);
408 static GstIterator *gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad,
411 /* sinkpad overrides */
412 static gboolean gst_rtp_jitter_buffer_sink_event (GstPad * pad,
413 GstObject * parent, GstEvent * event);
414 static GstFlowReturn gst_rtp_jitter_buffer_chain (GstPad * pad,
415 GstObject * parent, GstBuffer * buffer);
417 static gboolean gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad,
418 GstObject * parent, GstEvent * event);
419 static GstFlowReturn gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad,
420 GstObject * parent, GstBuffer * buffer);
422 static gboolean gst_rtp_jitter_buffer_sink_query (GstPad * pad,
423 GstObject * parent, GstQuery * query);
425 /* srcpad overrides */
426 static gboolean gst_rtp_jitter_buffer_src_event (GstPad * pad,
427 GstObject * parent, GstEvent * event);
428 static gboolean gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad,
429 GstObject * parent, GstPadMode mode, gboolean active);
430 static void gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer);
431 static gboolean gst_rtp_jitter_buffer_src_query (GstPad * pad,
432 GstObject * parent, GstQuery * query);
435 gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer);
437 gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jitterbuffer,
438 gboolean active, guint64 base_time);
439 static void do_handle_sync (GstRtpJitterBuffer * jitterbuffer);
441 static void unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer);
442 static void remove_all_timers (GstRtpJitterBuffer * jitterbuffer);
444 static void wait_next_timeout (GstRtpJitterBuffer * jitterbuffer);
446 static GstStructure *gst_rtp_jitter_buffer_create_stats (GstRtpJitterBuffer *
450 gst_rtp_jitter_buffer_class_init (GstRtpJitterBufferClass * klass)
452 GObjectClass *gobject_class;
453 GstElementClass *gstelement_class;
455 gobject_class = (GObjectClass *) klass;
456 gstelement_class = (GstElementClass *) klass;
458 g_type_class_add_private (klass, sizeof (GstRtpJitterBufferPrivate));
460 gobject_class->finalize = gst_rtp_jitter_buffer_finalize;
462 gobject_class->set_property = gst_rtp_jitter_buffer_set_property;
463 gobject_class->get_property = gst_rtp_jitter_buffer_get_property;
466 * GstRtpJitterBuffer:latency:
468 * The maximum latency of the jitterbuffer. Packets will be kept in the buffer
469 * for at most this time.
471 g_object_class_install_property (gobject_class, PROP_LATENCY,
472 g_param_spec_uint ("latency", "Buffer latency in ms",
473 "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
474 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
476 * GstRtpJitterBuffer:drop-on-latency:
478 * Drop oldest buffers when the queue is completely filled.
480 g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
481 g_param_spec_boolean ("drop-on-latency",
482 "Drop buffers when maximum latency is reached",
483 "Tells the jitterbuffer to never exceed the given latency in size",
484 DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
486 * GstRtpJitterBuffer:ts-offset:
488 * Adjust GStreamer output buffer timestamps in the jitterbuffer with offset.
489 * This is mainly used to ensure interstream synchronisation.
491 g_object_class_install_property (gobject_class, PROP_TS_OFFSET,
492 g_param_spec_int64 ("ts-offset", "Timestamp Offset",
493 "Adjust buffer timestamps with offset in nanoseconds", G_MININT64,
494 G_MAXINT64, DEFAULT_TS_OFFSET,
495 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
498 * GstRtpJitterBuffer:do-lost:
500 * Send out a GstRTPPacketLost event downstream when a packet is considered
503 g_object_class_install_property (gobject_class, PROP_DO_LOST,
504 g_param_spec_boolean ("do-lost", "Do Lost",
505 "Send an event downstream when a packet is lost", DEFAULT_DO_LOST,
506 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
509 * GstRtpJitterBuffer:mode:
511 * Control the buffering and timestamping mode used by the jitterbuffer.
513 g_object_class_install_property (gobject_class, PROP_MODE,
514 g_param_spec_enum ("mode", "Mode",
515 "Control the buffering algorithm in use", RTP_TYPE_JITTER_BUFFER_MODE,
516 DEFAULT_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
518 * GstRtpJitterBuffer:percent:
520 * The percent of the jitterbuffer that is filled.
522 g_object_class_install_property (gobject_class, PROP_PERCENT,
523 g_param_spec_int ("percent", "percent",
524 "The buffer filled percent", 0, 100,
525 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
527 * GstRtpJitterBuffer:do-retransmission:
529 * Send out a GstRTPRetransmission event upstream when a packet is considered
530 * late and should be retransmitted.
534 g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
535 g_param_spec_boolean ("do-retransmission", "Do Retransmission",
536 "Send retransmission events upstream when a packet is late",
537 DEFAULT_DO_RETRANSMISSION,
538 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
541 * GstRtpJitterBuffer:rtx-next-seqnum
543 * Estimate when the next packet should arrive and schedule a retransmission
545 * This is, when packet N arrives, a GstRTPRetransmission event is schedule
546 * for packet N+1. So it will be requested if it does not arrive at the expected time.
547 * The expected time is calculated using the dts of N and the packet spacing.
551 g_object_class_install_property (gobject_class, PROP_RTX_NEXT_SEQNUM,
552 g_param_spec_boolean ("rtx-next-seqnum", "RTX next seqnum",
553 "Estimate when the next packet should arrive and schedule a "
554 "retransmission request for it.",
555 DEFAULT_RTX_NEXT_SEQNUM, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
558 * GstRtpJitterBuffer:rtx-delay:
560 * When a packet did not arrive at the expected time, wait this extra amount
561 * of time before sending a retransmission event.
563 * When -1 is used, the max jitter will be used as extra delay.
567 g_object_class_install_property (gobject_class, PROP_RTX_DELAY,
568 g_param_spec_int ("rtx-delay", "RTX Delay",
569 "Extra time in ms to wait before sending retransmission "
570 "event (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_DELAY,
571 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
574 * GstRtpJitterBuffer:rtx-min-delay:
576 * When a packet did not arrive at the expected time, wait at least this extra amount
577 * of time before sending a retransmission event.
581 g_object_class_install_property (gobject_class, PROP_RTX_MIN_DELAY,
582 g_param_spec_uint ("rtx-min-delay", "Minimum RTX Delay",
583 "Minimum time in ms to wait before sending retransmission "
584 "event", 0, G_MAXUINT, DEFAULT_RTX_MIN_DELAY,
585 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
587 * GstRtpJitterBuffer:rtx-delay-reorder:
589 * Assume that a retransmission event should be sent when we see
590 * this much packet reordering.
592 * When -1 is used, the value will be estimated based on observed packet
597 g_object_class_install_property (gobject_class, PROP_RTX_DELAY_REORDER,
598 g_param_spec_int ("rtx-delay-reorder", "RTX Delay Reorder",
599 "Sending retransmission event when this much reordering (-1 automatic)",
600 -1, G_MAXINT, DEFAULT_RTX_DELAY_REORDER,
601 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
603 * GstRtpJitterBuffer::rtx-retry-timeout:
605 * When no packet has been received after sending a retransmission event
606 * for this time, retry sending a retransmission event.
608 * When -1 is used, the value will be estimated based on observed round
613 g_object_class_install_property (gobject_class, PROP_RTX_RETRY_TIMEOUT,
614 g_param_spec_int ("rtx-retry-timeout", "RTX Retry Timeout",
615 "Retry sending a transmission event after this timeout in "
616 "ms (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_TIMEOUT,
617 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
619 * GstRtpJitterBuffer::rtx-min-retry-timeout:
621 * The minimum amount of time between retry timeouts. When
622 * GstRtpJitterBuffer::rtx-retry-timeout is -1, this value ensures a
623 * minimum interval between retry timeouts.
625 * When -1 is used, the value will be estimated based on the
630 g_object_class_install_property (gobject_class, PROP_RTX_MIN_RETRY_TIMEOUT,
631 g_param_spec_int ("rtx-min-retry-timeout", "RTX Min Retry Timeout",
632 "Minimum timeout between sending a transmission event in "
633 "ms (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_MIN_RETRY_TIMEOUT,
634 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
636 * GstRtpJitterBuffer:rtx-retry-period:
638 * The amount of time to try to get a retransmission.
640 * When -1 is used, the value will be estimated based on the jitterbuffer
641 * latency and the observed round trip time.
645 g_object_class_install_property (gobject_class, PROP_RTX_RETRY_PERIOD,
646 g_param_spec_int ("rtx-retry-period", "RTX Retry Period",
647 "Try to get a retransmission for this many ms "
648 "(-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_PERIOD,
649 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
651 * GstRtpJitterBuffer:rtx-max-retries:
653 * The maximum number of retries to request a retransmission.
655 * This implies that as maximum (rtx-max-retries + 1) retransmissions will be requested.
656 * When -1 is used, the number of retransmission request will not be limited.
660 g_object_class_install_property (gobject_class, PROP_RTX_MAX_RETRIES,
661 g_param_spec_int ("rtx-max-retries", "RTX Max Retries",
662 "The maximum number of retries to request a retransmission. "
663 "(-1 not limited)", -1, G_MAXINT, DEFAULT_RTX_MAX_RETRIES,
664 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
666 * GstRtpJitterBuffer:stats:
668 * Various jitterbuffer statistics. This property returns a GstStructure
669 * with name application/x-rtp-jitterbuffer-stats with the following fields:
675 * <classname>"rtx-count"</classname>:
676 * the number of retransmissions requested.
682 * <classname>"rtx-success-count"</classname>:
683 * the number of successful retransmissions.
689 * <classname>"rtx-per-packet"</classname>:
690 * average number of RTX per packet.
696 * <classname>"rtx-rtt"</classname>:
697 * average round trip time per RTX.
704 g_object_class_install_property (gobject_class, PROP_STATS,
705 g_param_spec_boxed ("stats", "Statistics",
706 "Various statistics", GST_TYPE_STRUCTURE,
707 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
710 * GstRtpJitterBuffer::request-pt-map:
711 * @buffer: the object which received the signal
714 * Request the payload type as #GstCaps for @pt.
716 gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP] =
717 g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
718 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
719 request_pt_map), NULL, NULL, g_cclosure_marshal_generic,
720 GST_TYPE_CAPS, 1, G_TYPE_UINT);
722 * GstRtpJitterBuffer::handle-sync:
723 * @buffer: the object which received the signal
724 * @struct: a GstStructure containing sync values.
726 * Be notified of new sync values.
728 gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC] =
729 g_signal_new ("handle-sync", G_TYPE_FROM_CLASS (klass),
730 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
731 handle_sync), NULL, NULL, g_cclosure_marshal_VOID__BOXED,
732 G_TYPE_NONE, 1, GST_TYPE_STRUCTURE | G_SIGNAL_TYPE_STATIC_SCOPE);
735 * GstRtpJitterBuffer::on-npt-stop:
736 * @buffer: the object which received the signal
738 * Signal that the jitterbufer has pushed the RTP packet that corresponds to
739 * the npt-stop position.
741 gst_rtp_jitter_buffer_signals[SIGNAL_ON_NPT_STOP] =
742 g_signal_new ("on-npt-stop", G_TYPE_FROM_CLASS (klass),
743 G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
744 on_npt_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID,
745 G_TYPE_NONE, 0, G_TYPE_NONE);
748 * GstRtpJitterBuffer::clear-pt-map:
749 * @buffer: the object which received the signal
751 * Invalidate the clock-rate as obtained with the
752 * #GstRtpJitterBuffer::request-pt-map signal.
754 gst_rtp_jitter_buffer_signals[SIGNAL_CLEAR_PT_MAP] =
755 g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
756 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
757 G_STRUCT_OFFSET (GstRtpJitterBufferClass, clear_pt_map), NULL, NULL,
758 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
761 * GstRtpJitterBuffer::set-active:
762 * @buffer: the object which received the signal
764 * Start pushing out packets with the given base time. This signal is only
765 * useful in buffering mode.
767 * Returns: the time of the last pushed packet.
769 gst_rtp_jitter_buffer_signals[SIGNAL_SET_ACTIVE] =
770 g_signal_new ("set-active", G_TYPE_FROM_CLASS (klass),
771 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
772 G_STRUCT_OFFSET (GstRtpJitterBufferClass, set_active), NULL, NULL,
773 g_cclosure_marshal_generic, G_TYPE_UINT64, 2, G_TYPE_BOOLEAN,
776 gstelement_class->change_state =
777 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_change_state);
778 gstelement_class->request_new_pad =
779 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_request_new_pad);
780 gstelement_class->release_pad =
781 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_release_pad);
782 gstelement_class->provide_clock =
783 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_provide_clock);
785 gst_element_class_add_pad_template (gstelement_class,
786 gst_static_pad_template_get (&gst_rtp_jitter_buffer_src_template));
787 gst_element_class_add_pad_template (gstelement_class,
788 gst_static_pad_template_get (&gst_rtp_jitter_buffer_sink_template));
789 gst_element_class_add_pad_template (gstelement_class,
790 gst_static_pad_template_get (&gst_rtp_jitter_buffer_sink_rtcp_template));
792 gst_element_class_set_static_metadata (gstelement_class,
793 "RTP packet jitter-buffer", "Filter/Network/RTP",
794 "A buffer that deals with network jitter and other transmission faults",
795 "Philippe Kalaf <philippe.kalaf@collabora.co.uk>, "
796 "Wim Taymans <wim.taymans@gmail.com>");
798 klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_clear_pt_map);
799 klass->set_active = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_set_active);
801 GST_DEBUG_CATEGORY_INIT
802 (rtpjitterbuffer_debug, "rtpjitterbuffer", 0, "RTP Jitter Buffer");
806 gst_rtp_jitter_buffer_init (GstRtpJitterBuffer * jitterbuffer)
808 GstRtpJitterBufferPrivate *priv;
810 priv = GST_RTP_JITTER_BUFFER_GET_PRIVATE (jitterbuffer);
811 jitterbuffer->priv = priv;
813 priv->latency_ms = DEFAULT_LATENCY_MS;
814 priv->latency_ns = priv->latency_ms * GST_MSECOND;
815 priv->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
816 priv->do_lost = DEFAULT_DO_LOST;
817 priv->do_retransmission = DEFAULT_DO_RETRANSMISSION;
818 priv->rtx_next_seqnum = DEFAULT_RTX_NEXT_SEQNUM;
819 priv->rtx_delay = DEFAULT_RTX_DELAY;
820 priv->rtx_min_delay = DEFAULT_RTX_MIN_DELAY;
821 priv->rtx_delay_reorder = DEFAULT_RTX_DELAY_REORDER;
822 priv->rtx_retry_timeout = DEFAULT_RTX_RETRY_TIMEOUT;
823 priv->rtx_min_retry_timeout = DEFAULT_RTX_MIN_RETRY_TIMEOUT;
824 priv->rtx_retry_period = DEFAULT_RTX_RETRY_PERIOD;
825 priv->rtx_max_retries = DEFAULT_RTX_MAX_RETRIES;
828 priv->last_rtptime = -1;
829 priv->avg_jitter = 0;
830 priv->timers = g_array_new (FALSE, TRUE, sizeof (TimerData));
831 priv->jbuf = rtp_jitter_buffer_new ();
832 g_mutex_init (&priv->jbuf_lock);
833 g_cond_init (&priv->jbuf_timer);
834 g_cond_init (&priv->jbuf_event);
835 g_cond_init (&priv->jbuf_query);
836 g_queue_init (&priv->gap_packets);
838 /* reset skew detection initialy */
839 rtp_jitter_buffer_reset_skew (priv->jbuf);
840 rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
841 rtp_jitter_buffer_set_buffering (priv->jbuf, FALSE);
845 gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_src_template,
848 gst_pad_set_activatemode_function (priv->srcpad,
849 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_activate_mode));
850 gst_pad_set_query_function (priv->srcpad,
851 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_query));
852 gst_pad_set_event_function (priv->srcpad,
853 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_event));
856 gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_sink_template,
859 gst_pad_set_chain_function (priv->sinkpad,
860 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_chain));
861 gst_pad_set_event_function (priv->sinkpad,
862 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_event));
863 gst_pad_set_query_function (priv->sinkpad,
864 GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_query));
866 gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->srcpad);
867 gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->sinkpad);
869 GST_OBJECT_FLAG_SET (jitterbuffer, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
872 #define IS_DROPABLE(it) (((it)->type == ITEM_TYPE_BUFFER) || ((it)->type == ITEM_TYPE_LOST))
874 #define ITEM_TYPE_BUFFER 0
875 #define ITEM_TYPE_LOST 1
876 #define ITEM_TYPE_EVENT 2
877 #define ITEM_TYPE_QUERY 3
879 static RTPJitterBufferItem *
880 alloc_item (gpointer data, guint type, GstClockTime dts, GstClockTime pts,
881 guint seqnum, guint count, guint rtptime)
883 RTPJitterBufferItem *item;
885 item = g_slice_new (RTPJitterBufferItem);
892 item->seqnum = seqnum;
894 item->rtptime = rtptime;
900 free_item (RTPJitterBufferItem * item)
902 g_return_if_fail (item != NULL);
904 if (item->data && item->type != ITEM_TYPE_QUERY)
905 gst_mini_object_unref (item->data);
906 g_slice_free (RTPJitterBufferItem, item);
910 free_item_and_retain_events (RTPJitterBufferItem * item, gpointer user_data)
912 GList **l = user_data;
914 if (item->data && item->type == ITEM_TYPE_EVENT
915 && GST_EVENT_IS_STICKY (item->data)) {
916 *l = g_list_prepend (*l, item->data);
917 } else if (item->data && item->type != ITEM_TYPE_QUERY) {
918 gst_mini_object_unref (item->data);
920 g_slice_free (RTPJitterBufferItem, item);
924 gst_rtp_jitter_buffer_finalize (GObject * object)
926 GstRtpJitterBuffer *jitterbuffer;
927 GstRtpJitterBufferPrivate *priv;
929 jitterbuffer = GST_RTP_JITTER_BUFFER (object);
930 priv = jitterbuffer->priv;
932 g_array_free (priv->timers, TRUE);
933 g_mutex_clear (&priv->jbuf_lock);
934 g_cond_clear (&priv->jbuf_timer);
935 g_cond_clear (&priv->jbuf_event);
936 g_cond_clear (&priv->jbuf_query);
938 rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
939 g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
940 g_queue_clear (&priv->gap_packets);
941 g_object_unref (priv->jbuf);
943 G_OBJECT_CLASS (parent_class)->finalize (object);
947 gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad, GstObject * parent)
949 GstRtpJitterBuffer *jitterbuffer;
950 GstPad *otherpad = NULL;
951 GstIterator *it = NULL;
954 jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
956 if (pad == jitterbuffer->priv->sinkpad) {
957 otherpad = jitterbuffer->priv->srcpad;
958 } else if (pad == jitterbuffer->priv->srcpad) {
959 otherpad = jitterbuffer->priv->sinkpad;
960 } else if (pad == jitterbuffer->priv->rtcpsinkpad) {
961 it = gst_iterator_new_single (GST_TYPE_PAD, NULL);
965 g_value_init (&val, GST_TYPE_PAD);
966 g_value_set_object (&val, otherpad);
967 it = gst_iterator_new_single (GST_TYPE_PAD, &val);
968 g_value_unset (&val);
975 create_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
977 GstRtpJitterBufferPrivate *priv;
979 priv = jitterbuffer->priv;
981 GST_DEBUG_OBJECT (jitterbuffer, "creating RTCP sink pad");
984 gst_pad_new_from_static_template
985 (&gst_rtp_jitter_buffer_sink_rtcp_template, "sink_rtcp");
986 gst_pad_set_chain_function (priv->rtcpsinkpad,
987 gst_rtp_jitter_buffer_chain_rtcp);
988 gst_pad_set_event_function (priv->rtcpsinkpad,
989 (GstPadEventFunction) gst_rtp_jitter_buffer_sink_rtcp_event);
990 gst_pad_set_iterate_internal_links_function (priv->rtcpsinkpad,
991 gst_rtp_jitter_buffer_iterate_internal_links);
992 gst_pad_set_active (priv->rtcpsinkpad, TRUE);
993 gst_element_add_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
995 return priv->rtcpsinkpad;
999 remove_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
1001 GstRtpJitterBufferPrivate *priv;
1003 priv = jitterbuffer->priv;
1005 GST_DEBUG_OBJECT (jitterbuffer, "removing RTCP sink pad");
1007 gst_pad_set_active (priv->rtcpsinkpad, FALSE);
1009 gst_element_remove_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
1010 priv->rtcpsinkpad = NULL;
1014 gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
1015 GstPadTemplate * templ, const gchar * name, const GstCaps * filter)
1017 GstRtpJitterBuffer *jitterbuffer;
1018 GstElementClass *klass;
1020 GstRtpJitterBufferPrivate *priv;
1022 g_return_val_if_fail (templ != NULL, NULL);
1023 g_return_val_if_fail (GST_IS_RTP_JITTER_BUFFER (element), NULL);
1025 jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (element);
1026 priv = jitterbuffer->priv;
1027 klass = GST_ELEMENT_GET_CLASS (element);
1029 GST_DEBUG_OBJECT (element, "requesting pad %s", GST_STR_NULL (name));
1031 /* figure out the template */
1032 if (templ == gst_element_class_get_pad_template (klass, "sink_rtcp")) {
1033 if (priv->rtcpsinkpad != NULL)
1036 result = create_rtcp_sink (jitterbuffer);
1038 goto wrong_template;
1045 g_warning ("rtpjitterbuffer: this is not our template");
1050 g_warning ("rtpjitterbuffer: pad already requested");
1056 gst_rtp_jitter_buffer_release_pad (GstElement * element, GstPad * pad)
1058 GstRtpJitterBuffer *jitterbuffer;
1059 GstRtpJitterBufferPrivate *priv;
1061 g_return_if_fail (GST_IS_RTP_JITTER_BUFFER (element));
1062 g_return_if_fail (GST_IS_PAD (pad));
1064 jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (element);
1065 priv = jitterbuffer->priv;
1067 GST_DEBUG_OBJECT (element, "releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1069 if (priv->rtcpsinkpad == pad) {
1070 remove_rtcp_sink (jitterbuffer);
1079 g_warning ("gstjitterbuffer: asked to release an unknown pad");
1085 gst_rtp_jitter_buffer_provide_clock (GstElement * element)
1087 return gst_system_clock_obtain ();
1091 gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer)
1093 GstRtpJitterBufferPrivate *priv;
1095 priv = jitterbuffer->priv;
1097 /* this will trigger a new pt-map request signal, FIXME, do something better. */
1100 priv->clock_rate = -1;
1101 /* do not clear current content, but refresh state for new arrival */
1102 GST_DEBUG_OBJECT (jitterbuffer, "reset jitterbuffer");
1103 rtp_jitter_buffer_reset_skew (priv->jbuf);
1108 gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jbuf, gboolean active,
1111 GstRtpJitterBufferPrivate *priv;
1112 GstClockTime last_out;
1113 RTPJitterBufferItem *item;
1118 GST_DEBUG_OBJECT (jbuf, "setting active %d with offset %" GST_TIME_FORMAT,
1119 active, GST_TIME_ARGS (offset));
1121 if (active != priv->active) {
1122 /* add the amount of time spent in paused to the output offset. All
1123 * outgoing buffers will have this offset applied to their timestamps in
1124 * order to make them arrive in time in the sink. */
1125 priv->out_offset = offset;
1126 GST_DEBUG_OBJECT (jbuf, "out offset %" GST_TIME_FORMAT,
1127 GST_TIME_ARGS (priv->out_offset));
1128 priv->active = active;
1129 JBUF_SIGNAL_EVENT (priv);
1132 rtp_jitter_buffer_set_buffering (priv->jbuf, TRUE);
1134 if ((item = rtp_jitter_buffer_peek (priv->jbuf))) {
1135 /* head buffer timestamp and offset gives our output time */
1136 last_out = item->dts + priv->ts_offset;
1138 /* use last known time when the buffer is empty */
1139 last_out = priv->last_out_time;
1147 gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter)
1149 GstRtpJitterBuffer *jitterbuffer;
1150 GstRtpJitterBufferPrivate *priv;
1155 jitterbuffer = GST_RTP_JITTER_BUFFER (gst_pad_get_parent (pad));
1156 priv = jitterbuffer->priv;
1158 other = (pad == priv->srcpad ? priv->sinkpad : priv->srcpad);
1160 caps = gst_pad_peer_query_caps (other, filter);
1162 templ = gst_pad_get_pad_template_caps (pad);
1164 GST_DEBUG_OBJECT (jitterbuffer, "use template");
1169 GST_DEBUG_OBJECT (jitterbuffer, "intersect with template");
1171 intersect = gst_caps_intersect (caps, templ);
1172 gst_caps_unref (caps);
1173 gst_caps_unref (templ);
1177 gst_object_unref (jitterbuffer);
1183 * Must be called with JBUF_LOCK held
1187 gst_jitter_buffer_sink_parse_caps (GstRtpJitterBuffer * jitterbuffer,
1190 GstRtpJitterBufferPrivate *priv;
1191 GstStructure *caps_struct;
1195 priv = jitterbuffer->priv;
1197 /* first parse the caps */
1198 caps_struct = gst_caps_get_structure (caps, 0);
1200 GST_DEBUG_OBJECT (jitterbuffer, "got caps");
1202 /* we need a clock-rate to convert the rtp timestamps to GStreamer time and to
1203 * measure the amount of data in the buffer */
1204 if (!gst_structure_get_int (caps_struct, "clock-rate", &priv->clock_rate))
1207 if (priv->clock_rate <= 0)
1210 GST_DEBUG_OBJECT (jitterbuffer, "got clock-rate %d", priv->clock_rate);
1212 rtp_jitter_buffer_set_clock_rate (priv->jbuf, priv->clock_rate);
1214 /* The clock base is the RTP timestamp corrsponding to the npt-start value. We
1215 * can use this to track the amount of time elapsed on the sender. */
1216 if (gst_structure_get_uint (caps_struct, "clock-base", &val))
1217 priv->clock_base = val;
1219 priv->clock_base = -1;
1221 priv->ext_timestamp = priv->clock_base;
1223 GST_DEBUG_OBJECT (jitterbuffer, "got clock-base %" G_GINT64_FORMAT,
1226 if (gst_structure_get_uint (caps_struct, "seqnum-base", &val)) {
1227 /* first expected seqnum, only update when we didn't have a previous base. */
1228 if (priv->next_in_seqnum == -1)
1229 priv->next_in_seqnum = val;
1230 if (priv->next_seqnum == -1) {
1231 priv->next_seqnum = val;
1232 JBUF_SIGNAL_EVENT (priv);
1234 priv->seqnum_base = val;
1236 priv->seqnum_base = -1;
1239 GST_DEBUG_OBJECT (jitterbuffer, "got seqnum-base %d", priv->next_in_seqnum);
1241 /* the start and stop times. The seqnum-base corresponds to the start time. We
1242 * will keep track of the seqnums on the output and when we reach the one
1243 * corresponding to npt-stop, we emit the npt-stop-reached signal */
1244 if (gst_structure_get_clock_time (caps_struct, "npt-start", &tval))
1245 priv->npt_start = tval;
1247 priv->npt_start = 0;
1249 if (gst_structure_get_clock_time (caps_struct, "npt-stop", &tval))
1250 priv->npt_stop = tval;
1252 priv->npt_stop = -1;
1254 GST_DEBUG_OBJECT (jitterbuffer,
1255 "npt start/stop: %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
1256 GST_TIME_ARGS (priv->npt_start), GST_TIME_ARGS (priv->npt_stop));
1263 GST_DEBUG_OBJECT (jitterbuffer, "No clock-rate in caps!");
1268 GST_DEBUG_OBJECT (jitterbuffer, "Invalid clock-rate %d", priv->clock_rate);
1274 gst_rtp_jitter_buffer_flush_start (GstRtpJitterBuffer * jitterbuffer)
1276 GstRtpJitterBufferPrivate *priv;
1278 priv = jitterbuffer->priv;
1281 /* mark ourselves as flushing */
1282 priv->srcresult = GST_FLOW_FLUSHING;
1283 GST_DEBUG_OBJECT (jitterbuffer, "Disabling pop on queue");
1284 /* this unblocks any waiting pops on the src pad task */
1285 JBUF_SIGNAL_EVENT (priv);
1286 JBUF_SIGNAL_QUERY (priv, FALSE);
1291 gst_rtp_jitter_buffer_flush_stop (GstRtpJitterBuffer * jitterbuffer)
1293 GstRtpJitterBufferPrivate *priv;
1295 priv = jitterbuffer->priv;
1298 GST_DEBUG_OBJECT (jitterbuffer, "Enabling pop on queue");
1299 /* Mark as non flushing */
1300 priv->srcresult = GST_FLOW_OK;
1301 gst_segment_init (&priv->segment, GST_FORMAT_TIME);
1302 priv->last_popped_seqnum = -1;
1303 priv->last_out_time = -1;
1304 priv->next_seqnum = -1;
1305 priv->seqnum_base = -1;
1306 priv->ips_rtptime = -1;
1307 priv->ips_dts = GST_CLOCK_TIME_NONE;
1308 priv->packet_spacing = 0;
1309 priv->next_in_seqnum = -1;
1310 priv->clock_rate = -1;
1313 priv->estimated_eos = -1;
1314 priv->last_elapsed = 0;
1315 priv->ext_timestamp = -1;
1316 priv->avg_jitter = 0;
1317 priv->last_dts = -1;
1318 priv->last_rtptime = -1;
1319 GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
1320 rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
1321 rtp_jitter_buffer_disable_buffering (priv->jbuf, FALSE);
1322 rtp_jitter_buffer_reset_skew (priv->jbuf);
1323 remove_all_timers (jitterbuffer);
1324 g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
1325 g_queue_clear (&priv->gap_packets);
1330 gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad, GstObject * parent,
1331 GstPadMode mode, gboolean active)
1334 GstRtpJitterBuffer *jitterbuffer = NULL;
1336 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1339 case GST_PAD_MODE_PUSH:
1341 /* allow data processing */
1342 gst_rtp_jitter_buffer_flush_stop (jitterbuffer);
1344 /* start pushing out buffers */
1345 GST_DEBUG_OBJECT (jitterbuffer, "Starting task on srcpad");
1346 result = gst_pad_start_task (jitterbuffer->priv->srcpad,
1347 (GstTaskFunction) gst_rtp_jitter_buffer_loop, jitterbuffer, NULL);
1349 /* make sure all data processing stops ASAP */
1350 gst_rtp_jitter_buffer_flush_start (jitterbuffer);
1352 /* NOTE this will hardlock if the state change is called from the src pad
1353 * task thread because we will _join() the thread. */
1354 GST_DEBUG_OBJECT (jitterbuffer, "Stopping task on srcpad");
1355 result = gst_pad_stop_task (pad);
1365 static GstStateChangeReturn
1366 gst_rtp_jitter_buffer_change_state (GstElement * element,
1367 GstStateChange transition)
1369 GstRtpJitterBuffer *jitterbuffer;
1370 GstRtpJitterBufferPrivate *priv;
1371 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1373 jitterbuffer = GST_RTP_JITTER_BUFFER (element);
1374 priv = jitterbuffer->priv;
1376 switch (transition) {
1377 case GST_STATE_CHANGE_NULL_TO_READY:
1379 case GST_STATE_CHANGE_READY_TO_PAUSED:
1381 /* reset negotiated values */
1382 priv->clock_rate = -1;
1383 priv->clock_base = -1;
1384 priv->peer_latency = 0;
1386 /* block until we go to PLAYING */
1387 priv->blocked = TRUE;
1388 priv->timer_running = TRUE;
1389 priv->timer_thread =
1390 g_thread_new ("timer", (GThreadFunc) wait_next_timeout, jitterbuffer);
1393 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1395 /* unblock to allow streaming in PLAYING */
1396 priv->blocked = FALSE;
1397 JBUF_SIGNAL_EVENT (priv);
1398 JBUF_SIGNAL_TIMER (priv);
1405 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1407 switch (transition) {
1408 case GST_STATE_CHANGE_READY_TO_PAUSED:
1409 /* we are a live element because we sync to the clock, which we can only
1410 * do in the PLAYING state */
1411 if (ret != GST_STATE_CHANGE_FAILURE)
1412 ret = GST_STATE_CHANGE_NO_PREROLL;
1414 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1416 /* block to stop streaming when PAUSED */
1417 priv->blocked = TRUE;
1418 unschedule_current_timer (jitterbuffer);
1420 if (ret != GST_STATE_CHANGE_FAILURE)
1421 ret = GST_STATE_CHANGE_NO_PREROLL;
1423 case GST_STATE_CHANGE_PAUSED_TO_READY:
1425 gst_buffer_replace (&priv->last_sr, NULL);
1426 priv->timer_running = FALSE;
1427 unschedule_current_timer (jitterbuffer);
1428 JBUF_SIGNAL_TIMER (priv);
1429 JBUF_SIGNAL_QUERY (priv, FALSE);
1431 g_thread_join (priv->timer_thread);
1432 priv->timer_thread = NULL;
1434 case GST_STATE_CHANGE_READY_TO_NULL:
1444 gst_rtp_jitter_buffer_src_event (GstPad * pad, GstObject * parent,
1447 gboolean ret = TRUE;
1448 GstRtpJitterBuffer *jitterbuffer;
1449 GstRtpJitterBufferPrivate *priv;
1451 jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
1452 priv = jitterbuffer->priv;
1454 GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1456 switch (GST_EVENT_TYPE (event)) {
1457 case GST_EVENT_LATENCY:
1459 GstClockTime latency;
1461 gst_event_parse_latency (event, &latency);
1463 GST_DEBUG_OBJECT (jitterbuffer,
1464 "configuring latency of %" GST_TIME_FORMAT, GST_TIME_ARGS (latency));
1467 /* adjust the overall buffer delay to the total pipeline latency in
1468 * buffering mode because if downstream consumes too fast (because of
1469 * large latency or queues, we would start rebuffering again. */
1470 if (rtp_jitter_buffer_get_mode (priv->jbuf) ==
1471 RTP_JITTER_BUFFER_MODE_BUFFER) {
1472 rtp_jitter_buffer_set_delay (priv->jbuf, latency);
1476 ret = gst_pad_push_event (priv->sinkpad, event);
1480 ret = gst_pad_push_event (priv->sinkpad, event);
1487 /* handles and stores the event in the jitterbuffer, must be called with
1490 queue_event (GstRtpJitterBuffer * jitterbuffer, GstEvent * event)
1492 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1493 RTPJitterBufferItem *item;
1496 switch (GST_EVENT_TYPE (event)) {
1497 case GST_EVENT_CAPS:
1501 gst_event_parse_caps (event, &caps);
1502 gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1505 case GST_EVENT_SEGMENT:
1506 gst_event_copy_segment (event, &priv->segment);
1508 /* we need time for now */
1509 if (priv->segment.format != GST_FORMAT_TIME)
1510 goto newseg_wrong_format;
1512 GST_DEBUG_OBJECT (jitterbuffer,
1513 "segment: %" GST_SEGMENT_FORMAT, &priv->segment);
1517 rtp_jitter_buffer_disable_buffering (priv->jbuf, TRUE);
1524 GST_DEBUG_OBJECT (jitterbuffer, "adding event");
1525 item = alloc_item (event, ITEM_TYPE_EVENT, -1, -1, -1, 0, -1);
1526 rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
1528 JBUF_SIGNAL_EVENT (priv);
1533 newseg_wrong_format:
1535 GST_DEBUG_OBJECT (jitterbuffer, "received non TIME newsegment");
1536 gst_event_unref (event);
1542 gst_rtp_jitter_buffer_sink_event (GstPad * pad, GstObject * parent,
1545 gboolean ret = TRUE;
1546 GstRtpJitterBuffer *jitterbuffer;
1547 GstRtpJitterBufferPrivate *priv;
1549 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1550 priv = jitterbuffer->priv;
1552 GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1554 switch (GST_EVENT_TYPE (event)) {
1555 case GST_EVENT_FLUSH_START:
1556 ret = gst_pad_push_event (priv->srcpad, event);
1557 gst_rtp_jitter_buffer_flush_start (jitterbuffer);
1558 /* wait for the loop to go into PAUSED */
1559 gst_pad_pause_task (priv->srcpad);
1561 case GST_EVENT_FLUSH_STOP:
1562 ret = gst_pad_push_event (priv->srcpad, event);
1564 gst_rtp_jitter_buffer_src_activate_mode (priv->srcpad, parent,
1565 GST_PAD_MODE_PUSH, TRUE);
1568 if (GST_EVENT_IS_SERIALIZED (event)) {
1569 /* serialized events go in the queue */
1571 if (priv->srcresult != GST_FLOW_OK) {
1572 /* Errors in sticky event pushing are no problem and ignored here
1573 * as they will cause more meaningful errors during data flow.
1574 * For EOS events, that are not followed by data flow, we still
1575 * return FALSE here though.
1577 if (!GST_EVENT_IS_STICKY (event) ||
1578 GST_EVENT_TYPE (event) == GST_EVENT_EOS)
1579 goto out_flow_error;
1581 /* refuse more events on EOS */
1584 ret = queue_event (jitterbuffer, event);
1587 /* non-serialized events are forwarded downstream immediately */
1588 ret = gst_pad_push_event (priv->srcpad, event);
1597 GST_DEBUG_OBJECT (jitterbuffer,
1598 "refusing event, we have a downstream flow error: %s",
1599 gst_flow_get_name (priv->srcresult));
1601 gst_event_unref (event);
1606 GST_DEBUG_OBJECT (jitterbuffer, "refusing event, we are EOS");
1608 gst_event_unref (event);
1614 gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad, GstObject * parent,
1617 gboolean ret = TRUE;
1618 GstRtpJitterBuffer *jitterbuffer;
1620 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1622 GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1624 switch (GST_EVENT_TYPE (event)) {
1625 case GST_EVENT_FLUSH_START:
1626 gst_event_unref (event);
1628 case GST_EVENT_FLUSH_STOP:
1629 gst_event_unref (event);
1632 ret = gst_pad_event_default (pad, parent, event);
1640 * Must be called with JBUF_LOCK held, will release the LOCK when emiting the
1641 * signal. The function returns GST_FLOW_ERROR when a parsing error happened and
1642 * GST_FLOW_FLUSHING when the element is shutting down. On success
1643 * GST_FLOW_OK is returned.
1645 static GstFlowReturn
1646 gst_rtp_jitter_buffer_get_clock_rate (GstRtpJitterBuffer * jitterbuffer,
1650 GValue args[2] = { {0}, {0} };
1654 g_value_init (&args[0], GST_TYPE_ELEMENT);
1655 g_value_set_object (&args[0], jitterbuffer);
1656 g_value_init (&args[1], G_TYPE_UINT);
1657 g_value_set_uint (&args[1], pt);
1659 g_value_init (&ret, GST_TYPE_CAPS);
1660 g_value_set_boxed (&ret, NULL);
1662 JBUF_UNLOCK (jitterbuffer->priv);
1663 g_signal_emitv (args, gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP], 0,
1665 JBUF_LOCK_CHECK (jitterbuffer->priv, out_flushing);
1667 g_value_unset (&args[0]);
1668 g_value_unset (&args[1]);
1669 caps = (GstCaps *) g_value_dup_boxed (&ret);
1670 g_value_unset (&ret);
1674 res = gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1675 gst_caps_unref (caps);
1677 if (G_UNLIKELY (!res))
1685 GST_DEBUG_OBJECT (jitterbuffer, "could not get caps");
1686 return GST_FLOW_ERROR;
1690 GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
1691 return GST_FLOW_FLUSHING;
1695 GST_DEBUG_OBJECT (jitterbuffer, "parse failed");
1696 return GST_FLOW_ERROR;
1700 /* call with jbuf lock held */
1702 check_buffering_percent (GstRtpJitterBuffer * jitterbuffer, gint percent)
1704 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1705 GstMessage *message = NULL;
1710 /* Post a buffering message */
1711 if (priv->last_percent != percent) {
1712 priv->last_percent = percent;
1714 gst_message_new_buffering (GST_OBJECT_CAST (jitterbuffer), percent);
1715 gst_message_set_buffering_stats (message, GST_BUFFERING_LIVE, -1, -1, -1);
1722 apply_offset (GstRtpJitterBuffer * jitterbuffer, GstClockTime timestamp)
1724 GstRtpJitterBufferPrivate *priv;
1726 priv = jitterbuffer->priv;
1728 if (timestamp == -1)
1731 /* apply the timestamp offset, this is used for inter stream sync */
1732 timestamp += priv->ts_offset;
1733 /* add the offset, this is used when buffering */
1734 timestamp += priv->out_offset;
1740 find_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type, guint16 seqnum)
1742 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1743 TimerData *timer = NULL;
1746 len = priv->timers->len;
1747 for (i = 0; i < len; i++) {
1748 TimerData *test = &g_array_index (priv->timers, TimerData, i);
1749 if (test->seqnum == seqnum && test->type == type) {
1758 unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer)
1760 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1762 if (priv->clock_id) {
1763 GST_DEBUG_OBJECT (jitterbuffer, "unschedule current timer");
1764 gst_clock_id_unschedule (priv->clock_id);
1765 priv->clock_id = NULL;
1770 get_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1772 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1773 GstClockTime test_timeout;
1775 if ((test_timeout = timer->timeout) == -1)
1778 if (timer->type != TIMER_TYPE_EXPECTED) {
1779 /* add our latency and offset to get output times. */
1780 test_timeout = apply_offset (jitterbuffer, test_timeout);
1781 test_timeout += priv->latency_ns;
1783 return test_timeout;
1787 recalculate_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1789 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1791 if (priv->clock_id) {
1792 GstClockTime timeout = get_timeout (jitterbuffer, timer);
1794 GST_DEBUG ("%" GST_TIME_FORMAT " <> %" GST_TIME_FORMAT,
1795 GST_TIME_ARGS (timeout), GST_TIME_ARGS (priv->timer_timeout));
1797 if (timeout == -1 || timeout < priv->timer_timeout)
1798 unschedule_current_timer (jitterbuffer);
1803 add_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
1804 guint16 seqnum, guint num, GstClockTime timeout, GstClockTime delay,
1805 GstClockTime duration)
1807 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1811 GST_DEBUG_OBJECT (jitterbuffer,
1812 "add timer %d for seqnum %d to %" GST_TIME_FORMAT ", delay %"
1813 GST_TIME_FORMAT, type, seqnum, GST_TIME_ARGS (timeout),
1814 GST_TIME_ARGS (delay));
1816 len = priv->timers->len;
1817 g_array_set_size (priv->timers, len + 1);
1818 timer = &g_array_index (priv->timers, TimerData, len);
1821 timer->seqnum = seqnum;
1823 timer->timeout = timeout + delay;
1824 timer->duration = duration;
1825 if (type == TIMER_TYPE_EXPECTED) {
1826 timer->rtx_base = timeout;
1827 timer->rtx_delay = delay;
1828 timer->rtx_retry = 0;
1830 timer->num_rtx_retry = 0;
1831 recalculate_timer (jitterbuffer, timer);
1832 JBUF_SIGNAL_TIMER (priv);
1838 reschedule_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
1839 guint16 seqnum, GstClockTime timeout, GstClockTime delay, gboolean reset)
1841 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1842 gboolean seqchange, timechange;
1845 seqchange = timer->seqnum != seqnum;
1846 timechange = timer->timeout != timeout;
1848 if (!seqchange && !timechange)
1851 oldseq = timer->seqnum;
1853 GST_DEBUG_OBJECT (jitterbuffer,
1854 "replace timer for seqnum %d->%d to %" GST_TIME_FORMAT,
1855 oldseq, seqnum, GST_TIME_ARGS (timeout + delay));
1857 timer->timeout = timeout + delay;
1858 timer->seqnum = seqnum;
1860 timer->rtx_base = timeout;
1861 timer->rtx_delay = delay;
1862 timer->rtx_retry = 0;
1865 timer->num_rtx_retry = 0;
1867 if (priv->clock_id) {
1868 /* we changed the seqnum and there is a timer currently waiting with this
1869 * seqnum, unschedule it */
1870 if (seqchange && priv->timer_seqnum == oldseq)
1871 unschedule_current_timer (jitterbuffer);
1872 /* we changed the time, check if it is earlier than what we are waiting
1873 * for and unschedule if so */
1874 else if (timechange)
1875 recalculate_timer (jitterbuffer, timer);
1880 set_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
1881 guint16 seqnum, GstClockTime timeout)
1885 /* find the seqnum timer */
1886 timer = find_timer (jitterbuffer, type, seqnum);
1887 if (timer == NULL) {
1888 timer = add_timer (jitterbuffer, type, seqnum, 0, timeout, 0, -1);
1890 reschedule_timer (jitterbuffer, timer, seqnum, timeout, 0, FALSE);
1896 remove_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1898 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1901 if (priv->clock_id && priv->timer_seqnum == timer->seqnum)
1902 unschedule_current_timer (jitterbuffer);
1905 GST_DEBUG_OBJECT (jitterbuffer, "removed index %d", idx);
1906 g_array_remove_index_fast (priv->timers, idx);
1911 remove_all_timers (GstRtpJitterBuffer * jitterbuffer)
1913 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1914 GST_DEBUG_OBJECT (jitterbuffer, "removed all timers");
1915 g_array_set_size (priv->timers, 0);
1916 unschedule_current_timer (jitterbuffer);
1919 /* get the extra delay to wait before sending RTX */
1921 get_rtx_delay (GstRtpJitterBufferPrivate * priv)
1925 if (priv->rtx_delay == -1) {
1926 if (priv->avg_jitter == 0 && priv->packet_spacing == 0) {
1927 delay = DEFAULT_AUTO_RTX_DELAY;
1929 /* jitter is in nanoseconds, maximum of 2x jitter and half the
1930 * packet spacing is a good margin */
1931 delay = MAX (priv->avg_jitter * 2, priv->packet_spacing / 2);
1934 delay = priv->rtx_delay * GST_MSECOND;
1936 if (priv->rtx_min_delay > 0)
1937 delay = MAX (delay, priv->rtx_min_delay * GST_MSECOND);
1942 /* we just received a packet with seqnum and dts.
1944 * First check for old seqnum that we are still expecting. If the gap with the
1945 * current seqnum is too big, unschedule the timeouts.
1947 * If we have a valid packet spacing estimate we can set a timer for when we
1948 * should receive the next packet.
1949 * If we don't have a valid estimate, we remove any timer we might have
1950 * had for this packet.
1953 update_timers (GstRtpJitterBuffer * jitterbuffer, guint16 seqnum,
1954 GstClockTime dts, gboolean do_next_seqnum)
1956 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1957 TimerData *timer = NULL;
1960 /* go through all timers and unschedule the ones with a large gap, also find
1961 * the timer for the seqnum */
1962 len = priv->timers->len;
1963 for (i = 0; i < len; i++) {
1964 TimerData *test = &g_array_index (priv->timers, TimerData, i);
1967 gap = gst_rtp_buffer_compare_seqnum (test->seqnum, seqnum);
1969 GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, #%d<->#%d gap %d", i,
1970 test->type, test->seqnum, seqnum, gap);
1973 GST_DEBUG ("found timer for current seqnum");
1974 /* the timer for the current seqnum */
1976 /* when no retransmission, we can stop now, we only need to find the
1977 * timer for the current seqnum */
1978 if (!priv->do_retransmission)
1980 } else if (gap > priv->rtx_delay_reorder) {
1981 /* max gap, we exceeded the max reorder distance and we don't expect the
1982 * missing packet to be this reordered */
1983 if (test->num_rtx_retry == 0 && test->type == TIMER_TYPE_EXPECTED)
1984 reschedule_timer (jitterbuffer, test, test->seqnum, -1, 0, FALSE);
1988 do_next_seqnum = do_next_seqnum && priv->packet_spacing > 0
1989 && priv->do_retransmission && priv->rtx_next_seqnum;
1991 if (timer && timer->type != TIMER_TYPE_DEADLINE) {
1992 if (timer->num_rtx_retry > 0) {
1993 GstClockTime rtx_last, delay;
1995 /* we scheduled a retry for this packet and now we have it */
1996 priv->num_rtx_success++;
1997 /* all the previous retry attempts failed */
1998 priv->num_rtx_failed += timer->num_rtx_retry - 1;
1999 /* number of retries before receiving the packet */
2000 if (priv->avg_rtx_num == 0.0)
2001 priv->avg_rtx_num = timer->num_rtx_retry;
2003 priv->avg_rtx_num = (timer->num_rtx_retry + 7 * priv->avg_rtx_num) / 8;
2004 /* calculate the delay between retransmission request and receiving this
2005 * packet, start with when we scheduled this timeout last */
2006 rtx_last = timer->rtx_last;
2007 if (dts != GST_CLOCK_TIME_NONE && dts > rtx_last) {
2008 /* we have a valid delay if this packet arrived after we scheduled the
2010 delay = dts - rtx_last;
2011 if (priv->avg_rtx_rtt == 0)
2012 priv->avg_rtx_rtt = delay;
2014 priv->avg_rtx_rtt = (delay + 7 * priv->avg_rtx_rtt) / 8;
2018 GST_LOG_OBJECT (jitterbuffer,
2019 "RTX success %" G_GUINT64_FORMAT ", failed %" G_GUINT64_FORMAT
2020 ", requests %" G_GUINT64_FORMAT ", dups %" G_GUINT64_FORMAT
2021 ", avg-num %g, delay %" GST_TIME_FORMAT ", avg-rtt %" GST_TIME_FORMAT,
2022 priv->num_rtx_success, priv->num_rtx_failed, priv->num_rtx_requests,
2023 priv->num_duplicates, priv->avg_rtx_num, GST_TIME_ARGS (delay),
2024 GST_TIME_ARGS (priv->avg_rtx_rtt));
2026 /* don't try to estimate the next seqnum because this is a retransmitted
2027 * packet and it probably did not arrive with the expected packet
2029 do_next_seqnum = FALSE;
2033 if (do_next_seqnum) {
2034 GstClockTime expected, delay;
2036 /* calculate expected arrival time of the next seqnum */
2037 expected = dts + priv->packet_spacing;
2039 delay = get_rtx_delay (priv);
2041 /* and update/install timer for next seqnum */
2043 reschedule_timer (jitterbuffer, timer, priv->next_in_seqnum, expected,
2046 add_timer (jitterbuffer, TIMER_TYPE_EXPECTED, priv->next_in_seqnum, 0,
2047 expected, delay, priv->packet_spacing);
2048 } else if (timer && timer->type != TIMER_TYPE_DEADLINE) {
2049 /* if we had a timer, remove it, we don't know when to expect the next
2051 remove_timer (jitterbuffer, timer);
2056 calculate_packet_spacing (GstRtpJitterBuffer * jitterbuffer, guint32 rtptime,
2059 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2061 /* we need consecutive seqnums with a different
2062 * rtptime to estimate the packet spacing. */
2063 if (priv->ips_rtptime != rtptime) {
2064 /* rtptime changed, check dts diff */
2065 if (priv->ips_dts != -1 && dts != -1 && dts > priv->ips_dts) {
2066 GstClockTime new_packet_spacing = dts - priv->ips_dts;
2067 GstClockTime old_packet_spacing = priv->packet_spacing;
2069 /* Biased towards bigger packet spacings to prevent
2070 * too many unneeded retransmission requests for next
2071 * packets that just arrive a little later than we would
2073 if (old_packet_spacing > new_packet_spacing)
2074 priv->packet_spacing =
2075 (new_packet_spacing + 3 * old_packet_spacing) / 4;
2076 else if (old_packet_spacing > 0)
2077 priv->packet_spacing =
2078 (3 * new_packet_spacing + old_packet_spacing) / 4;
2080 priv->packet_spacing = new_packet_spacing;
2082 GST_DEBUG_OBJECT (jitterbuffer,
2083 "new packet spacing %" GST_TIME_FORMAT
2084 " old packet spacing %" GST_TIME_FORMAT
2085 " combined to %" GST_TIME_FORMAT,
2086 GST_TIME_ARGS (new_packet_spacing),
2087 GST_TIME_ARGS (old_packet_spacing),
2088 GST_TIME_ARGS (priv->packet_spacing));
2090 priv->ips_rtptime = rtptime;
2091 priv->ips_dts = dts;
2096 calculate_expected (GstRtpJitterBuffer * jitterbuffer, guint32 expected,
2097 guint16 seqnum, GstClockTime dts, gint gap)
2099 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2100 GstClockTime total_duration, duration, expected_dts;
2102 guint lost_packets = 0;
2104 GST_DEBUG_OBJECT (jitterbuffer,
2105 "dts %" GST_TIME_FORMAT ", last %" GST_TIME_FORMAT,
2106 GST_TIME_ARGS (dts), GST_TIME_ARGS (priv->last_in_dts));
2108 /* the total duration spanned by the missing packets */
2109 if (dts >= priv->last_in_dts)
2110 total_duration = dts - priv->last_in_dts;
2114 /* interpolate between the current time and the last time based on
2115 * number of packets we are missing, this is the estimated duration
2116 * for the missing packet based on equidistant packet spacing. */
2117 duration = total_duration / (gap + 1);
2119 GST_DEBUG_OBJECT (jitterbuffer, "duration %" GST_TIME_FORMAT,
2120 GST_TIME_ARGS (duration));
2122 if (total_duration > priv->latency_ns) {
2123 GstClockTime gap_time;
2125 gap_time = total_duration - priv->latency_ns;
2128 lost_packets = gap_time / duration;
2129 gap_time = lost_packets * duration;
2134 /* too many lost packets, some of the missing packets are already
2135 * too late and we can generate lost packet events for them. */
2136 GST_DEBUG_OBJECT (jitterbuffer, "too many lost packets %" GST_TIME_FORMAT
2137 " > %" GST_TIME_FORMAT ", consider %u lost",
2138 GST_TIME_ARGS (total_duration), GST_TIME_ARGS (priv->latency_ns),
2141 /* this timer will fire immediately and the lost event will be pushed from
2142 * the timer thread */
2143 add_timer (jitterbuffer, TIMER_TYPE_LOST, expected, lost_packets,
2144 priv->last_in_dts + duration, 0, gap_time);
2146 expected += lost_packets;
2147 priv->last_in_dts += gap_time;
2150 expected_dts = priv->last_in_dts + (lost_packets + 1) * duration;
2152 if (priv->do_retransmission) {
2155 type = TIMER_TYPE_EXPECTED;
2156 /* if we had a timer for the first missing packet, update it. */
2157 if ((timer = find_timer (jitterbuffer, type, expected))) {
2158 GstClockTime timeout = timer->timeout;
2160 timer->duration = duration;
2161 if (timeout > (expected_dts + timer->rtx_retry)) {
2162 GstClockTime delay = timeout - expected_dts - timer->rtx_retry;
2163 reschedule_timer (jitterbuffer, timer, timer->seqnum, expected_dts,
2167 expected_dts += duration;
2170 type = TIMER_TYPE_LOST;
2173 while (gst_rtp_buffer_compare_seqnum (expected, seqnum) > 0) {
2174 add_timer (jitterbuffer, type, expected, 0, expected_dts, 0, duration);
2175 expected_dts += duration;
2181 calculate_jitter (GstRtpJitterBuffer * jitterbuffer, GstClockTime dts,
2185 GstClockTimeDiff dtsdiff, rtpdiffns, diff;
2186 GstRtpJitterBufferPrivate *priv;
2188 priv = jitterbuffer->priv;
2190 if (G_UNLIKELY (dts == GST_CLOCK_TIME_NONE) || priv->clock_rate <= 0)
2193 if (priv->last_dts != -1)
2194 dtsdiff = dts - priv->last_dts;
2198 if (priv->last_rtptime != -1)
2199 rtpdiff = rtptime - (guint32) priv->last_rtptime;
2203 priv->last_dts = dts;
2204 priv->last_rtptime = rtptime;
2208 gst_util_uint64_scale_int (rtpdiff, GST_SECOND, priv->clock_rate);
2211 -gst_util_uint64_scale_int (-rtpdiff, GST_SECOND, priv->clock_rate);
2213 diff = ABS (dtsdiff - rtpdiffns);
2215 /* jitter is stored in nanoseconds */
2216 priv->avg_jitter = (diff + (15 * priv->avg_jitter)) >> 4;
2218 GST_LOG_OBJECT (jitterbuffer,
2219 "dtsdiff %" GST_TIME_FORMAT " rtptime %" GST_TIME_FORMAT
2220 ", clock-rate %d, diff %" GST_TIME_FORMAT ", jitter: %" GST_TIME_FORMAT,
2221 GST_TIME_ARGS (dtsdiff), GST_TIME_ARGS (rtpdiffns), priv->clock_rate,
2222 GST_TIME_ARGS (diff), GST_TIME_ARGS (priv->avg_jitter));
2229 GST_DEBUG_OBJECT (jitterbuffer,
2230 "no dts or no clock-rate, can't calculate jitter");
2236 compare_buffer_seqnum (GstBuffer * a, GstBuffer * b, gpointer user_data)
2238 GstRTPBuffer rtp_a = GST_RTP_BUFFER_INIT;
2239 GstRTPBuffer rtp_b = GST_RTP_BUFFER_INIT;
2242 gst_rtp_buffer_map (a, GST_MAP_READ, &rtp_a);
2243 seq_a = gst_rtp_buffer_get_seq (&rtp_a);
2244 gst_rtp_buffer_unmap (&rtp_a);
2246 gst_rtp_buffer_map (b, GST_MAP_READ, &rtp_b);
2247 seq_b = gst_rtp_buffer_get_seq (&rtp_b);
2248 gst_rtp_buffer_unmap (&rtp_b);
2250 return gst_rtp_buffer_compare_seqnum (seq_b, seq_a);
2254 handle_big_gap_buffer (GstRtpJitterBuffer * jitterbuffer, gboolean future,
2255 GstBuffer * buffer, guint8 pt, guint16 seqnum, gint gap)
2257 GstRtpJitterBufferPrivate *priv;
2258 guint gap_packets_length;
2259 gboolean reset = FALSE;
2261 priv = jitterbuffer->priv;
2263 if ((gap_packets_length = g_queue_get_length (&priv->gap_packets)) > 0) {
2265 guint32 prev_gap_seq = -1;
2266 gboolean all_consecutive = TRUE;
2268 g_queue_insert_sorted (&priv->gap_packets, buffer,
2269 (GCompareDataFunc) compare_buffer_seqnum, NULL);
2271 for (l = priv->gap_packets.head; l; l = l->next) {
2272 GstBuffer *gap_buffer = l->data;
2273 GstRTPBuffer gap_rtp = GST_RTP_BUFFER_INIT;
2276 gst_rtp_buffer_map (gap_buffer, GST_MAP_READ, &gap_rtp);
2278 all_consecutive = (gst_rtp_buffer_get_payload_type (&gap_rtp) == pt);
2280 gap_seq = gst_rtp_buffer_get_seq (&gap_rtp);
2281 if (prev_gap_seq == -1)
2282 prev_gap_seq = gap_seq;
2283 else if (gst_rtp_buffer_compare_seqnum (gap_seq, prev_gap_seq) != -1)
2284 all_consecutive = FALSE;
2286 prev_gap_seq = gap_seq;
2288 gst_rtp_buffer_unmap (&gap_rtp);
2289 if (!all_consecutive)
2293 if (all_consecutive && gap_packets_length > 3) {
2294 GST_DEBUG_OBJECT (jitterbuffer,
2295 "buffer too %s %d < %d, got 5 consecutive ones - reset",
2296 (future ? "new" : "old"), gap,
2297 (future ? RTP_MAX_DROPOUT : -RTP_MAX_MISORDER));
2299 } else if (!all_consecutive) {
2300 g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
2301 g_queue_clear (&priv->gap_packets);
2302 GST_DEBUG_OBJECT (jitterbuffer,
2303 "buffer too %s %d < %d, got no 5 consecutive ones - dropping",
2304 (future ? "new" : "old"), gap,
2305 (future ? RTP_MAX_DROPOUT : -RTP_MAX_MISORDER));
2308 GST_DEBUG_OBJECT (jitterbuffer,
2309 "buffer too %s %d < %d, got %u consecutive ones - waiting",
2310 (future ? "new" : "old"), gap,
2311 (future ? RTP_MAX_DROPOUT : -RTP_MAX_MISORDER),
2312 gap_packets_length + 1);
2316 GST_DEBUG_OBJECT (jitterbuffer,
2317 "buffer too %s %d < %d, first one - waiting", (future ? "new" : "old"),
2318 gap, -RTP_MAX_MISORDER);
2319 g_queue_push_tail (&priv->gap_packets, buffer);
2326 static GstFlowReturn
2327 gst_rtp_jitter_buffer_chain (GstPad * pad, GstObject * parent,
2330 GstRtpJitterBuffer *jitterbuffer;
2331 GstRtpJitterBufferPrivate *priv;
2333 guint32 expected, rtptime;
2334 GstFlowReturn ret = GST_FLOW_OK;
2335 GstClockTime dts, pts;
2340 GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
2341 gboolean do_next_seqnum = FALSE;
2342 RTPJitterBufferItem *item;
2343 GstMessage *msg = NULL;
2345 jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
2347 priv = jitterbuffer->priv;
2349 if (G_UNLIKELY (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)))
2350 goto invalid_buffer;
2352 pt = gst_rtp_buffer_get_payload_type (&rtp);
2353 seqnum = gst_rtp_buffer_get_seq (&rtp);
2354 rtptime = gst_rtp_buffer_get_timestamp (&rtp);
2355 gst_rtp_buffer_unmap (&rtp);
2357 /* make sure we have PTS and DTS set */
2358 pts = GST_BUFFER_PTS (buffer);
2359 dts = GST_BUFFER_DTS (buffer);
2365 /* take the DTS of the buffer. This is the time when the packet was
2366 * received and is used to calculate jitter and clock skew. We will adjust
2367 * this DTS with the smoothed value after processing it in the
2368 * jitterbuffer and assign it as the PTS. */
2369 /* bring to running time */
2370 dts = gst_segment_to_running_time (&priv->segment, GST_FORMAT_TIME, dts);
2372 GST_DEBUG_OBJECT (jitterbuffer,
2373 "Received packet #%d at time %" GST_TIME_FORMAT ", discont %d", seqnum,
2374 GST_TIME_ARGS (dts), GST_BUFFER_IS_DISCONT (buffer));
2376 JBUF_LOCK_CHECK (priv, out_flushing);
2378 if (G_UNLIKELY (priv->last_pt != pt)) {
2381 GST_DEBUG_OBJECT (jitterbuffer, "pt changed from %u to %u", priv->last_pt,
2385 /* reset clock-rate so that we get a new one */
2386 priv->clock_rate = -1;
2388 /* Try to get the clock-rate from the caps first if we can. If there are no
2389 * caps we must fire the signal to get the clock-rate. */
2390 if ((caps = gst_pad_get_current_caps (pad))) {
2391 gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
2392 gst_caps_unref (caps);
2396 if (G_UNLIKELY (priv->clock_rate == -1)) {
2397 /* no clock rate given on the caps, try to get one with the signal */
2398 if (gst_rtp_jitter_buffer_get_clock_rate (jitterbuffer,
2399 pt) == GST_FLOW_FLUSHING)
2402 if (G_UNLIKELY (priv->clock_rate == -1))
2406 /* don't accept more data on EOS */
2407 if (G_UNLIKELY (priv->eos))
2410 calculate_jitter (jitterbuffer, dts, rtptime);
2412 if (priv->seqnum_base != -1) {
2415 gap = gst_rtp_buffer_compare_seqnum (priv->seqnum_base, seqnum);
2418 GST_DEBUG_OBJECT (jitterbuffer,
2419 "packet seqnum #%d before seqnum-base #%d", seqnum,
2421 gst_buffer_unref (buffer);
2424 } else if (gap > 16384) {
2425 /* From now on don't compare against the seqnum base anymore as
2426 * at some point in the future we will wrap around and also that
2427 * much reordering is very unlikely */
2428 priv->seqnum_base = -1;
2432 expected = priv->next_in_seqnum;
2434 /* now check against our expected seqnum */
2435 if (G_LIKELY (expected != -1)) {
2438 /* now calculate gap */
2439 gap = gst_rtp_buffer_compare_seqnum (expected, seqnum);
2441 GST_DEBUG_OBJECT (jitterbuffer, "expected #%d, got #%d, gap of %d",
2442 expected, seqnum, gap);
2444 if (G_LIKELY (gap == 0)) {
2445 /* packet is expected */
2446 calculate_packet_spacing (jitterbuffer, rtptime, dts);
2447 do_next_seqnum = TRUE;
2449 gboolean reset = FALSE;
2451 if (!GST_CLOCK_TIME_IS_VALID (dts)) {
2452 /* We would run into calculations with GST_CLOCK_TIME_NONE below
2453 * and can't compensate for anything without DTS on RTP packets
2455 goto gap_but_no_dts;
2456 } else if (gap < 0) {
2457 /* we received an old packet */
2458 if (G_UNLIKELY (gap != -1 && gap < -RTP_MAX_MISORDER)) {
2460 handle_big_gap_buffer (jitterbuffer, FALSE, buffer, pt, seqnum,
2464 GST_DEBUG_OBJECT (jitterbuffer, "old packet received");
2467 /* new packet, we are missing some packets */
2468 if (G_UNLIKELY (gap >= RTP_MAX_DROPOUT)) {
2470 handle_big_gap_buffer (jitterbuffer, TRUE, buffer, pt, seqnum,
2474 GST_DEBUG_OBJECT (jitterbuffer, "%d missing packets", gap);
2475 /* fill in the gap with EXPECTED timers */
2476 calculate_expected (jitterbuffer, expected, seqnum, dts, gap);
2478 do_next_seqnum = TRUE;
2481 if (G_UNLIKELY (reset)) {
2482 GList *events = NULL, *l;
2485 GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
2486 rtp_jitter_buffer_flush (priv->jbuf,
2487 (GFunc) free_item_and_retain_events, &events);
2488 rtp_jitter_buffer_reset_skew (priv->jbuf);
2489 remove_all_timers (jitterbuffer);
2490 priv->discont = TRUE;
2491 priv->last_popped_seqnum = -1;
2492 priv->next_seqnum = seqnum;
2494 priv->last_in_seqnum = -1;
2495 priv->last_in_dts = -1;
2496 priv->next_in_seqnum = -1;
2498 /* Insert all sticky events again in order, otherwise we would
2499 * potentially loose STREAM_START, CAPS or SEGMENT events
2501 events = g_list_reverse (events);
2502 for (l = events; l; l = l->next) {
2503 RTPJitterBufferItem *item;
2505 item = alloc_item (l->data, ITEM_TYPE_EVENT, -1, -1, -1, 0, -1);
2506 rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
2508 g_list_free (events);
2510 JBUF_SIGNAL_EVENT (priv);
2512 /* reset spacing estimation when gap */
2513 priv->ips_rtptime = -1;
2514 priv->ips_dts = GST_CLOCK_TIME_NONE;
2516 buffers = g_list_copy (priv->gap_packets.head);
2517 g_queue_clear (&priv->gap_packets);
2519 priv->ips_rtptime = -1;
2520 priv->ips_dts = GST_CLOCK_TIME_NONE;
2521 JBUF_UNLOCK (jitterbuffer->priv);
2523 for (l = buffers; l; l = l->next) {
2524 ret = gst_rtp_jitter_buffer_chain (pad, parent, l->data);
2526 if (ret != GST_FLOW_OK)
2529 for (; l; l = l->next)
2530 gst_buffer_unref (l->data);
2531 g_list_free (buffers);
2535 /* reset spacing estimation when gap */
2536 priv->ips_rtptime = -1;
2537 priv->ips_dts = GST_CLOCK_TIME_NONE;
2540 GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
2541 /* we don't know what the next_in_seqnum should be, wait for the last
2542 * possible moment to push this buffer, maybe we get an earlier seqnum
2544 set_timer (jitterbuffer, TIMER_TYPE_DEADLINE, seqnum, dts);
2545 do_next_seqnum = TRUE;
2546 /* take rtptime and dts to calculate packet spacing */
2547 priv->ips_rtptime = rtptime;
2548 priv->ips_dts = dts;
2551 /* We had no huge gap, let's drop all the gap packets */
2552 if (buffer != NULL) {
2553 GST_DEBUG_OBJECT (jitterbuffer, "Clearing gap packets");
2554 g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
2555 g_queue_clear (&priv->gap_packets);
2557 GST_DEBUG_OBJECT (jitterbuffer,
2558 "Had big gap, waiting for more consecutive packets");
2559 JBUF_UNLOCK (jitterbuffer->priv);
2563 if (do_next_seqnum) {
2564 priv->last_in_seqnum = seqnum;
2565 priv->last_in_dts = dts;
2566 priv->next_in_seqnum = (seqnum + 1) & 0xffff;
2569 /* let's check if this buffer is too late, we can only accept packets with
2570 * bigger seqnum than the one we last pushed. */
2571 if (G_LIKELY (priv->last_popped_seqnum != -1)) {
2574 gap = gst_rtp_buffer_compare_seqnum (priv->last_popped_seqnum, seqnum);
2576 /* priv->last_popped_seqnum >= seqnum, we're too late. */
2577 if (G_UNLIKELY (gap <= 0))
2581 /* let's drop oldest packet if the queue is already full and drop-on-latency
2582 * is set. We can only do this when there actually is a latency. When no
2583 * latency is set, we just pump it in the queue and let the other end push it
2584 * out as fast as possible. */
2585 if (priv->latency_ms && priv->drop_on_latency) {
2587 gst_util_uint64_scale_int (priv->latency_ms, priv->clock_rate, 1000);
2589 if (G_UNLIKELY (rtp_jitter_buffer_get_ts_diff (priv->jbuf) >= latency_ts)) {
2590 RTPJitterBufferItem *old_item;
2592 old_item = rtp_jitter_buffer_peek (priv->jbuf);
2594 if (IS_DROPABLE (old_item)) {
2595 old_item = rtp_jitter_buffer_pop (priv->jbuf, &percent);
2596 GST_DEBUG_OBJECT (jitterbuffer, "Queue full, dropping old packet %p",
2598 priv->next_seqnum = (old_item->seqnum + 1) & 0xffff;
2599 free_item (old_item);
2601 /* we might have removed some head buffers, signal the pushing thread to
2602 * see if it can push now */
2603 JBUF_SIGNAL_EVENT (priv);
2607 item = alloc_item (buffer, ITEM_TYPE_BUFFER, dts, pts, seqnum, 1, rtptime);
2609 /* now insert the packet into the queue in sorted order. This function returns
2610 * FALSE if a packet with the same seqnum was already in the queue, meaning we
2611 * have a duplicate. */
2612 if (G_UNLIKELY (!rtp_jitter_buffer_insert (priv->jbuf, item,
2617 update_timers (jitterbuffer, seqnum, dts, do_next_seqnum);
2619 /* we had an unhandled SR, handle it now */
2621 do_handle_sync (jitterbuffer);
2623 if (G_UNLIKELY (head)) {
2624 /* signal addition of new buffer when the _loop is waiting. */
2625 if (G_LIKELY (priv->active))
2626 JBUF_SIGNAL_EVENT (priv);
2628 /* let's unschedule and unblock any waiting buffers. We only want to do this
2629 * when the head buffer changed */
2630 if (G_UNLIKELY (priv->clock_id)) {
2631 GST_DEBUG_OBJECT (jitterbuffer, "Unscheduling waiting new buffer");
2632 unschedule_current_timer (jitterbuffer);
2636 GST_DEBUG_OBJECT (jitterbuffer,
2637 "Pushed packet #%d, now %d packets, head: %d, " "percent %d", seqnum,
2638 rtp_jitter_buffer_num_packets (priv->jbuf), head, percent);
2640 msg = check_buffering_percent (jitterbuffer, percent);
2646 gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), msg);
2653 /* this is not fatal but should be filtered earlier */
2654 GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
2655 ("Received invalid RTP payload, dropping"));
2656 gst_buffer_unref (buffer);
2661 GST_WARNING_OBJECT (jitterbuffer,
2662 "No clock-rate in caps!, dropping buffer");
2663 gst_buffer_unref (buffer);
2668 ret = priv->srcresult;
2669 GST_DEBUG_OBJECT (jitterbuffer, "flushing %s", gst_flow_get_name (ret));
2670 gst_buffer_unref (buffer);
2676 GST_WARNING_OBJECT (jitterbuffer, "we are EOS, refusing buffer");
2677 gst_buffer_unref (buffer);
2682 GST_WARNING_OBJECT (jitterbuffer, "Packet #%d too late as #%d was already"
2683 " popped, dropping", seqnum, priv->last_popped_seqnum);
2685 gst_buffer_unref (buffer);
2690 GST_WARNING_OBJECT (jitterbuffer, "Duplicate packet #%d detected, dropping",
2692 priv->num_duplicates++;
2698 /* this is fatal as we can't compensate for gaps without DTS */
2699 GST_ELEMENT_ERROR (jitterbuffer, STREAM, DECODE, (NULL),
2700 ("Received packet without DTS after a gap"));
2701 gst_buffer_unref (buffer);
2702 ret = GST_FLOW_ERROR;
2708 compute_elapsed (GstRtpJitterBuffer * jitterbuffer, RTPJitterBufferItem * item)
2710 guint64 ext_time, elapsed;
2712 GstRtpJitterBufferPrivate *priv;
2714 priv = jitterbuffer->priv;
2715 rtp_time = item->rtptime;
2717 GST_LOG_OBJECT (jitterbuffer, "rtp %" G_GUINT32_FORMAT ", ext %"
2718 G_GUINT64_FORMAT, rtp_time, priv->ext_timestamp);
2720 ext_time = priv->ext_timestamp;
2721 ext_time = gst_rtp_buffer_ext_timestamp (&ext_time, rtp_time);
2722 if (ext_time < priv->ext_timestamp) {
2723 ext_time = priv->ext_timestamp;
2725 priv->ext_timestamp = ext_time;
2728 if (ext_time > priv->clock_base)
2729 elapsed = ext_time - priv->clock_base;
2733 elapsed = gst_util_uint64_scale_int (elapsed, GST_SECOND, priv->clock_rate);
2738 update_estimated_eos (GstRtpJitterBuffer * jitterbuffer,
2739 RTPJitterBufferItem * item)
2741 guint64 total, elapsed, left, estimated;
2742 GstClockTime out_time;
2743 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2745 if (priv->npt_stop == -1 || priv->ext_timestamp == -1
2746 || priv->clock_base == -1 || priv->clock_rate <= 0)
2749 /* compute the elapsed time */
2750 elapsed = compute_elapsed (jitterbuffer, item);
2752 /* do nothing if elapsed time doesn't increment */
2753 if (priv->last_elapsed && elapsed <= priv->last_elapsed)
2756 priv->last_elapsed = elapsed;
2758 /* this is the total time we need to play */
2759 total = priv->npt_stop - priv->npt_start;
2760 GST_LOG_OBJECT (jitterbuffer, "total %" GST_TIME_FORMAT,
2761 GST_TIME_ARGS (total));
2763 /* this is how much time there is left */
2764 if (total > elapsed)
2765 left = total - elapsed;
2769 /* if we have less time left that the size of the buffer, we will not
2770 * be able to keep it filled, disabled buffering then */
2771 if (left < rtp_jitter_buffer_get_delay (priv->jbuf)) {
2772 GST_DEBUG_OBJECT (jitterbuffer, "left %" GST_TIME_FORMAT
2773 ", disable buffering close to EOS", GST_TIME_ARGS (left));
2774 rtp_jitter_buffer_disable_buffering (priv->jbuf, TRUE);
2777 /* this is the current time as running-time */
2778 out_time = item->dts;
2781 estimated = gst_util_uint64_scale (out_time, total, elapsed);
2783 /* if there is almost nothing left,
2784 * we may never advance enough to end up in the above case */
2785 if (total < GST_SECOND)
2786 estimated = GST_SECOND;
2790 GST_LOG_OBJECT (jitterbuffer, "elapsed %" GST_TIME_FORMAT ", estimated %"
2791 GST_TIME_FORMAT, GST_TIME_ARGS (elapsed), GST_TIME_ARGS (estimated));
2793 if (estimated != -1 && priv->estimated_eos != estimated) {
2794 set_timer (jitterbuffer, TIMER_TYPE_EOS, -1, estimated);
2795 priv->estimated_eos = estimated;
2799 /* take a buffer from the queue and push it */
2800 static GstFlowReturn
2801 pop_and_push_next (GstRtpJitterBuffer * jitterbuffer, guint seqnum)
2803 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2804 GstFlowReturn result = GST_FLOW_OK;
2805 RTPJitterBufferItem *item;
2806 GstBuffer *outbuf = NULL;
2807 GstEvent *outevent = NULL;
2808 GstQuery *outquery = NULL;
2809 GstClockTime dts, pts;
2811 gboolean do_push = TRUE;
2815 /* when we get here we are ready to pop and push the buffer */
2816 item = rtp_jitter_buffer_pop (priv->jbuf, &percent);
2820 case ITEM_TYPE_BUFFER:
2822 /* we need to make writable to change the flags and timestamps */
2823 outbuf = gst_buffer_make_writable (item->data);
2825 if (G_UNLIKELY (priv->discont)) {
2826 /* set DISCONT flag when we missed a packet. We pushed the buffer writable
2827 * into the jitterbuffer so we can modify now. */
2828 GST_DEBUG_OBJECT (jitterbuffer, "mark output buffer discont");
2829 GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
2830 priv->discont = FALSE;
2832 if (G_UNLIKELY (priv->ts_discont)) {
2833 GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_RESYNC);
2834 priv->ts_discont = FALSE;
2838 gst_segment_to_position (&priv->segment, GST_FORMAT_TIME, item->dts);
2840 gst_segment_to_position (&priv->segment, GST_FORMAT_TIME, item->pts);
2842 /* apply timestamp with offset to buffer now */
2843 GST_BUFFER_DTS (outbuf) = apply_offset (jitterbuffer, dts);
2844 GST_BUFFER_PTS (outbuf) = apply_offset (jitterbuffer, pts);
2846 /* update the elapsed time when we need to check against the npt stop time. */
2847 update_estimated_eos (jitterbuffer, item);
2849 priv->last_out_time = GST_BUFFER_PTS (outbuf);
2851 case ITEM_TYPE_LOST:
2852 priv->discont = TRUE;
2856 case ITEM_TYPE_EVENT:
2857 outevent = item->data;
2859 case ITEM_TYPE_QUERY:
2860 outquery = item->data;
2864 /* now we are ready to push the buffer. Save the seqnum and release the lock
2865 * so the other end can push stuff in the queue again. */
2867 priv->last_popped_seqnum = seqnum;
2868 priv->next_seqnum = (seqnum + item->count) & 0xffff;
2870 msg = check_buffering_percent (jitterbuffer, percent);
2877 gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), msg);
2880 case ITEM_TYPE_BUFFER:
2882 GST_DEBUG_OBJECT (jitterbuffer,
2883 "Pushing buffer %d, dts %" GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT,
2884 seqnum, GST_TIME_ARGS (GST_BUFFER_DTS (outbuf)),
2885 GST_TIME_ARGS (GST_BUFFER_PTS (outbuf)));
2886 result = gst_pad_push (priv->srcpad, outbuf);
2888 JBUF_LOCK_CHECK (priv, out_flushing);
2890 case ITEM_TYPE_LOST:
2891 case ITEM_TYPE_EVENT:
2892 /* We got not enough consecutive packets with a huge gap, we can
2893 * as well just drop them here now on EOS */
2894 if (GST_EVENT_TYPE (outevent) == GST_EVENT_EOS) {
2895 GST_DEBUG_OBJECT (jitterbuffer, "Clearing gap packets on EOS");
2896 g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
2897 g_queue_clear (&priv->gap_packets);
2900 GST_DEBUG_OBJECT (jitterbuffer, "%sPushing event %" GST_PTR_FORMAT
2901 ", seqnum %d", do_push ? "" : "NOT ", outevent, seqnum);
2904 gst_pad_push_event (priv->srcpad, outevent);
2906 gst_event_unref (outevent);
2908 result = GST_FLOW_OK;
2910 JBUF_LOCK_CHECK (priv, out_flushing);
2912 case ITEM_TYPE_QUERY:
2916 res = gst_pad_peer_query (priv->srcpad, outquery);
2918 JBUF_LOCK_CHECK (priv, out_flushing);
2919 result = GST_FLOW_OK;
2920 GST_LOG_OBJECT (jitterbuffer, "did query %p, return %d", outquery, res);
2921 JBUF_SIGNAL_QUERY (priv, res);
2930 return priv->srcresult;
2934 #define GST_FLOW_WAIT GST_FLOW_CUSTOM_SUCCESS
2936 /* Peek a buffer and compare the seqnum to the expected seqnum.
2937 * If all is fine, the buffer is pushed.
2938 * If something is wrong, we wait for some event
2940 static GstFlowReturn
2941 handle_next_buffer (GstRtpJitterBuffer * jitterbuffer)
2943 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2944 GstFlowReturn result = GST_FLOW_OK;
2945 RTPJitterBufferItem *item;
2947 guint32 next_seqnum;
2950 /* only push buffers when PLAYING and active and not buffering */
2951 if (priv->blocked || !priv->active ||
2952 rtp_jitter_buffer_is_buffering (priv->jbuf))
2953 return GST_FLOW_WAIT;
2956 /* peek a buffer, we're just looking at the sequence number.
2957 * If all is fine, we'll pop and push it. If the sequence number is wrong we
2958 * wait for a timeout or something to change.
2959 * The peeked buffer is valid for as long as we hold the jitterbuffer lock. */
2960 item = rtp_jitter_buffer_peek (priv->jbuf);
2964 /* get the seqnum and the next expected seqnum */
2965 seqnum = item->seqnum;
2969 next_seqnum = priv->next_seqnum;
2971 /* get the gap between this and the previous packet. If we don't know the
2972 * previous packet seqnum assume no gap. */
2973 if (G_UNLIKELY (next_seqnum == -1)) {
2974 GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
2975 /* we don't know what the next_seqnum should be, the chain function should
2976 * have scheduled a DEADLINE timer that will increment next_seqnum when it
2977 * fires, so wait for that */
2978 result = GST_FLOW_WAIT;
2980 /* else calculate GAP */
2981 gap = gst_rtp_buffer_compare_seqnum (next_seqnum, seqnum);
2983 if (G_LIKELY (gap == 0)) {
2985 /* no missing packet, pop and push */
2986 result = pop_and_push_next (jitterbuffer, seqnum);
2987 } else if (G_UNLIKELY (gap < 0)) {
2988 RTPJitterBufferItem *item;
2989 /* if we have a packet that we already pushed or considered dropped, pop it
2990 * off and get the next packet */
2991 GST_DEBUG_OBJECT (jitterbuffer, "Old packet #%d, next #%d dropping",
2992 seqnum, next_seqnum);
2993 item = rtp_jitter_buffer_pop (priv->jbuf, NULL);
2997 /* the chain function has scheduled timers to request retransmission or
2998 * when to consider the packet lost, wait for that */
2999 GST_DEBUG_OBJECT (jitterbuffer,
3000 "Sequence number GAP detected: expected %d instead of %d (%d missing)",
3001 next_seqnum, seqnum, gap);
3002 result = GST_FLOW_WAIT;
3009 GST_DEBUG_OBJECT (jitterbuffer, "no buffer, going to wait");
3011 result = GST_FLOW_EOS;
3013 result = GST_FLOW_WAIT;
3019 get_rtx_retry_timeout (GstRtpJitterBufferPrivate * priv)
3021 GstClockTime rtx_retry_timeout;
3022 GstClockTime rtx_min_retry_timeout;
3024 if (priv->rtx_retry_timeout == -1) {
3025 if (priv->avg_rtx_rtt == 0)
3026 rtx_retry_timeout = DEFAULT_AUTO_RTX_TIMEOUT;
3028 /* we want to ask for a retransmission after we waited for a
3029 * complete RTT and the additional jitter */
3030 rtx_retry_timeout = priv->avg_rtx_rtt + priv->avg_jitter * 2;
3032 rtx_retry_timeout = priv->rtx_retry_timeout * GST_MSECOND;
3034 /* make sure we don't retry too often. On very low latency networks,
3035 * the RTT and jitter can be very low. */
3036 if (priv->rtx_min_retry_timeout == -1) {
3037 rtx_min_retry_timeout = priv->packet_spacing;
3039 rtx_min_retry_timeout = priv->rtx_min_retry_timeout * GST_MSECOND;
3041 rtx_retry_timeout = MAX (rtx_retry_timeout, rtx_min_retry_timeout);
3043 return rtx_retry_timeout;
3047 get_rtx_retry_period (GstRtpJitterBufferPrivate * priv,
3048 GstClockTime rtx_retry_timeout)
3050 GstClockTime rtx_retry_period;
3052 if (priv->rtx_retry_period == -1) {
3053 /* we retry up to the configured jitterbuffer size but leaving some
3054 * room for the retransmission to arrive in time */
3055 if (rtx_retry_timeout > priv->latency_ns) {
3056 rtx_retry_period = 0;
3058 rtx_retry_period = priv->latency_ns - rtx_retry_timeout;
3061 rtx_retry_period = priv->rtx_retry_period * GST_MSECOND;
3063 return rtx_retry_period;
3066 /* the timeout for when we expected a packet expired */
3068 do_expected_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3071 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3073 guint delay, delay_ms, avg_rtx_rtt_ms;
3074 guint rtx_retry_timeout_ms, rtx_retry_period_ms;
3075 GstClockTime rtx_retry_period;
3076 GstClockTime rtx_retry_timeout;
3079 GST_DEBUG_OBJECT (jitterbuffer, "expected %d didn't arrive, now %"
3080 GST_TIME_FORMAT, timer->seqnum, GST_TIME_ARGS (now));
3082 rtx_retry_timeout = get_rtx_retry_timeout (priv);
3083 rtx_retry_period = get_rtx_retry_period (priv, rtx_retry_timeout);
3085 GST_DEBUG_OBJECT (jitterbuffer, "timeout %" GST_TIME_FORMAT ", period %"
3086 GST_TIME_FORMAT, GST_TIME_ARGS (rtx_retry_timeout),
3087 GST_TIME_ARGS (rtx_retry_period));
3089 delay = timer->rtx_delay + timer->rtx_retry;
3091 delay_ms = GST_TIME_AS_MSECONDS (delay);
3092 rtx_retry_timeout_ms = GST_TIME_AS_MSECONDS (rtx_retry_timeout);
3093 rtx_retry_period_ms = GST_TIME_AS_MSECONDS (rtx_retry_period);
3094 avg_rtx_rtt_ms = GST_TIME_AS_MSECONDS (priv->avg_rtx_rtt);
3096 event = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
3097 gst_structure_new ("GstRTPRetransmissionRequest",
3098 "seqnum", G_TYPE_UINT, (guint) timer->seqnum,
3099 "running-time", G_TYPE_UINT64, timer->rtx_base,
3100 "delay", G_TYPE_UINT, delay_ms,
3101 "retry", G_TYPE_UINT, timer->num_rtx_retry,
3102 "frequency", G_TYPE_UINT, rtx_retry_timeout_ms,
3103 "period", G_TYPE_UINT, rtx_retry_period_ms,
3104 "deadline", G_TYPE_UINT, priv->latency_ms,
3105 "packet-spacing", G_TYPE_UINT64, priv->packet_spacing,
3106 "avg-rtt", G_TYPE_UINT, avg_rtx_rtt_ms, NULL));
3108 priv->num_rtx_requests++;
3109 timer->num_rtx_retry++;
3111 GST_OBJECT_LOCK (jitterbuffer);
3112 if ((clock = GST_ELEMENT_CLOCK (jitterbuffer))) {
3113 timer->rtx_last = gst_clock_get_time (clock);
3114 timer->rtx_last -= GST_ELEMENT_CAST (jitterbuffer)->base_time;
3116 timer->rtx_last = now;
3118 GST_OBJECT_UNLOCK (jitterbuffer);
3120 /* calculate the timeout for the next retransmission attempt */
3121 timer->rtx_retry += rtx_retry_timeout;
3122 GST_DEBUG_OBJECT (jitterbuffer, "base %" GST_TIME_FORMAT ", delay %"
3123 GST_TIME_FORMAT ", retry %" GST_TIME_FORMAT ", num_retry %u",
3124 GST_TIME_ARGS (timer->rtx_base), GST_TIME_ARGS (timer->rtx_delay),
3125 GST_TIME_ARGS (timer->rtx_retry), timer->num_rtx_retry);
3126 if ((priv->rtx_max_retries != -1
3127 && timer->num_rtx_retry >= priv->rtx_max_retries)
3128 || (timer->rtx_retry + timer->rtx_delay > rtx_retry_period)) {
3129 GST_DEBUG_OBJECT (jitterbuffer, "reschedule as LOST timer");
3130 /* too many retransmission request, we now convert the timer
3131 * to a lost timer, leave the num_rtx_retry as it is for stats */
3132 timer->type = TIMER_TYPE_LOST;
3133 timer->rtx_delay = 0;
3134 timer->rtx_retry = 0;
3136 reschedule_timer (jitterbuffer, timer, timer->seqnum,
3137 timer->rtx_base + timer->rtx_retry, timer->rtx_delay, FALSE);
3140 gst_pad_push_event (priv->sinkpad, event);
3146 /* a packet is lost */
3148 do_lost_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3151 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3152 GstClockTime duration, timestamp;
3153 guint seqnum, lost_packets, num_rtx_retry, next_in_seqnum;
3154 gboolean late, head;
3156 RTPJitterBufferItem *item;
3158 seqnum = timer->seqnum;
3159 timestamp = apply_offset (jitterbuffer, timer->timeout);
3160 duration = timer->duration;
3161 if (duration == GST_CLOCK_TIME_NONE && priv->packet_spacing > 0)
3162 duration = priv->packet_spacing;
3163 lost_packets = MAX (timer->num, 1);
3164 late = timer->num > 0;
3165 num_rtx_retry = timer->num_rtx_retry;
3167 /* we had a gap and thus we lost some packets. Create an event for this. */
3168 if (lost_packets > 1)
3169 GST_DEBUG_OBJECT (jitterbuffer, "Packets #%d -> #%d lost", seqnum,
3170 seqnum + lost_packets - 1);
3172 GST_DEBUG_OBJECT (jitterbuffer, "Packet #%d lost", seqnum);
3174 priv->num_late += lost_packets;
3175 priv->num_rtx_failed += num_rtx_retry;
3177 next_in_seqnum = (seqnum + lost_packets) & 0xffff;
3179 /* we now only accept seqnum bigger than this */
3180 if (gst_rtp_buffer_compare_seqnum (priv->next_in_seqnum, next_in_seqnum) > 0)
3181 priv->next_in_seqnum = next_in_seqnum;
3183 /* create paket lost event */
3184 event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM,
3185 gst_structure_new ("GstRTPPacketLost",
3186 "seqnum", G_TYPE_UINT, (guint) seqnum,
3187 "timestamp", G_TYPE_UINT64, timestamp,
3188 "duration", G_TYPE_UINT64, duration,
3189 "late", G_TYPE_BOOLEAN, late,
3190 "retry", G_TYPE_UINT, num_rtx_retry, NULL));
3192 item = alloc_item (event, ITEM_TYPE_LOST, -1, -1, seqnum, lost_packets, -1);
3193 rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
3195 /* remove timer now */
3196 remove_timer (jitterbuffer, timer);
3198 JBUF_SIGNAL_EVENT (priv);
3204 do_eos_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3207 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3209 GST_INFO_OBJECT (jitterbuffer, "got the NPT timeout");
3210 remove_timer (jitterbuffer, timer);
3212 /* there was no EOS in the buffer, put one in there now */
3213 queue_event (jitterbuffer, gst_event_new_eos ());
3215 JBUF_SIGNAL_EVENT (priv);
3221 do_deadline_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3224 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3226 GST_INFO_OBJECT (jitterbuffer, "got deadline timeout");
3228 /* timer seqnum might have been obsoleted by caps seqnum-base,
3229 * only mess with current ongoing seqnum if still unknown */
3230 if (priv->next_seqnum == -1)
3231 priv->next_seqnum = timer->seqnum;
3232 remove_timer (jitterbuffer, timer);
3233 JBUF_SIGNAL_EVENT (priv);
3239 do_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3242 gboolean removed = FALSE;
3244 switch (timer->type) {
3245 case TIMER_TYPE_EXPECTED:
3246 removed = do_expected_timeout (jitterbuffer, timer, now);
3248 case TIMER_TYPE_LOST:
3249 removed = do_lost_timeout (jitterbuffer, timer, now);
3251 case TIMER_TYPE_DEADLINE:
3252 removed = do_deadline_timeout (jitterbuffer, timer, now);
3254 case TIMER_TYPE_EOS:
3255 removed = do_eos_timeout (jitterbuffer, timer, now);
3261 /* called when we need to wait for the next timeout.
3263 * We loop over the array of recorded timeouts and wait for the earliest one.
3264 * When it timed out, do the logic associated with the timer.
3266 * If there are no timers, we wait on a gcond until something new happens.
3269 wait_next_timeout (GstRtpJitterBuffer * jitterbuffer)
3271 GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3272 GstClockTime now = 0;
3275 while (priv->timer_running) {
3276 TimerData *timer = NULL;
3277 GstClockTime timer_timeout = -1;
3280 GST_DEBUG_OBJECT (jitterbuffer, "now %" GST_TIME_FORMAT,
3281 GST_TIME_ARGS (now));
3283 len = priv->timers->len;
3284 for (i = 0; i < len; i++) {
3285 TimerData *test = &g_array_index (priv->timers, TimerData, i);
3286 GstClockTime test_timeout = get_timeout (jitterbuffer, test);
3287 gboolean save_best = FALSE;
3289 GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, %d, %" GST_TIME_FORMAT,
3290 i, test->type, test->seqnum, GST_TIME_ARGS (test_timeout));
3292 /* find the smallest timeout */
3293 if (timer == NULL) {
3295 } else if (timer_timeout == -1) {
3296 /* we already have an immediate timeout, the new timer must be an
3297 * immediate timer with smaller seqnum to become the best */
3298 if (test_timeout == -1
3299 && (gst_rtp_buffer_compare_seqnum (test->seqnum,
3300 timer->seqnum) > 0))
3302 } else if (test_timeout == -1) {
3303 /* first immediate timer */
3305 } else if (test_timeout < timer_timeout) {
3308 } else if (test_timeout == timer_timeout
3309 && (gst_rtp_buffer_compare_seqnum (test->seqnum,
3310 timer->seqnum) > 0)) {
3311 /* same timer, smaller seqnum */
3315 GST_DEBUG_OBJECT (jitterbuffer, "new best %d", i);
3317 timer_timeout = test_timeout;
3320 if (timer && !priv->blocked) {
3322 GstClockTime sync_time;
3325 GstClockTimeDiff clock_jitter;
3327 if (timer_timeout == -1 || timer_timeout <= now) {
3328 do_timeout (jitterbuffer, timer, now);
3329 /* check here, do_timeout could have released the lock */
3330 if (!priv->timer_running)
3335 GST_OBJECT_LOCK (jitterbuffer);
3336 clock = GST_ELEMENT_CLOCK (jitterbuffer);
3338 GST_OBJECT_UNLOCK (jitterbuffer);
3339 /* let's just push if there is no clock */
3340 GST_DEBUG_OBJECT (jitterbuffer, "No clock, timeout right away");
3341 now = timer_timeout;
3345 /* prepare for sync against clock */
3346 sync_time = timer_timeout + GST_ELEMENT_CAST (jitterbuffer)->base_time;
3347 /* add latency of peer to get input time */
3348 sync_time += priv->peer_latency;
3350 GST_DEBUG_OBJECT (jitterbuffer, "sync to timestamp %" GST_TIME_FORMAT
3351 " with sync time %" GST_TIME_FORMAT,
3352 GST_TIME_ARGS (timer_timeout), GST_TIME_ARGS (sync_time));
3354 /* create an entry for the clock */
3355 id = priv->clock_id = gst_clock_new_single_shot_id (clock, sync_time);
3356 priv->timer_timeout = timer_timeout;
3357 priv->timer_seqnum = timer->seqnum;
3358 GST_OBJECT_UNLOCK (jitterbuffer);
3360 /* release the lock so that the other end can push stuff or unlock */
3363 ret = gst_clock_id_wait (id, &clock_jitter);
3366 if (!priv->timer_running) {
3367 gst_clock_id_unref (id);
3368 priv->clock_id = NULL;
3372 if (ret != GST_CLOCK_UNSCHEDULED) {
3373 now = timer_timeout + MAX (clock_jitter, 0);
3374 GST_DEBUG_OBJECT (jitterbuffer, "sync done, %d, #%d, %" G_GINT64_FORMAT,
3375 ret, priv->timer_seqnum, clock_jitter);
3377 GST_DEBUG_OBJECT (jitterbuffer, "sync unscheduled");
3379 /* and free the entry */
3380 gst_clock_id_unref (id);
3381 priv->clock_id = NULL;
3383 /* no timers, wait for activity */
3384 JBUF_WAIT_TIMER (priv);
3389 GST_DEBUG_OBJECT (jitterbuffer, "we are stopping");
3394 * This funcion implements the main pushing loop on the source pad.
3396 * It first tries to push as many buffers as possible. If there is a seqnum
3397 * mismatch, we wait for the next timeouts.
3400 gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer)
3402 GstRtpJitterBufferPrivate *priv;
3403 GstFlowReturn result = GST_FLOW_OK;
3405 priv = jitterbuffer->priv;
3407 JBUF_LOCK_CHECK (priv, flushing);
3409 result = handle_next_buffer (jitterbuffer);
3410 if (G_LIKELY (result == GST_FLOW_WAIT)) {
3411 /* now wait for the next event */
3412 JBUF_WAIT_EVENT (priv, flushing);
3413 result = GST_FLOW_OK;
3415 } while (result == GST_FLOW_OK);
3416 /* store result for upstream */
3417 priv->srcresult = result;
3418 /* if we get here we need to pause */
3424 result = priv->srcresult;
3431 JBUF_SIGNAL_QUERY (priv, FALSE);
3434 GST_DEBUG_OBJECT (jitterbuffer, "pausing task, reason %s",
3435 gst_flow_get_name (result));
3436 gst_pad_pause_task (priv->srcpad);
3437 if (result == GST_FLOW_EOS) {
3438 event = gst_event_new_eos ();
3439 gst_pad_push_event (priv->srcpad, event);
3445 /* collect the info from the lastest RTCP packet and the jitterbuffer sync, do
3446 * some sanity checks and then emit the handle-sync signal with the parameters.
3447 * This function must be called with the LOCK */
3449 do_handle_sync (GstRtpJitterBuffer * jitterbuffer)
3451 GstRtpJitterBufferPrivate *priv;
3452 guint64 base_rtptime, base_time;
3454 guint64 last_rtptime;
3456 guint64 ext_rtptime, diff;
3457 gboolean valid = TRUE, keep = FALSE;
3459 priv = jitterbuffer->priv;
3461 /* get the last values from the jitterbuffer */
3462 rtp_jitter_buffer_get_sync (priv->jbuf, &base_rtptime, &base_time,
3463 &clock_rate, &last_rtptime);
3465 clock_base = priv->clock_base;
3466 ext_rtptime = priv->ext_rtptime;
3468 GST_DEBUG_OBJECT (jitterbuffer, "ext SR %" G_GUINT64_FORMAT ", base %"
3469 G_GUINT64_FORMAT ", clock-rate %" G_GUINT32_FORMAT
3470 ", clock-base %" G_GUINT64_FORMAT ", last-rtptime %" G_GUINT64_FORMAT,
3471 ext_rtptime, base_rtptime, clock_rate, clock_base, last_rtptime);
3473 if (base_rtptime == -1 || clock_rate == -1 || base_time == -1) {
3474 /* we keep this SR packet for later. When we get a valid RTP packet the
3475 * above values will be set and we can try to use the SR packet */
3476 GST_DEBUG_OBJECT (jitterbuffer, "keeping for later, no RTP values");
3479 /* we can't accept anything that happened before we did the last resync */
3480 if (base_rtptime > ext_rtptime) {
3481 GST_DEBUG_OBJECT (jitterbuffer, "dropping, older than base time");
3484 /* the SR RTP timestamp must be something close to what we last observed
3485 * in the jitterbuffer */
3486 if (ext_rtptime > last_rtptime) {
3487 /* check how far ahead it is to our RTP timestamps */
3488 diff = ext_rtptime - last_rtptime;
3489 /* if bigger than 1 second, we drop it */
3490 if (diff > clock_rate) {
3491 GST_DEBUG_OBJECT (jitterbuffer, "too far ahead");
3492 /* should drop this, but some RTSP servers end up with bogus
3493 * way too ahead RTCP packet when repeated PAUSE/PLAY,
3494 * so still trigger rptbin sync but invalidate RTCP data
3495 * (sync might use other methods) */
3498 GST_DEBUG_OBJECT (jitterbuffer, "ext last %" G_GUINT64_FORMAT ", diff %"
3499 G_GUINT64_FORMAT, last_rtptime, diff);
3505 GST_DEBUG_OBJECT (jitterbuffer, "keeping RTCP packet for later");
3509 s = gst_structure_new ("application/x-rtp-sync",
3510 "base-rtptime", G_TYPE_UINT64, base_rtptime,
3511 "base-time", G_TYPE_UINT64, base_time,
3512 "clock-rate", G_TYPE_UINT, clock_rate,
3513 "clock-base", G_TYPE_UINT64, clock_base,
3514 "sr-ext-rtptime", G_TYPE_UINT64, ext_rtptime,
3515 "sr-buffer", GST_TYPE_BUFFER, priv->last_sr, NULL);
3517 GST_DEBUG_OBJECT (jitterbuffer, "signaling sync");
3518 gst_buffer_replace (&priv->last_sr, NULL);
3520 g_signal_emit (jitterbuffer,
3521 gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC], 0, s);
3523 gst_structure_free (s);
3525 GST_DEBUG_OBJECT (jitterbuffer, "dropping RTCP packet");
3526 gst_buffer_replace (&priv->last_sr, NULL);
3530 static GstFlowReturn
3531 gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad, GstObject * parent,
3534 GstRtpJitterBuffer *jitterbuffer;
3535 GstRtpJitterBufferPrivate *priv;
3536 GstFlowReturn ret = GST_FLOW_OK;
3538 GstRTCPPacket packet;
3539 guint64 ext_rtptime;
3541 GstRTCPBuffer rtcp = { NULL, };
3543 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3545 if (G_UNLIKELY (!gst_rtcp_buffer_validate_reduced (buffer)))
3546 goto invalid_buffer;
3548 priv = jitterbuffer->priv;
3550 gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
3552 if (!gst_rtcp_buffer_get_first_packet (&rtcp, &packet))
3555 /* first packet must be SR or RR or else the validate would have failed */
3556 switch (gst_rtcp_packet_get_type (&packet)) {
3557 case GST_RTCP_TYPE_SR:
3558 gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, NULL, &rtptime,
3564 gst_rtcp_buffer_unmap (&rtcp);
3566 GST_DEBUG_OBJECT (jitterbuffer, "received RTCP of SSRC %08x", ssrc);
3569 /* convert the RTP timestamp to our extended timestamp, using the same offset
3570 * we used in the jitterbuffer */
3571 ext_rtptime = priv->jbuf->ext_rtptime;
3572 ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
3574 priv->ext_rtptime = ext_rtptime;
3575 gst_buffer_replace (&priv->last_sr, buffer);
3577 do_handle_sync (jitterbuffer);
3581 gst_buffer_unref (buffer);
3587 /* this is not fatal but should be filtered earlier */
3588 GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
3589 ("Received invalid RTCP payload, dropping"));
3595 /* this is not fatal but should be filtered earlier */
3596 GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
3597 ("Received empty RTCP payload, dropping"));
3598 gst_rtcp_buffer_unmap (&rtcp);
3604 GST_DEBUG_OBJECT (jitterbuffer, "ignoring RTCP packet");
3605 gst_rtcp_buffer_unmap (&rtcp);
3612 gst_rtp_jitter_buffer_sink_query (GstPad * pad, GstObject * parent,
3615 gboolean res = FALSE;
3616 GstRtpJitterBuffer *jitterbuffer;
3617 GstRtpJitterBufferPrivate *priv;
3619 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3620 priv = jitterbuffer->priv;
3622 switch (GST_QUERY_TYPE (query)) {
3623 case GST_QUERY_CAPS:
3625 GstCaps *filter, *caps;
3627 gst_query_parse_caps (query, &filter);
3628 caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
3629 gst_query_set_caps_result (query, caps);
3630 gst_caps_unref (caps);
3635 if (GST_QUERY_IS_SERIALIZED (query)) {
3636 RTPJitterBufferItem *item;
3639 JBUF_LOCK_CHECK (priv, out_flushing);
3640 if (rtp_jitter_buffer_get_mode (priv->jbuf) !=
3641 RTP_JITTER_BUFFER_MODE_BUFFER) {
3642 GST_DEBUG_OBJECT (jitterbuffer, "adding serialized query");
3643 item = alloc_item (query, ITEM_TYPE_QUERY, -1, -1, -1, 0, -1);
3644 rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
3646 JBUF_SIGNAL_EVENT (priv);
3647 JBUF_WAIT_QUERY (priv, out_flushing);
3648 res = priv->last_query;
3650 GST_DEBUG_OBJECT (jitterbuffer, "refusing query, we are buffering");
3655 res = gst_pad_query_default (pad, parent, query);
3663 GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
3671 gst_rtp_jitter_buffer_src_query (GstPad * pad, GstObject * parent,
3674 GstRtpJitterBuffer *jitterbuffer;
3675 GstRtpJitterBufferPrivate *priv;
3676 gboolean res = FALSE;
3678 jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3679 priv = jitterbuffer->priv;
3681 switch (GST_QUERY_TYPE (query)) {
3682 case GST_QUERY_LATENCY:
3684 /* We need to send the query upstream and add the returned latency to our
3686 GstClockTime min_latency, max_latency;
3688 GstClockTime our_latency;
3690 if ((res = gst_pad_peer_query (priv->sinkpad, query))) {
3691 gst_query_parse_latency (query, &us_live, &min_latency, &max_latency);
3693 GST_DEBUG_OBJECT (jitterbuffer, "Peer latency: min %"
3694 GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
3695 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3697 /* store this so that we can safely sync on the peer buffers. */
3699 priv->peer_latency = min_latency;
3700 our_latency = priv->latency_ns;
3703 GST_DEBUG_OBJECT (jitterbuffer, "Our latency: %" GST_TIME_FORMAT,
3704 GST_TIME_ARGS (our_latency));
3706 /* we add some latency but can buffer an infinite amount of time */
3707 min_latency += our_latency;
3710 GST_DEBUG_OBJECT (jitterbuffer, "Calculated total latency : min %"
3711 GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
3712 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3714 gst_query_set_latency (query, TRUE, min_latency, max_latency);
3718 case GST_QUERY_POSITION:
3720 GstClockTime start, last_out;
3723 gst_query_parse_position (query, &fmt, NULL);
3724 if (fmt != GST_FORMAT_TIME) {
3725 res = gst_pad_query_default (pad, parent, query);
3730 start = priv->npt_start;
3731 last_out = priv->last_out_time;
3734 GST_DEBUG_OBJECT (jitterbuffer, "npt start %" GST_TIME_FORMAT
3735 ", last out %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
3736 GST_TIME_ARGS (last_out));
3738 if (GST_CLOCK_TIME_IS_VALID (start) && GST_CLOCK_TIME_IS_VALID (last_out)) {
3739 /* bring 0-based outgoing time to stream time */
3740 gst_query_set_position (query, GST_FORMAT_TIME, start + last_out);
3743 res = gst_pad_query_default (pad, parent, query);
3747 case GST_QUERY_CAPS:
3749 GstCaps *filter, *caps;
3751 gst_query_parse_caps (query, &filter);
3752 caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
3753 gst_query_set_caps_result (query, caps);
3754 gst_caps_unref (caps);
3759 res = gst_pad_query_default (pad, parent, query);
3767 gst_rtp_jitter_buffer_set_property (GObject * object,
3768 guint prop_id, const GValue * value, GParamSpec * pspec)
3770 GstRtpJitterBuffer *jitterbuffer;
3771 GstRtpJitterBufferPrivate *priv;
3773 jitterbuffer = GST_RTP_JITTER_BUFFER (object);
3774 priv = jitterbuffer->priv;
3779 guint new_latency, old_latency;
3781 new_latency = g_value_get_uint (value);
3784 old_latency = priv->latency_ms;
3785 priv->latency_ms = new_latency;
3786 priv->latency_ns = priv->latency_ms * GST_MSECOND;
3787 rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
3790 /* post message if latency changed, this will inform the parent pipeline
3791 * that a latency reconfiguration is possible/needed. */
3792 if (new_latency != old_latency) {
3793 GST_DEBUG_OBJECT (jitterbuffer, "latency changed to: %" GST_TIME_FORMAT,
3794 GST_TIME_ARGS (new_latency * GST_MSECOND));
3796 gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer),
3797 gst_message_new_latency (GST_OBJECT_CAST (jitterbuffer)));
3801 case PROP_DROP_ON_LATENCY:
3803 priv->drop_on_latency = g_value_get_boolean (value);
3806 case PROP_TS_OFFSET:
3808 priv->ts_offset = g_value_get_int64 (value);
3809 priv->ts_discont = TRUE;
3814 priv->do_lost = g_value_get_boolean (value);
3819 rtp_jitter_buffer_set_mode (priv->jbuf, g_value_get_enum (value));
3822 case PROP_DO_RETRANSMISSION:
3824 priv->do_retransmission = g_value_get_boolean (value);
3827 case PROP_RTX_NEXT_SEQNUM:
3829 priv->rtx_next_seqnum = g_value_get_boolean (value);
3832 case PROP_RTX_DELAY:
3834 priv->rtx_delay = g_value_get_int (value);
3837 case PROP_RTX_MIN_DELAY:
3839 priv->rtx_min_delay = g_value_get_uint (value);
3842 case PROP_RTX_DELAY_REORDER:
3844 priv->rtx_delay_reorder = g_value_get_int (value);
3847 case PROP_RTX_RETRY_TIMEOUT:
3849 priv->rtx_retry_timeout = g_value_get_int (value);
3852 case PROP_RTX_MIN_RETRY_TIMEOUT:
3854 priv->rtx_min_retry_timeout = g_value_get_int (value);
3857 case PROP_RTX_RETRY_PERIOD:
3859 priv->rtx_retry_period = g_value_get_int (value);
3862 case PROP_RTX_MAX_RETRIES:
3864 priv->rtx_max_retries = g_value_get_int (value);
3868 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3874 gst_rtp_jitter_buffer_get_property (GObject * object,
3875 guint prop_id, GValue * value, GParamSpec * pspec)
3877 GstRtpJitterBuffer *jitterbuffer;
3878 GstRtpJitterBufferPrivate *priv;
3880 jitterbuffer = GST_RTP_JITTER_BUFFER (object);
3881 priv = jitterbuffer->priv;
3886 g_value_set_uint (value, priv->latency_ms);
3889 case PROP_DROP_ON_LATENCY:
3891 g_value_set_boolean (value, priv->drop_on_latency);
3894 case PROP_TS_OFFSET:
3896 g_value_set_int64 (value, priv->ts_offset);
3901 g_value_set_boolean (value, priv->do_lost);
3906 g_value_set_enum (value, rtp_jitter_buffer_get_mode (priv->jbuf));
3914 if (priv->srcresult != GST_FLOW_OK)
3917 percent = rtp_jitter_buffer_get_percent (priv->jbuf);
3919 g_value_set_int (value, percent);
3923 case PROP_DO_RETRANSMISSION:
3925 g_value_set_boolean (value, priv->do_retransmission);
3928 case PROP_RTX_NEXT_SEQNUM:
3930 g_value_set_boolean (value, priv->rtx_next_seqnum);
3933 case PROP_RTX_DELAY:
3935 g_value_set_int (value, priv->rtx_delay);
3938 case PROP_RTX_MIN_DELAY:
3940 g_value_set_uint (value, priv->rtx_min_delay);
3943 case PROP_RTX_DELAY_REORDER:
3945 g_value_set_int (value, priv->rtx_delay_reorder);
3948 case PROP_RTX_RETRY_TIMEOUT:
3950 g_value_set_int (value, priv->rtx_retry_timeout);
3953 case PROP_RTX_MIN_RETRY_TIMEOUT:
3955 g_value_set_int (value, priv->rtx_min_retry_timeout);
3958 case PROP_RTX_RETRY_PERIOD:
3960 g_value_set_int (value, priv->rtx_retry_period);
3963 case PROP_RTX_MAX_RETRIES:
3965 g_value_set_int (value, priv->rtx_max_retries);
3969 g_value_take_boxed (value,
3970 gst_rtp_jitter_buffer_create_stats (jitterbuffer));
3973 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3978 static GstStructure *
3979 gst_rtp_jitter_buffer_create_stats (GstRtpJitterBuffer * jbuf)
3983 JBUF_LOCK (jbuf->priv);
3984 s = gst_structure_new ("application/x-rtp-jitterbuffer-stats",
3985 "rtx-count", G_TYPE_UINT64, jbuf->priv->num_rtx_requests,
3986 "rtx-success-count", G_TYPE_UINT64, jbuf->priv->num_rtx_success,
3987 "rtx-per-packet", G_TYPE_DOUBLE, jbuf->priv->avg_rtx_num,
3988 "rtx-rtt", G_TYPE_UINT64, jbuf->priv->avg_rtx_rtt, NULL);
3989 JBUF_UNLOCK (jbuf->priv);