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