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