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