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