7079e168a73e0606e979826aa7d97149930db38b
[platform/upstream/gst-plugins-good.git] / gst / rtpmanager / rtpsource.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3  * Copyright (C)  2015 Kurento (http://kurento.org/)
4  *   @author: Miguel ParĂ­s <mparisdiaz@gmail.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21 #include <string.h>
22
23 #include <gst/rtp/gstrtpbuffer.h>
24 #include <gst/rtp/gstrtcpbuffer.h>
25
26 #include "rtpsource.h"
27
28 GST_DEBUG_CATEGORY_STATIC (rtp_source_debug);
29 #define GST_CAT_DEFAULT rtp_source_debug
30
31 #define RTP_MAX_PROBATION_LEN  32
32
33 /* signals and args */
34 enum
35 {
36   LAST_SIGNAL
37 };
38
39 #define DEFAULT_SSRC                 0
40 #define DEFAULT_IS_CSRC              FALSE
41 #define DEFAULT_IS_VALIDATED         FALSE
42 #define DEFAULT_IS_SENDER            FALSE
43 #define DEFAULT_SDES                 NULL
44 #define DEFAULT_PROBATION            RTP_DEFAULT_PROBATION
45 #define DEFAULT_MAX_DROPOUT_TIME     60000
46 #define DEFAULT_MAX_MISORDER_TIME    2000
47 #define DEFAULT_DISABLE_RTCP         FALSE
48
49 enum
50 {
51   PROP_0,
52   PROP_SSRC,
53   PROP_IS_CSRC,
54   PROP_IS_VALIDATED,
55   PROP_IS_SENDER,
56   PROP_SDES,
57   PROP_STATS,
58   PROP_PROBATION,
59   PROP_MAX_DROPOUT_TIME,
60   PROP_MAX_MISORDER_TIME,
61   PROP_DISABLE_RTCP
62 };
63
64 /* GObject vmethods */
65 static void rtp_source_finalize (GObject * object);
66 static void rtp_source_set_property (GObject * object, guint prop_id,
67     const GValue * value, GParamSpec * pspec);
68 static void rtp_source_get_property (GObject * object, guint prop_id,
69     GValue * value, GParamSpec * pspec);
70
71 /* static guint rtp_source_signals[LAST_SIGNAL] = { 0 }; */
72
73 G_DEFINE_TYPE (RTPSource, rtp_source, G_TYPE_OBJECT);
74
75 static void
76 rtp_source_class_init (RTPSourceClass * klass)
77 {
78   GObjectClass *gobject_class;
79
80   gobject_class = (GObjectClass *) klass;
81
82   gobject_class->finalize = rtp_source_finalize;
83
84   gobject_class->set_property = rtp_source_set_property;
85   gobject_class->get_property = rtp_source_get_property;
86
87   g_object_class_install_property (gobject_class, PROP_SSRC,
88       g_param_spec_uint ("ssrc", "SSRC",
89           "The SSRC of this source", 0, G_MAXUINT, DEFAULT_SSRC,
90           G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
91
92   g_object_class_install_property (gobject_class, PROP_IS_CSRC,
93       g_param_spec_boolean ("is-csrc", "Is CSRC",
94           "If this SSRC is acting as a contributing source",
95           DEFAULT_IS_CSRC, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
96
97   g_object_class_install_property (gobject_class, PROP_IS_VALIDATED,
98       g_param_spec_boolean ("is-validated", "Is Validated",
99           "If this SSRC is validated", DEFAULT_IS_VALIDATED,
100           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
101
102   g_object_class_install_property (gobject_class, PROP_IS_SENDER,
103       g_param_spec_boolean ("is-sender", "Is Sender",
104           "If this SSRC is a sender", DEFAULT_IS_SENDER,
105           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
106
107   /**
108    * RTPSource::sdes
109    *
110    * The current SDES items of the source. Returns a structure with name
111    * application/x-rtp-source-sdes and may contain the following fields:
112    *
113    *  'cname'       G_TYPE_STRING  : The canonical name in the form user@host
114    *  'name'        G_TYPE_STRING  : The user name
115    *  'email'       G_TYPE_STRING  : The user's electronic mail address
116    *  'phone'       G_TYPE_STRING  : The user's phone number
117    *  'location'    G_TYPE_STRING  : The geographic user location
118    *  'tool'        G_TYPE_STRING  : The name of application or tool
119    *  'note'        G_TYPE_STRING  : A notice about the source
120    *
121    *  Other fields may be present and these represent private items in
122    *  the SDES where the field name is the prefix.
123    */
124   g_object_class_install_property (gobject_class, PROP_SDES,
125       g_param_spec_boxed ("sdes", "SDES",
126           "The SDES information for this source",
127           GST_TYPE_STRUCTURE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
128
129   /**
130    * RTPSource::stats
131    *
132    * This property returns a GstStructure named application/x-rtp-source-stats with
133    * fields useful for statistics and diagnostics.
134    *
135    * Take note of each respective field's units:
136    *
137    * - NTP times are in the appropriate 32-bit or 64-bit fixed-point format
138    *   starting from January 1, 1970 (except for timespans).
139    * - RTP times are in clock rate units (i.e. clock rate = 1 second)
140    *   starting at a random offset.
141    * - For fields indicating packet loss, note that late packets are not considered lost,
142    *   and duplicates are not taken into account. Hence, the loss may be negative
143    *   if there are duplicates.
144    *
145    * The following fields are always present.
146    *
147    *  "ssrc"         G_TYPE_UINT     the SSRC of this source
148    *  "internal"     G_TYPE_BOOLEAN  this source is a source of the session
149    *  "validated"    G_TYPE_BOOLEAN  the source is validated
150    *  "received-bye" G_TYPE_BOOLEAN  we received a BYE from this source
151    *  "is-csrc"      G_TYPE_BOOLEAN  this source was found as CSRC
152    *  "is-sender"    G_TYPE_BOOLEAN  this source is a sender
153    *  "seqnum-base"  G_TYPE_INT      first seqnum if known
154    *  "clock-rate"   G_TYPE_INT      the clock rate of the media
155    *
156    * The following fields are only present when known.
157    *
158    *  "rtp-from"     G_TYPE_STRING   where we received the last RTP packet from
159    *  "rtcp-from"    G_TYPE_STRING   where we received the last RTCP packet from
160    *
161    * The following fields make sense for internal sources and will only increase
162    * when "is-sender" is TRUE.
163    *
164    *  "octets-sent"  G_TYPE_UINT64   number of bytes we sent
165    *  "packets-sent" G_TYPE_UINT64   number of packets we sent
166    *
167    * The following fields make sense for non-internal sources and will only
168    * increase when "is-sender" is TRUE.
169    *
170    *  "octets-received"  G_TYPE_UINT64  total number of bytes received
171    *  "packets-received" G_TYPE_UINT64  total number of packets received
172    *
173    * Following fields are updated when "is-sender" is TRUE.
174    *
175    *  "bitrate"      G_TYPE_UINT64   bitrate in bits per second
176    *  "jitter"       G_TYPE_UINT     estimated jitter (in clock rate units)
177    *  "packets-lost" G_TYPE_INT      estimated amount of packets lost
178    *
179    * The last SR report this source sent. This only updates when "is-sender" is
180    * TRUE.
181    *
182    *  "have-sr"         G_TYPE_BOOLEAN  the source has sent SR
183    *  "sr-ntptime"      G_TYPE_UINT64   NTP time of SR (in NTP Timestamp Format, 32.32 fixed point)
184    *  "sr-rtptime"      G_TYPE_UINT     RTP time of SR (in clock rate units)
185    *  "sr-octet-count"  G_TYPE_UINT     the number of bytes in the SR
186    *  "sr-packet-count" G_TYPE_UINT     the number of packets in the SR
187    *
188    * The following fields are only present for non-internal sources and
189    * represent the content of the last RB packet that was sent to this source.
190    * These values are only updated when the source is sending.
191    *
192    *  "sent-rb"               G_TYPE_BOOLEAN  we have sent an RB
193    *  "sent-rb-fractionlost"  G_TYPE_UINT     calculated lost 8-bit fraction
194    *  "sent-rb-packetslost"   G_TYPE_INT      lost packets
195    *  "sent-rb-exthighestseq" G_TYPE_UINT     last seen seqnum
196    *  "sent-rb-jitter"        G_TYPE_UINT     jitter (in clock rate units)
197    *  "sent-rb-lsr"           G_TYPE_UINT     last SR time (seconds in NTP Short Format, 16.16 fixed point)
198    *  "sent-rb-dlsr"          G_TYPE_UINT     delay since last SR (seconds in NTP Short Format, 16.16 fixed point)
199    *
200    * The following fields are only present for non-internal sources and
201    * represents the last RB that this source sent. This is only updated
202    * when the source is receiving data and sending RB blocks.
203    *
204    *  "have-rb"          G_TYPE_BOOLEAN  the source has sent RB
205    *  "rb-fractionlost"  G_TYPE_UINT     lost 8-bit fraction
206    *  "rb-packetslost"   G_TYPE_INT      lost packets
207    *  "rb-exthighestseq" G_TYPE_UINT     highest received seqnum
208    *  "rb-jitter"        G_TYPE_UINT     reception jitter (in clock rate units)
209    *  "rb-lsr"           G_TYPE_UINT     last SR time (seconds in NTP Short Format, 16.16 fixed point)
210    *  "rb-dlsr"          G_TYPE_UINT     delay since last SR (seconds in NTP Short Format, 16.16 fixed point)
211    *
212    * The round trip of this source is calculated from the last RB
213    * values and the reception time of the last RB packet. It is only present for
214    * non-internal sources.
215    *
216    *  "rb-round-trip"    G_TYPE_UINT     the round-trip time (seconds in NTP Short Format, 16.16 fixed point)
217    *
218    */
219   g_object_class_install_property (gobject_class, PROP_STATS,
220       g_param_spec_boxed ("stats", "Stats",
221           "The stats of this source", GST_TYPE_STRUCTURE,
222           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
223
224   g_object_class_install_property (gobject_class, PROP_PROBATION,
225       g_param_spec_uint ("probation", "Number of probations",
226           "Consecutive packet sequence numbers to accept the source",
227           0, G_MAXUINT, DEFAULT_PROBATION,
228           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
229
230   g_object_class_install_property (gobject_class, PROP_MAX_DROPOUT_TIME,
231       g_param_spec_uint ("max-dropout-time", "Max dropout time",
232           "The maximum time (milliseconds) of missing packets tolerated.",
233           0, G_MAXUINT, DEFAULT_MAX_DROPOUT_TIME,
234           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
235
236   g_object_class_install_property (gobject_class, PROP_MAX_MISORDER_TIME,
237       g_param_spec_uint ("max-misorder-time", "Max misorder time",
238           "The maximum time (milliseconds) of misordered packets tolerated.",
239           0, G_MAXUINT, DEFAULT_MAX_MISORDER_TIME,
240           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
241
242   /**
243    * RTPSession::disable-rtcp:
244    *
245    * Allow disabling the sending of RTCP packets for this source.
246    */
247   g_object_class_install_property (gobject_class, PROP_DISABLE_RTCP,
248       g_param_spec_boolean ("disable-rtcp", "Disable RTCP",
249           "Disable sending RTCP packets for this source",
250           DEFAULT_DISABLE_RTCP, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
251
252   GST_DEBUG_CATEGORY_INIT (rtp_source_debug, "rtpsource", 0, "RTP Source");
253 }
254
255 /**
256  * rtp_source_reset:
257  * @src: an #RTPSource
258  *
259  * Reset the stats of @src.
260  */
261 void
262 rtp_source_reset (RTPSource * src)
263 {
264   src->marked_bye = FALSE;
265   if (src->bye_reason)
266     g_free (src->bye_reason);
267   src->bye_reason = NULL;
268   src->sent_bye = FALSE;
269   g_hash_table_remove_all (src->reported_in_sr_of);
270   g_queue_foreach (src->retained_feedback, (GFunc) gst_buffer_unref, NULL);
271   g_queue_clear (src->retained_feedback);
272   src->last_rtptime = -1;
273
274   src->stats.cycles = -1;
275   src->stats.jitter = 0;
276   src->stats.transit = -1;
277   src->stats.curr_sr = 0;
278   src->stats.sr[0].is_valid = FALSE;
279   src->stats.curr_rr = 0;
280   src->stats.rr[0].is_valid = FALSE;
281   src->stats.prev_rtptime = GST_CLOCK_TIME_NONE;
282   src->stats.prev_rtcptime = GST_CLOCK_TIME_NONE;
283   src->stats.last_rtptime = GST_CLOCK_TIME_NONE;
284   src->stats.last_rtcptime = GST_CLOCK_TIME_NONE;
285   g_array_set_size (src->nacks, 0);
286
287   src->stats.sent_pli_count = 0;
288   src->stats.sent_fir_count = 0;
289   src->stats.sent_nack_count = 0;
290   src->stats.recv_nack_count = 0;
291 }
292
293 static void
294 rtp_source_init (RTPSource * src)
295 {
296   /* sources are initially on probation until we receive enough valid RTP
297    * packets or a valid RTCP packet */
298   src->validated = FALSE;
299   src->internal = FALSE;
300   src->probation = DEFAULT_PROBATION;
301   src->curr_probation = src->probation;
302   src->closing = FALSE;
303   src->max_dropout_time = DEFAULT_MAX_DROPOUT_TIME;
304   src->max_misorder_time = DEFAULT_MAX_MISORDER_TIME;
305
306   src->sdes = gst_structure_new_empty ("application/x-rtp-source-sdes");
307
308   src->payload = -1;
309   src->clock_rate = -1;
310   src->packets = g_queue_new ();
311   src->seqnum_offset = -1;
312
313   src->retained_feedback = g_queue_new ();
314   src->nacks = g_array_new (FALSE, FALSE, sizeof (guint16));
315   src->nack_deadlines = g_array_new (FALSE, FALSE, sizeof (GstClockTime));
316
317   src->reported_in_sr_of = g_hash_table_new (g_direct_hash, g_direct_equal);
318
319   src->last_keyframe_request = GST_CLOCK_TIME_NONE;
320
321   rtp_source_reset (src);
322
323   src->pt_set = FALSE;
324 }
325
326 void
327 rtp_conflicting_address_free (RTPConflictingAddress * addr)
328 {
329   g_object_unref (addr->address);
330   g_slice_free (RTPConflictingAddress, addr);
331 }
332
333 static void
334 rtp_source_finalize (GObject * object)
335 {
336   RTPSource *src;
337
338   src = RTP_SOURCE_CAST (object);
339
340   g_queue_foreach (src->packets, (GFunc) gst_buffer_unref, NULL);
341   g_queue_free (src->packets);
342
343   gst_structure_free (src->sdes);
344
345   g_free (src->bye_reason);
346
347   gst_caps_replace (&src->caps, NULL);
348
349   g_list_free_full (src->conflicting_addresses,
350       (GDestroyNotify) rtp_conflicting_address_free);
351   g_queue_foreach (src->retained_feedback, (GFunc) gst_buffer_unref, NULL);
352   g_queue_free (src->retained_feedback);
353
354   g_array_free (src->nacks, TRUE);
355   g_array_free (src->nack_deadlines, TRUE);
356
357   if (src->rtp_from)
358     g_object_unref (src->rtp_from);
359   if (src->rtcp_from)
360     g_object_unref (src->rtcp_from);
361
362   g_hash_table_unref (src->reported_in_sr_of);
363
364   G_OBJECT_CLASS (rtp_source_parent_class)->finalize (object);
365 }
366
367 static GstStructure *
368 rtp_source_create_stats (RTPSource * src)
369 {
370   GstStructure *s;
371   gboolean is_sender = src->is_sender;
372   gboolean internal = src->internal;
373   gchar *address_str;
374   gboolean have_rb;
375   guint8 fractionlost = 0;
376   gint32 packetslost = 0;
377   guint32 exthighestseq = 0;
378   guint32 jitter = 0;
379   guint32 lsr = 0;
380   guint32 dlsr = 0;
381   guint32 round_trip = 0;
382   gboolean have_sr;
383   GstClockTime time = 0;
384   guint64 ntptime = 0;
385   guint32 rtptime = 0;
386   guint32 packet_count = 0;
387   guint32 octet_count = 0;
388
389
390   /* common data for all types of sources */
391   s = gst_structure_new ("application/x-rtp-source-stats",
392       "ssrc", G_TYPE_UINT, (guint) src->ssrc,
393       "internal", G_TYPE_BOOLEAN, internal,
394       "validated", G_TYPE_BOOLEAN, src->validated,
395       "received-bye", G_TYPE_BOOLEAN, src->marked_bye,
396       "is-csrc", G_TYPE_BOOLEAN, src->is_csrc,
397       "is-sender", G_TYPE_BOOLEAN, is_sender,
398       "seqnum-base", G_TYPE_INT, src->seqnum_offset,
399       "clock-rate", G_TYPE_INT, src->clock_rate, NULL);
400
401   /* add address and port */
402   if (src->rtp_from) {
403     address_str = __g_socket_address_to_string (src->rtp_from);
404     gst_structure_set (s, "rtp-from", G_TYPE_STRING, address_str, NULL);
405     g_free (address_str);
406   }
407   if (src->rtcp_from) {
408     address_str = __g_socket_address_to_string (src->rtcp_from);
409     gst_structure_set (s, "rtcp-from", G_TYPE_STRING, address_str, NULL);
410     g_free (address_str);
411   }
412
413   gst_structure_set (s,
414       "octets-sent", G_TYPE_UINT64, src->stats.octets_sent,
415       "packets-sent", G_TYPE_UINT64, src->stats.packets_sent,
416       "octets-received", G_TYPE_UINT64, src->stats.octets_received,
417       "packets-received", G_TYPE_UINT64, src->stats.packets_received,
418       "bitrate", G_TYPE_UINT64, src->bitrate,
419       "packets-lost", G_TYPE_INT,
420       (gint) rtp_stats_get_packets_lost (&src->stats), "jitter", G_TYPE_UINT,
421       (guint) (src->stats.jitter >> 4),
422       "sent-pli-count", G_TYPE_UINT, src->stats.sent_pli_count,
423       "recv-pli-count", G_TYPE_UINT, src->stats.recv_pli_count,
424       "sent-fir-count", G_TYPE_UINT, src->stats.sent_fir_count,
425       "recv-fir-count", G_TYPE_UINT, src->stats.recv_fir_count,
426       "sent-nack-count", G_TYPE_UINT, src->stats.sent_nack_count,
427       "recv-nack-count", G_TYPE_UINT, src->stats.recv_nack_count, NULL);
428
429   /* get the last SR. */
430   have_sr = rtp_source_get_last_sr (src, &time, &ntptime, &rtptime,
431       &packet_count, &octet_count);
432   gst_structure_set (s,
433       "have-sr", G_TYPE_BOOLEAN, have_sr,
434       "sr-ntptime", G_TYPE_UINT64, ntptime,
435       "sr-rtptime", G_TYPE_UINT, (guint) rtptime,
436       "sr-octet-count", G_TYPE_UINT, (guint) octet_count,
437       "sr-packet-count", G_TYPE_UINT, (guint) packet_count, NULL);
438
439   if (!internal) {
440     /* get the last RB we sent */
441     gst_structure_set (s,
442         "sent-rb", G_TYPE_BOOLEAN, src->last_rr.is_valid,
443         "sent-rb-fractionlost", G_TYPE_UINT, (guint) src->last_rr.fractionlost,
444         "sent-rb-packetslost", G_TYPE_INT, (gint) src->last_rr.packetslost,
445         "sent-rb-exthighestseq", G_TYPE_UINT,
446         (guint) src->last_rr.exthighestseq, "sent-rb-jitter", G_TYPE_UINT,
447         (guint) src->last_rr.jitter, "sent-rb-lsr", G_TYPE_UINT,
448         (guint) src->last_rr.lsr, "sent-rb-dlsr", G_TYPE_UINT,
449         (guint) src->last_rr.dlsr, NULL);
450
451     /* get the last RB */
452     have_rb = rtp_source_get_last_rb (src, &fractionlost, &packetslost,
453         &exthighestseq, &jitter, &lsr, &dlsr, &round_trip);
454
455     gst_structure_set (s,
456         "have-rb", G_TYPE_BOOLEAN, have_rb,
457         "rb-fractionlost", G_TYPE_UINT, (guint) fractionlost,
458         "rb-packetslost", G_TYPE_INT, (gint) packetslost,
459         "rb-exthighestseq", G_TYPE_UINT, (guint) exthighestseq,
460         "rb-jitter", G_TYPE_UINT, (guint) jitter,
461         "rb-lsr", G_TYPE_UINT, (guint) lsr,
462         "rb-dlsr", G_TYPE_UINT, (guint) dlsr,
463         "rb-round-trip", G_TYPE_UINT, (guint) round_trip, NULL);
464   }
465
466   return s;
467 }
468
469 /**
470  * rtp_source_get_sdes_struct:
471  * @src: an #RTPSource
472  *
473  * Get the SDES from @src. See the SDES property for more details.
474  *
475  * Returns: %GstStructure of type "application/x-rtp-source-sdes". The result is
476  * valid until the SDES items of @src are modified.
477  */
478 const GstStructure *
479 rtp_source_get_sdes_struct (RTPSource * src)
480 {
481   g_return_val_if_fail (RTP_IS_SOURCE (src), NULL);
482
483   return src->sdes;
484 }
485
486 static gboolean
487 sdes_struct_compare_func (GQuark field_id, const GValue * value,
488     gpointer user_data)
489 {
490   GstStructure *old;
491   const gchar *field;
492
493   old = GST_STRUCTURE (user_data);
494   field = g_quark_to_string (field_id);
495
496   if (!gst_structure_has_field (old, field))
497     return FALSE;
498
499   g_assert (G_VALUE_HOLDS_STRING (value));
500
501   return strcmp (g_value_get_string (value), gst_structure_get_string (old,
502           field)) == 0;
503 }
504
505 /**
506  * rtp_source_set_sdes_struct:
507  * @src: an #RTPSource
508  * @sdes: the SDES structure
509  *
510  * Store the @sdes in @src. @sdes must be a structure of type
511  * "application/x-rtp-source-sdes", see the SDES property for more details.
512  *
513  * This function takes ownership of @sdes.
514  *
515  * Returns: %FALSE if the SDES was unchanged.
516  */
517 gboolean
518 rtp_source_set_sdes_struct (RTPSource * src, GstStructure * sdes)
519 {
520   gboolean changed;
521
522   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
523   g_return_val_if_fail (strcmp (gst_structure_get_name (sdes),
524           "application/x-rtp-source-sdes") == 0, FALSE);
525
526   changed = !gst_structure_foreach (sdes, sdes_struct_compare_func, src->sdes);
527
528   if (changed) {
529     gst_structure_free (src->sdes);
530     src->sdes = sdes;
531   } else {
532     gst_structure_free (sdes);
533   }
534   return changed;
535 }
536
537 static void
538 rtp_source_set_property (GObject * object, guint prop_id,
539     const GValue * value, GParamSpec * pspec)
540 {
541   RTPSource *src;
542
543   src = RTP_SOURCE (object);
544
545   switch (prop_id) {
546     case PROP_SSRC:
547       src->ssrc = g_value_get_uint (value);
548       break;
549     case PROP_PROBATION:
550       src->probation = g_value_get_uint (value);
551       break;
552     case PROP_MAX_DROPOUT_TIME:
553       src->max_dropout_time = g_value_get_uint (value);
554       break;
555     case PROP_MAX_MISORDER_TIME:
556       src->max_misorder_time = g_value_get_uint (value);
557       break;
558     case PROP_DISABLE_RTCP:
559       src->disable_rtcp = g_value_get_boolean (value);
560       break;
561     default:
562       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
563       break;
564   }
565 }
566
567 static void
568 rtp_source_get_property (GObject * object, guint prop_id,
569     GValue * value, GParamSpec * pspec)
570 {
571   RTPSource *src;
572
573   src = RTP_SOURCE (object);
574
575   switch (prop_id) {
576     case PROP_SSRC:
577       g_value_set_uint (value, rtp_source_get_ssrc (src));
578       break;
579     case PROP_IS_CSRC:
580       g_value_set_boolean (value, rtp_source_is_as_csrc (src));
581       break;
582     case PROP_IS_VALIDATED:
583       g_value_set_boolean (value, rtp_source_is_validated (src));
584       break;
585     case PROP_IS_SENDER:
586       g_value_set_boolean (value, rtp_source_is_sender (src));
587       break;
588     case PROP_SDES:
589       g_value_set_boxed (value, rtp_source_get_sdes_struct (src));
590       break;
591     case PROP_STATS:
592       g_value_take_boxed (value, rtp_source_create_stats (src));
593       break;
594     case PROP_PROBATION:
595       g_value_set_uint (value, src->probation);
596       break;
597     case PROP_MAX_DROPOUT_TIME:
598       g_value_set_uint (value, src->max_dropout_time);
599       break;
600     case PROP_MAX_MISORDER_TIME:
601       g_value_set_uint (value, src->max_misorder_time);
602       break;
603     case PROP_DISABLE_RTCP:
604       g_value_set_boolean (value, src->disable_rtcp);
605       break;
606     default:
607       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
608       break;
609   }
610 }
611
612 /**
613  * rtp_source_new:
614  * @ssrc: an SSRC
615  *
616  * Create a #RTPSource with @ssrc.
617  *
618  * Returns: a new #RTPSource. Use g_object_unref() after usage.
619  */
620 RTPSource *
621 rtp_source_new (guint32 ssrc)
622 {
623   RTPSource *src;
624
625   src = g_object_new (RTP_TYPE_SOURCE, NULL);
626   src->ssrc = ssrc;
627
628   return src;
629 }
630
631 /**
632  * rtp_source_set_callbacks:
633  * @src: an #RTPSource
634  * @cb: callback functions
635  * @user_data: user data
636  *
637  * Set the callbacks for the source.
638  */
639 void
640 rtp_source_set_callbacks (RTPSource * src, RTPSourceCallbacks * cb,
641     gpointer user_data)
642 {
643   g_return_if_fail (RTP_IS_SOURCE (src));
644
645   src->callbacks.push_rtp = cb->push_rtp;
646   src->callbacks.clock_rate = cb->clock_rate;
647   src->user_data = user_data;
648 }
649
650 /**
651  * rtp_source_get_ssrc:
652  * @src: an #RTPSource
653  *
654  * Get the SSRC of @source.
655  *
656  * Returns: the SSRC of src.
657  */
658 guint32
659 rtp_source_get_ssrc (RTPSource * src)
660 {
661   guint32 result;
662
663   g_return_val_if_fail (RTP_IS_SOURCE (src), 0);
664
665   result = src->ssrc;
666
667   return result;
668 }
669
670 /**
671  * rtp_source_set_as_csrc:
672  * @src: an #RTPSource
673  *
674  * Configure @src as a CSRC, this will also validate @src.
675  */
676 void
677 rtp_source_set_as_csrc (RTPSource * src)
678 {
679   g_return_if_fail (RTP_IS_SOURCE (src));
680
681   src->validated = TRUE;
682   src->is_csrc = TRUE;
683 }
684
685 /**
686  * rtp_source_is_as_csrc:
687  * @src: an #RTPSource
688  *
689  * Check if @src is a contributing source.
690  *
691  * Returns: %TRUE if @src is acting as a contributing source.
692  */
693 gboolean
694 rtp_source_is_as_csrc (RTPSource * src)
695 {
696   gboolean result;
697
698   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
699
700   result = src->is_csrc;
701
702   return result;
703 }
704
705 /**
706  * rtp_source_is_active:
707  * @src: an #RTPSource
708  *
709  * Check if @src is an active source. A source is active if it has been
710  * validated and has not yet received a BYE packet
711  *
712  * Returns: %TRUE if @src is an qactive source.
713  */
714 gboolean
715 rtp_source_is_active (RTPSource * src)
716 {
717   gboolean result;
718
719   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
720
721   result = RTP_SOURCE_IS_ACTIVE (src);
722
723   return result;
724 }
725
726 /**
727  * rtp_source_is_validated:
728  * @src: an #RTPSource
729  *
730  * Check if @src is a validated source.
731  *
732  * Returns: %TRUE if @src is a validated source.
733  */
734 gboolean
735 rtp_source_is_validated (RTPSource * src)
736 {
737   gboolean result;
738
739   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
740
741   result = src->validated;
742
743   return result;
744 }
745
746 /**
747  * rtp_source_is_sender:
748  * @src: an #RTPSource
749  *
750  * Check if @src is a sending source.
751  *
752  * Returns: %TRUE if @src is a sending source.
753  */
754 gboolean
755 rtp_source_is_sender (RTPSource * src)
756 {
757   gboolean result;
758
759   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
760
761   result = RTP_SOURCE_IS_SENDER (src);
762
763   return result;
764 }
765
766 /**
767  * rtp_source_is_marked_bye:
768  * @src: an #RTPSource
769  *
770  * Check if @src is marked as leaving the session with a BYE packet.
771  *
772  * Returns: %TRUE if @src has been marked BYE.
773  */
774 gboolean
775 rtp_source_is_marked_bye (RTPSource * src)
776 {
777   gboolean result;
778
779   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
780
781   result = RTP_SOURCE_IS_MARKED_BYE (src);
782
783   return result;
784 }
785
786
787 /**
788  * rtp_source_get_bye_reason:
789  * @src: an #RTPSource
790  *
791  * Get the BYE reason for @src. Check if the source is marked as leaving the
792  * session with a BYE message first with rtp_source_is_marked_bye().
793  *
794  * Returns: The BYE reason or NULL when no reason was given or the source was
795  * not marked BYE yet. g_free() after usage.
796  */
797 gchar *
798 rtp_source_get_bye_reason (RTPSource * src)
799 {
800   gchar *result;
801
802   g_return_val_if_fail (RTP_IS_SOURCE (src), NULL);
803
804   result = g_strdup (src->bye_reason);
805
806   return result;
807 }
808
809 /**
810  * rtp_source_update_caps:
811  * @src: an #RTPSource
812  * @caps: a #GstCaps
813  *
814  * Parse @caps and store all relevant information in @source.
815  */
816 void
817 rtp_source_update_caps (RTPSource * src, GstCaps * caps)
818 {
819   GstStructure *s;
820   guint val;
821   gint ival;
822   gboolean rtx;
823
824   /* nothing changed, return */
825   if (caps == NULL || src->caps == caps)
826     return;
827
828   s = gst_caps_get_structure (caps, 0);
829
830   rtx = (gst_structure_get_uint (s, "rtx-ssrc", &val) && val == src->ssrc);
831
832   if (gst_structure_get_int (s, rtx ? "rtx-payload" : "payload", &ival))
833     src->payload = ival;
834   else
835     src->payload = -1;
836
837   GST_DEBUG ("got %spayload %d", rtx ? "rtx " : "", src->payload);
838
839   if (gst_structure_get_int (s, "clock-rate", &ival))
840     src->clock_rate = ival;
841   else
842     src->clock_rate = -1;
843
844   GST_DEBUG ("got clock-rate %d", src->clock_rate);
845
846   if (gst_structure_get_uint (s, rtx ? "rtx-seqnum-offset" : "seqnum-offset",
847           &val))
848     src->seqnum_offset = val;
849   else
850     src->seqnum_offset = -1;
851
852   GST_DEBUG ("got %sseqnum-offset %" G_GINT32_FORMAT, rtx ? "rtx " : "",
853       src->seqnum_offset);
854
855   gst_caps_replace (&src->caps, caps);
856 }
857
858 /**
859  * rtp_source_set_rtp_from:
860  * @src: an #RTPSource
861  * @address: the RTP address to set
862  *
863  * Set that @src is receiving RTP packets from @address. This is used for
864  * collistion checking.
865  */
866 void
867 rtp_source_set_rtp_from (RTPSource * src, GSocketAddress * address)
868 {
869   g_return_if_fail (RTP_IS_SOURCE (src));
870
871   if (src->rtp_from)
872     g_object_unref (src->rtp_from);
873   src->rtp_from = G_SOCKET_ADDRESS (g_object_ref (address));
874 }
875
876 /**
877  * rtp_source_set_rtcp_from:
878  * @src: an #RTPSource
879  * @address: the RTCP address to set
880  *
881  * Set that @src is receiving RTCP packets from @address. This is used for
882  * collistion checking.
883  */
884 void
885 rtp_source_set_rtcp_from (RTPSource * src, GSocketAddress * address)
886 {
887   g_return_if_fail (RTP_IS_SOURCE (src));
888
889   if (src->rtcp_from)
890     g_object_unref (src->rtcp_from);
891   src->rtcp_from = G_SOCKET_ADDRESS (g_object_ref (address));
892 }
893
894 static GstFlowReturn
895 push_packet (RTPSource * src, GstBuffer * buffer)
896 {
897   GstFlowReturn ret = GST_FLOW_OK;
898
899   /* push queued packets first if any */
900   while (!g_queue_is_empty (src->packets)) {
901     GstBuffer *buffer = GST_BUFFER_CAST (g_queue_pop_head (src->packets));
902
903     GST_LOG ("pushing queued packet");
904     if (src->callbacks.push_rtp)
905       src->callbacks.push_rtp (src, buffer, src->user_data);
906     else
907       gst_buffer_unref (buffer);
908   }
909   GST_LOG ("pushing new packet");
910   /* push packet */
911   if (src->callbacks.push_rtp)
912     ret = src->callbacks.push_rtp (src, buffer, src->user_data);
913   else
914     gst_buffer_unref (buffer);
915
916   return ret;
917 }
918
919 static gint
920 get_clock_rate (RTPSource * src, guint8 payload)
921 {
922   if (src->payload == -1) {
923     /* first payload received, nothing was in the caps, lock on to this payload */
924     src->payload = payload;
925     GST_DEBUG ("first payload %d", payload);
926   } else if (payload != src->payload) {
927     /* we have a different payload than before, reset the clock-rate */
928     GST_DEBUG ("new payload %d", payload);
929     src->payload = payload;
930     src->clock_rate = -1;
931     src->stats.transit = -1;
932   }
933
934   if (src->clock_rate == -1) {
935     gint clock_rate = -1;
936
937     if (src->callbacks.clock_rate)
938       clock_rate = src->callbacks.clock_rate (src, payload, src->user_data);
939
940     GST_DEBUG ("got clock-rate %d", clock_rate);
941
942     src->clock_rate = clock_rate;
943     gst_rtp_packet_rate_ctx_reset (&src->packet_rate_ctx, clock_rate);
944   }
945   return src->clock_rate;
946 }
947
948 /* Jitter is the variation in the delay of received packets in a flow. It is
949  * measured by comparing the interval when RTP packets were sent to the interval
950  * at which they were received. For instance, if packet #1 and packet #2 leave
951  * 50 milliseconds apart and arrive 60 milliseconds apart, then the jitter is 10
952  * milliseconds. */
953 static void
954 calculate_jitter (RTPSource * src, RTPPacketInfo * pinfo)
955 {
956   GstClockTime running_time;
957   guint32 rtparrival, transit, rtptime;
958   gint32 diff;
959   gint clock_rate;
960   guint8 pt;
961
962   /* get arrival time */
963   if ((running_time = pinfo->running_time) == GST_CLOCK_TIME_NONE)
964     goto no_time;
965
966   pt = pinfo->pt;
967
968   GST_LOG ("SSRC %08x got payload %d", src->ssrc, pt);
969
970   /* get clockrate */
971   if ((clock_rate = get_clock_rate (src, pt)) == -1)
972     goto no_clock_rate;
973
974   rtptime = pinfo->rtptime;
975
976   /* convert arrival time to RTP timestamp units, truncate to 32 bits, we don't
977    * care about the absolute value, just the difference. */
978   rtparrival = gst_util_uint64_scale_int (running_time, clock_rate, GST_SECOND);
979
980   /* transit time is difference with RTP timestamp */
981   transit = rtparrival - rtptime;
982
983   /* get ABS diff with previous transit time */
984   if (src->stats.transit != -1) {
985     if (transit > src->stats.transit)
986       diff = transit - src->stats.transit;
987     else
988       diff = src->stats.transit - transit;
989   } else
990     diff = 0;
991
992   src->stats.transit = transit;
993
994   /* update jitter, the value we store is scaled up so we can keep precision. */
995   src->stats.jitter += diff - ((src->stats.jitter + 8) >> 4);
996
997   src->stats.prev_rtptime = src->stats.last_rtptime;
998   src->stats.last_rtptime = rtparrival;
999
1000   GST_LOG ("rtparrival %u, rtptime %u, clock-rate %d, diff %d, jitter: %f",
1001       rtparrival, rtptime, clock_rate, diff, (src->stats.jitter) / 16.0);
1002
1003   return;
1004
1005   /* ERRORS */
1006 no_time:
1007   {
1008     GST_WARNING ("cannot get current running_time");
1009     return;
1010   }
1011 no_clock_rate:
1012   {
1013     GST_WARNING ("cannot get clock-rate for pt %d", pt);
1014     return;
1015   }
1016 }
1017
1018 static void
1019 init_seq (RTPSource * src, guint16 seq)
1020 {
1021   src->stats.base_seq = seq;
1022   src->stats.max_seq = seq;
1023   src->stats.bad_seq = RTP_SEQ_MOD + 1; /* so seq == bad_seq is false */
1024   src->stats.cycles = 0;
1025   src->stats.packets_received = 0;
1026   src->stats.octets_received = 0;
1027   src->stats.bytes_received = 0;
1028   src->stats.prev_received = 0;
1029   src->stats.prev_expected = 0;
1030   src->stats.recv_pli_count = 0;
1031   src->stats.recv_fir_count = 0;
1032
1033   GST_DEBUG ("base_seq %d", seq);
1034 }
1035
1036 #define BITRATE_INTERVAL (2 * GST_SECOND)
1037
1038 static void
1039 do_bitrate_estimation (RTPSource * src, GstClockTime running_time,
1040     guint64 * bytes_handled)
1041 {
1042   guint64 elapsed;
1043
1044   if (src->prev_rtime) {
1045     elapsed = running_time - src->prev_rtime;
1046
1047     if (elapsed > BITRATE_INTERVAL) {
1048       guint64 rate;
1049
1050       rate = gst_util_uint64_scale (*bytes_handled, 8 * GST_SECOND, elapsed);
1051
1052       GST_LOG ("Elapsed %" G_GUINT64_FORMAT ", bytes %" G_GUINT64_FORMAT
1053           ", rate %" G_GUINT64_FORMAT, elapsed, *bytes_handled, rate);
1054
1055       if (src->bitrate == 0)
1056         src->bitrate = rate;
1057       else
1058         src->bitrate = ((src->bitrate * 3) + rate) / 4;
1059
1060       src->prev_rtime = running_time;
1061       *bytes_handled = 0;
1062     }
1063   } else {
1064     GST_LOG ("Reset bitrate measurement");
1065     src->prev_rtime = running_time;
1066     src->bitrate = 0;
1067   }
1068 }
1069
1070 static gboolean
1071 update_receiver_stats (RTPSource * src, RTPPacketInfo * pinfo,
1072     gboolean is_receive)
1073 {
1074   guint16 seqnr, expected;
1075   RTPSourceStats *stats;
1076   gint16 delta;
1077   gint32 packet_rate, max_dropout, max_misorder;
1078
1079   stats = &src->stats;
1080
1081   seqnr = pinfo->seqnum;
1082
1083   packet_rate =
1084       gst_rtp_packet_rate_ctx_update (&src->packet_rate_ctx, pinfo->seqnum,
1085       pinfo->rtptime);
1086   max_dropout =
1087       gst_rtp_packet_rate_ctx_get_max_dropout (&src->packet_rate_ctx,
1088       src->max_dropout_time);
1089   max_misorder =
1090       gst_rtp_packet_rate_ctx_get_max_misorder (&src->packet_rate_ctx,
1091       src->max_misorder_time);
1092   GST_TRACE ("SSRC %08x, packet_rate: %d, max_dropout: %d, max_misorder: %d",
1093       src->ssrc, packet_rate, max_dropout, max_misorder);
1094
1095   if (stats->cycles == -1) {
1096     GST_DEBUG ("received first packet");
1097     /* first time we heard of this source */
1098     init_seq (src, seqnr);
1099     src->stats.max_seq = seqnr - 1;
1100     src->curr_probation = src->probation;
1101   }
1102
1103   if (is_receive) {
1104     expected = src->stats.max_seq + 1;
1105     delta = gst_rtp_buffer_compare_seqnum (expected, seqnr);
1106
1107     /* if we are still on probation, check seqnum */
1108     if (src->curr_probation) {
1109       /* when in probation, we require consecutive seqnums */
1110       if (delta == 0) {
1111         /* expected packet */
1112         GST_DEBUG ("probation: seqnr %d == expected %d", seqnr, expected);
1113         src->curr_probation--;
1114         if (seqnr < stats->max_seq) {
1115           /* sequence number wrapped - count another 64K cycle. */
1116           stats->cycles += RTP_SEQ_MOD;
1117         }
1118         src->stats.max_seq = seqnr;
1119
1120         if (src->curr_probation == 0) {
1121           GST_DEBUG ("probation done!");
1122           init_seq (src, seqnr);
1123         } else {
1124           GstBuffer *q;
1125
1126           GST_DEBUG ("probation %d: queue packet", src->curr_probation);
1127           /* when still in probation, keep packets in a list. */
1128           g_queue_push_tail (src->packets, pinfo->data);
1129           pinfo->data = NULL;
1130           /* remove packets from queue if there are too many */
1131           while (g_queue_get_length (src->packets) > RTP_MAX_PROBATION_LEN) {
1132             q = g_queue_pop_head (src->packets);
1133             gst_buffer_unref (q);
1134           }
1135           goto done;
1136         }
1137       } else {
1138         /* unexpected seqnum in probation
1139          *
1140          * There is no need to clean the queue at this point because the
1141          * invalid packets in the queue are not going to be pushed as we are
1142          * still in probation, and some cleanup will be performed at future
1143          * probation attempts anyway if there are too many old packets in the
1144          * queue.
1145          */
1146         goto probation_seqnum;
1147       }
1148     } else if (delta >= 0 && delta < max_dropout) {
1149       /* Clear bad packets */
1150       stats->bad_seq = RTP_SEQ_MOD + 1; /* so seq == bad_seq is false */
1151       g_queue_foreach (src->packets, (GFunc) gst_buffer_unref, NULL);
1152       g_queue_clear (src->packets);
1153
1154       /* in order, with permissible gap */
1155       if (seqnr < stats->max_seq) {
1156         /* sequence number wrapped - count another 64K cycle. */
1157         stats->cycles += RTP_SEQ_MOD;
1158       }
1159       stats->max_seq = seqnr;
1160     } else if (delta < -max_misorder || delta >= max_dropout) {
1161       /* the sequence number made a very large jump */
1162       if (seqnr == stats->bad_seq && src->packets->head) {
1163         /* two sequential packets -- assume that the other side
1164          * restarted without telling us so just re-sync
1165          * (i.e., pretend this was the first packet).  */
1166         init_seq (src, seqnr);
1167       } else {
1168         /* unacceptable jump */
1169         stats->bad_seq = (seqnr + 1) & (RTP_SEQ_MOD - 1);
1170         g_queue_foreach (src->packets, (GFunc) gst_buffer_unref, NULL);
1171         g_queue_clear (src->packets);
1172         g_queue_push_tail (src->packets, pinfo->data);
1173         pinfo->data = NULL;
1174         goto bad_sequence;
1175       }
1176     } else {                    /* delta < 0 && delta >= -max_misorder */
1177       /* Clear bad packets */
1178       stats->bad_seq = RTP_SEQ_MOD + 1; /* so seq == bad_seq is false */
1179       g_queue_foreach (src->packets, (GFunc) gst_buffer_unref, NULL);
1180       g_queue_clear (src->packets);
1181
1182       /* duplicate or reordered packet, will be filtered by jitterbuffer. */
1183       GST_INFO ("duplicate or reordered packet (seqnr %u, expected %u)",
1184           seqnr, expected);
1185     }
1186   }
1187
1188   src->stats.octets_received += pinfo->payload_len;
1189   src->stats.bytes_received += pinfo->bytes;
1190   src->stats.packets_received += pinfo->packets;
1191   /* for the bitrate estimation */
1192   src->bytes_received += pinfo->payload_len;
1193
1194   GST_LOG ("seq %u, PC: %" G_GUINT64_FORMAT ", OC: %" G_GUINT64_FORMAT,
1195       seqnr, src->stats.packets_received, src->stats.octets_received);
1196
1197   return TRUE;
1198
1199   /* ERRORS */
1200 done:
1201   {
1202     return FALSE;
1203   }
1204 bad_sequence:
1205   {
1206     GST_WARNING
1207         ("unacceptable seqnum received (seqnr %u, delta %d, packet_rate: %d, max_dropout: %d, max_misorder: %d)",
1208         seqnr, delta, packet_rate, max_dropout, max_misorder);
1209     return FALSE;
1210   }
1211 probation_seqnum:
1212   {
1213     GST_WARNING ("probation: seqnr %d != expected %d "
1214         "(SSRC %u curr_probation %i probation %i)", seqnr, expected, src->ssrc,
1215         src->curr_probation, src->probation);
1216     src->curr_probation = src->probation;
1217     src->stats.max_seq = seqnr;
1218     return FALSE;
1219   }
1220 }
1221
1222 /**
1223  * rtp_source_process_rtp:
1224  * @src: an #RTPSource
1225  * @pinfo: an #RTPPacketInfo
1226  *
1227  * Let @src handle the incoming RTP packet described in @pinfo.
1228  *
1229  * Returns: a #GstFlowReturn.
1230  */
1231 GstFlowReturn
1232 rtp_source_process_rtp (RTPSource * src, RTPPacketInfo * pinfo)
1233 {
1234   GstFlowReturn result;
1235
1236   g_return_val_if_fail (RTP_IS_SOURCE (src), GST_FLOW_ERROR);
1237   g_return_val_if_fail (pinfo != NULL, GST_FLOW_ERROR);
1238
1239   if (!update_receiver_stats (src, pinfo, TRUE))
1240     return GST_FLOW_OK;
1241
1242   /* the source that sent the packet must be a sender */
1243   src->is_sender = TRUE;
1244   src->validated = TRUE;
1245
1246   do_bitrate_estimation (src, pinfo->running_time, &src->bytes_received);
1247
1248   /* calculate jitter for the stats */
1249   calculate_jitter (src, pinfo);
1250
1251   /* we're ready to push the RTP packet now */
1252   result = push_packet (src, pinfo->data);
1253   pinfo->data = NULL;
1254
1255   return result;
1256 }
1257
1258 /**
1259  * rtp_source_mark_bye:
1260  * @src: an #RTPSource
1261  * @reason: the reason for leaving
1262  *
1263  * Mark @src in the BYE state. This can happen when the source wants to
1264  * leave the sesssion or when a BYE packets has been received.
1265  *
1266  * This will make the source inactive.
1267  */
1268 void
1269 rtp_source_mark_bye (RTPSource * src, const gchar * reason)
1270 {
1271   g_return_if_fail (RTP_IS_SOURCE (src));
1272
1273   GST_DEBUG ("marking SSRC %08x as BYE, reason: %s", src->ssrc,
1274       GST_STR_NULL (reason));
1275
1276   /* copy the reason and mark as bye */
1277   g_free (src->bye_reason);
1278   src->bye_reason = g_strdup (reason);
1279   src->marked_bye = TRUE;
1280 }
1281
1282 /**
1283  * rtp_source_send_rtp:
1284  * @src: an #RTPSource
1285  * @pinfo: an #RTPPacketInfo
1286  *
1287  * Send data (an RTP buffer or buffer list from @pinfo) originating from @src.
1288  * This will make @src a sender. This function takes ownership of the data and
1289  * modifies the SSRC in the RTP packet to that of @src when needed.
1290  *
1291  * Returns: a #GstFlowReturn.
1292  */
1293 GstFlowReturn
1294 rtp_source_send_rtp (RTPSource * src, RTPPacketInfo * pinfo)
1295 {
1296   GstFlowReturn result;
1297   GstClockTime running_time;
1298   guint32 rtptime;
1299   guint64 ext_rtptime;
1300   guint64 rt_diff, rtp_diff;
1301
1302   g_return_val_if_fail (RTP_IS_SOURCE (src), GST_FLOW_ERROR);
1303
1304   /* we are a sender now */
1305   src->is_sender = TRUE;
1306
1307   /* we are also a receiver of our packets */
1308   if (!update_receiver_stats (src, pinfo, FALSE))
1309     return GST_FLOW_OK;
1310
1311   if (src->pt_set && src->pt != pinfo->pt) {
1312     GST_WARNING ("Changing pt from %u to %u for SSRC %u", src->pt, pinfo->pt,
1313         src->ssrc);
1314   }
1315
1316   src->pt = pinfo->pt;
1317   src->pt_set = TRUE;
1318
1319   /* update stats for the SR */
1320   src->stats.packets_sent += pinfo->packets;
1321   src->stats.octets_sent += pinfo->payload_len;
1322   src->bytes_sent += pinfo->payload_len;
1323
1324   running_time = pinfo->running_time;
1325
1326   do_bitrate_estimation (src, running_time, &src->bytes_sent);
1327
1328   rtptime = pinfo->rtptime;
1329
1330   ext_rtptime = src->last_rtptime;
1331   ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
1332
1333   GST_LOG ("SSRC %08x, RTP %" G_GUINT64_FORMAT ", running_time %"
1334       GST_TIME_FORMAT, src->ssrc, ext_rtptime, GST_TIME_ARGS (running_time));
1335
1336   if (ext_rtptime > src->last_rtptime) {
1337     rtp_diff = ext_rtptime - src->last_rtptime;
1338     rt_diff = running_time - src->last_rtime;
1339
1340     /* calc the diff so we can detect drift at the sender. This can also be used
1341      * to guestimate the clock rate if the NTP time is locked to the RTP
1342      * timestamps (as is the case when the capture device is providing the clock). */
1343     GST_LOG ("SSRC %08x, diff RTP %" G_GUINT64_FORMAT ", diff running_time %"
1344         GST_TIME_FORMAT, src->ssrc, rtp_diff, GST_TIME_ARGS (rt_diff));
1345   }
1346
1347   /* we keep track of the last received RTP timestamp and the corresponding
1348    * buffer running_time so that we can use this info when constructing SR reports */
1349   src->last_rtime = running_time;
1350   src->last_rtptime = ext_rtptime;
1351
1352   /* push packet */
1353   if (!src->callbacks.push_rtp)
1354     goto no_callback;
1355
1356   GST_LOG ("pushing RTP %s %" G_GUINT64_FORMAT,
1357       pinfo->is_list ? "list" : "packet", src->stats.packets_sent);
1358
1359   result = src->callbacks.push_rtp (src, pinfo->data, src->user_data);
1360   pinfo->data = NULL;
1361
1362   return result;
1363
1364   /* ERRORS */
1365 no_callback:
1366   {
1367     GST_WARNING ("no callback installed, dropping packet");
1368     return GST_FLOW_OK;
1369   }
1370 }
1371
1372 /**
1373  * rtp_source_process_sr:
1374  * @src: an #RTPSource
1375  * @time: time of packet arrival
1376  * @ntptime: the NTP time (in NTP Timestamp Format, 32.32 fixed point)
1377  * @rtptime: the RTP time (in clock rate units)
1378  * @packet_count: the packet count
1379  * @octet_count: the octet count
1380  *
1381  * Update the sender report in @src.
1382  */
1383 void
1384 rtp_source_process_sr (RTPSource * src, GstClockTime time, guint64 ntptime,
1385     guint32 rtptime, guint32 packet_count, guint32 octet_count)
1386 {
1387   RTPSenderReport *curr;
1388   gint curridx;
1389
1390   g_return_if_fail (RTP_IS_SOURCE (src));
1391
1392   GST_DEBUG ("got SR packet: SSRC %08x, NTP %08x:%08x, RTP %" G_GUINT32_FORMAT
1393       ", PC %" G_GUINT32_FORMAT ", OC %" G_GUINT32_FORMAT, src->ssrc,
1394       (guint32) (ntptime >> 32), (guint32) (ntptime & 0xffffffff), rtptime,
1395       packet_count, octet_count);
1396
1397   curridx = src->stats.curr_sr ^ 1;
1398   curr = &src->stats.sr[curridx];
1399
1400   /* this is a sender now */
1401   src->is_sender = TRUE;
1402
1403   /* update current */
1404   curr->is_valid = TRUE;
1405   curr->ntptime = ntptime;
1406   curr->rtptime = rtptime;
1407   curr->packet_count = packet_count;
1408   curr->octet_count = octet_count;
1409   curr->time = time;
1410
1411   /* make current */
1412   src->stats.curr_sr = curridx;
1413
1414   src->stats.prev_rtcptime = src->stats.last_rtcptime;
1415   src->stats.last_rtcptime = time;
1416 }
1417
1418 /**
1419  * rtp_source_process_rb:
1420  * @src: an #RTPSource
1421  * @ntpnstime: the current time in nanoseconds since 1970
1422  * @fractionlost: fraction lost since last SR/RR
1423  * @packetslost: the cumulative number of packets lost
1424  * @exthighestseq: the extended last sequence number received
1425  * @jitter: the interarrival jitter (in clock rate units)
1426  * @lsr: the time of the last SR packet on this source
1427  *   (in NTP Short Format, 16.16 fixed point)
1428  * @dlsr: the delay since the last SR packet
1429  *   (in NTP Short Format, 16.16 fixed point)
1430  *
1431  * Update the report block in @src.
1432  */
1433 void
1434 rtp_source_process_rb (RTPSource * src, guint64 ntpnstime,
1435     guint8 fractionlost, gint32 packetslost, guint32 exthighestseq,
1436     guint32 jitter, guint32 lsr, guint32 dlsr)
1437 {
1438   RTPReceiverReport *curr;
1439   gint curridx;
1440   guint32 ntp, A;
1441   guint64 f_ntp;
1442
1443   g_return_if_fail (RTP_IS_SOURCE (src));
1444
1445   GST_DEBUG ("got RB packet: SSRC %08x, FL %2x, PL %d, HS %" G_GUINT32_FORMAT
1446       ", jitter %" G_GUINT32_FORMAT ", LSR %04x:%04x, DLSR %04x:%04x",
1447       src->ssrc, fractionlost, packetslost, exthighestseq, jitter, lsr >> 16,
1448       lsr & 0xffff, dlsr >> 16, dlsr & 0xffff);
1449
1450   curridx = src->stats.curr_rr ^ 1;
1451   curr = &src->stats.rr[curridx];
1452
1453   /* update current */
1454   curr->is_valid = TRUE;
1455   curr->fractionlost = fractionlost;
1456   curr->packetslost = packetslost;
1457   curr->exthighestseq = exthighestseq;
1458   curr->jitter = jitter;
1459   curr->lsr = lsr;
1460   curr->dlsr = dlsr;
1461
1462   /* convert the NTP time in nanoseconds to 32.32 fixed point */
1463   f_ntp = gst_util_uint64_scale (ntpnstime, (1LL << 32), GST_SECOND);
1464   /* calculate round trip, round the time up */
1465   ntp = ((f_ntp + 0xffff) >> 16) & 0xffffffff;
1466
1467   A = dlsr + lsr;
1468   if (A > 0 && ntp > A)
1469     A = ntp - A;
1470   else
1471     A = 0;
1472   curr->round_trip = A;
1473
1474   GST_DEBUG ("NTP %04x:%04x, round trip %04x:%04x", ntp >> 16, ntp & 0xffff,
1475       A >> 16, A & 0xffff);
1476
1477   /* make current */
1478   src->stats.curr_rr = curridx;
1479 }
1480
1481 /**
1482  * rtp_source_get_new_sr:
1483  * @src: an #RTPSource
1484  * @ntpnstime: the current time in nanoseconds since 1970
1485  * @running_time: the current running_time of the pipeline
1486  * @ntptime: the NTP time (in NTP Timestamp Format, 32.32 fixed point)
1487  * @rtptime: the RTP time corresponding to @ntptime (in clock rate units)
1488  * @packet_count: the packet count
1489  * @octet_count: the octet count
1490  *
1491  * Get new values to put into a new SR report from this source.
1492  *
1493  * @running_time and @ntpnstime are captured at the same time and represent the
1494  * running time of the pipeline clock and the absolute current system time in
1495  * nanoseconds respectively. Together with the last running_time and RTP timestamp
1496  * we have observed in the source, we can generate @ntptime and @rtptime for an SR
1497  * packet. @ntptime is basically the fixed point representation of @ntpnstime
1498  * and @rtptime the associated RTP timestamp.
1499  *
1500  * Returns: %TRUE on success.
1501  */
1502 gboolean
1503 rtp_source_get_new_sr (RTPSource * src, guint64 ntpnstime,
1504     GstClockTime running_time, guint64 * ntptime, guint32 * rtptime,
1505     guint32 * packet_count, guint32 * octet_count)
1506 {
1507   guint64 t_rtp;
1508   guint64 t_current_ntp;
1509   GstClockTimeDiff diff;
1510
1511   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1512
1513   /* We last saw a buffer with last_rtptime at last_rtime. Given a running_time
1514    * and an NTP time, we can scale the RTP timestamps so that they match the
1515    * given NTP time.  for scaling, we assume that the slope of the rtptime vs
1516    * running_time vs ntptime curve is close to 1, which is certainly
1517    * sufficient for the frequency at which we report SR and the rate we send
1518    * out RTP packets. */
1519   t_rtp = src->last_rtptime;
1520
1521   GST_DEBUG ("last_rtime %" GST_TIME_FORMAT ", last_rtptime %"
1522       G_GUINT64_FORMAT, GST_TIME_ARGS (src->last_rtime), t_rtp);
1523
1524   if (src->clock_rate == -1 && src->pt_set) {
1525     GST_INFO ("no clock-rate, getting for pt %u and SSRC %u", src->pt,
1526         src->ssrc);
1527     get_clock_rate (src, src->pt);
1528   }
1529
1530   if (src->clock_rate != -1) {
1531     /* get the diff between the clock running_time and the buffer running_time.
1532      * This is the elapsed time, as measured against the pipeline clock, between
1533      * when the rtp timestamp was observed and the current running_time.
1534      *
1535      * We need to apply this diff to the RTP timestamp to get the RTP timestamp
1536      * for the given ntpnstime. */
1537     diff = GST_CLOCK_DIFF (src->last_rtime, running_time);
1538     GST_DEBUG ("running_time %" GST_TIME_FORMAT ", diff %" GST_STIME_FORMAT,
1539         GST_TIME_ARGS (running_time), GST_STIME_ARGS (diff));
1540
1541     /* now translate the diff to RTP time, handle positive and negative cases.
1542      * If there is no diff, we already set rtptime correctly above. */
1543     if (diff > 0) {
1544       t_rtp += gst_util_uint64_scale_int (diff, src->clock_rate, GST_SECOND);
1545     } else {
1546       diff = -diff;
1547       t_rtp -= gst_util_uint64_scale_int (diff, src->clock_rate, GST_SECOND);
1548     }
1549   } else {
1550     GST_WARNING ("no clock-rate, cannot interpolate rtp time for SSRC %u",
1551         src->ssrc);
1552   }
1553
1554   /* convert the NTP time in nanoseconds to 32.32 fixed point */
1555   t_current_ntp = gst_util_uint64_scale (ntpnstime, (1LL << 32), GST_SECOND);
1556
1557   GST_DEBUG ("NTP %08x:%08x, RTP %" G_GUINT32_FORMAT,
1558       (guint32) (t_current_ntp >> 32), (guint32) (t_current_ntp & 0xffffffff),
1559       (guint32) t_rtp);
1560
1561   if (ntptime)
1562     *ntptime = t_current_ntp;
1563   if (rtptime)
1564     *rtptime = t_rtp;
1565   if (packet_count)
1566     *packet_count = src->stats.packets_sent;
1567   if (octet_count)
1568     *octet_count = src->stats.octets_sent;
1569
1570   return TRUE;
1571 }
1572
1573 /**
1574  * rtp_source_get_new_rb:
1575  * @src: an #RTPSource
1576  * @time: the current time of the system clock
1577  * @fractionlost: fraction lost since last SR/RR
1578  * @packetslost: the cumulative number of packets lost
1579  * @exthighestseq: the extended last sequence number received
1580  * @jitter: the interarrival jitter (in clock rate units)
1581  * @lsr: the time of the last SR packet on this source
1582  *   (in NTP Short Format, 16.16 fixed point)
1583  * @dlsr: the delay since the last SR packet
1584  *   (in NTP Short Format, 16.16 fixed point)
1585  *
1586  * Get new values to put into a new report block from this source.
1587  *
1588  * Returns: %TRUE on success.
1589  */
1590 gboolean
1591 rtp_source_get_new_rb (RTPSource * src, GstClockTime time,
1592     guint8 * fractionlost, gint32 * packetslost, guint32 * exthighestseq,
1593     guint32 * jitter, guint32 * lsr, guint32 * dlsr)
1594 {
1595   RTPSourceStats *stats;
1596   guint64 extended_max, expected;
1597   guint64 expected_interval, received_interval, ntptime;
1598   gint64 lost, lost_interval;
1599   guint32 fraction, LSR, DLSR;
1600   GstClockTime sr_time;
1601
1602   stats = &src->stats;
1603
1604   extended_max = stats->cycles + stats->max_seq;
1605   expected = extended_max - stats->base_seq + 1;
1606
1607   GST_DEBUG ("ext_max %" G_GUINT64_FORMAT ", expected %" G_GUINT64_FORMAT
1608       ", received %" G_GUINT64_FORMAT ", base_seq %" G_GUINT32_FORMAT,
1609       extended_max, expected, stats->packets_received, stats->base_seq);
1610
1611   lost = expected - stats->packets_received;
1612   lost = CLAMP (lost, -0x800000, 0x7fffff);
1613
1614   expected_interval = expected - stats->prev_expected;
1615   stats->prev_expected = expected;
1616   received_interval = stats->packets_received - stats->prev_received;
1617   stats->prev_received = stats->packets_received;
1618
1619   lost_interval = expected_interval - received_interval;
1620
1621   if (expected_interval == 0 || lost_interval <= 0)
1622     fraction = 0;
1623   else
1624     fraction = (lost_interval << 8) / expected_interval;
1625
1626   GST_DEBUG ("add RR for SSRC %08x", src->ssrc);
1627   /* we scaled the jitter up for additional precision */
1628   GST_DEBUG ("fraction %" G_GUINT32_FORMAT ", lost %" G_GINT64_FORMAT
1629       ", extseq %" G_GUINT64_FORMAT ", jitter %d", fraction, lost,
1630       extended_max, stats->jitter >> 4);
1631
1632   if (rtp_source_get_last_sr (src, &sr_time, &ntptime, NULL, NULL, NULL)) {
1633     GstClockTime diff;
1634
1635     /* LSR is middle 32 bits of the last ntptime */
1636     LSR = (ntptime >> 16) & 0xffffffff;
1637     diff = time - sr_time;
1638     GST_DEBUG ("last SR time diff %" GST_TIME_FORMAT, GST_TIME_ARGS (diff));
1639     /* DLSR, delay since last SR is expressed in 1/65536 second units */
1640     DLSR = gst_util_uint64_scale_int (diff, 65536, GST_SECOND);
1641   } else {
1642     /* No valid SR received, LSR/DLSR are set to 0 then */
1643     GST_DEBUG ("no valid SR received");
1644     LSR = 0;
1645     DLSR = 0;
1646   }
1647   GST_DEBUG ("LSR %04x:%04x, DLSR %04x:%04x", LSR >> 16, LSR & 0xffff,
1648       DLSR >> 16, DLSR & 0xffff);
1649
1650   if (fractionlost)
1651     *fractionlost = fraction;
1652   if (packetslost)
1653     *packetslost = lost;
1654   if (exthighestseq)
1655     *exthighestseq = extended_max;
1656   if (jitter)
1657     *jitter = stats->jitter >> 4;
1658   if (lsr)
1659     *lsr = LSR;
1660   if (dlsr)
1661     *dlsr = DLSR;
1662
1663   return TRUE;
1664 }
1665
1666 /**
1667  * rtp_source_get_last_sr:
1668  * @src: an #RTPSource
1669  * @time: time of packet arrival
1670  * @ntptime: the NTP time (in NTP Timestamp Format, 32.32 fixed point)
1671  * @rtptime: the RTP time (in clock rate units)
1672  * @packet_count: the packet count
1673  * @octet_count: the octet count
1674  *
1675  * Get the values of the last sender report as set with rtp_source_process_sr().
1676  *
1677  * Returns: %TRUE if there was a valid SR report.
1678  */
1679 gboolean
1680 rtp_source_get_last_sr (RTPSource * src, GstClockTime * time, guint64 * ntptime,
1681     guint32 * rtptime, guint32 * packet_count, guint32 * octet_count)
1682 {
1683   RTPSenderReport *curr;
1684
1685   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1686
1687   curr = &src->stats.sr[src->stats.curr_sr];
1688   if (!curr->is_valid)
1689     return FALSE;
1690
1691   if (ntptime)
1692     *ntptime = curr->ntptime;
1693   if (rtptime)
1694     *rtptime = curr->rtptime;
1695   if (packet_count)
1696     *packet_count = curr->packet_count;
1697   if (octet_count)
1698     *octet_count = curr->octet_count;
1699   if (time)
1700     *time = curr->time;
1701
1702   return TRUE;
1703 }
1704
1705 /**
1706  * rtp_source_get_last_rb:
1707  * @src: an #RTPSource
1708  * @fractionlost: fraction lost since last SR/RR
1709  * @packetslost: the cumulative number of packets lost
1710  * @exthighestseq: the extended last sequence number received
1711  * @jitter: the interarrival jitter (in clock rate units)
1712  * @lsr: the time of the last SR packet on this source
1713  *   (in NTP Short Format, 16.16 fixed point)
1714  * @dlsr: the delay since the last SR packet
1715  *   (in NTP Short Format, 16.16 fixed point)
1716  * @round_trip: the round-trip time
1717  *   (in NTP Short Format, 16.16 fixed point)
1718  *
1719  * Get the values of the last RB report set with rtp_source_process_rb().
1720  *
1721  * Returns: %TRUE if there was a valid SB report.
1722  */
1723 gboolean
1724 rtp_source_get_last_rb (RTPSource * src, guint8 * fractionlost,
1725     gint32 * packetslost, guint32 * exthighestseq, guint32 * jitter,
1726     guint32 * lsr, guint32 * dlsr, guint32 * round_trip)
1727 {
1728   RTPReceiverReport *curr;
1729
1730   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1731
1732   curr = &src->stats.rr[src->stats.curr_rr];
1733   if (!curr->is_valid)
1734     return FALSE;
1735
1736   if (fractionlost)
1737     *fractionlost = curr->fractionlost;
1738   if (packetslost)
1739     *packetslost = curr->packetslost;
1740   if (exthighestseq)
1741     *exthighestseq = curr->exthighestseq;
1742   if (jitter)
1743     *jitter = curr->jitter;
1744   if (lsr)
1745     *lsr = curr->lsr;
1746   if (dlsr)
1747     *dlsr = curr->dlsr;
1748   if (round_trip)
1749     *round_trip = curr->round_trip;
1750
1751   return TRUE;
1752 }
1753
1754 gboolean
1755 find_conflicting_address (GList * conflicting_addresses,
1756     GSocketAddress * address, GstClockTime time)
1757 {
1758   GList *item;
1759
1760   for (item = conflicting_addresses; item; item = g_list_next (item)) {
1761     RTPConflictingAddress *known_conflict = item->data;
1762
1763     if (__g_socket_address_equal (address, known_conflict->address)) {
1764       known_conflict->time = time;
1765       return TRUE;
1766     }
1767   }
1768
1769   return FALSE;
1770 }
1771
1772 GList *
1773 add_conflicting_address (GList * conflicting_addresses,
1774     GSocketAddress * address, GstClockTime time)
1775 {
1776   RTPConflictingAddress *new_conflict;
1777
1778   new_conflict = g_slice_new (RTPConflictingAddress);
1779
1780   new_conflict->address = G_SOCKET_ADDRESS (g_object_ref (address));
1781   new_conflict->time = time;
1782
1783   return g_list_prepend (conflicting_addresses, new_conflict);
1784 }
1785
1786 GList *
1787 timeout_conflicting_addresses (GList * conflicting_addresses,
1788     GstClockTime current_time)
1789 {
1790   GList *item;
1791   /* "a relatively long time" -- RFC 3550 section 8.2 */
1792   const GstClockTime collision_timeout =
1793       RTP_STATS_MIN_INTERVAL * GST_SECOND * 10;
1794
1795   item = g_list_first (conflicting_addresses);
1796   while (item) {
1797     RTPConflictingAddress *known_conflict = item->data;
1798     GList *next_item = g_list_next (item);
1799
1800     if (known_conflict->time < current_time - collision_timeout) {
1801       gchar *buf;
1802
1803       conflicting_addresses = g_list_delete_link (conflicting_addresses, item);
1804       buf = __g_socket_address_to_string (known_conflict->address);
1805       GST_DEBUG ("collision %p timed out: %s", known_conflict, buf);
1806       g_free (buf);
1807       rtp_conflicting_address_free (known_conflict);
1808     }
1809     item = next_item;
1810   }
1811
1812   return conflicting_addresses;
1813 }
1814
1815 /**
1816  * rtp_source_find_conflicting_address:
1817  * @src: The source the packet came in
1818  * @address: address to check for
1819  * @time: The time when the packet that is possibly in conflict arrived
1820  *
1821  * Checks if an address which has a conflict is already known. If it is
1822  * a known conflict, remember the time
1823  *
1824  * Returns: TRUE if it was a known conflict, FALSE otherwise
1825  */
1826 gboolean
1827 rtp_source_find_conflicting_address (RTPSource * src, GSocketAddress * address,
1828     GstClockTime time)
1829 {
1830   return find_conflicting_address (src->conflicting_addresses, address, time);
1831 }
1832
1833 /**
1834  * rtp_source_add_conflicting_address:
1835  * @src: The source the packet came in
1836  * @address: address to remember
1837  * @time: The time when the packet that is in conflict arrived
1838  *
1839  * Adds a new conflict address
1840  */
1841 void
1842 rtp_source_add_conflicting_address (RTPSource * src,
1843     GSocketAddress * address, GstClockTime time)
1844 {
1845   src->conflicting_addresses =
1846       add_conflicting_address (src->conflicting_addresses, address, time);
1847 }
1848
1849 /**
1850  * rtp_source_timeout:
1851  * @src: The #RTPSource
1852  * @current_time: The current time
1853  * @feedback_retention_window: The running time before which retained feedback
1854  * packets have to be discarded
1855  *
1856  * This is processed on each RTCP interval. It times out old collisions.
1857  * It also times out old retained feedback packets
1858  */
1859 void
1860 rtp_source_timeout (RTPSource * src, GstClockTime current_time,
1861     GstClockTime running_time, GstClockTime feedback_retention_window)
1862 {
1863   GstRTCPPacket *pkt;
1864   GstClockTime max_pts_window;
1865   guint pruned = 0;
1866
1867   src->conflicting_addresses =
1868       timeout_conflicting_addresses (src->conflicting_addresses, current_time);
1869
1870   if (feedback_retention_window == GST_CLOCK_TIME_NONE ||
1871       running_time < feedback_retention_window) {
1872     return;
1873   }
1874
1875   max_pts_window = running_time - feedback_retention_window;
1876
1877   /* Time out AVPF packets that are older than the desired length */
1878   while ((pkt = g_queue_peek_head (src->retained_feedback)) &&
1879       GST_BUFFER_PTS (pkt) < max_pts_window) {
1880     gst_buffer_unref (g_queue_pop_head (src->retained_feedback));
1881     pruned++;
1882   }
1883
1884   GST_LOG_OBJECT (src,
1885       "%u RTCP packets pruned with PTS less than %" GST_TIME_FORMAT
1886       ", queue len: %u", pruned, GST_TIME_ARGS (max_pts_window),
1887       g_queue_get_length (src->retained_feedback));
1888 }
1889
1890 static gint
1891 compare_buffers (gconstpointer a, gconstpointer b, gpointer user_data)
1892 {
1893   const GstBuffer *bufa = a;
1894   const GstBuffer *bufb = b;
1895
1896   g_return_val_if_fail (GST_BUFFER_PTS (bufa) != GST_CLOCK_TIME_NONE, -1);
1897   g_return_val_if_fail (GST_BUFFER_PTS (bufb) != GST_CLOCK_TIME_NONE, 1);
1898
1899   if (GST_BUFFER_PTS (bufa) < GST_BUFFER_PTS (bufb)) {
1900     return -1;
1901   } else if (GST_BUFFER_PTS (bufa) > GST_BUFFER_PTS (bufb)) {
1902     return 1;
1903   }
1904
1905   return 0;
1906 }
1907
1908 void
1909 rtp_source_retain_rtcp_packet (RTPSource * src, GstRTCPPacket * packet,
1910     GstClockTime running_time)
1911 {
1912   GstBuffer *buffer;
1913
1914   g_return_if_fail (running_time != GST_CLOCK_TIME_NONE);
1915
1916   buffer = gst_buffer_copy_region (packet->rtcp->buffer, GST_BUFFER_COPY_MEMORY,
1917       packet->offset, (gst_rtcp_packet_get_length (packet) + 1) * 4);
1918
1919   GST_BUFFER_PTS (buffer) = running_time;
1920
1921   g_queue_insert_sorted (src->retained_feedback, buffer, compare_buffers, NULL);
1922
1923   GST_LOG_OBJECT (src, "RTCP packet retained with PTS: %" GST_TIME_FORMAT,
1924       GST_TIME_ARGS (running_time));
1925 }
1926
1927 gboolean
1928 rtp_source_has_retained (RTPSource * src, GCompareFunc func, gconstpointer data)
1929 {
1930   if (g_queue_find_custom (src->retained_feedback, data, func))
1931     return TRUE;
1932   else
1933     return FALSE;
1934 }
1935
1936 /**
1937  * rtp_source_register_nack:
1938  * @src: The #RTPSource
1939  * @seqnum: a seqnum
1940  * @deadline: the deadline before which RTX is still possible
1941  *
1942  * Register that @seqnum has not been received from @src.
1943  */
1944 void
1945 rtp_source_register_nack (RTPSource * src, guint16 seqnum,
1946     GstClockTime deadline)
1947 {
1948   gint i;
1949   guint len;
1950   gint diff = -1;
1951   guint16 tseq;
1952
1953   len = src->nacks->len;
1954   for (i = len - 1; i >= 0; i--) {
1955     tseq = g_array_index (src->nacks, guint16, i);
1956     diff = gst_rtp_buffer_compare_seqnum (tseq, seqnum);
1957
1958     GST_TRACE ("[%u] %u %u diff %i len %u", i, tseq, seqnum, diff, len);
1959
1960     if (diff >= 0)
1961       break;
1962   }
1963
1964   if (diff == 0) {
1965     GST_DEBUG ("update NACK #%u deadline to %" GST_TIME_FORMAT, seqnum,
1966         GST_TIME_ARGS (deadline));
1967     g_array_index (src->nack_deadlines, GstClockTime, i) = deadline;
1968   } else if (i == len - 1) {
1969     GST_DEBUG ("append NACK #%u with deadline %" GST_TIME_FORMAT, seqnum,
1970         GST_TIME_ARGS (deadline));
1971     g_array_append_val (src->nacks, seqnum);
1972     g_array_append_val (src->nack_deadlines, deadline);
1973   } else {
1974     GST_DEBUG ("insert NACK #%u with deadline %" GST_TIME_FORMAT, seqnum,
1975         GST_TIME_ARGS (deadline));
1976     g_array_insert_val (src->nacks, i + 1, seqnum);
1977     g_array_insert_val (src->nack_deadlines, i + 1, deadline);
1978   }
1979
1980   src->send_nack = TRUE;
1981 }
1982
1983 /**
1984  * rtp_source_get_nacks:
1985  * @src: The #RTPSource
1986  * @n_nacks: result number of nacks
1987  *
1988  * Get the registered NACKS since the last rtp_source_clear_nacks().
1989  *
1990  * Returns: an array of @n_nacks seqnum values.
1991  */
1992 guint16 *
1993 rtp_source_get_nacks (RTPSource * src, guint * n_nacks)
1994 {
1995   if (n_nacks)
1996     *n_nacks = src->nacks->len;
1997
1998   return (guint16 *) src->nacks->data;
1999 }
2000
2001 /**
2002  * rtp_source_get_nacks:
2003  * @src: The #RTPSource
2004  * @n_nacks: result number of nacks
2005  *
2006  * Get the registered NACKS deadlines.
2007  *
2008  * Returns: an array of @n_nacks deadline values.
2009  */
2010 GstClockTime *
2011 rtp_source_get_nack_deadlines (RTPSource * src, guint * n_nacks)
2012 {
2013   if (n_nacks)
2014     *n_nacks = src->nack_deadlines->len;
2015
2016   return (GstClockTime *) src->nack_deadlines->data;
2017 }
2018
2019 /**
2020  * rtp_source_clear_nacks:
2021  * @src: The #RTPSource
2022  * @n_nacks: number of nacks
2023  *
2024  * Remove @n_nacks oldest NACKS form array.
2025  */
2026 void
2027 rtp_source_clear_nacks (RTPSource * src, guint n_nacks)
2028 {
2029   g_return_if_fail (n_nacks <= src->nacks->len);
2030
2031   if (src->nacks->len == n_nacks) {
2032     g_array_set_size (src->nacks, 0);
2033     g_array_set_size (src->nack_deadlines, 0);
2034     src->send_nack = FALSE;
2035   } else {
2036     g_array_remove_range (src->nacks, 0, n_nacks);
2037     g_array_remove_range (src->nack_deadlines, 0, n_nacks);
2038   }
2039 }