Add ssrc to application/x-rtp-source-sdes structure
[platform/upstream/gst-plugins-good.git] / gst / rtpmanager / rtpsource.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19 #include <string.h>
20
21 #include <gst/rtp/gstrtpbuffer.h>
22 #include <gst/rtp/gstrtcpbuffer.h>
23
24 #include "rtpsource.h"
25
26 GST_DEBUG_CATEGORY_STATIC (rtp_source_debug);
27 #define GST_CAT_DEFAULT rtp_source_debug
28
29 #define RTP_MAX_PROBATION_LEN   32
30
31 /* signals and args */
32 enum
33 {
34   LAST_SIGNAL
35 };
36
37 #define DEFAULT_SSRC                 0
38 #define DEFAULT_IS_CSRC              FALSE
39 #define DEFAULT_IS_VALIDATED         FALSE
40 #define DEFAULT_IS_SENDER            FALSE
41 #define DEFAULT_SDES                 NULL
42
43 enum
44 {
45   PROP_0,
46   PROP_SSRC,
47   PROP_IS_CSRC,
48   PROP_IS_VALIDATED,
49   PROP_IS_SENDER,
50   PROP_SDES,
51   PROP_STATS,
52   PROP_LAST
53 };
54
55 /* GObject vmethods */
56 static void rtp_source_finalize (GObject * object);
57 static void rtp_source_set_property (GObject * object, guint prop_id,
58     const GValue * value, GParamSpec * pspec);
59 static void rtp_source_get_property (GObject * object, guint prop_id,
60     GValue * value, GParamSpec * pspec);
61
62 /* static guint rtp_source_signals[LAST_SIGNAL] = { 0 }; */
63
64 G_DEFINE_TYPE (RTPSource, rtp_source, G_TYPE_OBJECT);
65
66 static void
67 rtp_source_class_init (RTPSourceClass * klass)
68 {
69   GObjectClass *gobject_class;
70
71   gobject_class = (GObjectClass *) klass;
72
73   gobject_class->finalize = rtp_source_finalize;
74
75   gobject_class->set_property = rtp_source_set_property;
76   gobject_class->get_property = rtp_source_get_property;
77
78   g_object_class_install_property (gobject_class, PROP_SSRC,
79       g_param_spec_uint ("ssrc", "SSRC",
80           "The SSRC of this source", 0, G_MAXUINT, DEFAULT_SSRC,
81           G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
82
83   g_object_class_install_property (gobject_class, PROP_IS_CSRC,
84       g_param_spec_boolean ("is-csrc", "Is CSRC",
85           "If this SSRC is acting as a contributing source",
86           DEFAULT_IS_CSRC, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
87
88   g_object_class_install_property (gobject_class, PROP_IS_VALIDATED,
89       g_param_spec_boolean ("is-validated", "Is Validated",
90           "If this SSRC is validated", DEFAULT_IS_VALIDATED,
91           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
92
93   g_object_class_install_property (gobject_class, PROP_IS_SENDER,
94       g_param_spec_boolean ("is-sender", "Is Sender",
95           "If this SSRC is a sender", DEFAULT_IS_SENDER,
96           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
97
98   /**
99    * RTPSource::sdes
100    *
101    * The current SDES items of the source. Returns a structure with the
102    * following fields:
103    *
104    *  'cname'    G_TYPE_STRING  : The canonical name 
105    *  'name'     G_TYPE_STRING  : The user name 
106    *  'email'    G_TYPE_STRING  : The user's electronic mail address
107    *  'phone'    G_TYPE_STRING  : The user's phone number
108    *  'location' G_TYPE_STRING  : The geographic user location
109    *  'tool'     G_TYPE_STRING  : The name of application or tool
110    *  'note'     G_TYPE_STRING  : A notice about the source
111    */
112   g_object_class_install_property (gobject_class, PROP_SDES,
113       g_param_spec_boxed ("sdes", "SDES",
114           "The SDES information for this source",
115           GST_TYPE_STRUCTURE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
116
117   /**
118    * RTPSource::stats
119    *
120    * The statistics of the source. This property returns a GstStructure with
121    * name application/x-rtp-source-stats with the following fields:
122    * 
123    */
124   g_object_class_install_property (gobject_class, PROP_STATS,
125       g_param_spec_boxed ("stats", "Stats",
126           "The stats of this source", GST_TYPE_STRUCTURE,
127           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
128
129   GST_DEBUG_CATEGORY_INIT (rtp_source_debug, "rtpsource", 0, "RTP Source");
130 }
131
132 /**
133  * rtp_source_reset:
134  * @src: an #RTPSource
135  *
136  * Reset the stats of @src.
137  */
138 void
139 rtp_source_reset (RTPSource * src)
140 {
141   src->received_bye = FALSE;
142
143   src->stats.cycles = -1;
144   src->stats.jitter = 0;
145   src->stats.transit = -1;
146   src->stats.curr_sr = 0;
147   src->stats.curr_rr = 0;
148 }
149
150 static void
151 rtp_source_init (RTPSource * src)
152 {
153   /* sources are initialy on probation until we receive enough valid RTP
154    * packets or a valid RTCP packet */
155   src->validated = FALSE;
156   src->internal = FALSE;
157   src->probation = RTP_DEFAULT_PROBATION;
158
159   src->payload = -1;
160   src->clock_rate = -1;
161   src->packets = g_queue_new ();
162   src->seqnum_base = -1;
163   src->last_rtptime = -1;
164
165   rtp_source_reset (src);
166 }
167
168 static void
169 rtp_source_finalize (GObject * object)
170 {
171   RTPSource *src;
172   GstBuffer *buffer;
173   gint i;
174
175   src = RTP_SOURCE_CAST (object);
176
177   while ((buffer = g_queue_pop_head (src->packets)))
178     gst_buffer_unref (buffer);
179   g_queue_free (src->packets);
180
181   for (i = 0; i < 9; i++)
182     g_free (src->sdes[i]);
183
184   g_free (src->bye_reason);
185
186   gst_caps_replace (&src->caps, NULL);
187
188   G_OBJECT_CLASS (rtp_source_parent_class)->finalize (object);
189 }
190
191 #define MAX_ADDRESS  64
192 static void
193 make_address_string (GstNetAddress * addr, gchar * dest, gulong n)
194 {
195   switch (gst_netaddress_get_net_type (addr)) {
196     case GST_NET_TYPE_IP4:
197     {
198       guint32 address;
199       guint16 port;
200
201       gst_netaddress_get_ip4_address (addr, &address, &port);
202       address = g_ntohl (address);
203
204       g_snprintf (dest, n, "%d.%d.%d.%d:%d", (address >> 24) & 0xff,
205           (address >> 16) & 0xff, (address >> 8) & 0xff, address & 0xff,
206           g_ntohs (port));
207       break;
208     }
209     case GST_NET_TYPE_IP6:
210     {
211       guint8 address[16];
212       guint16 port;
213
214       gst_netaddress_get_ip6_address (addr, address, &port);
215
216       g_snprintf (dest, n, "[%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x]:%d",
217           (address[0] << 8) | address[1], (address[2] << 8) | address[3],
218           (address[4] << 8) | address[5], (address[6] << 8) | address[7],
219           (address[8] << 8) | address[9], (address[10] << 8) | address[11],
220           (address[12] << 8) | address[13], (address[14] << 8) | address[15],
221           g_ntohs (port));
222       break;
223     }
224     default:
225       dest[0] = 0;
226       break;
227   }
228 }
229
230 static GstStructure *
231 rtp_source_create_stats (RTPSource * src)
232 {
233   GstStructure *s;
234   gboolean is_sender = src->is_sender;
235   gboolean internal = src->internal;
236   gchar address_str[MAX_ADDRESS];
237
238   /* common data for all types of sources */
239   s = gst_structure_new ("application/x-rtp-source-stats",
240       "ssrc", G_TYPE_UINT, (guint) src->ssrc,
241       "internal", G_TYPE_BOOLEAN, internal,
242       "validated", G_TYPE_BOOLEAN, src->validated,
243       "received-bye", G_TYPE_BOOLEAN, src->received_bye,
244       "is-csrc", G_TYPE_BOOLEAN, src->is_csrc,
245       "is-sender", G_TYPE_BOOLEAN, is_sender, NULL);
246
247   /* add address and port */
248   if (src->have_rtp_from) {
249     make_address_string (&src->rtp_from, address_str, sizeof (address_str));
250     gst_structure_set (s, "rtp-from", G_TYPE_STRING, address_str, NULL);
251   }
252   if (src->have_rtcp_from) {
253     make_address_string (&src->rtcp_from, address_str, sizeof (address_str));
254     gst_structure_set (s, "rtcp-from", G_TYPE_STRING, address_str, NULL);
255   }
256
257   if (internal) {
258     /* our internal source */
259     if (is_sender) {
260       /* if we are sending, report about how much we sent, other sources will
261        * have a RB with info on reception. */
262       gst_structure_set (s,
263           "octets-sent", G_TYPE_UINT64, src->stats.octets_sent,
264           "packets-sent", G_TYPE_UINT64, src->stats.packets_sent,
265           "bitrate", G_TYPE_UINT64, src->bitrate, NULL);
266     } else {
267       /* if we are not sending we have nothing more to report */
268     }
269   } else {
270     gboolean have_rb;
271     guint8 fractionlost = 0;
272     gint32 packetslost = 0;
273     guint32 exthighestseq = 0;
274     guint32 jitter = 0;
275     guint32 lsr = 0;
276     guint32 dlsr = 0;
277     guint32 round_trip = 0;
278
279     /* other sources */
280     if (is_sender) {
281       gboolean have_sr;
282       GstClockTime time = 0;
283       guint64 ntptime = 0;
284       guint32 rtptime = 0;
285       guint32 packet_count = 0;
286       guint32 octet_count = 0;
287
288       /* this source is sending to us, get the last SR. */
289       have_sr = rtp_source_get_last_sr (src, &time, &ntptime, &rtptime,
290           &packet_count, &octet_count);
291       gst_structure_set (s,
292           "octets-received", G_TYPE_UINT64, src->stats.octets_received,
293           "packets-received", G_TYPE_UINT64, src->stats.packets_received,
294           "have-sr", G_TYPE_BOOLEAN, have_sr,
295           "sr-ntptime", G_TYPE_UINT64, ntptime,
296           "sr-rtptime", G_TYPE_UINT, (guint) rtptime,
297           "sr-octet-count", G_TYPE_UINT, (guint) octet_count,
298           "sr-packet-count", G_TYPE_UINT, (guint) packet_count, NULL);
299     }
300     /* we might be sending to this SSRC so we report about how it is
301      * receiving our data */
302     have_rb = rtp_source_get_last_rb (src, &fractionlost, &packetslost,
303         &exthighestseq, &jitter, &lsr, &dlsr, &round_trip);
304
305     gst_structure_set (s,
306         "have-rb", G_TYPE_BOOLEAN, have_rb,
307         "rb-fractionlost", G_TYPE_UINT, (guint) fractionlost,
308         "rb-packetslost", G_TYPE_INT, (gint) packetslost,
309         "rb-exthighestseq", G_TYPE_UINT, (guint) exthighestseq,
310         "rb-jitter", G_TYPE_UINT, (guint) jitter,
311         "rb-lsr", G_TYPE_UINT, (guint) lsr,
312         "rb-dlsr", G_TYPE_UINT, (guint) dlsr,
313         "rb-round-trip", G_TYPE_UINT, (guint) round_trip, NULL);
314   }
315
316   return s;
317 }
318
319 static GstStructure *
320 rtp_source_create_sdes (RTPSource * src)
321 {
322   GstStructure *s;
323   gchar *str;
324
325   s = gst_structure_new ("application/x-rtp-source-sdes",
326       "ssrc", G_TYPE_UINT, (guint) src->ssrc, NULL);
327
328   if ((str = rtp_source_get_sdes_string (src, GST_RTCP_SDES_CNAME))) {
329     gst_structure_set (s, "cname", G_TYPE_STRING, str, NULL);
330     g_free (str);
331   }
332   if ((str = rtp_source_get_sdes_string (src, GST_RTCP_SDES_NAME))) {
333     gst_structure_set (s, "name", G_TYPE_STRING, str, NULL);
334     g_free (str);
335   }
336   if ((str = rtp_source_get_sdes_string (src, GST_RTCP_SDES_EMAIL))) {
337     gst_structure_set (s, "email", G_TYPE_STRING, str, NULL);
338     g_free (str);
339   }
340   if ((str = rtp_source_get_sdes_string (src, GST_RTCP_SDES_PHONE))) {
341     gst_structure_set (s, "phone", G_TYPE_STRING, str, NULL);
342     g_free (str);
343   }
344   if ((str = rtp_source_get_sdes_string (src, GST_RTCP_SDES_LOC))) {
345     gst_structure_set (s, "location", G_TYPE_STRING, str, NULL);
346     g_free (str);
347   }
348   if ((str = rtp_source_get_sdes_string (src, GST_RTCP_SDES_TOOL))) {
349     gst_structure_set (s, "tool", G_TYPE_STRING, str, NULL);
350     g_free (str);
351   }
352   if ((str = rtp_source_get_sdes_string (src, GST_RTCP_SDES_NOTE))) {
353     gst_structure_set (s, "note", G_TYPE_STRING, str, NULL);
354     g_free (str);
355   }
356   return s;
357 }
358
359 static void
360 rtp_source_set_property (GObject * object, guint prop_id,
361     const GValue * value, GParamSpec * pspec)
362 {
363   RTPSource *src;
364
365   src = RTP_SOURCE (object);
366
367   switch (prop_id) {
368     case PROP_SSRC:
369       src->ssrc = g_value_get_uint (value);
370       break;
371     default:
372       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
373       break;
374   }
375 }
376
377 static void
378 rtp_source_get_property (GObject * object, guint prop_id,
379     GValue * value, GParamSpec * pspec)
380 {
381   RTPSource *src;
382
383   src = RTP_SOURCE (object);
384
385   switch (prop_id) {
386     case PROP_SSRC:
387       g_value_set_uint (value, rtp_source_get_ssrc (src));
388       break;
389     case PROP_IS_CSRC:
390       g_value_set_boolean (value, rtp_source_is_as_csrc (src));
391       break;
392     case PROP_IS_VALIDATED:
393       g_value_set_boolean (value, rtp_source_is_validated (src));
394       break;
395     case PROP_IS_SENDER:
396       g_value_set_boolean (value, rtp_source_is_sender (src));
397       break;
398     case PROP_SDES:
399       g_value_take_boxed (value, rtp_source_create_sdes (src));
400       break;
401     case PROP_STATS:
402       g_value_take_boxed (value, rtp_source_create_stats (src));
403       break;
404     default:
405       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
406       break;
407   }
408 }
409
410 /**
411  * rtp_source_new:
412  * @ssrc: an SSRC
413  *
414  * Create a #RTPSource with @ssrc.
415  *
416  * Returns: a new #RTPSource. Use g_object_unref() after usage.
417  */
418 RTPSource *
419 rtp_source_new (guint32 ssrc)
420 {
421   RTPSource *src;
422
423   src = g_object_new (RTP_TYPE_SOURCE, NULL);
424   src->ssrc = ssrc;
425
426   return src;
427 }
428
429 /**
430  * rtp_source_set_callbacks:
431  * @src: an #RTPSource
432  * @cb: callback functions
433  * @user_data: user data
434  *
435  * Set the callbacks for the source.
436  */
437 void
438 rtp_source_set_callbacks (RTPSource * src, RTPSourceCallbacks * cb,
439     gpointer user_data)
440 {
441   g_return_if_fail (RTP_IS_SOURCE (src));
442
443   src->callbacks.push_rtp = cb->push_rtp;
444   src->callbacks.clock_rate = cb->clock_rate;
445   src->user_data = user_data;
446 }
447
448 /**
449  * rtp_source_get_ssrc:
450  * @src: an #RTPSource
451  *
452  * Get the SSRC of @source.
453  *
454  * Returns: the SSRC of src.
455  */
456 guint32
457 rtp_source_get_ssrc (RTPSource * src)
458 {
459   guint32 result;
460
461   g_return_val_if_fail (RTP_IS_SOURCE (src), 0);
462
463   result = src->ssrc;
464
465   return result;
466 }
467
468 /**
469  * rtp_source_set_as_csrc:
470  * @src: an #RTPSource
471  *
472  * Configure @src as a CSRC, this will also validate @src.
473  */
474 void
475 rtp_source_set_as_csrc (RTPSource * src)
476 {
477   g_return_if_fail (RTP_IS_SOURCE (src));
478
479   src->validated = TRUE;
480   src->is_csrc = TRUE;
481 }
482
483 /**
484  * rtp_source_is_as_csrc:
485  * @src: an #RTPSource
486  *
487  * Check if @src is a contributing source.
488  *
489  * Returns: %TRUE if @src is acting as a contributing source.
490  */
491 gboolean
492 rtp_source_is_as_csrc (RTPSource * src)
493 {
494   gboolean result;
495
496   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
497
498   result = src->is_csrc;
499
500   return result;
501 }
502
503 /**
504  * rtp_source_is_active:
505  * @src: an #RTPSource
506  *
507  * Check if @src is an active source. A source is active if it has been
508  * validated and has not yet received a BYE packet
509  *
510  * Returns: %TRUE if @src is an qactive source.
511  */
512 gboolean
513 rtp_source_is_active (RTPSource * src)
514 {
515   gboolean result;
516
517   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
518
519   result = RTP_SOURCE_IS_ACTIVE (src);
520
521   return result;
522 }
523
524 /**
525  * rtp_source_is_validated:
526  * @src: an #RTPSource
527  *
528  * Check if @src is a validated source.
529  *
530  * Returns: %TRUE if @src is a validated source.
531  */
532 gboolean
533 rtp_source_is_validated (RTPSource * src)
534 {
535   gboolean result;
536
537   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
538
539   result = src->validated;
540
541   return result;
542 }
543
544 /**
545  * rtp_source_is_sender:
546  * @src: an #RTPSource
547  *
548  * Check if @src is a sending source.
549  *
550  * Returns: %TRUE if @src is a sending source.
551  */
552 gboolean
553 rtp_source_is_sender (RTPSource * src)
554 {
555   gboolean result;
556
557   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
558
559   result = RTP_SOURCE_IS_SENDER (src);
560
561   return result;
562 }
563
564 /**
565  * rtp_source_received_bye:
566  * @src: an #RTPSource
567  *
568  * Check if @src has receoved a BYE packet.
569  *
570  * Returns: %TRUE if @src has received a BYE packet.
571  */
572 gboolean
573 rtp_source_received_bye (RTPSource * src)
574 {
575   gboolean result;
576
577   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
578
579   result = src->received_bye;
580
581   return result;
582 }
583
584
585 /**
586  * rtp_source_get_bye_reason:
587  * @src: an #RTPSource
588  *
589  * Get the BYE reason for @src. Check if the source receoved a BYE message first
590  * with rtp_source_received_bye().
591  *
592  * Returns: The BYE reason or NULL when no reason was given or the source did
593  * not receive a BYE message yet. g_fee() after usage.
594  */
595 gchar *
596 rtp_source_get_bye_reason (RTPSource * src)
597 {
598   gchar *result;
599
600   g_return_val_if_fail (RTP_IS_SOURCE (src), NULL);
601
602   result = g_strdup (src->bye_reason);
603
604   return result;
605 }
606
607 /**
608  * rtp_source_update_caps:
609  * @src: an #RTPSource
610  * @caps: a #GstCaps
611  *
612  * Parse @caps and store all relevant information in @source.
613  */
614 void
615 rtp_source_update_caps (RTPSource * src, GstCaps * caps)
616 {
617   GstStructure *s;
618   guint val;
619   gint ival;
620
621   /* nothing changed, return */
622   if (src->caps == caps)
623     return;
624
625   s = gst_caps_get_structure (caps, 0);
626
627   if (gst_structure_get_int (s, "payload", &ival))
628     src->payload = ival;
629   else
630     src->payload = -1;
631   GST_DEBUG ("got payload %d", src->payload);
632
633   if (gst_structure_get_int (s, "clock-rate", &ival))
634     src->clock_rate = ival;
635   else
636     src->clock_rate = -1;
637
638   GST_DEBUG ("got clock-rate %d", src->clock_rate);
639
640   if (gst_structure_get_uint (s, "seqnum-base", &val))
641     src->seqnum_base = val;
642   else
643     src->seqnum_base = -1;
644
645   GST_DEBUG ("got seqnum-base %" G_GINT32_FORMAT, src->seqnum_base);
646
647   gst_caps_replace (&src->caps, caps);
648 }
649
650 /**
651  * rtp_source_set_sdes:
652  * @src: an #RTPSource
653  * @type: the type of the SDES item
654  * @data: the SDES data
655  * @len: the SDES length
656  *
657  * Store an SDES item of @type in @src. 
658  *
659  * Returns: %FALSE if the SDES item was unchanged or @type is unknown.
660  */
661 gboolean
662 rtp_source_set_sdes (RTPSource * src, GstRTCPSDESType type,
663     const guint8 * data, guint len)
664 {
665   guint8 *old;
666
667   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
668
669   if (type < 0 || type > GST_RTCP_SDES_PRIV)
670     return FALSE;
671
672   old = src->sdes[type];
673
674   /* lengths are the same, check if the data is the same */
675   if ((src->sdes_len[type] == len))
676     if (data != NULL && old != NULL && (memcmp (old, data, len) == 0))
677       return FALSE;
678
679   /* NULL data, make sure we store 0 length or if no length is given,
680    * take strlen */
681   if (data == NULL)
682     len = 0;
683
684   g_free (src->sdes[type]);
685   src->sdes[type] = g_memdup (data, len);
686   src->sdes_len[type] = len;
687
688   return TRUE;
689 }
690
691 /**
692  * rtp_source_set_sdes_string:
693  * @src: an #RTPSource
694  * @type: the type of the SDES item
695  * @data: the SDES data
696  *
697  * Store an SDES item of @type in @src. This function is similar to
698  * rtp_source_set_sdes() but takes a null-terminated string for convenience.
699  *
700  * Returns: %FALSE if the SDES item was unchanged or @type is unknown.
701  */
702 gboolean
703 rtp_source_set_sdes_string (RTPSource * src, GstRTCPSDESType type,
704     const gchar * data)
705 {
706   guint len;
707   gboolean result;
708
709   if (data)
710     len = strlen (data);
711   else
712     len = 0;
713
714   result = rtp_source_set_sdes (src, type, (guint8 *) data, len);
715
716   return result;
717 }
718
719 /**
720  * rtp_source_get_sdes:
721  * @src: an #RTPSource
722  * @type: the type of the SDES item
723  * @data: location to store the SDES data or NULL
724  * @len: location to store the SDES length or NULL
725  *
726  * Get the SDES item of @type from @src. Note that @data does not always point
727  * to a null-terminated string, use rtp_source_get_sdes_string() to retrieve a
728  * null-terminated string instead.
729  *
730  * @data remains valid until the next call to rtp_source_set_sdes().
731  *
732  * Returns: %TRUE if @type was valid and @data and @len contain valid
733  * data. @data can be NULL when the item was unset.
734  */
735 gboolean
736 rtp_source_get_sdes (RTPSource * src, GstRTCPSDESType type, guint8 ** data,
737     guint * len)
738 {
739   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
740
741   if (type < 0 || type > GST_RTCP_SDES_PRIV)
742     return FALSE;
743
744   if (data)
745     *data = src->sdes[type];
746   if (len)
747     *len = src->sdes_len[type];
748
749   return TRUE;
750 }
751
752 /**
753  * rtp_source_get_sdes_string:
754  * @src: an #RTPSource
755  * @type: the type of the SDES item
756  *
757  * Get the SDES item of @type from @src. 
758  *
759  * Returns: a null-terminated copy of the SDES item or NULL when @type was not
760  * valid or the SDES item was unset. g_free() after usage.
761  */
762 gchar *
763 rtp_source_get_sdes_string (RTPSource * src, GstRTCPSDESType type)
764 {
765   gchar *result;
766
767   g_return_val_if_fail (RTP_IS_SOURCE (src), NULL);
768
769   if (type < 0 || type > GST_RTCP_SDES_PRIV)
770     return NULL;
771
772   result = g_strndup ((const gchar *) src->sdes[type], src->sdes_len[type]);
773
774   return result;
775 }
776
777 /**
778  * rtp_source_set_rtp_from:
779  * @src: an #RTPSource
780  * @address: the RTP address to set
781  *
782  * Set that @src is receiving RTP packets from @address. This is used for
783  * collistion checking.
784  */
785 void
786 rtp_source_set_rtp_from (RTPSource * src, GstNetAddress * address)
787 {
788   g_return_if_fail (RTP_IS_SOURCE (src));
789
790   src->have_rtp_from = TRUE;
791   memcpy (&src->rtp_from, address, sizeof (GstNetAddress));
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, GstNetAddress * address)
804 {
805   g_return_if_fail (RTP_IS_SOURCE (src));
806
807   src->have_rtcp_from = TRUE;
808   memcpy (&src->rtcp_from, address, sizeof (GstNetAddress));
809 }
810
811 static GstFlowReturn
812 push_packet (RTPSource * src, GstBuffer * buffer)
813 {
814   GstFlowReturn ret = GST_FLOW_OK;
815
816   /* push queued packets first if any */
817   while (!g_queue_is_empty (src->packets)) {
818     GstBuffer *buffer = GST_BUFFER_CAST (g_queue_pop_head (src->packets));
819
820     GST_LOG ("pushing queued packet");
821     if (src->callbacks.push_rtp)
822       src->callbacks.push_rtp (src, buffer, src->user_data);
823     else
824       gst_buffer_unref (buffer);
825   }
826   GST_LOG ("pushing new packet");
827   /* push packet */
828   if (src->callbacks.push_rtp)
829     ret = src->callbacks.push_rtp (src, buffer, src->user_data);
830   else
831     gst_buffer_unref (buffer);
832
833   return ret;
834 }
835
836 static gint
837 get_clock_rate (RTPSource * src, guint8 payload)
838 {
839   if (src->payload == -1) {
840     /* first payload received, nothing was in the caps, lock on to this payload */
841     src->payload = payload;
842     GST_DEBUG ("first payload %d", payload);
843   } else if (payload != src->payload) {
844     /* we have a different payload than before, reset the clock-rate */
845     GST_DEBUG ("new payload %d", payload);
846     src->payload = payload;
847     src->clock_rate = -1;
848     src->stats.transit = -1;
849   }
850
851   if (src->clock_rate == -1) {
852     gint clock_rate = -1;
853
854     if (src->callbacks.clock_rate)
855       clock_rate = src->callbacks.clock_rate (src, payload, src->user_data);
856
857     GST_DEBUG ("got clock-rate %d", clock_rate);
858
859     src->clock_rate = clock_rate;
860   }
861   return src->clock_rate;
862 }
863
864 /* Jitter is the variation in the delay of received packets in a flow. It is
865  * measured by comparing the interval when RTP packets were sent to the interval
866  * at which they were received. For instance, if packet #1 and packet #2 leave
867  * 50 milliseconds apart and arrive 60 milliseconds apart, then the jitter is 10
868  * milliseconds. */
869 static void
870 calculate_jitter (RTPSource * src, GstBuffer * buffer,
871     RTPArrivalStats * arrival)
872 {
873   guint64 ntpnstime;
874   guint32 rtparrival, transit, rtptime;
875   gint32 diff;
876   gint clock_rate;
877   guint8 pt;
878
879   /* get arrival time */
880   if ((ntpnstime = arrival->ntpnstime) == GST_CLOCK_TIME_NONE)
881     goto no_time;
882
883   pt = gst_rtp_buffer_get_payload_type (buffer);
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 = gst_rtp_buffer_get_timestamp (buffer);
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 (ntpnstime, 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 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 /**
952  * rtp_source_process_rtp:
953  * @src: an #RTPSource
954  * @buffer: an RTP buffer
955  *
956  * Let @src handle the incomming RTP @buffer.
957  *
958  * Returns: a #GstFlowReturn.
959  */
960 GstFlowReturn
961 rtp_source_process_rtp (RTPSource * src, GstBuffer * buffer,
962     RTPArrivalStats * arrival)
963 {
964   GstFlowReturn result = GST_FLOW_OK;
965   guint16 seqnr, udelta;
966   RTPSourceStats *stats;
967
968   g_return_val_if_fail (RTP_IS_SOURCE (src), GST_FLOW_ERROR);
969   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
970
971   stats = &src->stats;
972
973   seqnr = gst_rtp_buffer_get_seq (buffer);
974
975   rtp_source_update_caps (src, GST_BUFFER_CAPS (buffer));
976
977   if (stats->cycles == -1) {
978     GST_DEBUG ("received first buffer");
979     /* first time we heard of this source */
980     init_seq (src, seqnr);
981     src->stats.max_seq = seqnr - 1;
982     src->probation = RTP_DEFAULT_PROBATION;
983   }
984
985   udelta = seqnr - stats->max_seq;
986
987   /* if we are still on probation, check seqnum */
988   if (src->probation) {
989     guint16 expected;
990
991     expected = src->stats.max_seq + 1;
992
993     /* when in probation, we require consecutive seqnums */
994     if (seqnr == expected) {
995       /* expected packet */
996       GST_DEBUG ("probation: seqnr %d == expected %d", seqnr, expected);
997       src->probation--;
998       src->stats.max_seq = seqnr;
999       if (src->probation == 0) {
1000         GST_DEBUG ("probation done!");
1001         init_seq (src, seqnr);
1002       } else {
1003         GstBuffer *q;
1004
1005         GST_DEBUG ("probation %d: queue buffer", src->probation);
1006         /* when still in probation, keep packets in a list. */
1007         g_queue_push_tail (src->packets, buffer);
1008         /* remove packets from queue if there are too many */
1009         while (g_queue_get_length (src->packets) > RTP_MAX_PROBATION_LEN) {
1010           q = g_queue_pop_head (src->packets);
1011           gst_buffer_unref (q);
1012         }
1013         goto done;
1014       }
1015     } else {
1016       GST_DEBUG ("probation: seqnr %d != expected %d", seqnr, expected);
1017       src->probation = RTP_DEFAULT_PROBATION;
1018       src->stats.max_seq = seqnr;
1019       goto done;
1020     }
1021   } else if (udelta < RTP_MAX_DROPOUT) {
1022     /* in order, with permissible gap */
1023     if (seqnr < stats->max_seq) {
1024       /* sequence number wrapped - count another 64K cycle. */
1025       stats->cycles += RTP_SEQ_MOD;
1026     }
1027     stats->max_seq = seqnr;
1028   } else if (udelta <= RTP_SEQ_MOD - RTP_MAX_MISORDER) {
1029     /* the sequence number made a very large jump */
1030     if (seqnr == stats->bad_seq) {
1031       /* two sequential packets -- assume that the other side
1032        * restarted without telling us so just re-sync
1033        * (i.e., pretend this was the first packet).  */
1034       init_seq (src, seqnr);
1035     } else {
1036       /* unacceptable jump */
1037       stats->bad_seq = (seqnr + 1) & (RTP_SEQ_MOD - 1);
1038       goto bad_sequence;
1039     }
1040   } else {
1041     /* duplicate or reordered packet, will be filtered by jitterbuffer. */
1042     GST_WARNING ("duplicate or reordered packet");
1043   }
1044
1045   src->stats.octets_received += arrival->payload_len;
1046   src->stats.bytes_received += arrival->bytes;
1047   src->stats.packets_received++;
1048   /* the source that sent the packet must be a sender */
1049   src->is_sender = TRUE;
1050   src->validated = TRUE;
1051
1052   GST_LOG ("seq %d, PC: %" G_GUINT64_FORMAT ", OC: %" G_GUINT64_FORMAT,
1053       seqnr, src->stats.packets_received, src->stats.octets_received);
1054
1055   /* calculate jitter for the stats */
1056   calculate_jitter (src, buffer, arrival);
1057
1058   /* we're ready to push the RTP packet now */
1059   result = push_packet (src, buffer);
1060
1061 done:
1062   return result;
1063
1064   /* ERRORS */
1065 bad_sequence:
1066   {
1067     GST_WARNING ("unacceptable seqnum received");
1068     return GST_FLOW_OK;
1069   }
1070 }
1071
1072 /**
1073  * rtp_source_process_bye:
1074  * @src: an #RTPSource
1075  * @reason: the reason for leaving
1076  *
1077  * Notify @src that a BYE packet has been received. This will make the source
1078  * inactive.
1079  */
1080 void
1081 rtp_source_process_bye (RTPSource * src, const gchar * reason)
1082 {
1083   g_return_if_fail (RTP_IS_SOURCE (src));
1084
1085   GST_DEBUG ("marking SSRC %08x as BYE, reason: %s", src->ssrc,
1086       GST_STR_NULL (reason));
1087
1088   /* copy the reason and mark as received_bye */
1089   g_free (src->bye_reason);
1090   src->bye_reason = g_strdup (reason);
1091   src->received_bye = TRUE;
1092 }
1093
1094 /**
1095  * rtp_source_send_rtp:
1096  * @src: an #RTPSource
1097  * @buffer: an RTP buffer
1098  * @ntpnstime: the NTP time when this buffer was captured in nanoseconds. This
1099  * is the buffer timestamp converted to NTP time.
1100  *
1101  * Send an RTP @buffer originating from @src. This will make @src a sender.
1102  * This function takes ownership of @buffer and modifies the SSRC in the RTP
1103  * packet to that of @src when needed.
1104  *
1105  * Returns: a #GstFlowReturn.
1106  */
1107 GstFlowReturn
1108 rtp_source_send_rtp (RTPSource * src, GstBuffer * buffer, guint64 ntpnstime)
1109 {
1110   GstFlowReturn result = GST_FLOW_OK;
1111   guint len;
1112   guint32 rtptime;
1113   guint64 ext_rtptime;
1114   guint64 ntp_diff, rtp_diff;
1115   guint64 elapsed;
1116
1117   g_return_val_if_fail (RTP_IS_SOURCE (src), GST_FLOW_ERROR);
1118   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
1119
1120   len = gst_rtp_buffer_get_payload_len (buffer);
1121
1122   rtp_source_update_caps (src, GST_BUFFER_CAPS (buffer));
1123
1124   /* we are a sender now */
1125   src->is_sender = TRUE;
1126
1127   /* update stats for the SR */
1128   src->stats.packets_sent++;
1129   src->stats.octets_sent += len;
1130   src->bytes_sent += len;
1131
1132   if (src->prev_ntpnstime) {
1133     elapsed = ntpnstime - src->prev_ntpnstime;
1134
1135     if (elapsed > (G_GINT64_CONSTANT (1) << 31)) {
1136       guint64 rate;
1137
1138       rate =
1139           gst_util_uint64_scale (src->bytes_sent, elapsed,
1140           (G_GINT64_CONSTANT (1) << 29));
1141
1142       GST_LOG ("Elapsed %" G_GUINT64_FORMAT ", bytes %" G_GUINT64_FORMAT
1143           ", rate %" G_GUINT64_FORMAT, elapsed, src->bytes_sent, rate);
1144
1145       if (src->bitrate == 0)
1146         src->bitrate = rate;
1147       else
1148         src->bitrate = ((src->bitrate * 3) + rate) / 4;
1149
1150       src->prev_ntpnstime = ntpnstime;
1151       src->bytes_sent = 0;
1152     }
1153   } else {
1154     GST_LOG ("Reset bitrate measurement");
1155     src->prev_ntpnstime = ntpnstime;
1156     src->bitrate = 0;
1157   }
1158
1159   rtptime = gst_rtp_buffer_get_timestamp (buffer);
1160   ext_rtptime = src->last_rtptime;
1161   ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
1162
1163   GST_LOG ("SSRC %08x, RTP %" G_GUINT64_FORMAT ", NTP %" GST_TIME_FORMAT,
1164       src->ssrc, ext_rtptime, GST_TIME_ARGS (ntpnstime));
1165
1166   if (ext_rtptime > src->last_rtptime) {
1167     rtp_diff = ext_rtptime - src->last_rtptime;
1168     ntp_diff = ntpnstime - src->last_ntpnstime;
1169
1170     /* calc the diff so we can detect drift at the sender. This can also be used
1171      * to guestimate the clock rate if the NTP time is locked to the RTP
1172      * timestamps (as is the case when the capture device is providing the clock). */
1173     GST_LOG ("SSRC %08x, diff RTP %" G_GUINT64_FORMAT ", diff NTP %"
1174         GST_TIME_FORMAT, src->ssrc, rtp_diff, GST_TIME_ARGS (ntp_diff));
1175   }
1176
1177   /* we keep track of the last received RTP timestamp and the corresponding
1178    * NTP timestamp so that we can use this info when constructing SR reports */
1179   src->last_rtptime = ext_rtptime;
1180   src->last_ntpnstime = ntpnstime;
1181
1182   /* push packet */
1183   if (src->callbacks.push_rtp) {
1184     guint32 ssrc;
1185
1186     ssrc = gst_rtp_buffer_get_ssrc (buffer);
1187     if (ssrc != src->ssrc) {
1188       /* the SSRC of the packet is not correct, make a writable buffer and
1189        * update the SSRC. This could involve a complete copy of the packet when
1190        * it is not writable. Usually the payloader will use caps negotiation to
1191        * get the correct SSRC from the session manager before pushing anything. */
1192       buffer = gst_buffer_make_writable (buffer);
1193
1194       /* FIXME, we don't want to warn yet because we can't inform any payloader
1195        * of the changes SSRC yet because we don't implement pad-alloc. */
1196       GST_LOG ("updating SSRC from %08x to %08x, fix the payloader", ssrc,
1197           src->ssrc);
1198       gst_rtp_buffer_set_ssrc (buffer, src->ssrc);
1199     }
1200     GST_LOG ("pushing RTP packet %" G_GUINT64_FORMAT, src->stats.packets_sent);
1201     result = src->callbacks.push_rtp (src, buffer, src->user_data);
1202   } else {
1203     GST_WARNING ("no callback installed, dropping packet");
1204     gst_buffer_unref (buffer);
1205   }
1206
1207   return result;
1208 }
1209
1210 /**
1211  * rtp_source_process_sr:
1212  * @src: an #RTPSource
1213  * @time: time of packet arrival
1214  * @ntptime: the NTP time in 32.32 fixed point
1215  * @rtptime: the RTP time
1216  * @packet_count: the packet count
1217  * @octet_count: the octect count
1218  *
1219  * Update the sender report in @src.
1220  */
1221 void
1222 rtp_source_process_sr (RTPSource * src, GstClockTime time, guint64 ntptime,
1223     guint32 rtptime, guint32 packet_count, guint32 octet_count)
1224 {
1225   RTPSenderReport *curr;
1226   gint curridx;
1227
1228   g_return_if_fail (RTP_IS_SOURCE (src));
1229
1230   GST_DEBUG ("got SR packet: SSRC %08x, NTP %08x:%08x, RTP %" G_GUINT32_FORMAT
1231       ", PC %" G_GUINT32_FORMAT ", OC %" G_GUINT32_FORMAT, src->ssrc,
1232       (guint32) (ntptime >> 32), (guint32) (ntptime & 0xffffffff), rtptime,
1233       packet_count, octet_count);
1234
1235   curridx = src->stats.curr_sr ^ 1;
1236   curr = &src->stats.sr[curridx];
1237
1238   /* this is a sender now */
1239   src->is_sender = TRUE;
1240
1241   /* update current */
1242   curr->is_valid = TRUE;
1243   curr->ntptime = ntptime;
1244   curr->rtptime = rtptime;
1245   curr->packet_count = packet_count;
1246   curr->octet_count = octet_count;
1247   curr->time = time;
1248
1249   /* make current */
1250   src->stats.curr_sr = curridx;
1251 }
1252
1253 /**
1254  * rtp_source_process_rb:
1255  * @src: an #RTPSource
1256  * @time: the current time in nanoseconds since 1970
1257  * @fractionlost: fraction lost since last SR/RR
1258  * @packetslost: the cumululative number of packets lost
1259  * @exthighestseq: the extended last sequence number received
1260  * @jitter: the interarrival jitter
1261  * @lsr: the last SR packet from this source
1262  * @dlsr: the delay since last SR packet
1263  *
1264  * Update the report block in @src.
1265  */
1266 void
1267 rtp_source_process_rb (RTPSource * src, GstClockTime time, guint8 fractionlost,
1268     gint32 packetslost, guint32 exthighestseq, guint32 jitter, guint32 lsr,
1269     guint32 dlsr)
1270 {
1271   RTPReceiverReport *curr;
1272   gint curridx;
1273   guint32 ntp, A;
1274
1275   g_return_if_fail (RTP_IS_SOURCE (src));
1276
1277   GST_DEBUG ("got RB packet: SSRC %08x, FL %2x, PL %d, HS %" G_GUINT32_FORMAT
1278       ", jitter %" G_GUINT32_FORMAT ", LSR %04x:%04x, DLSR %04x:%04x",
1279       src->ssrc, fractionlost, packetslost, exthighestseq, jitter, lsr >> 16,
1280       lsr & 0xffff, dlsr >> 16, dlsr & 0xffff);
1281
1282   curridx = src->stats.curr_rr ^ 1;
1283   curr = &src->stats.rr[curridx];
1284
1285   /* update current */
1286   curr->is_valid = TRUE;
1287   curr->fractionlost = fractionlost;
1288   curr->packetslost = packetslost;
1289   curr->exthighestseq = exthighestseq;
1290   curr->jitter = jitter;
1291   curr->lsr = lsr;
1292   curr->dlsr = dlsr;
1293
1294   /* calculate round trip, round the time up */
1295   ntp = ((gst_rtcp_unix_to_ntp (time) + 0xffff) >> 16) & 0xffffffff;
1296   A = dlsr + lsr;
1297   if (A > 0 && ntp > A)
1298     A = ntp - A;
1299   else
1300     A = 0;
1301   curr->round_trip = A;
1302
1303   GST_DEBUG ("NTP %04x:%04x, round trip %04x:%04x", ntp >> 16, ntp & 0xffff,
1304       A >> 16, A & 0xffff);
1305
1306   /* make current */
1307   src->stats.curr_rr = curridx;
1308 }
1309
1310 /**
1311  * rtp_source_get_new_sr:
1312  * @src: an #RTPSource
1313  * @ntpnstime: the current time in nanoseconds since 1970
1314  * @ntptime: the NTP time in 32.32 fixed point
1315  * @rtptime: the RTP time corresponding to @ntptime
1316  * @packet_count: the packet count
1317  * @octet_count: the octect count
1318  *
1319  * Get new values to put into a new SR report from this source.
1320  *
1321  * Returns: %TRUE on success.
1322  */
1323 gboolean
1324 rtp_source_get_new_sr (RTPSource * src, guint64 ntpnstime,
1325     guint64 * ntptime, guint32 * rtptime, guint32 * packet_count,
1326     guint32 * octet_count)
1327 {
1328   guint64 t_rtp;
1329   guint64 t_current_ntp;
1330   GstClockTimeDiff diff;
1331
1332   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1333
1334   /* use the sync params to interpolate the date->time member to rtptime. We
1335    * use the last sent timestamp and rtptime as reference points. We assume
1336    * that the slope of the rtptime vs timestamp curve is 1, which is certainly
1337    * sufficient for the frequency at which we report SR and the rate we send
1338    * out RTP packets. */
1339   t_rtp = src->last_rtptime;
1340
1341   GST_DEBUG ("last_ntpnstime %" GST_TIME_FORMAT ", last_rtptime %"
1342       G_GUINT64_FORMAT, GST_TIME_ARGS (src->last_ntpnstime), t_rtp);
1343
1344   if (src->clock_rate != -1) {
1345     /* get the diff with the SR time */
1346     diff = GST_CLOCK_DIFF (src->last_ntpnstime, ntpnstime);
1347
1348     /* now translate the diff to RTP time, handle positive and negative cases.
1349      * If there is no diff, we already set rtptime correctly above. */
1350     if (diff > 0) {
1351       GST_DEBUG ("ntpnstime %" GST_TIME_FORMAT ", diff %" GST_TIME_FORMAT,
1352           GST_TIME_ARGS (ntpnstime), GST_TIME_ARGS (diff));
1353       t_rtp += gst_util_uint64_scale_int (diff, src->clock_rate, GST_SECOND);
1354     } else {
1355       diff = -diff;
1356       GST_DEBUG ("ntpnstime %" GST_TIME_FORMAT ", diff -%" GST_TIME_FORMAT,
1357           GST_TIME_ARGS (ntpnstime), GST_TIME_ARGS (diff));
1358       t_rtp -= gst_util_uint64_scale_int (diff, src->clock_rate, GST_SECOND);
1359     }
1360   } else {
1361     GST_WARNING ("no clock-rate, cannot interpolate rtp time");
1362   }
1363
1364   /* convert the NTP time in nanoseconds to 32.32 fixed point */
1365   t_current_ntp = gst_util_uint64_scale (ntpnstime, (1LL << 32), GST_SECOND);
1366
1367   GST_DEBUG ("NTP %08x:%08x, RTP %" G_GUINT32_FORMAT,
1368       (guint32) (t_current_ntp >> 32), (guint32) (t_current_ntp & 0xffffffff),
1369       (guint32) t_rtp);
1370
1371   if (ntptime)
1372     *ntptime = t_current_ntp;
1373   if (rtptime)
1374     *rtptime = t_rtp;
1375   if (packet_count)
1376     *packet_count = src->stats.packets_sent;
1377   if (octet_count)
1378     *octet_count = src->stats.octets_sent;
1379
1380   return TRUE;
1381 }
1382
1383 /**
1384  * rtp_source_get_new_rb:
1385  * @src: an #RTPSource
1386  * @time: the current time of the system clock
1387  * @fractionlost: fraction lost since last SR/RR
1388  * @packetslost: the cumululative number of packets lost
1389  * @exthighestseq: the extended last sequence number received
1390  * @jitter: the interarrival jitter
1391  * @lsr: the last SR packet from this source
1392  * @dlsr: the delay since last SR packet
1393  *
1394  * Get new values to put into a new report block from this source.
1395  *
1396  * Returns: %TRUE on success.
1397  */
1398 gboolean
1399 rtp_source_get_new_rb (RTPSource * src, GstClockTime time,
1400     guint8 * fractionlost, gint32 * packetslost, guint32 * exthighestseq,
1401     guint32 * jitter, guint32 * lsr, guint32 * dlsr)
1402 {
1403   RTPSourceStats *stats;
1404   guint64 extended_max, expected;
1405   guint64 expected_interval, received_interval, ntptime;
1406   gint64 lost, lost_interval;
1407   guint32 fraction, LSR, DLSR;
1408   GstClockTime sr_time;
1409
1410   stats = &src->stats;
1411
1412   extended_max = stats->cycles + stats->max_seq;
1413   expected = extended_max - stats->base_seq + 1;
1414
1415   GST_DEBUG ("ext_max %" G_GUINT64_FORMAT ", expected %" G_GUINT64_FORMAT
1416       ", received %" G_GUINT64_FORMAT ", base_seq %" G_GUINT32_FORMAT,
1417       extended_max, expected, stats->packets_received, stats->base_seq);
1418
1419   lost = expected - stats->packets_received;
1420   lost = CLAMP (lost, -0x800000, 0x7fffff);
1421
1422   expected_interval = expected - stats->prev_expected;
1423   stats->prev_expected = expected;
1424   received_interval = stats->packets_received - stats->prev_received;
1425   stats->prev_received = stats->packets_received;
1426
1427   lost_interval = expected_interval - received_interval;
1428
1429   if (expected_interval == 0 || lost_interval <= 0)
1430     fraction = 0;
1431   else
1432     fraction = (lost_interval << 8) / expected_interval;
1433
1434   GST_DEBUG ("add RR for SSRC %08x", src->ssrc);
1435   /* we scaled the jitter up for additional precision */
1436   GST_DEBUG ("fraction %" G_GUINT32_FORMAT ", lost %" G_GINT64_FORMAT
1437       ", extseq %" G_GUINT64_FORMAT ", jitter %d", fraction, lost,
1438       extended_max, stats->jitter >> 4);
1439
1440   if (rtp_source_get_last_sr (src, &sr_time, &ntptime, NULL, NULL, NULL)) {
1441     GstClockTime diff;
1442
1443     /* LSR is middle 32 bits of the last ntptime */
1444     LSR = (ntptime >> 16) & 0xffffffff;
1445     diff = time - sr_time;
1446     GST_DEBUG ("last SR time diff %" GST_TIME_FORMAT, GST_TIME_ARGS (diff));
1447     /* DLSR, delay since last SR is expressed in 1/65536 second units */
1448     DLSR = gst_util_uint64_scale_int (diff, 65536, GST_SECOND);
1449   } else {
1450     /* No valid SR received, LSR/DLSR are set to 0 then */
1451     GST_DEBUG ("no valid SR received");
1452     LSR = 0;
1453     DLSR = 0;
1454   }
1455   GST_DEBUG ("LSR %04x:%04x, DLSR %04x:%04x", LSR >> 16, LSR & 0xffff,
1456       DLSR >> 16, DLSR & 0xffff);
1457
1458   if (fractionlost)
1459     *fractionlost = fraction;
1460   if (packetslost)
1461     *packetslost = lost;
1462   if (exthighestseq)
1463     *exthighestseq = extended_max;
1464   if (jitter)
1465     *jitter = stats->jitter >> 4;
1466   if (lsr)
1467     *lsr = LSR;
1468   if (dlsr)
1469     *dlsr = DLSR;
1470
1471   return TRUE;
1472 }
1473
1474 /**
1475  * rtp_source_get_last_sr:
1476  * @src: an #RTPSource
1477  * @time: time of packet arrival
1478  * @ntptime: the NTP time in 32.32 fixed point
1479  * @rtptime: the RTP time
1480  * @packet_count: the packet count
1481  * @octet_count: the octect count
1482  *
1483  * Get the values of the last sender report as set with rtp_source_process_sr().
1484  *
1485  * Returns: %TRUE if there was a valid SR report.
1486  */
1487 gboolean
1488 rtp_source_get_last_sr (RTPSource * src, GstClockTime * time, guint64 * ntptime,
1489     guint32 * rtptime, guint32 * packet_count, guint32 * octet_count)
1490 {
1491   RTPSenderReport *curr;
1492
1493   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1494
1495   curr = &src->stats.sr[src->stats.curr_sr];
1496   if (!curr->is_valid)
1497     return FALSE;
1498
1499   if (ntptime)
1500     *ntptime = curr->ntptime;
1501   if (rtptime)
1502     *rtptime = curr->rtptime;
1503   if (packet_count)
1504     *packet_count = curr->packet_count;
1505   if (octet_count)
1506     *octet_count = curr->octet_count;
1507   if (time)
1508     *time = curr->time;
1509
1510   return TRUE;
1511 }
1512
1513 /**
1514  * rtp_source_get_last_rb:
1515  * @src: an #RTPSource
1516  * @fractionlost: fraction lost since last SR/RR
1517  * @packetslost: the cumululative number of packets lost
1518  * @exthighestseq: the extended last sequence number received
1519  * @jitter: the interarrival jitter
1520  * @lsr: the last SR packet from this source
1521  * @dlsr: the delay since last SR packet
1522  * @round_trip: the round trip time
1523  *
1524  * Get the values of the last RB report set with rtp_source_process_rb().
1525  *
1526  * Returns: %TRUE if there was a valid SB report.
1527  */
1528 gboolean
1529 rtp_source_get_last_rb (RTPSource * src, guint8 * fractionlost,
1530     gint32 * packetslost, guint32 * exthighestseq, guint32 * jitter,
1531     guint32 * lsr, guint32 * dlsr, guint32 * round_trip)
1532 {
1533   RTPReceiverReport *curr;
1534
1535   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1536
1537   curr = &src->stats.rr[src->stats.curr_rr];
1538   if (!curr->is_valid)
1539     return FALSE;
1540
1541   if (fractionlost)
1542     *fractionlost = curr->fractionlost;
1543   if (packetslost)
1544     *packetslost = curr->packetslost;
1545   if (exthighestseq)
1546     *exthighestseq = curr->exthighestseq;
1547   if (jitter)
1548     *jitter = curr->jitter;
1549   if (lsr)
1550     *lsr = curr->lsr;
1551   if (dlsr)
1552     *dlsr = curr->dlsr;
1553   if (round_trip)
1554     *round_trip = curr->round_trip;
1555
1556   return TRUE;
1557 }