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