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