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