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