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