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