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