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