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