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