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