blob: 678210be94aa6b028bb8121ebd29e3da2bd7fc13 [file] [log] [blame]
/*
* Farsight Voice+Video library
*
* Copyright 2007 Collabora Ltd,
* Copyright 2007 Nokia Corporation
* @author: Philippe Kalaf <philippe.kalaf@collabora.co.uk>.
* Copyright 2007 Wim Taymans <wim.taymans@gmail.com>
* Copyright 2015 Kurento (http://kurento.org/)
* @author: Miguel ParĂ­s <mparisdiaz@gmail.com>
* Copyright 2016 Pexip AS
* @author: Havard Graff <havard@pexip.com>
* @author: Stian Selnes <stian@pexip.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
/**
* SECTION:element-rtpjitterbuffer
*
* This element reorders and removes duplicate RTP packets as they are received
* from a network source.
*
* The element needs the clock-rate of the RTP payload in order to estimate the
* delay. This information is obtained either from the caps on the sink pad or,
* when no caps are present, from the #GstRtpJitterBuffer::request-pt-map signal.
* To clear the previous pt-map use the #GstRtpJitterBuffer::clear-pt-map signal.
*
* The rtpjitterbuffer will wait for missing packets up to a configurable time
* limit using the #GstRtpJitterBuffer:latency property. Packets arriving too
* late are considered to be lost packets. If the #GstRtpJitterBuffer:do-lost
* property is set, lost packets will result in a custom serialized downstream
* event of name GstRTPPacketLost. The lost packet events are usually used by a
* depayloader or other element to create concealment data or some other logic
* to gracefully handle the missing packets.
*
* The jitterbuffer will use the DTS (or PTS if no DTS is set) of the incomming
* buffer and the rtptime inside the RTP packet to create a PTS on the outgoing
* buffer.
*
* The jitterbuffer can also be configured to send early retransmission events
* upstream by setting the #GstRtpJitterBuffer:do-retransmission property. In
* this mode, the jitterbuffer tries to estimate when a packet should arrive and
* sends a custom upstream event named GstRTPRetransmissionRequest when the
* packet is considered late. The initial expected packet arrival time is
* calculated as follows:
*
* - If seqnum N arrived at time T, seqnum N+1 is expected to arrive at
* T + packet-spacing + #GstRtpJitterBuffer:rtx-delay. The packet spacing is
* calculated from the DTS (or PTS is no DTS) of two consecutive RTP
* packets with different rtptime.
*
* - If seqnum N0 arrived at time T0 and seqnum Nm arrived at time Tm,
* seqnum Ni is expected at time Ti = T0 + i*(Tm - T0)/(Nm - N0). Any
* previously scheduled timeout is overwritten.
*
* - If seqnum N arrived, all seqnum older than
* N - #GstRtpJitterBuffer:rtx-delay-reorder are considered late
* immediately. This is to request fast feedback for abonormally reorder
* packets before any of the previous timeouts is triggered.
*
* A late packet triggers the GstRTPRetransmissionRequest custom upstream
* event. After the initial timeout expires and the retransmission event is
* sent, the timeout is scheduled for
* T + #GstRtpJitterBuffer:rtx-retry-timeout. If the missing packet did not
* arrive after #GstRtpJitterBuffer:rtx-retry-timeout, a new
* GstRTPRetransmissionRequest is sent upstream and the timeout is rescheduled
* again for T + #GstRtpJitterBuffer:rtx-retry-timeout. This repeats until
* #GstRtpJitterBuffer:rtx-retry-period elapsed, at which point no further
* retransmission requests are sent and the regular logic is performed to
* schedule a lost packet as discussed above.
*
* This element acts as a live element and so adds #GstRtpJitterBuffer:latency
* to the pipeline.
*
* This element will automatically be used inside rtpbin.
*
* <refsect2>
* <title>Example pipelines</title>
* |[
* gst-launch-1.0 rtspsrc location=rtsp://192.168.1.133:8554/mpeg1or2AudioVideoTest ! rtpjitterbuffer ! rtpmpvdepay ! mpeg2dec ! xvimagesink
* ]| Connect to a streaming server and decode the MPEG video. The jitterbuffer is
* inserted into the pipeline to smooth out network jitter and to reorder the
* out-of-order RTP packets.
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gst/rtp/gstrtpbuffer.h>
#include <gst/net/net.h>
#include "gstrtpjitterbuffer.h"
#include "rtpjitterbuffer.h"
#include "rtpstats.h"
#include <gst/glib-compat-private.h>
GST_DEBUG_CATEGORY (rtpjitterbuffer_debug);
#define GST_CAT_DEFAULT (rtpjitterbuffer_debug)
/* RTPJitterBuffer signals and args */
enum
{
SIGNAL_REQUEST_PT_MAP,
SIGNAL_CLEAR_PT_MAP,
SIGNAL_HANDLE_SYNC,
SIGNAL_ON_NPT_STOP,
SIGNAL_SET_ACTIVE,
LAST_SIGNAL
};
#define DEFAULT_LATENCY_MS 200
#define DEFAULT_DROP_ON_LATENCY FALSE
#define DEFAULT_TS_OFFSET 0
#define DEFAULT_MAX_TS_OFFSET_ADJUSTMENT 0
#define DEFAULT_DO_LOST FALSE
#define DEFAULT_MODE RTP_JITTER_BUFFER_MODE_SLAVE
#define DEFAULT_PERCENT 0
#define DEFAULT_DO_RETRANSMISSION FALSE
#define DEFAULT_RTX_NEXT_SEQNUM TRUE
#define DEFAULT_RTX_DELAY -1
#define DEFAULT_RTX_MIN_DELAY 0
#define DEFAULT_RTX_DELAY_REORDER 3
#define DEFAULT_RTX_RETRY_TIMEOUT -1
#define DEFAULT_RTX_MIN_RETRY_TIMEOUT -1
#define DEFAULT_RTX_RETRY_PERIOD -1
#define DEFAULT_RTX_MAX_RETRIES -1
#define DEFAULT_RTX_DEADLINE -1
#define DEFAULT_RTX_STATS_TIMEOUT 1000
#define DEFAULT_MAX_RTCP_RTP_TIME_DIFF 1000
#define DEFAULT_MAX_DROPOUT_TIME 60000
#define DEFAULT_MAX_MISORDER_TIME 2000
#define DEFAULT_RFC7273_SYNC FALSE
#define DEFAULT_FASTSTART_MIN_PACKETS 0
#define DEFAULT_AUTO_RTX_DELAY (20 * GST_MSECOND)
#define DEFAULT_AUTO_RTX_TIMEOUT (40 * GST_MSECOND)
enum
{
PROP_0,
PROP_LATENCY,
PROP_DROP_ON_LATENCY,
PROP_TS_OFFSET,
PROP_MAX_TS_OFFSET_ADJUSTMENT,
PROP_DO_LOST,
PROP_MODE,
PROP_PERCENT,
PROP_DO_RETRANSMISSION,
PROP_RTX_NEXT_SEQNUM,
PROP_RTX_DELAY,
PROP_RTX_MIN_DELAY,
PROP_RTX_DELAY_REORDER,
PROP_RTX_RETRY_TIMEOUT,
PROP_RTX_MIN_RETRY_TIMEOUT,
PROP_RTX_RETRY_PERIOD,
PROP_RTX_MAX_RETRIES,
PROP_RTX_DEADLINE,
PROP_RTX_STATS_TIMEOUT,
PROP_STATS,
PROP_MAX_RTCP_RTP_TIME_DIFF,
PROP_MAX_DROPOUT_TIME,
PROP_MAX_MISORDER_TIME,
PROP_RFC7273_SYNC,
PROP_FASTSTART_MIN_PACKETS
};
#define JBUF_LOCK(priv) G_STMT_START { \
GST_TRACE("Locking from thread %p", g_thread_self()); \
(g_mutex_lock (&(priv)->jbuf_lock)); \
GST_TRACE("Locked from thread %p", g_thread_self()); \
} G_STMT_END
#define JBUF_LOCK_CHECK(priv,label) G_STMT_START { \
JBUF_LOCK (priv); \
if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK)) \
goto label; \
} G_STMT_END
#define JBUF_UNLOCK(priv) G_STMT_START { \
GST_TRACE ("Unlocking from thread %p", g_thread_self ()); \
(g_mutex_unlock (&(priv)->jbuf_lock)); \
} G_STMT_END
#define JBUF_WAIT_TIMER(priv) G_STMT_START { \
GST_DEBUG ("waiting timer"); \
(priv)->waiting_timer = TRUE; \
g_cond_wait (&(priv)->jbuf_timer, &(priv)->jbuf_lock); \
(priv)->waiting_timer = FALSE; \
GST_DEBUG ("waiting timer done"); \
} G_STMT_END
#define JBUF_SIGNAL_TIMER(priv) G_STMT_START { \
if (G_UNLIKELY ((priv)->waiting_timer)) { \
GST_DEBUG ("signal timer"); \
g_cond_signal (&(priv)->jbuf_timer); \
} \
} G_STMT_END
#define JBUF_WAIT_EVENT(priv,label) G_STMT_START { \
GST_DEBUG ("waiting event"); \
(priv)->waiting_event = TRUE; \
g_cond_wait (&(priv)->jbuf_event, &(priv)->jbuf_lock); \
(priv)->waiting_event = FALSE; \
GST_DEBUG ("waiting event done"); \
if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK)) \
goto label; \
} G_STMT_END
#define JBUF_SIGNAL_EVENT(priv) G_STMT_START { \
if (G_UNLIKELY ((priv)->waiting_event)) { \
GST_DEBUG ("signal event"); \
g_cond_signal (&(priv)->jbuf_event); \
} \
} G_STMT_END
#define JBUF_WAIT_QUERY(priv,label) G_STMT_START { \
GST_DEBUG ("waiting query"); \
(priv)->waiting_query = TRUE; \
g_cond_wait (&(priv)->jbuf_query, &(priv)->jbuf_lock); \
(priv)->waiting_query = FALSE; \
GST_DEBUG ("waiting query done"); \
if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK)) \
goto label; \
} G_STMT_END
#define JBUF_SIGNAL_QUERY(priv,res) G_STMT_START { \
(priv)->last_query = res; \
if (G_UNLIKELY ((priv)->waiting_query)) { \
GST_DEBUG ("signal query"); \
g_cond_signal (&(priv)->jbuf_query); \
} \
} G_STMT_END
#define GST_BUFFER_IS_RETRANSMISSION(buffer) \
GST_BUFFER_FLAG_IS_SET (buffer, GST_RTP_BUFFER_FLAG_RETRANSMISSION)
typedef struct TimerQueue
{
GQueue *timers;
GHashTable *hashtable;
} TimerQueue;
struct _GstRtpJitterBufferPrivate
{
GstPad *sinkpad, *srcpad;
GstPad *rtcpsinkpad;
RTPJitterBuffer *jbuf;
GMutex jbuf_lock;
gboolean waiting_timer;
GCond jbuf_timer;
gboolean waiting_event;
GCond jbuf_event;
gboolean waiting_query;
GCond jbuf_query;
gboolean last_query;
gboolean discont;
gboolean ts_discont;
gboolean active;
guint64 out_offset;
gboolean timer_running;
GThread *timer_thread;
/* properties */
guint latency_ms;
guint64 latency_ns;
gboolean drop_on_latency;
gint64 ts_offset;
guint64 max_ts_offset_adjustment;
gboolean do_lost;
gboolean do_retransmission;
gboolean rtx_next_seqnum;
gint rtx_delay;
guint rtx_min_delay;
gint rtx_delay_reorder;
gint rtx_retry_timeout;
gint rtx_min_retry_timeout;
gint rtx_retry_period;
gint rtx_max_retries;
guint rtx_stats_timeout;
gint rtx_deadline_ms;
gint max_rtcp_rtp_time_diff;
guint32 max_dropout_time;
guint32 max_misorder_time;
guint faststart_min_packets;
/* the last seqnum we pushed out */
guint32 last_popped_seqnum;
/* the next expected seqnum we push */
guint32 next_seqnum;
/* seqnum-base, if known */
guint32 seqnum_base;
/* last output time */
GstClockTime last_out_time;
/* last valid input timestamp and rtptime pair */
GstClockTime ips_pts;
guint64 ips_rtptime;
GstClockTime packet_spacing;
gint equidistant;
GQueue gap_packets;
/* the next expected seqnum we receive */
GstClockTime last_in_pts;
guint32 next_in_seqnum;
GArray *timers;
TimerQueue *rtx_stats_timers;
/* start and stop ranges */
GstClockTime npt_start;
GstClockTime npt_stop;
guint64 ext_timestamp;
guint64 last_elapsed;
guint64 estimated_eos;
GstClockID eos_id;
/* state */
gboolean eos;
guint last_percent;
/* clock rate and rtp timestamp offset */
gint last_pt;
gint32 clock_rate;
gint64 clock_base;
gint64 ts_offset_remainder;
/* when we are shutting down */
GstFlowReturn srcresult;
gboolean blocked;
/* for sync */
GstSegment segment;
GstClockID clock_id;
GstClockTime timer_timeout;
guint16 timer_seqnum;
/* the latency of the upstream peer, we have to take this into account when
* synchronizing the buffers. */
GstClockTime peer_latency;
guint64 ext_rtptime;
GstBuffer *last_sr;
/* some accounting */
guint64 num_pushed;
guint64 num_lost;
guint64 num_late;
guint64 num_duplicates;
guint64 num_rtx_requests;
guint64 num_rtx_success;
guint64 num_rtx_failed;
gdouble avg_rtx_num;
guint64 avg_rtx_rtt;
RTPPacketRateCtx packet_rate_ctx;
/* for the jitter */
GstClockTime last_dts;
GstClockTime last_pts;
guint64 last_rtptime;
GstClockTime avg_jitter;
};
typedef enum
{
TIMER_TYPE_EXPECTED,
TIMER_TYPE_LOST,
TIMER_TYPE_DEADLINE,
TIMER_TYPE_EOS
} TimerType;
typedef struct
{
guint idx;
guint16 seqnum;
guint num;
TimerType type;
GstClockTime timeout;
GstClockTime duration;
GstClockTime rtx_base;
GstClockTime rtx_delay;
GstClockTime rtx_retry;
GstClockTime rtx_last;
guint num_rtx_retry;
guint num_rtx_received;
} TimerData;
#define GST_RTP_JITTER_BUFFER_GET_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), GST_TYPE_RTP_JITTER_BUFFER, \
GstRtpJitterBufferPrivate))
static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_template =
GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("application/x-rtp"
/* "clock-rate = (int) [ 1, 2147483647 ], "
* "payload = (int) , "
* "encoding-name = (string) "
*/ )
);
static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_rtcp_template =
GST_STATIC_PAD_TEMPLATE ("sink_rtcp",
GST_PAD_SINK,
GST_PAD_REQUEST,
GST_STATIC_CAPS ("application/x-rtcp")
);
static GstStaticPadTemplate gst_rtp_jitter_buffer_src_template =
GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("application/x-rtp"
/* "payload = (int) , "
* "clock-rate = (int) , "
* "encoding-name = (string) "
*/ )
);
static guint gst_rtp_jitter_buffer_signals[LAST_SIGNAL] = { 0 };
#define gst_rtp_jitter_buffer_parent_class parent_class
G_DEFINE_TYPE (GstRtpJitterBuffer, gst_rtp_jitter_buffer, GST_TYPE_ELEMENT);
/* object overrides */
static void gst_rtp_jitter_buffer_set_property (GObject * object,
guint prop_id, const GValue * value, GParamSpec * pspec);
static void gst_rtp_jitter_buffer_get_property (GObject * object,
guint prop_id, GValue * value, GParamSpec * pspec);
static void gst_rtp_jitter_buffer_finalize (GObject * object);
/* element overrides */
static GstStateChangeReturn gst_rtp_jitter_buffer_change_state (GstElement
* element, GstStateChange transition);
static GstPad *gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
GstPadTemplate * templ, const gchar * name, const GstCaps * filter);
static void gst_rtp_jitter_buffer_release_pad (GstElement * element,
GstPad * pad);
static GstClock *gst_rtp_jitter_buffer_provide_clock (GstElement * element);
static gboolean gst_rtp_jitter_buffer_set_clock (GstElement * element,
GstClock * clock);
/* pad overrides */
static GstCaps *gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter);
static GstIterator *gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad,
GstObject * parent);
/* sinkpad overrides */
static gboolean gst_rtp_jitter_buffer_sink_event (GstPad * pad,
GstObject * parent, GstEvent * event);
static GstFlowReturn gst_rtp_jitter_buffer_chain (GstPad * pad,
GstObject * parent, GstBuffer * buffer);
static GstFlowReturn gst_rtp_jitter_buffer_chain_list (GstPad * pad,
GstObject * parent, GstBufferList * buffer_list);
static gboolean gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad,
GstObject * parent, GstEvent * event);
static GstFlowReturn gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad,
GstObject * parent, GstBuffer * buffer);
static gboolean gst_rtp_jitter_buffer_sink_query (GstPad * pad,
GstObject * parent, GstQuery * query);
/* srcpad overrides */
static gboolean gst_rtp_jitter_buffer_src_event (GstPad * pad,
GstObject * parent, GstEvent * event);
static gboolean gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad,
GstObject * parent, GstPadMode mode, gboolean active);
static void gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer);
static gboolean gst_rtp_jitter_buffer_src_query (GstPad * pad,
GstObject * parent, GstQuery * query);
static void
gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer);
static GstClockTime
gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jitterbuffer,
gboolean active, guint64 base_time);
static void do_handle_sync (GstRtpJitterBuffer * jitterbuffer);
static void unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer);
static void remove_all_timers (GstRtpJitterBuffer * jitterbuffer);
static void wait_next_timeout (GstRtpJitterBuffer * jitterbuffer);
static GstStructure *gst_rtp_jitter_buffer_create_stats (GstRtpJitterBuffer *
jitterbuffer);
static void update_rtx_stats (GstRtpJitterBuffer * jitterbuffer,
TimerData * timer, GstClockTime dts, gboolean success);
static TimerQueue *timer_queue_new (void);
static void timer_queue_free (TimerQueue * queue);
static void
gst_rtp_jitter_buffer_class_init (GstRtpJitterBufferClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
g_type_class_add_private (klass, sizeof (GstRtpJitterBufferPrivate));
gobject_class->finalize = gst_rtp_jitter_buffer_finalize;
gobject_class->set_property = gst_rtp_jitter_buffer_set_property;
gobject_class->get_property = gst_rtp_jitter_buffer_get_property;
/**
* GstRtpJitterBuffer:latency:
*
* The maximum latency of the jitterbuffer. Packets will be kept in the buffer
* for at most this time.
*/
g_object_class_install_property (gobject_class, PROP_LATENCY,
g_param_spec_uint ("latency", "Buffer latency in ms",
"Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:drop-on-latency:
*
* Drop oldest buffers when the queue is completely filled.
*/
g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
g_param_spec_boolean ("drop-on-latency",
"Drop buffers when maximum latency is reached",
"Tells the jitterbuffer to never exceed the given latency in size",
DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:ts-offset:
*
* Adjust GStreamer output buffer timestamps in the jitterbuffer with offset.
* This is mainly used to ensure interstream synchronisation.
*/
g_object_class_install_property (gobject_class, PROP_TS_OFFSET,
g_param_spec_int64 ("ts-offset", "Timestamp Offset",
"Adjust buffer timestamps with offset in nanoseconds", G_MININT64,
G_MAXINT64, DEFAULT_TS_OFFSET,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:max-ts-offset-adjustment:
*
* The maximum number of nanoseconds per frame that time offset may be
* adjusted with. This is used to avoid sudden large changes to time stamps.
*/
g_object_class_install_property (gobject_class, PROP_MAX_TS_OFFSET_ADJUSTMENT,
g_param_spec_uint64 ("max-ts-offset-adjustment",
"Max Timestamp Offset Adjustment",
"The maximum number of nanoseconds per frame that time stamp "
"offsets may be adjusted (0 = no limit).", 0, G_MAXUINT64,
DEFAULT_MAX_TS_OFFSET_ADJUSTMENT, G_PARAM_READWRITE |
G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:do-lost:
*
* Send out a GstRTPPacketLost event downstream when a packet is considered
* lost.
*/
g_object_class_install_property (gobject_class, PROP_DO_LOST,
g_param_spec_boolean ("do-lost", "Do Lost",
"Send an event downstream when a packet is lost", DEFAULT_DO_LOST,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:mode:
*
* Control the buffering and timestamping mode used by the jitterbuffer.
*/
g_object_class_install_property (gobject_class, PROP_MODE,
g_param_spec_enum ("mode", "Mode",
"Control the buffering algorithm in use", RTP_TYPE_JITTER_BUFFER_MODE,
DEFAULT_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:percent:
*
* The percent of the jitterbuffer that is filled.
*/
g_object_class_install_property (gobject_class, PROP_PERCENT,
g_param_spec_int ("percent", "percent",
"The buffer filled percent", 0, 100,
0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:do-retransmission:
*
* Send out a GstRTPRetransmission event upstream when a packet is considered
* late and should be retransmitted.
*
* Since: 1.2
*/
g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
g_param_spec_boolean ("do-retransmission", "Do Retransmission",
"Send retransmission events upstream when a packet is late",
DEFAULT_DO_RETRANSMISSION,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:rtx-next-seqnum
*
* Estimate when the next packet should arrive and schedule a retransmission
* request for it.
* This is, when packet N arrives, a GstRTPRetransmission event is schedule
* for packet N+1. So it will be requested if it does not arrive at the expected time.
* The expected time is calculated using the dts of N and the packet spacing.
*
* Since: 1.6
*/
g_object_class_install_property (gobject_class, PROP_RTX_NEXT_SEQNUM,
g_param_spec_boolean ("rtx-next-seqnum", "RTX next seqnum",
"Estimate when the next packet should arrive and schedule a "
"retransmission request for it.",
DEFAULT_RTX_NEXT_SEQNUM, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:rtx-delay:
*
* When a packet did not arrive at the expected time, wait this extra amount
* of time before sending a retransmission event.
*
* When -1 is used, the max jitter will be used as extra delay.
*
* Since: 1.2
*/
g_object_class_install_property (gobject_class, PROP_RTX_DELAY,
g_param_spec_int ("rtx-delay", "RTX Delay",
"Extra time in ms to wait before sending retransmission "
"event (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_DELAY,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:rtx-min-delay:
*
* When a packet did not arrive at the expected time, wait at least this extra amount
* of time before sending a retransmission event.
*
* Since: 1.6
*/
g_object_class_install_property (gobject_class, PROP_RTX_MIN_DELAY,
g_param_spec_uint ("rtx-min-delay", "Minimum RTX Delay",
"Minimum time in ms to wait before sending retransmission "
"event", 0, G_MAXUINT, DEFAULT_RTX_MIN_DELAY,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:rtx-delay-reorder:
*
* Assume that a retransmission event should be sent when we see
* this much packet reordering.
*
* When -1 is used, the value will be estimated based on observed packet
* reordering. When 0 is used packet reordering alone will not cause a
* retransmission event (Since 1.10).
*
* Since: 1.2
*/
g_object_class_install_property (gobject_class, PROP_RTX_DELAY_REORDER,
g_param_spec_int ("rtx-delay-reorder", "RTX Delay Reorder",
"Sending retransmission event when this much reordering "
"(0 disable, -1 automatic)",
-1, G_MAXINT, DEFAULT_RTX_DELAY_REORDER,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer::rtx-retry-timeout:
*
* When no packet has been received after sending a retransmission event
* for this time, retry sending a retransmission event.
*
* When -1 is used, the value will be estimated based on observed round
* trip time.
*
* Since: 1.2
*/
g_object_class_install_property (gobject_class, PROP_RTX_RETRY_TIMEOUT,
g_param_spec_int ("rtx-retry-timeout", "RTX Retry Timeout",
"Retry sending a transmission event after this timeout in "
"ms (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_TIMEOUT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer::rtx-min-retry-timeout:
*
* The minimum amount of time between retry timeouts. When
* GstRtpJitterBuffer::rtx-retry-timeout is -1, this value ensures a
* minimum interval between retry timeouts.
*
* When -1 is used, the value will be estimated based on the
* packet spacing.
*
* Since: 1.6
*/
g_object_class_install_property (gobject_class, PROP_RTX_MIN_RETRY_TIMEOUT,
g_param_spec_int ("rtx-min-retry-timeout", "RTX Min Retry Timeout",
"Minimum timeout between sending a transmission event in "
"ms (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_MIN_RETRY_TIMEOUT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:rtx-retry-period:
*
* The amount of time to try to get a retransmission.
*
* When -1 is used, the value will be estimated based on the jitterbuffer
* latency and the observed round trip time.
*
* Since: 1.2
*/
g_object_class_install_property (gobject_class, PROP_RTX_RETRY_PERIOD,
g_param_spec_int ("rtx-retry-period", "RTX Retry Period",
"Try to get a retransmission for this many ms "
"(-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_PERIOD,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:rtx-max-retries:
*
* The maximum number of retries to request a retransmission.
*
* This implies that as maximum (rtx-max-retries + 1) retransmissions will be requested.
* When -1 is used, the number of retransmission request will not be limited.
*
* Since: 1.6
*/
g_object_class_install_property (gobject_class, PROP_RTX_MAX_RETRIES,
g_param_spec_int ("rtx-max-retries", "RTX Max Retries",
"The maximum number of retries to request a retransmission. "
"(-1 not limited)", -1, G_MAXINT, DEFAULT_RTX_MAX_RETRIES,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:rtx-deadline:
*
* The deadline for a valid RTX request in ms.
*
* How long the RTX RTCP will be valid for.
* When -1 is used, the size of the jitterbuffer will be used.
*
* Since: 1.10
*/
g_object_class_install_property (gobject_class, PROP_RTX_DEADLINE,
g_param_spec_int ("rtx-deadline", "RTX Deadline (ms)",
"The deadline for a valid RTX request in milliseconds. "
"(-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_DEADLINE,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer::rtx-stats-timeout:
*
* The time to wait for a retransmitted packet after it has been
* considered lost in order to collect RTX statistics.
*
* Since: 1.10
*/
g_object_class_install_property (gobject_class, PROP_RTX_STATS_TIMEOUT,
g_param_spec_uint ("rtx-stats-timeout", "RTX Statistics Timeout",
"The time to wait for a retransmitted packet after it has been "
"considered lost in order to collect statistics (ms)",
0, G_MAXUINT, DEFAULT_RTX_STATS_TIMEOUT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_MAX_DROPOUT_TIME,
g_param_spec_uint ("max-dropout-time", "Max dropout time",
"The maximum time (milliseconds) of missing packets tolerated.",
0, G_MAXUINT, DEFAULT_MAX_DROPOUT_TIME,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_MAX_MISORDER_TIME,
g_param_spec_uint ("max-misorder-time", "Max misorder time",
"The maximum time (milliseconds) of misordered packets tolerated.",
0, G_MAXUINT, DEFAULT_MAX_MISORDER_TIME,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:stats:
*
* Various jitterbuffer statistics. This property returns a GstStructure
* with name application/x-rtp-jitterbuffer-stats with the following fields:
*
* <itemizedlist>
* <listitem>
* <para>
* #guint64
* <classname>&quot;num-pushed&quot;</classname>:
* the number of packets pushed out.
* </para>
* </listitem>
* <listitem>
* <para>
* #guint64
* <classname>&quot;num-lost&quot;</classname>:
* the number of packets considered lost.
* </para>
* </listitem>
* <listitem>
* <para>
* #guint64
* <classname>&quot;num-late&quot;</classname>:
* the number of packets arriving too late.
* </para>
* </listitem>
* <listitem>
* <para>
* #guint64
* <classname>&quot;num-duplicates&quot;</classname>:
* the number of duplicate packets.
* </para>
* </listitem>
* <listitem>
* <para>
* #guint64
* <classname>&quot;rtx-count&quot;</classname>:
* the number of retransmissions requested.
* </para>
* </listitem>
* <listitem>
* <para>
* #guint64
* <classname>&quot;rtx-success-count&quot;</classname>:
* the number of successful retransmissions.
* </para>
* </listitem>
* <listitem>
* <para>
* #gdouble
* <classname>&quot;rtx-per-packet&quot;</classname>:
* average number of RTX per packet.
* </para>
* </listitem>
* <listitem>
* <para>
* #guint64
* <classname>&quot;rtx-rtt&quot;</classname>:
* average round trip time per RTX.
* </para>
* </listitem>
* </itemizedlist>
*
* Since: 1.4
*/
g_object_class_install_property (gobject_class, PROP_STATS,
g_param_spec_boxed ("stats", "Statistics",
"Various statistics", GST_TYPE_STRUCTURE,
G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:max-rtcp-rtp-time-diff
*
* The maximum amount of time in ms that the RTP time in the RTCP SRs
* is allowed to be ahead of the last RTP packet we received. Use
* -1 to disable ignoring of RTCP packets.
*
* Since: 1.8
*/
g_object_class_install_property (gobject_class, PROP_MAX_RTCP_RTP_TIME_DIFF,
g_param_spec_int ("max-rtcp-rtp-time-diff", "Max RTCP RTP Time Diff",
"Maximum amount of time in ms that the RTP time in RTCP SRs "
"is allowed to be ahead (-1 disabled)", -1, G_MAXINT,
DEFAULT_MAX_RTCP_RTP_TIME_DIFF,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_RFC7273_SYNC,
g_param_spec_boolean ("rfc7273-sync", "Sync on RFC7273 clock",
"Synchronize received streams to the RFC7273 clock "
"(requires clock and offset to be provided)", DEFAULT_RFC7273_SYNC,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer:faststart-min-packets
*
* The number of consecutive packets needed to start (set to 0 to
* disable faststart. The jitterbuffer will by default start after the
* latency has elapsed)
*
* Since: 1.14
*/
g_object_class_install_property (gobject_class, PROP_FASTSTART_MIN_PACKETS,
g_param_spec_uint ("faststart-min-packets", "Faststart minimum packets",
"The number of consecutive packets needed to start (set to 0 to "
"disable faststart. The jitterbuffer will by default start after "
"the latency has elapsed)",
0, G_MAXUINT, DEFAULT_FASTSTART_MIN_PACKETS,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
/**
* GstRtpJitterBuffer::request-pt-map:
* @buffer: the object which received the signal
* @pt: the pt
*
* Request the payload type as #GstCaps for @pt.
*/
gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP] =
g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
request_pt_map), NULL, NULL, g_cclosure_marshal_generic,
GST_TYPE_CAPS, 1, G_TYPE_UINT);
/**
* GstRtpJitterBuffer::handle-sync:
* @buffer: the object which received the signal
* @struct: a GstStructure containing sync values.
*
* Be notified of new sync values.
*/
gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC] =
g_signal_new ("handle-sync", G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
handle_sync), NULL, NULL, g_cclosure_marshal_VOID__BOXED,
G_TYPE_NONE, 1, GST_TYPE_STRUCTURE | G_SIGNAL_TYPE_STATIC_SCOPE);
/**
* GstRtpJitterBuffer::on-npt-stop:
* @buffer: the object which received the signal
*
* Signal that the jitterbufer has pushed the RTP packet that corresponds to
* the npt-stop position.
*/
gst_rtp_jitter_buffer_signals[SIGNAL_ON_NPT_STOP] =
g_signal_new ("on-npt-stop", G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
on_npt_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0, G_TYPE_NONE);
/**
* GstRtpJitterBuffer::clear-pt-map:
* @buffer: the object which received the signal
*
* Invalidate the clock-rate as obtained with the
* #GstRtpJitterBuffer::request-pt-map signal.
*/
gst_rtp_jitter_buffer_signals[SIGNAL_CLEAR_PT_MAP] =
g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (GstRtpJitterBufferClass, clear_pt_map), NULL, NULL,
g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
/**
* GstRtpJitterBuffer::set-active:
* @buffer: the object which received the signal
*
* Start pushing out packets with the given base time. This signal is only
* useful in buffering mode.
*
* Returns: the time of the last pushed packet.
*/
gst_rtp_jitter_buffer_signals[SIGNAL_SET_ACTIVE] =
g_signal_new ("set-active", G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
G_STRUCT_OFFSET (GstRtpJitterBufferClass, set_active), NULL, NULL,
g_cclosure_marshal_generic, G_TYPE_UINT64, 2, G_TYPE_BOOLEAN,
G_TYPE_UINT64);
gstelement_class->change_state =
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_change_state);
gstelement_class->request_new_pad =
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_request_new_pad);
gstelement_class->release_pad =
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_release_pad);
gstelement_class->provide_clock =
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_provide_clock);
gstelement_class->set_clock =
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_set_clock);
gst_element_class_add_static_pad_template (gstelement_class,
&gst_rtp_jitter_buffer_src_template);
gst_element_class_add_static_pad_template (gstelement_class,
&gst_rtp_jitter_buffer_sink_template);
gst_element_class_add_static_pad_template (gstelement_class,
&gst_rtp_jitter_buffer_sink_rtcp_template);
gst_element_class_set_static_metadata (gstelement_class,
"RTP packet jitter-buffer", "Filter/Network/RTP",
"A buffer that deals with network jitter and other transmission faults",
"Philippe Kalaf <philippe.kalaf@collabora.co.uk>, "
"Wim Taymans <wim.taymans@gmail.com>");
klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_clear_pt_map);
klass->set_active = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_set_active);
GST_DEBUG_CATEGORY_INIT
(rtpjitterbuffer_debug, "rtpjitterbuffer", 0, "RTP Jitter Buffer");
}
static void
gst_rtp_jitter_buffer_init (GstRtpJitterBuffer * jitterbuffer)
{
GstRtpJitterBufferPrivate *priv;
priv = GST_RTP_JITTER_BUFFER_GET_PRIVATE (jitterbuffer);
jitterbuffer->priv = priv;
priv->latency_ms = DEFAULT_LATENCY_MS;
priv->latency_ns = priv->latency_ms * GST_MSECOND;
priv->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
priv->ts_offset = DEFAULT_TS_OFFSET;
priv->max_ts_offset_adjustment = DEFAULT_MAX_TS_OFFSET_ADJUSTMENT;
priv->do_lost = DEFAULT_DO_LOST;
priv->do_retransmission = DEFAULT_DO_RETRANSMISSION;
priv->rtx_next_seqnum = DEFAULT_RTX_NEXT_SEQNUM;
priv->rtx_delay = DEFAULT_RTX_DELAY;
priv->rtx_min_delay = DEFAULT_RTX_MIN_DELAY;
priv->rtx_delay_reorder = DEFAULT_RTX_DELAY_REORDER;
priv->rtx_retry_timeout = DEFAULT_RTX_RETRY_TIMEOUT;
priv->rtx_min_retry_timeout = DEFAULT_RTX_MIN_RETRY_TIMEOUT;
priv->rtx_retry_period = DEFAULT_RTX_RETRY_PERIOD;
priv->rtx_max_retries = DEFAULT_RTX_MAX_RETRIES;
priv->rtx_deadline_ms = DEFAULT_RTX_DEADLINE;
priv->rtx_stats_timeout = DEFAULT_RTX_STATS_TIMEOUT;
priv->max_rtcp_rtp_time_diff = DEFAULT_MAX_RTCP_RTP_TIME_DIFF;
priv->max_dropout_time = DEFAULT_MAX_DROPOUT_TIME;
priv->max_misorder_time = DEFAULT_MAX_MISORDER_TIME;
priv->faststart_min_packets = DEFAULT_FASTSTART_MIN_PACKETS;
priv->ts_offset_remainder = 0;
priv->last_dts = -1;
priv->last_pts = -1;
priv->last_rtptime = -1;
priv->avg_jitter = 0;
priv->timers = g_array_new (FALSE, TRUE, sizeof (TimerData));
priv->rtx_stats_timers = timer_queue_new ();
priv->jbuf = rtp_jitter_buffer_new ();
g_mutex_init (&priv->jbuf_lock);
g_cond_init (&priv->jbuf_timer);
g_cond_init (&priv->jbuf_event);
g_cond_init (&priv->jbuf_query);
g_queue_init (&priv->gap_packets);
gst_segment_init (&priv->segment, GST_FORMAT_TIME);
/* reset skew detection initialy */
rtp_jitter_buffer_reset_skew (priv->jbuf);
rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
rtp_jitter_buffer_set_buffering (priv->jbuf, FALSE);
priv->active = TRUE;
priv->srcpad =
gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_src_template,
"src");
gst_pad_set_activatemode_function (priv->srcpad,
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_activate_mode));
gst_pad_set_query_function (priv->srcpad,
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_query));
gst_pad_set_event_function (priv->srcpad,
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_event));
priv->sinkpad =
gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_sink_template,
"sink");
gst_pad_set_chain_function (priv->sinkpad,
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_chain));
gst_pad_set_chain_list_function (priv->sinkpad,
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_chain_list));
gst_pad_set_event_function (priv->sinkpad,
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_event));
gst_pad_set_query_function (priv->sinkpad,
GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_query));
gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->srcpad);
gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->sinkpad);
GST_OBJECT_FLAG_SET (jitterbuffer, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
}
#define IS_DROPABLE(it) (((it)->type == ITEM_TYPE_BUFFER) || ((it)->type == ITEM_TYPE_LOST))
#define ITEM_TYPE_BUFFER 0
#define ITEM_TYPE_LOST 1
#define ITEM_TYPE_EVENT 2
#define ITEM_TYPE_QUERY 3
static RTPJitterBufferItem *
alloc_item (gpointer data, guint type, GstClockTime dts, GstClockTime pts,
guint seqnum, guint count, guint rtptime)
{
RTPJitterBufferItem *item;
item = g_slice_new (RTPJitterBufferItem);
item->data = data;
item->next = NULL;
item->prev = NULL;
item->type = type;
item->dts = dts;
item->pts = pts;
item->seqnum = seqnum;
item->count = count;
item->rtptime = rtptime;
return item;
}
static void
free_item (RTPJitterBufferItem * item)
{
g_return_if_fail (item != NULL);
if (item->data && item->type != ITEM_TYPE_QUERY)
gst_mini_object_unref (item->data);
g_slice_free (RTPJitterBufferItem, item);
}
static void
free_item_and_retain_events (RTPJitterBufferItem * item, gpointer user_data)
{
GList **l = user_data;
if (item->data && item->type == ITEM_TYPE_EVENT
&& GST_EVENT_IS_STICKY (item->data)) {
*l = g_list_prepend (*l, item->data);
} else if (item->data && item->type != ITEM_TYPE_QUERY) {
gst_mini_object_unref (item->data);
}
g_slice_free (RTPJitterBufferItem, item);
}
static void
gst_rtp_jitter_buffer_finalize (GObject * object)
{
GstRtpJitterBuffer *jitterbuffer;
GstRtpJitterBufferPrivate *priv;
jitterbuffer = GST_RTP_JITTER_BUFFER (object);
priv = jitterbuffer->priv;
g_array_free (priv->timers, TRUE);
timer_queue_free (priv->rtx_stats_timers);
g_mutex_clear (&priv->jbuf_lock);
g_cond_clear (&priv->jbuf_timer);
g_cond_clear (&priv->jbuf_event);
g_cond_clear (&priv->jbuf_query);
rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
g_queue_clear (&priv->gap_packets);
g_object_unref (priv->jbuf);
G_OBJECT_CLASS (parent_class)->finalize (object);
}
static GstIterator *
gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad, GstObject * parent)
{
GstRtpJitterBuffer *jitterbuffer;
GstPad *otherpad = NULL;
GstIterator *it = NULL;
GValue val = { 0, };
jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
if (pad == jitterbuffer->priv->sinkpad) {
otherpad = jitterbuffer->priv->srcpad;
} else if (pad == jitterbuffer->priv->srcpad) {
otherpad = jitterbuffer->priv->sinkpad;
} else if (pad == jitterbuffer->priv->rtcpsinkpad) {
it = gst_iterator_new_single (GST_TYPE_PAD, NULL);
}
if (it == NULL) {
g_value_init (&val, GST_TYPE_PAD);
g_value_set_object (&val, otherpad);
it = gst_iterator_new_single (GST_TYPE_PAD, &val);
g_value_unset (&val);
}
return it;
}
static GstPad *
create_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
{
GstRtpJitterBufferPrivate *priv;
priv = jitterbuffer->priv;
GST_DEBUG_OBJECT (jitterbuffer, "creating RTCP sink pad");
priv->rtcpsinkpad =
gst_pad_new_from_static_template
(&gst_rtp_jitter_buffer_sink_rtcp_template, "sink_rtcp");
gst_pad_set_chain_function (priv->rtcpsinkpad,
gst_rtp_jitter_buffer_chain_rtcp);
gst_pad_set_event_function (priv->rtcpsinkpad,
(GstPadEventFunction) gst_rtp_jitter_buffer_sink_rtcp_event);
gst_pad_set_iterate_internal_links_function (priv->rtcpsinkpad,
gst_rtp_jitter_buffer_iterate_internal_links);
gst_pad_set_active (priv->rtcpsinkpad, TRUE);
gst_element_add_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
return priv->rtcpsinkpad;
}
static void
remove_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
{
GstRtpJitterBufferPrivate *priv;
priv = jitterbuffer->priv;
GST_DEBUG_OBJECT (jitterbuffer, "removing RTCP sink pad");
gst_pad_set_active (priv->rtcpsinkpad, FALSE);
gst_element_remove_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
priv->rtcpsinkpad = NULL;
}
static GstPad *
gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
GstPadTemplate * templ, const gchar * name, const GstCaps * filter)
{
GstRtpJitterBuffer *jitterbuffer;
GstElementClass *klass;
GstPad *result;
GstRtpJitterBufferPrivate *priv;
g_return_val_if_fail (templ != NULL, NULL);
g_return_val_if_fail (GST_IS_RTP_JITTER_BUFFER (element), NULL);
jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (element);
priv = jitterbuffer->priv;
klass = GST_ELEMENT_GET_CLASS (element);
GST_DEBUG_OBJECT (element, "requesting pad %s", GST_STR_NULL (name));
/* figure out the template */
if (templ == gst_element_class_get_pad_template (klass, "sink_rtcp")) {
if (priv->rtcpsinkpad != NULL)
goto exists;
result = create_rtcp_sink (jitterbuffer);
} else
goto wrong_template;
return result;
/* ERRORS */
wrong_template:
{
g_warning ("rtpjitterbuffer: this is not our template");
return NULL;
}
exists:
{
g_warning ("rtpjitterbuffer: pad already requested");
return NULL;
}
}
static void
gst_rtp_jitter_buffer_release_pad (GstElement * element, GstPad * pad)
{
GstRtpJitterBuffer *jitterbuffer;
GstRtpJitterBufferPrivate *priv;
g_return_if_fail (GST_IS_RTP_JITTER_BUFFER (element));
g_return_if_fail (GST_IS_PAD (pad));
jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (element);
priv = jitterbuffer->priv;
GST_DEBUG_OBJECT (element, "releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
if (priv->rtcpsinkpad == pad) {
remove_rtcp_sink (jitterbuffer);
} else
goto wrong_pad;
return;
/* ERRORS */
wrong_pad:
{
g_warning ("gstjitterbuffer: asked to release an unknown pad");
return;
}
}
static GstClock *
gst_rtp_jitter_buffer_provide_clock (GstElement * element)
{
return gst_system_clock_obtain ();
}
static gboolean
gst_rtp_jitter_buffer_set_clock (GstElement * element, GstClock * clock)
{
GstRtpJitterBuffer *jitterbuffer = GST_RTP_JITTER_BUFFER (element);
rtp_jitter_buffer_set_pipeline_clock (jitterbuffer->priv->jbuf, clock);
return GST_ELEMENT_CLASS (parent_class)->set_clock (element, clock);
}
static void
gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer)
{
GstRtpJitterBufferPrivate *priv;
priv = jitterbuffer->priv;
/* this will trigger a new pt-map request signal, FIXME, do something better. */
JBUF_LOCK (priv);
priv->clock_rate = -1;
/* do not clear current content, but refresh state for new arrival */
GST_DEBUG_OBJECT (jitterbuffer, "reset jitterbuffer");
rtp_jitter_buffer_reset_skew (priv->jbuf);
JBUF_UNLOCK (priv);
}
static GstClockTime
gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jbuf, gboolean active,
guint64 offset)
{
GstRtpJitterBufferPrivate *priv;
GstClockTime last_out;
RTPJitterBufferItem *item;
priv = jbuf->priv;
JBUF_LOCK (priv);
GST_DEBUG_OBJECT (jbuf, "setting active %d with offset %" GST_TIME_FORMAT,
active, GST_TIME_ARGS (offset));
if (active != priv->active) {
/* add the amount of time spent in paused to the output offset. All
* outgoing buffers will have this offset applied to their timestamps in
* order to make them arrive in time in the sink. */
priv->out_offset = offset;
GST_DEBUG_OBJECT (jbuf, "out offset %" GST_TIME_FORMAT,
GST_TIME_ARGS (priv->out_offset));
priv->active = active;
JBUF_SIGNAL_EVENT (priv);
}
if (!active) {
rtp_jitter_buffer_set_buffering (priv->jbuf, TRUE);
}
if ((item = rtp_jitter_buffer_peek (priv->jbuf))) {
/* head buffer timestamp and offset gives our output time */
last_out = item->pts + priv->ts_offset;
} else {
/* use last known time when the buffer is empty */
last_out = priv->last_out_time;
}
JBUF_UNLOCK (priv);
return last_out;
}
static GstCaps *
gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter)
{
GstRtpJitterBuffer *jitterbuffer;
GstRtpJitterBufferPrivate *priv;
GstPad *other;
GstCaps *caps;
GstCaps *templ;
jitterbuffer = GST_RTP_JITTER_BUFFER (gst_pad_get_parent (pad));
priv = jitterbuffer->priv;
other = (pad == priv->srcpad ? priv->sinkpad : priv->srcpad);
caps = gst_pad_peer_query_caps (other, filter);
templ = gst_pad_get_pad_template_caps (pad);
if (caps == NULL) {
GST_DEBUG_OBJECT (jitterbuffer, "use template");
caps = templ;
} else {
GstCaps *intersect;
GST_DEBUG_OBJECT (jitterbuffer, "intersect with template");
intersect = gst_caps_intersect (caps, templ);
gst_caps_unref (caps);
gst_caps_unref (templ);
caps = intersect;
}
gst_object_unref (jitterbuffer);
return caps;
}
/*
* Must be called with JBUF_LOCK held
*/
static gboolean
gst_jitter_buffer_sink_parse_caps (GstRtpJitterBuffer * jitterbuffer,
GstCaps * caps, gint pt)
{
GstRtpJitterBufferPrivate *priv;
GstStructure *caps_struct;
guint val;
gint payload = -1;
GstClockTime tval;
const gchar *ts_refclk, *mediaclk;
priv = jitterbuffer->priv;
/* first parse the caps */
caps_struct = gst_caps_get_structure (caps, 0);
GST_DEBUG_OBJECT (jitterbuffer, "got caps %" GST_PTR_FORMAT, caps);
if (gst_structure_get_int (caps_struct, "payload", &payload) && pt != -1
&& payload != pt) {
GST_ERROR_OBJECT (jitterbuffer,
"Got caps with wrong payload type (got %d, expected %d)", pt, payload);
return FALSE;
}
if (payload != -1) {
GST_DEBUG_OBJECT (jitterbuffer, "Got payload type %d", payload);
priv->last_pt = payload;
}
/* we need a clock-rate to convert the rtp timestamps to GStreamer time and to
* measure the amount of data in the buffer */
if (!gst_structure_get_int (caps_struct, "clock-rate", &priv->clock_rate))
goto error;
if (priv->clock_rate <= 0)
goto wrong_rate;
GST_DEBUG_OBJECT (jitterbuffer, "got clock-rate %d", priv->clock_rate);
rtp_jitter_buffer_set_clock_rate (priv->jbuf, priv->clock_rate);
gst_rtp_packet_rate_ctx_reset (&priv->packet_rate_ctx, priv->clock_rate);
/* The clock base is the RTP timestamp corrsponding to the npt-start value. We
* can use this to track the amount of time elapsed on the sender. */
if (gst_structure_get_uint (caps_struct, "clock-base", &val))
priv->clock_base = val;
else
priv->clock_base = -1;
priv->ext_timestamp = priv->clock_base;
GST_DEBUG_OBJECT (jitterbuffer, "got clock-base %" G_GINT64_FORMAT,
priv->clock_base);
if (gst_structure_get_uint (caps_struct, "seqnum-base", &val)) {
/* first expected seqnum, only update when we didn't have a previous base. */
if (priv->next_in_seqnum == -1)
priv->next_in_seqnum = val;
if (priv->next_seqnum == -1) {
priv->next_seqnum = val;
JBUF_SIGNAL_EVENT (priv);
}
priv->seqnum_base = val;
} else {
priv->seqnum_base = -1;
}
GST_DEBUG_OBJECT (jitterbuffer, "got seqnum-base %d", priv->next_in_seqnum);
/* the start and stop times. The seqnum-base corresponds to the start time. We
* will keep track of the seqnums on the output and when we reach the one
* corresponding to npt-stop, we emit the npt-stop-reached signal */
if (gst_structure_get_clock_time (caps_struct, "npt-start", &tval))
priv->npt_start = tval;
else
priv->npt_start = 0;
if (gst_structure_get_clock_time (caps_struct, "npt-stop", &tval))
priv->npt_stop = tval;
else
priv->npt_stop = -1;
GST_DEBUG_OBJECT (jitterbuffer,
"npt start/stop: %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
GST_TIME_ARGS (priv->npt_start), GST_TIME_ARGS (priv->npt_stop));
if ((ts_refclk = gst_structure_get_string (caps_struct, "a-ts-refclk"))) {
GstClock *clock = NULL;
guint64 clock_offset = -1;
GST_DEBUG_OBJECT (jitterbuffer, "Have timestamp reference clock %s",
ts_refclk);
if (g_str_has_prefix (ts_refclk, "ntp=")) {
if (g_str_has_prefix (ts_refclk, "ntp=/traceable/")) {
GST_FIXME_OBJECT (jitterbuffer, "Can't handle traceable NTP clocks");
} else {
const gchar *host, *portstr;
gchar *hostname;
guint port;
host = ts_refclk + sizeof ("ntp=") - 1;
if (host[0] == '[') {
/* IPv6 */
portstr = strchr (host, ']');
if (portstr && portstr[1] == ':')
portstr = portstr + 1;
else
portstr = NULL;
} else {
portstr = strrchr (host, ':');
}
if (!portstr || sscanf (portstr, ":%u", &port) != 1)
port = 123;
if (portstr)
hostname = g_strndup (host, (portstr - host));
else
hostname = g_strdup (host);
clock = gst_ntp_clock_new (NULL, hostname, port, 0);
g_free (hostname);
}
} else if (g_str_has_prefix (ts_refclk, "ptp=IEEE1588-2008:")) {
const gchar *domainstr =
ts_refclk + sizeof ("ptp=IEEE1588-2008:XX-XX-XX-XX-XX-XX-XX-XX") - 1;
guint domain;
if (domainstr[0] != ':' || sscanf (domainstr, ":%u", &domain) != 1)
domain = 0;
clock = gst_ptp_clock_new (NULL, domain);
} else {
GST_FIXME_OBJECT (jitterbuffer, "Unsupported timestamp reference clock");
}
if ((mediaclk = gst_structure_get_string (caps_struct, "a-mediaclk"))) {
GST_DEBUG_OBJECT (jitterbuffer, "Got media clock %s", mediaclk);
if (!g_str_has_prefix (mediaclk, "direct=")
|| sscanf (mediaclk, "direct=%" G_GUINT64_FORMAT, &clock_offset) != 1)
GST_FIXME_OBJECT (jitterbuffer, "Unsupported media clock");
if (strstr (mediaclk, "rate=") != NULL) {
GST_FIXME_OBJECT (jitterbuffer, "Rate property not supported");
clock_offset = -1;
}
}
rtp_jitter_buffer_set_media_clock (priv->jbuf, clock, clock_offset);
} else {
rtp_jitter_buffer_set_media_clock (priv->jbuf, NULL, -1);
}
return TRUE;
/* ERRORS */
error:
{
GST_DEBUG_OBJECT (jitterbuffer, "No clock-rate in caps!");
return FALSE;
}
wrong_rate:
{
GST_DEBUG_OBJECT (jitterbuffer, "Invalid clock-rate %d", priv->clock_rate);
return FALSE;
}
}
static void
gst_rtp_jitter_buffer_flush_start (GstRtpJitterBuffer * jitterbuffer)
{
GstRtpJitterBufferPrivate *priv;
priv = jitterbuffer->priv;
JBUF_LOCK (priv);
/* mark ourselves as flushing */
priv->srcresult = GST_FLOW_FLUSHING;
GST_DEBUG_OBJECT (jitterbuffer, "Disabling pop on queue");
/* this unblocks any waiting pops on the src pad task */
JBUF_SIGNAL_EVENT (priv);
JBUF_SIGNAL_QUERY (priv, FALSE);
JBUF_UNLOCK (priv);
}
static void
gst_rtp_jitter_buffer_flush_stop (GstRtpJitterBuffer * jitterbuffer)
{
GstRtpJitterBufferPrivate *priv;
priv = jitterbuffer->priv;
JBUF_LOCK (priv);
GST_DEBUG_OBJECT (jitterbuffer, "Enabling pop on queue");
/* Mark as non flushing */
priv->srcresult = GST_FLOW_OK;
gst_segment_init (&priv->segment, GST_FORMAT_TIME);
priv->last_popped_seqnum = -1;
priv->last_out_time = GST_CLOCK_TIME_NONE;
priv->next_seqnum = -1;
priv->seqnum_base = -1;
priv->ips_rtptime = -1;
priv->ips_pts = GST_CLOCK_TIME_NONE;
priv->packet_spacing = 0;
priv->next_in_seqnum = -1;
priv->clock_rate = -1;
priv->last_pt = -1;
priv->eos = FALSE;
priv->estimated_eos = -1;
priv->last_elapsed = 0;
priv->ext_timestamp = -1;
priv->avg_jitter = 0;
priv->last_dts = -1;
priv->last_rtptime = -1;
priv->last_in_pts = 0;
priv->equidistant = 0;
GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
rtp_jitter_buffer_disable_buffering (priv->jbuf, FALSE);
rtp_jitter_buffer_reset_skew (priv->jbuf);
remove_all_timers (jitterbuffer);
g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
g_queue_clear (&priv->gap_packets);
JBUF_UNLOCK (priv);
}
static gboolean
gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad, GstObject * parent,
GstPadMode mode, gboolean active)
{
gboolean result;
GstRtpJitterBuffer *jitterbuffer = NULL;
jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
switch (mode) {
case GST_PAD_MODE_PUSH:
if (active) {
/* allow data processing */
gst_rtp_jitter_buffer_flush_stop (jitterbuffer);
/* start pushing out buffers */
GST_DEBUG_OBJECT (jitterbuffer, "Starting task on srcpad");
result = gst_pad_start_task (jitterbuffer->priv->srcpad,
(GstTaskFunction) gst_rtp_jitter_buffer_loop, jitterbuffer, NULL);
} else {
/* make sure all data processing stops ASAP */
gst_rtp_jitter_buffer_flush_start (jitterbuffer);
/* NOTE this will hardlock if the state change is called from the src pad
* task thread because we will _join() the thread. */
GST_DEBUG_OBJECT (jitterbuffer, "Stopping task on srcpad");
result = gst_pad_stop_task (pad);
}
break;
default:
result = FALSE;
break;
}
return result;
}
static GstStateChangeReturn
gst_rtp_jitter_buffer_change_state (GstElement * element,
GstStateChange transition)
{
GstRtpJitterBuffer *jitterbuffer;
GstRtpJitterBufferPrivate *priv;
GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
jitterbuffer = GST_RTP_JITTER_BUFFER (element);
priv = jitterbuffer->priv;
switch (transition) {
case GST_STATE_CHANGE_NULL_TO_READY:
break;
case GST_STATE_CHANGE_READY_TO_PAUSED:
JBUF_LOCK (priv);
/* reset negotiated values */
priv->clock_rate = -1;
priv->clock_base = -1;
priv->peer_latency = 0;
priv->last_pt = -1;
/* block until we go to PLAYING */
priv->blocked = TRUE;
priv->timer_running = TRUE;
priv->timer_thread =
g_thread_new ("timer", (GThreadFunc) wait_next_timeout, jitterbuffer);
JBUF_UNLOCK (priv);
break;
case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
JBUF_LOCK (priv);
/* unblock to allow streaming in PLAYING */
priv->blocked = FALSE;
JBUF_SIGNAL_EVENT (priv);
JBUF_SIGNAL_TIMER (priv);
JBUF_UNLOCK (priv);
break;
default:
break;
}
ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
switch (transition) {
case GST_STATE_CHANGE_READY_TO_PAUSED:
/* we are a live element because we sync to the clock, which we can only
* do in the PLAYING state */
if (ret != GST_STATE_CHANGE_FAILURE)
ret = GST_STATE_CHANGE_NO_PREROLL;
break;
case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
JBUF_LOCK (priv);
/* block to stop streaming when PAUSED */
priv->blocked = TRUE;
unschedule_current_timer (jitterbuffer);
JBUF_UNLOCK (priv);
if (ret != GST_STATE_CHANGE_FAILURE)
ret = GST_STATE_CHANGE_NO_PREROLL;
break;
case GST_STATE_CHANGE_PAUSED_TO_READY:
JBUF_LOCK (priv);
gst_buffer_replace (&priv->last_sr, NULL);
priv->timer_running = FALSE;
unschedule_current_timer (jitterbuffer);
JBUF_SIGNAL_TIMER (priv);
JBUF_SIGNAL_QUERY (priv, FALSE);
JBUF_UNLOCK (priv);
g_thread_join (priv->timer_thread);
priv->timer_thread = NULL;
break;
case GST_STATE_CHANGE_READY_TO_NULL:
break;
default:
break;
}
return ret;
}
static gboolean
gst_rtp_jitter_buffer_src_event (GstPad * pad, GstObject * parent,
GstEvent * event)
{
gboolean ret = TRUE;
GstRtpJitterBuffer *jitterbuffer;
GstRtpJitterBufferPrivate *priv;
jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
priv = jitterbuffer->priv;
GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
switch (GST_EVENT_TYPE (event)) {
case GST_EVENT_LATENCY:
{
GstClockTime latency;
gst_event_parse_latency (event, &latency);
GST_DEBUG_OBJECT (jitterbuffer,
"configuring latency of %" GST_TIME_FORMAT, GST_TIME_ARGS (latency));
JBUF_LOCK (priv);
/* adjust the overall buffer delay to the total pipeline latency in
* buffering mode because if downstream consumes too fast (because of
* large latency or queues, we would start rebuffering again. */
if (rtp_jitter_buffer_get_mode (priv->jbuf) ==
RTP_JITTER_BUFFER_MODE_BUFFER) {
rtp_jitter_buffer_set_delay (priv->jbuf, latency);
}
JBUF_UNLOCK (priv);
ret = gst_pad_push_event (priv->sinkpad, event);
break;
}
default:
ret = gst_pad_push_event (priv->sinkpad, event);
break;
}
return ret;
}
/* handles and stores the event in the jitterbuffer, must be called with
* LOCK */
static gboolean
queue_event (GstRtpJitterBuffer * jitterbuffer, GstEvent * event)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
RTPJitterBufferItem *item;
gboolean head;
switch (GST_EVENT_TYPE (event)) {
case GST_EVENT_CAPS:
{
GstCaps *caps;
gst_event_parse_caps (event, &caps);
gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps, -1);
break;
}
case GST_EVENT_SEGMENT:
{
GstSegment segment;
gst_event_copy_segment (event, &segment);
/* we need time for now */
if (segment.format != GST_FORMAT_TIME) {
GST_DEBUG_OBJECT (jitterbuffer, "ignoring non-TIME newsegment");
gst_event_unref (event);
gst_segment_init (&segment, GST_FORMAT_TIME);
event = gst_event_new_segment (&segment);
}
priv->segment = segment;
break;
}
case GST_EVENT_EOS:
priv->eos = TRUE;
rtp_jitter_buffer_disable_buffering (priv->jbuf, TRUE);
break;
default:
break;
}
GST_DEBUG_OBJECT (jitterbuffer, "adding event");
item = alloc_item (event, ITEM_TYPE_EVENT, -1, -1, -1, 0, -1);
rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
if (head)
JBUF_SIGNAL_EVENT (priv);
return TRUE;
}
static gboolean
gst_rtp_jitter_buffer_sink_event (GstPad * pad, GstObject * parent,
GstEvent * event)
{
gboolean ret = TRUE;
GstRtpJitterBuffer *jitterbuffer;
GstRtpJitterBufferPrivate *priv;
jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
priv = jitterbuffer->priv;
GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
switch (GST_EVENT_TYPE (event)) {
case GST_EVENT_FLUSH_START:
ret = gst_pad_push_event (priv->srcpad, event);
gst_rtp_jitter_buffer_flush_start (jitterbuffer);
/* wait for the loop to go into PAUSED */
gst_pad_pause_task (priv->srcpad);
break;
case GST_EVENT_FLUSH_STOP:
ret = gst_pad_push_event (priv->srcpad, event);
ret =
gst_rtp_jitter_buffer_src_activate_mode (priv->srcpad, parent,
GST_PAD_MODE_PUSH, TRUE);
break;
default:
if (GST_EVENT_IS_SERIALIZED (event)) {
/* serialized events go in the queue */
JBUF_LOCK (priv);
if (priv->srcresult != GST_FLOW_OK) {
/* Errors in sticky event pushing are no problem and ignored here
* as they will cause more meaningful errors during data flow.
* For EOS events, that are not followed by data flow, we still
* return FALSE here though.
*/
if (!GST_EVENT_IS_STICKY (event) ||
GST_EVENT_TYPE (event) == GST_EVENT_EOS)
goto out_flow_error;
}
/* refuse more events on EOS */
if (priv->eos)
goto out_eos;
ret = queue_event (jitterbuffer, event);
JBUF_UNLOCK (priv);
} else {
/* non-serialized events are forwarded downstream immediately */
ret = gst_pad_push_event (priv->srcpad, event);
}
break;
}
return ret;
/* ERRORS */
out_flow_error:
{
GST_DEBUG_OBJECT (jitterbuffer,
"refusing event, we have a downstream flow error: %s",
gst_flow_get_name (priv->srcresult));
JBUF_UNLOCK (priv);
gst_event_unref (event);
return FALSE;
}
out_eos:
{
GST_DEBUG_OBJECT (jitterbuffer, "refusing event, we are EOS");
JBUF_UNLOCK (priv);
gst_event_unref (event);
return FALSE;
}
}
static gboolean
gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad, GstObject * parent,
GstEvent * event)
{
gboolean ret = TRUE;
GstRtpJitterBuffer *jitterbuffer;
jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
switch (GST_EVENT_TYPE (event)) {
case GST_EVENT_FLUSH_START:
gst_event_unref (event);
break;
case GST_EVENT_FLUSH_STOP:
gst_event_unref (event);
break;
default:
ret = gst_pad_event_default (pad, parent, event);
break;
}
return ret;
}
/*
* Must be called with JBUF_LOCK held, will release the LOCK when emiting the
* signal. The function returns GST_FLOW_ERROR when a parsing error happened and
* GST_FLOW_FLUSHING when the element is shutting down. On success
* GST_FLOW_OK is returned.
*/
static GstFlowReturn
gst_rtp_jitter_buffer_get_clock_rate (GstRtpJitterBuffer * jitterbuffer,
guint8 pt)
{
GValue ret = { 0 };
GValue args[2] = { {0}, {0} };
GstCaps *caps;
gboolean res;
g_value_init (&args[0], GST_TYPE_ELEMENT);
g_value_set_object (&args[0], jitterbuffer);
g_value_init (&args[1], G_TYPE_UINT);
g_value_set_uint (&args[1], pt);
g_value_init (&ret, GST_TYPE_CAPS);
g_value_set_boxed (&ret, NULL);
JBUF_UNLOCK (jitterbuffer->priv);
g_signal_emitv (args, gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP], 0,
&ret);
JBUF_LOCK_CHECK (jitterbuffer->priv, out_flushing);
g_value_unset (&args[0]);
g_value_unset (&args[1]);
caps = (GstCaps *) g_value_dup_boxed (&ret);
g_value_unset (&ret);
if (!caps)
goto no_caps;
res = gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps, pt);
gst_caps_unref (caps);
if (G_UNLIKELY (!res))
goto parse_failed;
return GST_FLOW_OK;
/* ERRORS */
no_caps:
{
GST_DEBUG_OBJECT (jitterbuffer, "could not get caps");
return GST_FLOW_ERROR;
}
out_flushing:
{
GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
return GST_FLOW_FLUSHING;
}
parse_failed:
{
GST_DEBUG_OBJECT (jitterbuffer, "parse failed");
return GST_FLOW_ERROR;
}
}
/* call with jbuf lock held */
static GstMessage *
check_buffering_percent (GstRtpJitterBuffer * jitterbuffer, gint percent)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
GstMessage *message = NULL;
if (percent == -1)
return NULL;
/* Post a buffering message */
if (priv->last_percent != percent) {
priv->last_percent = percent;
message =
gst_message_new_buffering (GST_OBJECT_CAST (jitterbuffer), percent);
gst_message_set_buffering_stats (message, GST_BUFFERING_LIVE, -1, -1, -1);
}
return message;
}
static void
update_offset (GstRtpJitterBuffer * jitterbuffer)
{
GstRtpJitterBufferPrivate *priv;
priv = jitterbuffer->priv;
if (priv->ts_offset_remainder != 0) {
GST_DEBUG ("adjustment %" G_GUINT64_FORMAT " remain %" G_GINT64_FORMAT
" off %" G_GINT64_FORMAT, priv->max_ts_offset_adjustment,
priv->ts_offset_remainder, priv->ts_offset);
if (ABS (priv->ts_offset_remainder) > priv->max_ts_offset_adjustment) {
if (priv->ts_offset_remainder > 0) {
priv->ts_offset += priv->max_ts_offset_adjustment;
priv->ts_offset_remainder -= priv->max_ts_offset_adjustment;
} else {
priv->ts_offset -= priv->max_ts_offset_adjustment;
priv->ts_offset_remainder += priv->max_ts_offset_adjustment;
}
} else {
priv->ts_offset += priv->ts_offset_remainder;
priv->ts_offset_remainder = 0;
}
}
}
static GstClockTime
apply_offset (GstRtpJitterBuffer * jitterbuffer, GstClockTime timestamp)
{
GstRtpJitterBufferPrivate *priv;
priv = jitterbuffer->priv;
if (timestamp == -1)
return -1;
/* apply the timestamp offset, this is used for inter stream sync */
timestamp += priv->ts_offset;
/* add the offset, this is used when buffering */
timestamp += priv->out_offset;
return timestamp;
}
static TimerQueue *
timer_queue_new (void)
{
TimerQueue *queue;
queue = g_slice_new (TimerQueue);
queue->timers = g_queue_new ();
queue->hashtable = g_hash_table_new (NULL, NULL);
return queue;
}
static void
timer_queue_free (TimerQueue * queue)
{
if (!queue)
return;
g_hash_table_destroy (queue->hashtable);
g_queue_free_full (queue->timers, g_free);
g_slice_free (TimerQueue, queue);
}
static void
timer_queue_append (TimerQueue * queue, const TimerData * timer,
GstClockTime timeout, gboolean lost)
{
TimerData *copy;
copy = g_memdup (timer, sizeof (*timer));
copy->timeout = timeout;
copy->type = lost ? TIMER_TYPE_LOST : TIMER_TYPE_EXPECTED;
copy->idx = -1;
GST_LOG ("Append rtx-stats timer #%d, %" GST_TIME_FORMAT,
copy->seqnum, GST_TIME_ARGS (copy->timeout));
g_queue_push_tail (queue->timers, copy);
g_hash_table_insert (queue->hashtable, GINT_TO_POINTER (copy->seqnum), copy);
}
static void
timer_queue_clear_until (TimerQueue * queue, GstClockTime timeout)
{
TimerData *test;
test = g_queue_peek_head (queue->timers);
while (test && test->timeout < timeout) {
GST_LOG ("Pop rtx-stats timer #%d, %" GST_TIME_FORMAT " < %"
GST_TIME_FORMAT, test->seqnum, GST_TIME_ARGS (test->timeout),
GST_TIME_ARGS (timeout));
g_hash_table_remove (queue->hashtable, GINT_TO_POINTER (test->seqnum));
g_free (g_queue_pop_head (queue->timers));
test = g_queue_peek_head (queue->timers);
}
}
static TimerData *
timer_queue_find (TimerQueue * queue, guint16 seqnum)
{
return g_hash_table_lookup (queue->hashtable, GINT_TO_POINTER (seqnum));
}
static TimerData *
find_timer (GstRtpJitterBuffer * jitterbuffer, guint16 seqnum)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
TimerData *timer = NULL;
gint i, len;
len = priv->timers->len;
for (i = 0; i < len; i++) {
TimerData *test = &g_array_index (priv->timers, TimerData, i);
if (test->seqnum == seqnum) {
timer = test;
break;
}
}
return timer;
}
static void
unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
if (priv->clock_id) {
GST_DEBUG_OBJECT (jitterbuffer, "unschedule current timer");
gst_clock_id_unschedule (priv->clock_id);
priv->clock_id = NULL;
}
}
static GstClockTime
get_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
GstClockTime test_timeout;
if ((test_timeout = timer->timeout) == -1)
return -1;
if (timer->type != TIMER_TYPE_EXPECTED) {
/* add our latency and offset to get output times. */
test_timeout = apply_offset (jitterbuffer, test_timeout);
test_timeout += priv->latency_ns;
}
return test_timeout;
}
static void
recalculate_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
if (priv->clock_id) {
GstClockTime timeout = get_timeout (jitterbuffer, timer);
GST_DEBUG ("%" GST_TIME_FORMAT " <> %" GST_TIME_FORMAT,
GST_TIME_ARGS (timeout), GST_TIME_ARGS (priv->timer_timeout));
if (timeout == -1 || timeout < priv->timer_timeout)
unschedule_current_timer (jitterbuffer);
}
}
static TimerData *
add_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
guint16 seqnum, guint num, GstClockTime timeout, GstClockTime delay,
GstClockTime duration)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
TimerData *timer;
gint len;
GST_DEBUG_OBJECT (jitterbuffer,
"add timer %d for seqnum %d to %" GST_TIME_FORMAT ", delay %"
GST_TIME_FORMAT, type, seqnum, GST_TIME_ARGS (timeout),
GST_TIME_ARGS (delay));
len = priv->timers->len;
g_array_set_size (priv->timers, len + 1);
timer = &g_array_index (priv->timers, TimerData, len);
timer->idx = len;
timer->type = type;
timer->seqnum = seqnum;
timer->num = num;
timer->timeout = timeout + delay;
timer->duration = duration;
if (type == TIMER_TYPE_EXPECTED) {
timer->rtx_base = timeout;
timer->rtx_delay = delay;
timer->rtx_retry = 0;
}
timer->rtx_last = GST_CLOCK_TIME_NONE;
timer->num_rtx_retry = 0;
timer->num_rtx_received = 0;
recalculate_timer (jitterbuffer, timer);
JBUF_SIGNAL_TIMER (priv);
return timer;
}
static void
reschedule_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
guint16 seqnum, GstClockTime timeout, GstClockTime delay, gboolean reset)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
gboolean seqchange, timechange;
guint16 oldseq;
GstClockTime new_timeout;
oldseq = timer->seqnum;
new_timeout = timeout + delay;
seqchange = oldseq != seqnum;
timechange = timer->timeout != new_timeout;
if (!seqchange && !timechange) {
GST_DEBUG_OBJECT (jitterbuffer,
"No changes in seqnum (%d) and timeout (%" GST_TIME_FORMAT
"), skipping", oldseq, GST_TIME_ARGS (timer->timeout));
return;
}
GST_DEBUG_OBJECT (jitterbuffer,
"replace timer %d for seqnum %d->%d timeout %" GST_TIME_FORMAT
"->%" GST_TIME_FORMAT, timer->type, oldseq, seqnum,
GST_TIME_ARGS (timer->timeout), GST_TIME_ARGS (new_timeout));
timer->timeout = new_timeout;
timer->seqnum = seqnum;
if (reset) {
GST_DEBUG_OBJECT (jitterbuffer, "reset rtx delay %" GST_TIME_FORMAT
"->%" GST_TIME_FORMAT, GST_TIME_ARGS (timer->rtx_delay),
GST_TIME_ARGS (delay));
timer->rtx_base = timeout;
timer->rtx_delay = delay;
timer->rtx_retry = 0;
}
if (seqchange) {
timer->num_rtx_retry = 0;
timer->num_rtx_received = 0;
}
if (priv->clock_id) {
/* we changed the seqnum and there is a timer currently waiting with this
* seqnum, unschedule it */
if (seqchange && priv->timer_seqnum == oldseq)
unschedule_current_timer (jitterbuffer);
/* we changed the time, check if it is earlier than what we are waiting
* for and unschedule if so */
else if (timechange)
recalculate_timer (jitterbuffer, timer);
}
}
static TimerData *
set_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
guint16 seqnum, GstClockTime timeout)
{
TimerData *timer;
/* find the seqnum timer */
timer = find_timer (jitterbuffer, seqnum);
if (timer == NULL) {
timer = add_timer (jitterbuffer, type, seqnum, 0, timeout, 0, -1);
} else {
reschedule_timer (jitterbuffer, timer, seqnum, timeout, 0, FALSE);
}
return timer;
}
static void
remove_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
guint idx;
if (timer->idx == -1)
return;
if (priv->clock_id && priv->timer_seqnum == timer->seqnum)
unschedule_current_timer (jitterbuffer);
idx = timer->idx;
GST_DEBUG_OBJECT (jitterbuffer, "removed index %d", idx);
g_array_remove_index_fast (priv->timers, idx);
timer->idx = idx;
}
static void
remove_all_timers (GstRtpJitterBuffer * jitterbuffer)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
GST_DEBUG_OBJECT (jitterbuffer, "removed all timers");
g_array_set_size (priv->timers, 0);
unschedule_current_timer (jitterbuffer);
}
/* get the extra delay to wait before sending RTX */
static GstClockTime
get_rtx_delay (GstRtpJitterBufferPrivate * priv)
{
GstClockTime delay;
if (priv->rtx_delay == -1) {
if (priv->avg_jitter == 0 && priv->packet_spacing == 0) {
delay = DEFAULT_AUTO_RTX_DELAY;
} else {
/* jitter is in nanoseconds, maximum of 2x jitter and half the
* packet spacing is a good margin */
delay = MAX (priv->avg_jitter * 2, priv->packet_spacing / 2);
}
} else {
delay = priv->rtx_delay * GST_MSECOND;
}
if (priv->rtx_min_delay > 0)
delay = MAX (delay, priv->rtx_min_delay * GST_MSECOND);
return delay;
}
/* Check if packet with seqnum is already considered definitely lost by being
* part of a "lost timer" for multiple packets */
static gboolean
already_lost (GstRtpJitterBuffer * jitterbuffer, guint16 seqnum)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
gint i, len;
len = priv->timers->len;
for (i = 0; i < len; i++) {
TimerData *test = &g_array_index (priv->timers, TimerData, i);
gint gap = gst_rtp_buffer_compare_seqnum (test->seqnum, seqnum);
if (test->num > 1 && test->type == TIMER_TYPE_LOST && gap >= 0 &&
gap < test->num) {
GST_DEBUG ("seqnum #%d already considered definitely lost (#%d->#%d)",
seqnum, test->seqnum, (test->seqnum + test->num - 1) & 0xffff);
return TRUE;
}
}
return FALSE;
}
/* we just received a packet with seqnum and dts.
*
* First check for old seqnum that we are still expecting. If the gap with the
* current seqnum is too big, unschedule the timeouts.
*
* If we have a valid packet spacing estimate we can set a timer for when we
* should receive the next packet.
* If we don't have a valid estimate, we remove any timer we might have
* had for this packet.
*/
static void
update_timers (GstRtpJitterBuffer * jitterbuffer, guint16 seqnum,
GstClockTime dts, GstClockTime pts, gboolean do_next_seqnum,
gboolean is_rtx, TimerData * timer)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
/* go through all timers and unschedule the ones with a large gap */
if (priv->do_retransmission && priv->rtx_delay_reorder > 0) {
gint i, len;
len = priv->timers->len;
for (i = 0; i < len; i++) {
TimerData *test = &g_array_index (priv->timers, TimerData, i);
gint gap;
gap = gst_rtp_buffer_compare_seqnum (test->seqnum, seqnum);
GST_DEBUG_OBJECT (jitterbuffer, "%d, #%d<->#%d gap %d",
test->type, test->seqnum, seqnum, gap);
if (gap > priv->rtx_delay_reorder) {
/* max gap, we exceeded the max reorder distance and we don't expect the
* missing packet to be this reordered */
if (test->num_rtx_retry == 0 && test->type == TIMER_TYPE_EXPECTED)
reschedule_timer (jitterbuffer, test, test->seqnum, -1, 0, FALSE);
}
}
}
do_next_seqnum = do_next_seqnum && priv->packet_spacing > 0
&& priv->do_retransmission && priv->rtx_next_seqnum;
if (timer && timer->type != TIMER_TYPE_DEADLINE) {
if (timer->num_rtx_retry > 0) {
if (is_rtx) {
update_rtx_stats (jitterbuffer, timer, dts, TRUE);
/* don't try to estimate the next seqnum because this is a retransmitted
* packet and it probably did not arrive with the expected packet
* spacing. */
do_next_seqnum = FALSE;
}
if (!is_rtx || timer->num_rtx_retry > 1) {
/* Store timer in order to record stats when/if the retransmitted
* packet arrives. We should also store timer information if we've
* requested retransmission more than once since we may receive
* several retransmitted packets. For accuracy we should update the
* stats also when the redundant retransmitted packets arrives. */
timer_queue_append (priv->rtx_stats_timers, timer,
pts + priv->rtx_stats_timeout * GST_MSECOND, FALSE);
}
}
}
if (do_next_seqnum && pts != GST_CLOCK_TIME_NONE) {
GstClockTime expected, delay;
/* calculate expected arrival time of the next seqnum */
expected = pts + priv->packet_spacing;
delay = get_rtx_delay (priv);
/* and update/install timer for next seqnum */
GST_DEBUG_OBJECT (jitterbuffer, "Add RTX timer #%d, expected %"
GST_TIME_FORMAT ", delay %" GST_TIME_FORMAT ", packet-spacing %"
GST_TIME_FORMAT ", jitter %" GST_TIME_FORMAT, priv->next_in_seqnum,
GST_TIME_ARGS (expected), GST_TIME_ARGS (delay),
GST_TIME_ARGS (priv->packet_spacing), GST_TIME_ARGS (priv->avg_jitter));
if (timer) {
timer->type = TIMER_TYPE_EXPECTED;
reschedule_timer (jitterbuffer, timer, priv->next_in_seqnum, expected,
delay, TRUE);
} else {
add_timer (jitterbuffer, TIMER_TYPE_EXPECTED, priv->next_in_seqnum, 0,
expected, delay, priv->packet_spacing);
}
} else if (timer && timer->type != TIMER_TYPE_DEADLINE) {
/* if we had a timer, remove it, we don't know when to expect the next
* packet. */
remove_timer (jitterbuffer, timer);
}
}
static void
calculate_packet_spacing (GstRtpJitterBuffer * jitterbuffer, guint32 rtptime,
GstClockTime pts)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
/* we need consecutive seqnums with a different
* rtptime to estimate the packet spacing. */
if (priv->ips_rtptime != rtptime) {
/* rtptime changed, check pts diff */
if (priv->ips_pts != -1 && pts != -1 && pts > priv->ips_pts) {
GstClockTime new_packet_spacing = pts - priv->ips_pts;
GstClockTime old_packet_spacing = priv->packet_spacing;
/* Biased towards bigger packet spacings to prevent
* too many unneeded retransmission requests for next
* packets that just arrive a little later than we would
* expect */
if (old_packet_spacing > new_packet_spacing)
priv->packet_spacing =
(new_packet_spacing + 3 * old_packet_spacing) / 4;
else if (old_packet_spacing > 0)
priv->packet_spacing =
(3 * new_packet_spacing + old_packet_spacing) / 4;
else
priv->packet_spacing = new_packet_spacing;
GST_DEBUG_OBJECT (jitterbuffer,
"new packet spacing %" GST_TIME_FORMAT
" old packet spacing %" GST_TIME_FORMAT
" combined to %" GST_TIME_FORMAT,
GST_TIME_ARGS (new_packet_spacing),
GST_TIME_ARGS (old_packet_spacing),
GST_TIME_ARGS (priv->packet_spacing));
}
priv->ips_rtptime = rtptime;
priv->ips_pts = pts;
}
}
static void
calculate_expected (GstRtpJitterBuffer * jitterbuffer, guint32 expected,
guint16 seqnum, GstClockTime pts, gint gap)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
GstClockTime duration, expected_pts, delay;
TimerType type;
gboolean equidistant = priv->equidistant > 0;
GST_DEBUG_OBJECT (jitterbuffer,
"pts %" GST_TIME_FORMAT ", last %" GST_TIME_FORMAT,
GST_TIME_ARGS (pts), GST_TIME_ARGS (priv->last_in_pts));
if (pts == GST_CLOCK_TIME_NONE) {
GST_WARNING_OBJECT (jitterbuffer, "Have no PTS");
return;
}
if (equidistant) {
GstClockTime total_duration;
/* the total duration spanned by the missing packets */
if (pts >= priv->last_in_pts)
total_duration = pts - priv->last_in_pts;
else
total_duration = 0;
/* interpolate between the current time and the last time based on
* number of packets we are missing, this is the estimated duration
* for the missing packet based on equidistant packet spacing. */
duration = total_duration / (gap + 1);
GST_DEBUG_OBJECT (jitterbuffer, "duration %" GST_TIME_FORMAT,
GST_TIME_ARGS (duration));
if (total_duration > priv->latency_ns) {
GstClockTime gap_time;
guint lost_packets;
if (duration > 0) {
GstClockTime gap_dur = gap * duration;
if (gap_dur > priv->latency_ns)
gap_time = gap_dur - priv->latency_ns;
else
gap_time = 0;
lost_packets = gap_time / duration;
} else {
gap_time = total_duration - priv->latency_ns;
lost_packets = gap;
}
/* too many lost packets, some of the missing packets are already
* too late and we can generate lost packet events for them. */
GST_INFO_OBJECT (jitterbuffer,
"lost packets (%d, #%d->#%d) duration too large %" GST_TIME_FORMAT
" > %" GST_TIME_FORMAT ", consider %u lost (%" GST_TIME_FORMAT ")",
gap, expected, seqnum - 1, GST_TIME_ARGS (total_duration),
GST_TIME_ARGS (priv->latency_ns), lost_packets,
GST_TIME_ARGS (gap_time));
/* this timer will fire immediately and the lost event will be pushed from
* the timer thread */
if (lost_packets > 0) {
add_timer (jitterbuffer, TIMER_TYPE_LOST, expected, lost_packets,
priv->last_in_pts + duration, 0, gap_time);
expected += lost_packets;
priv->last_in_pts += gap_time;
}
}
expected_pts = priv->last_in_pts + duration;
} else {
/* If we cannot assume equidistant packet spacing, the only thing we now
* for sure is that the missing packets have expected pts not later than
* the last received pts. */
duration = 0;
expected_pts = pts;
}
delay = 0;
if (priv->do_retransmission) {
TimerData *timer = find_timer (jitterbuffer, expected);
type = TIMER_TYPE_EXPECTED;
delay = get_rtx_delay (priv);
/* if we had a timer for the first missing packet, update it. */
if (timer && timer->type == TIMER_TYPE_EXPECTED) {
GstClockTime timeout = timer->timeout;
timer->duration = duration;
if (timeout > (expected_pts + delay) && timer->num_rtx_retry == 0) {
reschedule_timer (jitterbuffer, timer, timer->seqnum, expected_pts,
delay, TRUE);
}
expected++;
expected_pts += duration;
}
} else {
type = TIMER_TYPE_LOST;
}
while (gst_rtp_buffer_compare_seqnum (expected, seqnum) > 0) {
add_timer (jitterbuffer, type, expected, 0, expected_pts, delay, duration);
expected_pts += duration;
expected++;
}
}
static void
calculate_jitter (GstRtpJitterBuffer * jitterbuffer, GstClockTime dts,
guint32 rtptime)
{
gint32 rtpdiff;
GstClockTimeDiff dtsdiff, rtpdiffns, diff;
GstRtpJitterBufferPrivate *priv;
priv = jitterbuffer->priv;
if (G_UNLIKELY (dts == GST_CLOCK_TIME_NONE) || priv->clock_rate <= 0)
goto no_time;
if (priv->last_dts != -1)
dtsdiff = dts - priv->last_dts;
else
dtsdiff = 0;
if (priv->last_rtptime != -1)
rtpdiff = rtptime - (guint32) priv->last_rtptime;
else
rtpdiff = 0;
/* Guess whether stream currently uses equidistant packet spacing. If we
* often see identical timestamps it means the packets are not
* equidistant. */
if (rtptime == priv->last_rtptime)
priv->equidistant -= 2;
else
priv->equidistant += 1;
priv->equidistant = CLAMP (priv->equidistant, -7, 7);
priv->last_dts = dts;
priv->last_rtptime = rtptime;
if (rtpdiff > 0)
rtpdiffns =
gst_util_uint64_scale_int (rtpdiff, GST_SECOND, priv->clock_rate);
else
rtpdiffns =
-gst_util_uint64_scale_int (-rtpdiff, GST_SECOND, priv->clock_rate);
diff = ABS (dtsdiff - rtpdiffns);
/* jitter is stored in nanoseconds */
priv->avg_jitter = (diff + (15 * priv->avg_jitter)) >> 4;
GST_LOG_OBJECT (jitterbuffer,
"dtsdiff %" GST_TIME_FORMAT " rtptime %" GST_TIME_FORMAT
", clock-rate %d, diff %" GST_TIME_FORMAT ", jitter: %" GST_TIME_FORMAT,
GST_TIME_ARGS (dtsdiff), GST_TIME_ARGS (rtpdiffns), priv->clock_rate,
GST_TIME_ARGS (diff), GST_TIME_ARGS (priv->avg_jitter));
return;
/* ERRORS */
no_time:
{
GST_DEBUG_OBJECT (jitterbuffer,
"no dts or no clock-rate, can't calculate jitter");
return;
}
}
static gint
compare_buffer_seqnum (GstBuffer * a, GstBuffer * b, gpointer user_data)
{
GstRTPBuffer rtp_a = GST_RTP_BUFFER_INIT;
GstRTPBuffer rtp_b = GST_RTP_BUFFER_INIT;
guint seq_a, seq_b;
gst_rtp_buffer_map (a, GST_MAP_READ, &rtp_a);
seq_a = gst_rtp_buffer_get_seq (&rtp_a);
gst_rtp_buffer_unmap (&rtp_a);
gst_rtp_buffer_map (b, GST_MAP_READ, &rtp_b);
seq_b = gst_rtp_buffer_get_seq (&rtp_b);
gst_rtp_buffer_unmap (&rtp_b);
return gst_rtp_buffer_compare_seqnum (seq_b, seq_a);
}
static gboolean
handle_big_gap_buffer (GstRtpJitterBuffer * jitterbuffer, GstBuffer * buffer,
guint8 pt, guint16 seqnum, gint gap, guint max_dropout, guint max_misorder)
{
GstRtpJitterBufferPrivate *priv;
guint gap_packets_length;
gboolean reset = FALSE;
gboolean future = gap > 0;
priv = jitterbuffer->priv;
if ((gap_packets_length = g_queue_get_length (&priv->gap_packets)) > 0) {
GList *l;
guint32 prev_gap_seq = -1;
gboolean all_consecutive = TRUE;
g_queue_insert_sorted (&priv->gap_packets, buffer,
(GCompareDataFunc) compare_buffer_seqnum, NULL);
for (l = priv->gap_packets.head; l; l = l->next) {
GstBuffer *gap_buffer = l->data;
GstRTPBuffer gap_rtp = GST_RTP_BUFFER_INIT;
guint32 gap_seq;
gst_rtp_buffer_map (gap_buffer, GST_MAP_READ, &gap_rtp);
all_consecutive = (gst_rtp_buffer_get_payload_type (&gap_rtp) == pt);
gap_seq = gst_rtp_buffer_get_seq (&gap_rtp);
if (prev_gap_seq == -1)
prev_gap_seq = gap_seq;
else if (gst_rtp_buffer_compare_seqnum (gap_seq, prev_gap_seq) != -1)
all_consecutive = FALSE;
else
prev_gap_seq = gap_seq;
gst_rtp_buffer_unmap (&gap_rtp);
if (!all_consecutive)
break;
}
if (all_consecutive && gap_packets_length > 3) {
GST_DEBUG_OBJECT (jitterbuffer,
"buffer too %s %d < %d, got 5 consecutive ones - reset",
(future ? "new" : "old"), gap,
(future ? max_dropout : -max_misorder));
reset = TRUE;
} else if (!all_consecutive) {
g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
g_queue_clear (&priv->gap_packets);
GST_DEBUG_OBJECT (jitterbuffer,
"buffer too %s %d < %d, got no 5 consecutive ones - dropping",
(future ? "new" : "old"), gap,
(future ? max_dropout : -max_misorder));
buffer = NULL;
} else {
GST_DEBUG_OBJECT (jitterbuffer,
"buffer too %s %d < %d, got %u consecutive ones - waiting",
(future ? "new" : "old"), gap,
(future ? max_dropout : -max_misorder), gap_packets_length + 1);
buffer = NULL;
}
} else {
GST_DEBUG_OBJECT (jitterbuffer,
"buffer too %s %d < %d, first one - waiting", (future ? "new" : "old"),
gap, -max_misorder);
g_queue_push_tail (&priv->gap_packets, buffer);
buffer = NULL;
}
return reset;
}
static GstClockTime
get_current_running_time (GstRtpJitterBuffer * jitterbuffer)
{
GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (jitterbuffer));
GstClockTime running_time = GST_CLOCK_TIME_NONE;
if (clock) {
GstClockTime base_time =
gst_element_get_base_time (GST_ELEMENT_CAST (jitterbuffer));
GstClockTime clock_time = gst_clock_get_time (clock);
if (clock_time > base_time)
running_time = clock_time - base_time;
else
running_time = 0;
gst_object_unref (clock);
}
return running_time;
}
static GstFlowReturn
gst_rtp_jitter_buffer_reset (GstRtpJitterBuffer * jitterbuffer,
GstPad * pad, GstObject * parent, guint16 seqnum)
{
GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
GstFlowReturn ret = GST_FLOW_OK;
GList *events = NULL, *l;
GList *buffers;
gboolean head;
GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
rtp_jitter_buffer_flush (priv->jbuf,
(GFunc) free_item_and_retain_events, &events);
rtp_jitter_buffer_reset_skew (priv->jbuf);
remove_all_timers (jitterbuffer);
priv->discont = TRUE;
priv->last_popped_seqnum = -1;
if (priv->gap_packets.head) {
GstBuffer *gap_buffer = priv->gap_packets.head->data;
GstRTPBuffer gap_rtp = GST_RTP_BUFFER_INIT;
gst_rtp_buffer_map (gap_buffer, GST_MAP_READ, &gap_rtp);
priv->next_seqnum = gst_rtp_buffer_get_seq (&gap_rtp);
gst_rtp_buffer_unmap (&gap_rtp);
} else {
priv->next_seqnum = seqnum;
}
priv->last_in_pts = -1;
priv->next_in_seqnum = -1;
/* Insert all sticky events again in order, otherwise we would
* potentially loose STREAM_START, CAPS or SEGMENT events
*/
events = g_list_reverse (events);
for (l = events; l; l = l->next) {
RTPJitterBufferItem *item;
item = alloc_item (l->data, ITEM_TYPE_EVENT, -1, -1, -1, 0, -1);
rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
}
g_list_free (events);
JBUF_SIGNAL_EVENT (priv);
/* reset spacing estimation when gap */
priv->ips_rtptime = -1;
priv->ips_pts = GST_CLOCK_TIME_NONE;
buffers = g_list_copy (priv->gap_packets.head);
g_queue_clear (&priv->gap_packets);
priv->ips_rtptime = -1;
priv->ips_pts = GST_CLOCK_TIME_NONE;
JBUF_UNLOCK (jitterbuffer->priv);
for (l = buffers; l; l = l->next) {
ret = gst_rtp_jitter_buffer_chain (pad, parent, l->data);
l->data = NULL;
if (ret != GST_FLOW_OK) {
l = l->next;
break;
}
}
for (; l; l = l->next)
gst_buffer_unref (l->data);
g_list_free (buffers);
return ret;
}
static gboolean
gst_rtp_jitter_buffer_fast_start (GstRtpJitterBuffer * jitterbuffer)
{
GstRtpJitterBufferPrivate *priv;
RTPJitterBufferItem *item;
TimerData *timer;
priv = jitterbuffer->priv;
if (priv->faststart_min_packets == 0)
return FALSE;
item = rtp_jitter_buffer_peek (priv->jbuf);
if (!item)
return FALSE;
timer = find_timer (jitterbuffer, item->seqnum);
if (!timer || timer->type != TIMER_TYPE_DEADLINE)
return FALSE;
if (rtp_jitter_buffer_can_fast_start (priv->jbuf,
priv->faststart_min_packets)) {
GST_INFO_OBJECT (jitterbuffer, "We found %i consecutive packet, start now",
priv->faststart_min_packets);
timer->timeout = -1;
return TRUE;
}
return FALSE;
}
static GstFlowReturn
gst_rtp_jitter_buffer_chain (GstPad * pad, GstObject * parent,
GstBuffer * buffer)
{
GstRtpJitterBuffer *jitterbuffer;
GstRtpJitterBufferPrivate *priv;
guint16 seqnum;
guint32 expected, rtptime;
GstFlowReturn ret = GST_FLOW_OK;
GstClockTime dts, pts;
guint64 latency_ts;
gboolean head;
gint percent = -1;
guint8 pt;
GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
gboolean do_next_seqnum = FALSE;
RTPJitterBufferItem *item;
GstMessage *msg = NULL;
gboolean estimated_dts = FALSE;
gint32 packet_rate, max_dropout, max_misorder;
TimerData *timer = NULL;
jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
priv = jitterbuffer->priv;
if (G_UNLIKELY (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)))
goto invalid_buffer;
pt = gst_rtp_buffer_get_payload_type (&rtp);
seqnum = gst_rtp_buffer_get_seq (&rtp);
rtptime = gst_rtp_buffer_get_timestamp (&rtp);
gst_rtp_buffer_unmap (&rtp);
/* make sure we have PTS and DTS set */
pts = GST_BUFFER_PTS (buffer);
dts = GST_BUFFER_DTS (buffer);
if (dts == -1)
dts = pts;
else if (pts == -1)
pts = dts;
if (dts == -1) {
/* If we have no DTS here, i.e. no capture time, get one from the
* clock now to have something to calculate with in the future. */
dts = get_current_running_time (jitterbuffer);
pts = dts;
/* Remember that we estimated the DTS if we are running already
* and this is not our first packet (or first packet after a reset).
* If it's the first packet, we somehow must generate a timestamp for
* everything, otherwise we can't calculate any times
*/
estimated_dts = (priv->next_in_seqnum != -1);
} else {
/* take the DTS of the buffer. This is the time when the packet was
* received and is used to calculate jitter and clock skew. We will adjust
* this DTS with the smoothed value after processing it in the
* jitterbuffer and assign it as the PTS. */
/* bring to running time */
dts = gst_segment_to_running_time (&priv->segment, GST_FORMAT_TIME, dts);
}
GST_DEBUG_OBJECT (jitterbuffer,
"Received packet #%d at time %" GST_TIME_FORMAT ", discont %d, rtx %d",
seqnum, GST_TIME_ARGS (dts), GST_BUFFER_IS_DISCONT (buffer),
GST_BUFFER_IS_RETRANSMISSION (buffer));
JBUF_LOCK_CHECK (priv, out_flushing);
if (G_UNLIKELY (priv->last_pt != pt)) {
GstCaps *caps;
GST_DEBUG_OBJECT (jitterbuffer, "pt changed from %u to %u", priv->last_pt,
pt);
priv->last_pt = pt;
/* reset clock-rate so that we get a new one */
priv->clock_rate = -1;
/* Try to get the clock-rate from the caps first if we can. If there are no
* caps we must fire the signal to get the clock-rate. */
if ((caps = gst_pad_get_current_caps (pad))) {
gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps, pt);
gst_caps_unref (caps);
}
}
if (G_UNLIKELY (priv->clock_rate == -1)) {
/* no clock rate given on the caps, try to get one with the signal */
if (gst_rtp_jitter_buffer_get_clock_rate (jitterbuffer,
pt) == GST_FLOW_FLUSHING)
goto out_flushing;
if (G_UNLIKELY (priv->clock_rate == -1))
goto no_clock_rate;
gst_rtp_packet_rate_ctx_reset (&priv->packet_rate_ctx, priv->clock_rate);
}
/* don't accept more data on EOS */
if (G_UNLIKELY (priv->eos))
goto have_eos;
if (!GST_BUFFER_IS_RETRANSMISSION (buffer))
calculate_jitter (jitterbuffer, dts, rtptime);
if (priv->seqnum_base != -1) {
gint gap;
gap = gst_rtp_buffer_compare_seqnum (priv->seqnum_base, seqnum);
if (gap < 0) {
GST_DEBUG_OBJECT (jitterbuffer,
"packet seqnum #%d before seqnum-base #%d", seqnum,
priv->seqnum_base);
gst_buffer_unref (buffer);
goto finished;
} else if (gap > 16384) {
/* From now on don't compare against the seqnum base anymore as
* at some point in the future we will wrap around and also that
* much reordering is very unlikely */
priv->seqnum_base = -1;
}
}
expected = priv->next_in_seqnum;
packet_rate =
gst_rtp_packet_rate_ctx_update (&priv->packet_rate_ctx, seqnum, rtptime);
max_dropout =
gst_rtp_packet_rate_ctx_get_max_dropout (&priv->packet_rate_ctx,
priv->max_dropout_time);
max_misorder =
gst_rtp_packet_rate_ctx_get_max_misorder (&priv->packet_rate_ctx,
priv->max_misorder_time);
GST_TRACE_OBJECT (jitterbuffer,
"packet_rate: %d, max_dropout: %d, max_misorder: %d", packet_rate,
max_dropout, max_misorder);
/* now check against our expected seqnum */
if (G_UNLIKELY (expected == -1)) {
GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
/* calculate a pts based on rtptime and arrival time (dts) */
pts =
rtp_jitter_buffer_calculate_pts (priv->jbuf, dts, estimated_dts,
rtptime, gst_element_get_base_time (GST_ELEMENT_CAST (jitterbuffer)));
/* we don't know what the next_in_seqnum should be, wait for the last
* possible moment to push this buffer, maybe we get an earlier seqnum
* while we wait */
set_timer (jitterbuffer, TIMER_TYPE_DEADLINE, seqnum, pts);
do_next_seqnum = TRUE;
/* take rtptime and pts to calculate packet spacing */
priv->ips_rtptime = rtptime;
priv->ips_pts = pts;
} else {
gint gap;
/* now calculate gap */
gap = gst_rtp_buffer_compare_seqnum (expected, seqnum);
GST_DEBUG_OBJECT (jitterbuffer, "expected #%d, got #%d, gap of %d",
expected, seqnum, gap);
if (G_UNLIKELY (gap > 0 && priv->timers->len >= max_dropout)) {
/* If we have timers for more than RTP_MAX_DROPOUT packets
* pending this means that we have a huge gap overall. We can
* reset the jitterbuffer at this point because there's
* just too much data missing to be able to do anything
* sensible with the past data. Just try again from the
* next packet */
GST_WARNING_OBJECT (jitterbuffer, "%d pending timers > %d - resetting",
priv->timers->len, max_dropout);
gst_buffer_unref (buffer);
return gst_rtp_jitter_buffer_reset (jitterbuffer, pad, parent, seqnum);
}
/* Special handling of large gaps */
if ((gap != -1 && gap < -max_misorder) || (gap >= max_dropout)) {
gboolean reset = handle_big_gap_buffer (jitterbuffer, buffer, pt, seqnum,
gap, max_dropout, max_misorder);
if (reset) {
return gst_rtp_jitter_buffer_reset (jitterbuffer, pad, parent, seqnum);
} else {
GST_DEBUG_OBJECT (jitterbuffer,
"Had big gap, waiting for more consecutive packets");
goto finished;
}
}
/* We had no huge gap, let's drop all the gap packets */
GST_DEBUG_OBJECT (jitterbuffer, "Clearing gap packets");
g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
g_queue_clear (&priv->gap_packets);
/* calculate a pts based on rtptime and arrival time (dts) */
/* If we estimated the DTS, don't consider it in the clock skew calculations */
pts =
rtp_jitter_buffer_calculate_pts (priv->jbuf, dts, estimated_dts,
rtptime, gst_element_get_base_time (GST_ELEMENT_CAST (jitterbuffer)));
if (G_LIKELY (gap == 0)) {
/* packet is expected */
calculate_packet_spacing (jitterbuffer, rtptime, pts);
do_next_seqnum = TRUE;
} else {
/* we have a gap */
if (gap > 0) {
GST_DEBUG_OBJECT (jitterbuffer, "%d missing packets", gap);
/* fill in the gap with EXPECTED timers */
calculate_expected (jitterbuffer, expected, seqnum, pts, gap);
do_next_seqnum = TRUE;
} else {
GST_DEBUG_OBJECT (jitterbuffer, "old packet received");
do_next_seqnum = FALSE;
}
/* reset spacing estimation when gap */
priv->ips_rtptime = -1;
priv->ips_pts = GST_CLOCK_TIME_NONE;
}
}
if (do_next_seqnum) {
priv->last_in_pts = pts;
priv->next_in_seqnum = (seqnum + 1) & 0xffff;
}
timer = find_timer (jitterbuffer, seqnum);
if (GST_BUFFER_IS_RETRANSMISSION (buffer)) {
if (!timer)
timer = timer_queue_find (priv->rtx_stats_timers, seqnum);
if (timer)
timer->num_rtx_received++;
}
/* let's check if this buffer is too late, we can only accept packets with
* bigger seqnum than the one we last pushed. */
if (G_LIKELY (priv->last_popped_seqnum != -1)) {
gint gap;
gap = gst_rtp_buffer_compare_seqnum (priv->last_popped_seqnum, seqnum);
/* priv->last_popped_seqnum >= seqnum, we're too late. */
if (G_UNLIKELY (gap <= 0)) {
if (priv->do_retransmission) {
if (GST_BUFFER_IS_RETRANSMISSION (buffer) && timer) {
update_rtx_stats (jitterbuffer, timer, dts, FALSE);
/* Only count the retranmitted packet too late if it has been
* considered lost. If the original packet arrived before the
* retransmitted we just count it as a duplicate. */
if (timer->type != TIMER_TYPE_LOST)
goto rtx_duplicate;
}
}
goto too_late;
}
}
if (already_lost (jitterbuffer, seqnum))
goto already_lost;
/* let's drop oldest packet if the queue is already full and drop-on-latency
* is set. We can only do this when there actually is a latency. When no
* latency is set, we just pump it in the queue and let the other end push it
* out as fast as possible. */
if (priv->latency_ms && priv->drop_on_latency) {
latency_ts =
gst_util_uint64_scale_int (priv->latency_ms, priv->clock_rate, 1000);
if (G_UNLIKELY (rtp_jitter_buffer_get_ts_diff (priv->jbuf) >= latency_ts)) {
RTPJitterBufferItem *old_item;
old_item = rtp_jitter_buffer_peek (priv->jbuf);
if (IS_DROPABLE (old_item)) {
old_item = rtp_jitter_buffer_pop (priv->jbuf, &<