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