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