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