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