rtpsource: Incoming buffers do not always have caps
[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 (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
977   g_return_val_if_fail (RTP_IS_SOURCE (src), GST_FLOW_ERROR);
978   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
979
980   stats = &src->stats;
981
982   seqnr = gst_rtp_buffer_get_seq (buffer);
983
984   if (GST_BUFFER_CAPS (buffer))
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     guint16 expected;
1000
1001     expected = src->stats.max_seq + 1;
1002
1003     /* when in probation, we require consecutive seqnums */
1004     if (seqnr == expected) {
1005       /* expected packet */
1006       GST_DEBUG ("probation: seqnr %d == expected %d", seqnr, expected);
1007       src->probation--;
1008       src->stats.max_seq = seqnr;
1009       if (src->probation == 0) {
1010         GST_DEBUG ("probation done!");
1011         init_seq (src, seqnr);
1012       } else {
1013         GstBuffer *q;
1014
1015         GST_DEBUG ("probation %d: queue buffer", src->probation);
1016         /* when still in probation, keep packets in a list. */
1017         g_queue_push_tail (src->packets, buffer);
1018         /* remove packets from queue if there are too many */
1019         while (g_queue_get_length (src->packets) > RTP_MAX_PROBATION_LEN) {
1020           q = g_queue_pop_head (src->packets);
1021           gst_buffer_unref (q);
1022         }
1023         goto done;
1024       }
1025     } else {
1026       GST_DEBUG ("probation: seqnr %d != expected %d", seqnr, expected);
1027       src->probation = RTP_DEFAULT_PROBATION;
1028       src->stats.max_seq = seqnr;
1029       goto done;
1030     }
1031   } else if (udelta < RTP_MAX_DROPOUT) {
1032     /* in order, with permissible gap */
1033     if (seqnr < stats->max_seq) {
1034       /* sequence number wrapped - count another 64K cycle. */
1035       stats->cycles += RTP_SEQ_MOD;
1036     }
1037     stats->max_seq = seqnr;
1038   } else if (udelta <= RTP_SEQ_MOD - RTP_MAX_MISORDER) {
1039     /* the sequence number made a very large jump */
1040     if (seqnr == stats->bad_seq) {
1041       /* two sequential packets -- assume that the other side
1042        * restarted without telling us so just re-sync
1043        * (i.e., pretend this was the first packet).  */
1044       init_seq (src, seqnr);
1045     } else {
1046       /* unacceptable jump */
1047       stats->bad_seq = (seqnr + 1) & (RTP_SEQ_MOD - 1);
1048       goto bad_sequence;
1049     }
1050   } else {
1051     /* duplicate or reordered packet, will be filtered by jitterbuffer. */
1052     GST_WARNING ("duplicate or reordered packet");
1053   }
1054
1055   src->stats.octets_received += arrival->payload_len;
1056   src->stats.bytes_received += arrival->bytes;
1057   src->stats.packets_received++;
1058   /* the source that sent the packet must be a sender */
1059   src->is_sender = TRUE;
1060   src->validated = TRUE;
1061
1062   GST_LOG ("seq %d, PC: %" G_GUINT64_FORMAT ", OC: %" G_GUINT64_FORMAT,
1063       seqnr, src->stats.packets_received, src->stats.octets_received);
1064
1065   /* calculate jitter for the stats */
1066   calculate_jitter (src, buffer, arrival);
1067
1068   /* we're ready to push the RTP packet now */
1069   result = push_packet (src, buffer);
1070
1071 done:
1072   return result;
1073
1074   /* ERRORS */
1075 bad_sequence:
1076   {
1077     GST_WARNING ("unacceptable seqnum received");
1078     return GST_FLOW_OK;
1079   }
1080 }
1081
1082 /**
1083  * rtp_source_process_bye:
1084  * @src: an #RTPSource
1085  * @reason: the reason for leaving
1086  *
1087  * Notify @src that a BYE packet has been received. This will make the source
1088  * inactive.
1089  */
1090 void
1091 rtp_source_process_bye (RTPSource * src, const gchar * reason)
1092 {
1093   g_return_if_fail (RTP_IS_SOURCE (src));
1094
1095   GST_DEBUG ("marking SSRC %08x as BYE, reason: %s", src->ssrc,
1096       GST_STR_NULL (reason));
1097
1098   /* copy the reason and mark as received_bye */
1099   g_free (src->bye_reason);
1100   src->bye_reason = g_strdup (reason);
1101   src->received_bye = TRUE;
1102 }
1103
1104 static GstBufferListItem
1105 set_ssrc (GstBuffer ** buffer, guint group, guint idx, RTPSource * src)
1106 {
1107   *buffer = gst_buffer_make_writable (*buffer);
1108   gst_rtp_buffer_set_ssrc (*buffer, src->ssrc);
1109   return GST_BUFFER_LIST_SKIP_GROUP;
1110 }
1111
1112 /**
1113  * rtp_source_send_rtp:
1114  * @src: an #RTPSource
1115  * @data: an RTP buffer or a list of RTP buffers
1116  * @is_list: if @data is a buffer or list
1117  * @ntpnstime: the NTP time when this buffer was captured in nanoseconds. This
1118  * is the buffer timestamp converted to NTP time.
1119  *
1120  * Send @data (an RTP buffer or list of buffers) originating from @src.
1121  * This will make @src a sender. This function takes ownership of @data and
1122  * modifies the SSRC in the RTP packet to that of @src when needed.
1123  *
1124  * Returns: a #GstFlowReturn.
1125  */
1126 GstFlowReturn
1127 rtp_source_send_rtp (RTPSource * src, gpointer data, gboolean is_list,
1128     guint64 ntpnstime)
1129 {
1130   GstFlowReturn result;
1131   guint len;
1132   guint32 rtptime;
1133   guint64 ext_rtptime;
1134   guint64 ntp_diff, rtp_diff;
1135   guint64 elapsed;
1136   GstBufferList *list = NULL;
1137   GstBuffer *buffer = NULL;
1138   guint packets;
1139   guint32 ssrc;
1140
1141   g_return_val_if_fail (RTP_IS_SOURCE (src), GST_FLOW_ERROR);
1142   g_return_val_if_fail (is_list || GST_IS_BUFFER (data), GST_FLOW_ERROR);
1143
1144   if (is_list) {
1145     list = GST_BUFFER_LIST_CAST (data);
1146
1147     /* We can grab the caps from the first group, since all
1148      * groups of a buffer list have same caps. */
1149     buffer = gst_buffer_list_get (list, 0, 0);
1150     if (!buffer)
1151       goto no_buffer;
1152   } else {
1153     buffer = GST_BUFFER_CAST (data);
1154   }
1155   rtp_source_update_caps (src, GST_BUFFER_CAPS (buffer));
1156
1157   /* we are a sender now */
1158   src->is_sender = TRUE;
1159
1160   if (is_list) {
1161     /* Each group makes up a network packet. */
1162     packets = gst_buffer_list_n_groups (list);
1163     len = gst_rtp_buffer_list_get_payload_len (list);
1164   } else {
1165     packets = 1;
1166     len = gst_rtp_buffer_get_payload_len (buffer);
1167   }
1168
1169   /* update stats for the SR */
1170   src->stats.packets_sent += packets;
1171   src->stats.octets_sent += len;
1172   src->bytes_sent += len;
1173
1174   if (src->prev_ntpnstime) {
1175     elapsed = ntpnstime - src->prev_ntpnstime;
1176
1177     if (elapsed > (G_GINT64_CONSTANT (1) << 31)) {
1178       guint64 rate;
1179
1180       rate =
1181           gst_util_uint64_scale (src->bytes_sent, elapsed,
1182           (G_GINT64_CONSTANT (1) << 29));
1183
1184       GST_LOG ("Elapsed %" G_GUINT64_FORMAT ", bytes %" G_GUINT64_FORMAT
1185           ", rate %" G_GUINT64_FORMAT, elapsed, src->bytes_sent, rate);
1186
1187       if (src->bitrate == 0)
1188         src->bitrate = rate;
1189       else
1190         src->bitrate = ((src->bitrate * 3) + rate) / 4;
1191
1192       src->prev_ntpnstime = ntpnstime;
1193       src->bytes_sent = 0;
1194     }
1195   } else {
1196     GST_LOG ("Reset bitrate measurement");
1197     src->prev_ntpnstime = ntpnstime;
1198     src->bitrate = 0;
1199   }
1200
1201   if (is_list) {
1202     rtptime = gst_rtp_buffer_list_get_timestamp (list);
1203   } else {
1204     rtptime = gst_rtp_buffer_get_timestamp (buffer);
1205   }
1206   ext_rtptime = src->last_rtptime;
1207   ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
1208
1209   GST_LOG ("SSRC %08x, RTP %" G_GUINT64_FORMAT ", NTP %" GST_TIME_FORMAT,
1210       src->ssrc, ext_rtptime, GST_TIME_ARGS (ntpnstime));
1211
1212   if (ext_rtptime > src->last_rtptime) {
1213     rtp_diff = ext_rtptime - src->last_rtptime;
1214     ntp_diff = ntpnstime - src->last_ntpnstime;
1215
1216     /* calc the diff so we can detect drift at the sender. This can also be used
1217      * to guestimate the clock rate if the NTP time is locked to the RTP
1218      * timestamps (as is the case when the capture device is providing the clock). */
1219     GST_LOG ("SSRC %08x, diff RTP %" G_GUINT64_FORMAT ", diff NTP %"
1220         GST_TIME_FORMAT, src->ssrc, rtp_diff, GST_TIME_ARGS (ntp_diff));
1221   }
1222
1223   /* we keep track of the last received RTP timestamp and the corresponding
1224    * NTP timestamp so that we can use this info when constructing SR reports */
1225   src->last_rtptime = ext_rtptime;
1226   src->last_ntpnstime = ntpnstime;
1227
1228   /* push packet */
1229   if (!src->callbacks.push_rtp)
1230     goto no_callback;
1231
1232   if (is_list) {
1233     ssrc = gst_rtp_buffer_list_get_ssrc (list);
1234   } else {
1235     ssrc = gst_rtp_buffer_get_ssrc (buffer);
1236   }
1237
1238   if (ssrc != src->ssrc) {
1239     /* the SSRC of the packet is not correct, make a writable buffer and
1240      * update the SSRC. This could involve a complete copy of the packet when
1241      * it is not writable. Usually the payloader will use caps negotiation to
1242      * get the correct SSRC from the session manager before pushing anything. */
1243
1244     /* FIXME, we don't want to warn yet because we can't inform any payloader
1245      * of the changes SSRC yet because we don't implement pad-alloc. */
1246     GST_LOG ("updating SSRC from %08x to %08x, fix the payloader", ssrc,
1247         src->ssrc);
1248
1249     if (is_list) {
1250       list = gst_buffer_list_make_writable (list);
1251       gst_buffer_list_foreach (list, (GstBufferListFunc) set_ssrc, src);
1252     } else {
1253       set_ssrc (&buffer, 0, 0, src);
1254     }
1255   }
1256   GST_LOG ("pushing RTP %s %" G_GUINT64_FORMAT, is_list ? "list" : "packet",
1257       src->stats.packets_sent);
1258
1259   result = src->callbacks.push_rtp (src, data, src->user_data);
1260
1261   return result;
1262
1263   /* ERRORS */
1264 no_buffer:
1265   {
1266     GST_WARNING ("no buffers in buffer list");
1267     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
1268     return GST_FLOW_OK;
1269   }
1270 no_callback:
1271   {
1272     GST_WARNING ("no callback installed, dropping packet");
1273     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
1274     return GST_FLOW_OK;
1275   }
1276 }
1277
1278 /**
1279  * rtp_source_process_sr:
1280  * @src: an #RTPSource
1281  * @time: time of packet arrival
1282  * @ntptime: the NTP time in 32.32 fixed point
1283  * @rtptime: the RTP time
1284  * @packet_count: the packet count
1285  * @octet_count: the octect count
1286  *
1287  * Update the sender report in @src.
1288  */
1289 void
1290 rtp_source_process_sr (RTPSource * src, GstClockTime time, guint64 ntptime,
1291     guint32 rtptime, guint32 packet_count, guint32 octet_count)
1292 {
1293   RTPSenderReport *curr;
1294   gint curridx;
1295
1296   g_return_if_fail (RTP_IS_SOURCE (src));
1297
1298   GST_DEBUG ("got SR packet: SSRC %08x, NTP %08x:%08x, RTP %" G_GUINT32_FORMAT
1299       ", PC %" G_GUINT32_FORMAT ", OC %" G_GUINT32_FORMAT, src->ssrc,
1300       (guint32) (ntptime >> 32), (guint32) (ntptime & 0xffffffff), rtptime,
1301       packet_count, octet_count);
1302
1303   curridx = src->stats.curr_sr ^ 1;
1304   curr = &src->stats.sr[curridx];
1305
1306   /* this is a sender now */
1307   src->is_sender = TRUE;
1308
1309   /* update current */
1310   curr->is_valid = TRUE;
1311   curr->ntptime = ntptime;
1312   curr->rtptime = rtptime;
1313   curr->packet_count = packet_count;
1314   curr->octet_count = octet_count;
1315   curr->time = time;
1316
1317   /* make current */
1318   src->stats.curr_sr = curridx;
1319 }
1320
1321 /**
1322  * rtp_source_process_rb:
1323  * @src: an #RTPSource
1324  * @time: the current time in nanoseconds since 1970
1325  * @fractionlost: fraction lost since last SR/RR
1326  * @packetslost: the cumululative number of packets lost
1327  * @exthighestseq: the extended last sequence number received
1328  * @jitter: the interarrival jitter
1329  * @lsr: the last SR packet from this source
1330  * @dlsr: the delay since last SR packet
1331  *
1332  * Update the report block in @src.
1333  */
1334 void
1335 rtp_source_process_rb (RTPSource * src, GstClockTime time, guint8 fractionlost,
1336     gint32 packetslost, guint32 exthighestseq, guint32 jitter, guint32 lsr,
1337     guint32 dlsr)
1338 {
1339   RTPReceiverReport *curr;
1340   gint curridx;
1341   guint32 ntp, A;
1342
1343   g_return_if_fail (RTP_IS_SOURCE (src));
1344
1345   GST_DEBUG ("got RB packet: SSRC %08x, FL %2x, PL %d, HS %" G_GUINT32_FORMAT
1346       ", jitter %" G_GUINT32_FORMAT ", LSR %04x:%04x, DLSR %04x:%04x",
1347       src->ssrc, fractionlost, packetslost, exthighestseq, jitter, lsr >> 16,
1348       lsr & 0xffff, dlsr >> 16, dlsr & 0xffff);
1349
1350   curridx = src->stats.curr_rr ^ 1;
1351   curr = &src->stats.rr[curridx];
1352
1353   /* update current */
1354   curr->is_valid = TRUE;
1355   curr->fractionlost = fractionlost;
1356   curr->packetslost = packetslost;
1357   curr->exthighestseq = exthighestseq;
1358   curr->jitter = jitter;
1359   curr->lsr = lsr;
1360   curr->dlsr = dlsr;
1361
1362   /* calculate round trip, round the time up */
1363   ntp = ((gst_rtcp_unix_to_ntp (time) + 0xffff) >> 16) & 0xffffffff;
1364   A = dlsr + lsr;
1365   if (A > 0 && ntp > A)
1366     A = ntp - A;
1367   else
1368     A = 0;
1369   curr->round_trip = A;
1370
1371   GST_DEBUG ("NTP %04x:%04x, round trip %04x:%04x", ntp >> 16, ntp & 0xffff,
1372       A >> 16, A & 0xffff);
1373
1374   /* make current */
1375   src->stats.curr_rr = curridx;
1376 }
1377
1378 /**
1379  * rtp_source_get_new_sr:
1380  * @src: an #RTPSource
1381  * @ntpnstime: the current time in nanoseconds since 1970
1382  * @ntptime: the NTP time in 32.32 fixed point
1383  * @rtptime: the RTP time corresponding to @ntptime
1384  * @packet_count: the packet count
1385  * @octet_count: the octect count
1386  *
1387  * Get new values to put into a new SR report from this source.
1388  *
1389  * Returns: %TRUE on success.
1390  */
1391 gboolean
1392 rtp_source_get_new_sr (RTPSource * src, guint64 ntpnstime,
1393     guint64 * ntptime, guint32 * rtptime, guint32 * packet_count,
1394     guint32 * octet_count)
1395 {
1396   guint64 t_rtp;
1397   guint64 t_current_ntp;
1398   GstClockTimeDiff diff;
1399
1400   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1401
1402   /* use the sync params to interpolate the date->time member to rtptime. We
1403    * use the last sent timestamp and rtptime as reference points. We assume
1404    * that the slope of the rtptime vs timestamp curve is 1, which is certainly
1405    * sufficient for the frequency at which we report SR and the rate we send
1406    * out RTP packets. */
1407   t_rtp = src->last_rtptime;
1408
1409   GST_DEBUG ("last_ntpnstime %" GST_TIME_FORMAT ", last_rtptime %"
1410       G_GUINT64_FORMAT, GST_TIME_ARGS (src->last_ntpnstime), t_rtp);
1411
1412   if (src->clock_rate != -1) {
1413     /* get the diff with the SR time */
1414     diff = GST_CLOCK_DIFF (src->last_ntpnstime, ntpnstime);
1415
1416     /* now translate the diff to RTP time, handle positive and negative cases.
1417      * If there is no diff, we already set rtptime correctly above. */
1418     if (diff > 0) {
1419       GST_DEBUG ("ntpnstime %" GST_TIME_FORMAT ", diff %" GST_TIME_FORMAT,
1420           GST_TIME_ARGS (ntpnstime), GST_TIME_ARGS (diff));
1421       t_rtp += gst_util_uint64_scale_int (diff, src->clock_rate, GST_SECOND);
1422     } else {
1423       diff = -diff;
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     }
1428   } else {
1429     GST_WARNING ("no clock-rate, cannot interpolate rtp time");
1430   }
1431
1432   /* convert the NTP time in nanoseconds to 32.32 fixed point */
1433   t_current_ntp = gst_util_uint64_scale (ntpnstime, (1LL << 32), GST_SECOND);
1434
1435   GST_DEBUG ("NTP %08x:%08x, RTP %" G_GUINT32_FORMAT,
1436       (guint32) (t_current_ntp >> 32), (guint32) (t_current_ntp & 0xffffffff),
1437       (guint32) t_rtp);
1438
1439   if (ntptime)
1440     *ntptime = t_current_ntp;
1441   if (rtptime)
1442     *rtptime = t_rtp;
1443   if (packet_count)
1444     *packet_count = src->stats.packets_sent;
1445   if (octet_count)
1446     *octet_count = src->stats.octets_sent;
1447
1448   return TRUE;
1449 }
1450
1451 /**
1452  * rtp_source_get_new_rb:
1453  * @src: an #RTPSource
1454  * @time: the current time of the system clock
1455  * @fractionlost: fraction lost since last SR/RR
1456  * @packetslost: the cumululative number of packets lost
1457  * @exthighestseq: the extended last sequence number received
1458  * @jitter: the interarrival jitter
1459  * @lsr: the last SR packet from this source
1460  * @dlsr: the delay since last SR packet
1461  *
1462  * Get new values to put into a new report block from this source.
1463  *
1464  * Returns: %TRUE on success.
1465  */
1466 gboolean
1467 rtp_source_get_new_rb (RTPSource * src, GstClockTime time,
1468     guint8 * fractionlost, gint32 * packetslost, guint32 * exthighestseq,
1469     guint32 * jitter, guint32 * lsr, guint32 * dlsr)
1470 {
1471   RTPSourceStats *stats;
1472   guint64 extended_max, expected;
1473   guint64 expected_interval, received_interval, ntptime;
1474   gint64 lost, lost_interval;
1475   guint32 fraction, LSR, DLSR;
1476   GstClockTime sr_time;
1477
1478   stats = &src->stats;
1479
1480   extended_max = stats->cycles + stats->max_seq;
1481   expected = extended_max - stats->base_seq + 1;
1482
1483   GST_DEBUG ("ext_max %" G_GUINT64_FORMAT ", expected %" G_GUINT64_FORMAT
1484       ", received %" G_GUINT64_FORMAT ", base_seq %" G_GUINT32_FORMAT,
1485       extended_max, expected, stats->packets_received, stats->base_seq);
1486
1487   lost = expected - stats->packets_received;
1488   lost = CLAMP (lost, -0x800000, 0x7fffff);
1489
1490   expected_interval = expected - stats->prev_expected;
1491   stats->prev_expected = expected;
1492   received_interval = stats->packets_received - stats->prev_received;
1493   stats->prev_received = stats->packets_received;
1494
1495   lost_interval = expected_interval - received_interval;
1496
1497   if (expected_interval == 0 || lost_interval <= 0)
1498     fraction = 0;
1499   else
1500     fraction = (lost_interval << 8) / expected_interval;
1501
1502   GST_DEBUG ("add RR for SSRC %08x", src->ssrc);
1503   /* we scaled the jitter up for additional precision */
1504   GST_DEBUG ("fraction %" G_GUINT32_FORMAT ", lost %" G_GINT64_FORMAT
1505       ", extseq %" G_GUINT64_FORMAT ", jitter %d", fraction, lost,
1506       extended_max, stats->jitter >> 4);
1507
1508   if (rtp_source_get_last_sr (src, &sr_time, &ntptime, NULL, NULL, NULL)) {
1509     GstClockTime diff;
1510
1511     /* LSR is middle 32 bits of the last ntptime */
1512     LSR = (ntptime >> 16) & 0xffffffff;
1513     diff = time - sr_time;
1514     GST_DEBUG ("last SR time diff %" GST_TIME_FORMAT, GST_TIME_ARGS (diff));
1515     /* DLSR, delay since last SR is expressed in 1/65536 second units */
1516     DLSR = gst_util_uint64_scale_int (diff, 65536, GST_SECOND);
1517   } else {
1518     /* No valid SR received, LSR/DLSR are set to 0 then */
1519     GST_DEBUG ("no valid SR received");
1520     LSR = 0;
1521     DLSR = 0;
1522   }
1523   GST_DEBUG ("LSR %04x:%04x, DLSR %04x:%04x", LSR >> 16, LSR & 0xffff,
1524       DLSR >> 16, DLSR & 0xffff);
1525
1526   if (fractionlost)
1527     *fractionlost = fraction;
1528   if (packetslost)
1529     *packetslost = lost;
1530   if (exthighestseq)
1531     *exthighestseq = extended_max;
1532   if (jitter)
1533     *jitter = stats->jitter >> 4;
1534   if (lsr)
1535     *lsr = LSR;
1536   if (dlsr)
1537     *dlsr = DLSR;
1538
1539   return TRUE;
1540 }
1541
1542 /**
1543  * rtp_source_get_last_sr:
1544  * @src: an #RTPSource
1545  * @time: time of packet arrival
1546  * @ntptime: the NTP time in 32.32 fixed point
1547  * @rtptime: the RTP time
1548  * @packet_count: the packet count
1549  * @octet_count: the octect count
1550  *
1551  * Get the values of the last sender report as set with rtp_source_process_sr().
1552  *
1553  * Returns: %TRUE if there was a valid SR report.
1554  */
1555 gboolean
1556 rtp_source_get_last_sr (RTPSource * src, GstClockTime * time, guint64 * ntptime,
1557     guint32 * rtptime, guint32 * packet_count, guint32 * octet_count)
1558 {
1559   RTPSenderReport *curr;
1560
1561   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1562
1563   curr = &src->stats.sr[src->stats.curr_sr];
1564   if (!curr->is_valid)
1565     return FALSE;
1566
1567   if (ntptime)
1568     *ntptime = curr->ntptime;
1569   if (rtptime)
1570     *rtptime = curr->rtptime;
1571   if (packet_count)
1572     *packet_count = curr->packet_count;
1573   if (octet_count)
1574     *octet_count = curr->octet_count;
1575   if (time)
1576     *time = curr->time;
1577
1578   return TRUE;
1579 }
1580
1581 /**
1582  * rtp_source_get_last_rb:
1583  * @src: an #RTPSource
1584  * @fractionlost: fraction lost since last SR/RR
1585  * @packetslost: the cumululative number of packets lost
1586  * @exthighestseq: the extended last sequence number received
1587  * @jitter: the interarrival jitter
1588  * @lsr: the last SR packet from this source
1589  * @dlsr: the delay since last SR packet
1590  * @round_trip: the round trip time
1591  *
1592  * Get the values of the last RB report set with rtp_source_process_rb().
1593  *
1594  * Returns: %TRUE if there was a valid SB report.
1595  */
1596 gboolean
1597 rtp_source_get_last_rb (RTPSource * src, guint8 * fractionlost,
1598     gint32 * packetslost, guint32 * exthighestseq, guint32 * jitter,
1599     guint32 * lsr, guint32 * dlsr, guint32 * round_trip)
1600 {
1601   RTPReceiverReport *curr;
1602
1603   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1604
1605   curr = &src->stats.rr[src->stats.curr_rr];
1606   if (!curr->is_valid)
1607     return FALSE;
1608
1609   if (fractionlost)
1610     *fractionlost = curr->fractionlost;
1611   if (packetslost)
1612     *packetslost = curr->packetslost;
1613   if (exthighestseq)
1614     *exthighestseq = curr->exthighestseq;
1615   if (jitter)
1616     *jitter = curr->jitter;
1617   if (lsr)
1618     *lsr = curr->lsr;
1619   if (dlsr)
1620     *dlsr = curr->dlsr;
1621   if (round_trip)
1622     *round_trip = curr->round_trip;
1623
1624   return TRUE;
1625 }