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