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