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