9fd12e152d3e1798e7c6208130aa765a8fd95d87
[platform/upstream/gst-plugins-good.git] / gst / rtpmanager / rtpsource.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 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_rtp_from:
760  * @src: an #RTPSource
761  * @address: the RTP address to set
762  *
763  * Set that @src is receiving RTP packets from @address. This is used for
764  * collistion checking.
765  */
766 void
767 rtp_source_set_rtp_from (RTPSource * src, GSocketAddress * address)
768 {
769   g_return_if_fail (RTP_IS_SOURCE (src));
770
771   if (src->rtp_from)
772     g_object_unref (src->rtp_from);
773   src->rtp_from = G_SOCKET_ADDRESS (g_object_ref (address));
774 }
775
776 /**
777  * rtp_source_set_rtcp_from:
778  * @src: an #RTPSource
779  * @address: the RTCP address to set
780  *
781  * Set that @src is receiving RTCP packets from @address. This is used for
782  * collistion checking.
783  */
784 void
785 rtp_source_set_rtcp_from (RTPSource * src, GSocketAddress * address)
786 {
787   g_return_if_fail (RTP_IS_SOURCE (src));
788
789   if (src->rtcp_from)
790     g_object_unref (src->rtcp_from);
791   src->rtcp_from = G_SOCKET_ADDRESS (g_object_ref (address));
792 }
793
794 static GstFlowReturn
795 push_packet (RTPSource * src, GstBuffer * buffer)
796 {
797   GstFlowReturn ret = GST_FLOW_OK;
798
799   /* push queued packets first if any */
800   while (!g_queue_is_empty (src->packets)) {
801     GstBuffer *buffer = GST_BUFFER_CAST (g_queue_pop_head (src->packets));
802
803     GST_LOG ("pushing queued packet");
804     if (src->callbacks.push_rtp)
805       src->callbacks.push_rtp (src, buffer, src->user_data);
806     else
807       gst_buffer_unref (buffer);
808   }
809   GST_LOG ("pushing new packet");
810   /* push packet */
811   if (src->callbacks.push_rtp)
812     ret = src->callbacks.push_rtp (src, buffer, src->user_data);
813   else
814     gst_buffer_unref (buffer);
815
816   return ret;
817 }
818
819 static gint
820 get_clock_rate (RTPSource * src, guint8 payload)
821 {
822   if (src->payload == -1) {
823     /* first payload received, nothing was in the caps, lock on to this payload */
824     src->payload = payload;
825     GST_DEBUG ("first payload %d", payload);
826   } else if (payload != src->payload) {
827     /* we have a different payload than before, reset the clock-rate */
828     GST_DEBUG ("new payload %d", payload);
829     src->payload = payload;
830     src->clock_rate = -1;
831     src->stats.transit = -1;
832   }
833
834   if (src->clock_rate == -1) {
835     gint clock_rate = -1;
836
837     if (src->callbacks.clock_rate)
838       clock_rate = src->callbacks.clock_rate (src, payload, src->user_data);
839
840     GST_DEBUG ("got clock-rate %d", clock_rate);
841
842     src->clock_rate = clock_rate;
843   }
844   return src->clock_rate;
845 }
846
847 /* Jitter is the variation in the delay of received packets in a flow. It is
848  * measured by comparing the interval when RTP packets were sent to the interval
849  * at which they were received. For instance, if packet #1 and packet #2 leave
850  * 50 milliseconds apart and arrive 60 milliseconds apart, then the jitter is 10
851  * milliseconds. */
852 static void
853 calculate_jitter (RTPSource * src, GstBuffer * buffer,
854     RTPArrivalStats * arrival)
855 {
856   GstClockTime running_time;
857   guint32 rtparrival, transit, rtptime;
858   gint32 diff;
859   gint clock_rate;
860   guint8 pt;
861   GstRTPBuffer rtp = { NULL };
862
863   /* get arrival time */
864   if ((running_time = arrival->running_time) == GST_CLOCK_TIME_NONE)
865     goto no_time;
866
867   if (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp))
868     goto invalid_packet;
869
870   pt = gst_rtp_buffer_get_payload_type (&rtp);
871
872   GST_LOG ("SSRC %08x got payload %d", src->ssrc, pt);
873
874   /* get clockrate */
875   if ((clock_rate = get_clock_rate (src, pt)) == -1) {
876     gst_rtp_buffer_unmap (&rtp);
877     goto no_clock_rate;
878   }
879
880   rtptime = gst_rtp_buffer_get_timestamp (&rtp);
881
882   /* convert arrival time to RTP timestamp units, truncate to 32 bits, we don't
883    * care about the absolute value, just the difference. */
884   rtparrival = gst_util_uint64_scale_int (running_time, clock_rate, GST_SECOND);
885
886   /* transit time is difference with RTP timestamp */
887   transit = rtparrival - rtptime;
888
889   /* get ABS diff with previous transit time */
890   if (src->stats.transit != -1) {
891     if (transit > src->stats.transit)
892       diff = transit - src->stats.transit;
893     else
894       diff = src->stats.transit - transit;
895   } else
896     diff = 0;
897
898   src->stats.transit = transit;
899
900   /* update jitter, the value we store is scaled up so we can keep precision. */
901   src->stats.jitter += diff - ((src->stats.jitter + 8) >> 4);
902
903   src->stats.prev_rtptime = src->stats.last_rtptime;
904   src->stats.last_rtptime = rtparrival;
905
906   GST_LOG ("rtparrival %u, rtptime %u, clock-rate %d, diff %d, jitter: %f",
907       rtparrival, rtptime, clock_rate, diff, (src->stats.jitter) / 16.0);
908
909   gst_rtp_buffer_unmap (&rtp);
910   return;
911
912   /* ERRORS */
913 no_time:
914   {
915     GST_WARNING ("cannot get current running_time");
916     return;
917   }
918 invalid_packet:
919   {
920     GST_WARNING ("invalid RTP packet");
921     return;
922   }
923 no_clock_rate:
924   {
925     GST_WARNING ("cannot get clock-rate for pt %d", pt);
926     return;
927   }
928 }
929
930 static void
931 init_seq (RTPSource * src, guint16 seq)
932 {
933   src->stats.base_seq = seq;
934   src->stats.max_seq = seq;
935   src->stats.bad_seq = RTP_SEQ_MOD + 1; /* so seq == bad_seq is false */
936   src->stats.cycles = 0;
937   src->stats.packets_received = 0;
938   src->stats.octets_received = 0;
939   src->stats.bytes_received = 0;
940   src->stats.prev_received = 0;
941   src->stats.prev_expected = 0;
942
943   GST_DEBUG ("base_seq %d", seq);
944 }
945
946 #define BITRATE_INTERVAL (2 * GST_SECOND)
947
948 static void
949 do_bitrate_estimation (RTPSource * src, GstClockTime running_time,
950     guint64 * bytes_handled)
951 {
952   guint64 elapsed;
953
954   if (src->prev_rtime) {
955     elapsed = running_time - src->prev_rtime;
956
957     if (elapsed > BITRATE_INTERVAL) {
958       guint64 rate;
959
960       rate = gst_util_uint64_scale (*bytes_handled, 8 * GST_SECOND, elapsed);
961
962       GST_LOG ("Elapsed %" G_GUINT64_FORMAT ", bytes %" G_GUINT64_FORMAT
963           ", rate %" G_GUINT64_FORMAT, elapsed, *bytes_handled, rate);
964
965       if (src->bitrate == 0)
966         src->bitrate = rate;
967       else
968         src->bitrate = ((src->bitrate * 3) + rate) / 4;
969
970       src->prev_rtime = running_time;
971       *bytes_handled = 0;
972     }
973   } else {
974     GST_LOG ("Reset bitrate measurement");
975     src->prev_rtime = running_time;
976     src->bitrate = 0;
977   }
978 }
979
980 /**
981  * rtp_source_process_rtp:
982  * @src: an #RTPSource
983  * @buffer: an RTP buffer
984  *
985  * Let @src handle the incomming RTP @buffer.
986  *
987  * Returns: a #GstFlowReturn.
988  */
989 GstFlowReturn
990 rtp_source_process_rtp (RTPSource * src, GstBuffer * buffer,
991     RTPArrivalStats * arrival)
992 {
993   GstFlowReturn result = GST_FLOW_OK;
994   guint16 seqnr, udelta;
995   RTPSourceStats *stats;
996   guint16 expected;
997   GstRTPBuffer rtp = { NULL };
998
999   g_return_val_if_fail (RTP_IS_SOURCE (src), GST_FLOW_ERROR);
1000   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
1001
1002   stats = &src->stats;
1003
1004   if (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp))
1005     goto invalid_packet;
1006
1007   seqnr = gst_rtp_buffer_get_seq (&rtp);
1008   gst_rtp_buffer_unmap (&rtp);
1009
1010   if (stats->cycles == -1) {
1011     GST_DEBUG ("received first buffer");
1012     /* first time we heard of this source */
1013     init_seq (src, seqnr);
1014     src->stats.max_seq = seqnr - 1;
1015     src->curr_probation = src->probation;
1016   }
1017
1018   udelta = seqnr - stats->max_seq;
1019
1020   /* if we are still on probation, check seqnum */
1021   if (src->curr_probation) {
1022     expected = src->stats.max_seq + 1;
1023
1024     /* when in probation, we require consecutive seqnums */
1025     if (seqnr == expected) {
1026       /* expected packet */
1027       GST_DEBUG ("probation: seqnr %d == expected %d", seqnr, expected);
1028       src->curr_probation--;
1029       src->stats.max_seq = seqnr;
1030       if (src->curr_probation == 0) {
1031         GST_DEBUG ("probation done!");
1032         init_seq (src, seqnr);
1033       } else {
1034         GstBuffer *q;
1035
1036         GST_DEBUG ("probation %d: queue buffer", src->curr_probation);
1037         /* when still in probation, keep packets in a list. */
1038         g_queue_push_tail (src->packets, buffer);
1039         /* remove packets from queue if there are too many */
1040         while (g_queue_get_length (src->packets) > RTP_MAX_PROBATION_LEN) {
1041           q = g_queue_pop_head (src->packets);
1042           gst_buffer_unref (q);
1043         }
1044         goto done;
1045       }
1046     } else {
1047       /* unexpected seqnum in probation */
1048       goto probation_seqnum;
1049     }
1050   } else if (udelta < RTP_MAX_DROPOUT) {
1051     /* in order, with permissible gap */
1052     if (seqnr < stats->max_seq) {
1053       /* sequence number wrapped - count another 64K cycle. */
1054       stats->cycles += RTP_SEQ_MOD;
1055     }
1056     stats->max_seq = seqnr;
1057   } else if (udelta <= RTP_SEQ_MOD - RTP_MAX_MISORDER) {
1058     /* the sequence number made a very large jump */
1059     if (seqnr == stats->bad_seq) {
1060       /* two sequential packets -- assume that the other side
1061        * restarted without telling us so just re-sync
1062        * (i.e., pretend this was the first packet).  */
1063       init_seq (src, seqnr);
1064     } else {
1065       /* unacceptable jump */
1066       stats->bad_seq = (seqnr + 1) & (RTP_SEQ_MOD - 1);
1067       goto bad_sequence;
1068     }
1069   } else {
1070     /* duplicate or reordered packet, will be filtered by jitterbuffer. */
1071     GST_WARNING ("duplicate or reordered packet (seqnr %d)", seqnr);
1072   }
1073
1074   src->stats.octets_received += arrival->payload_len;
1075   src->stats.bytes_received += arrival->bytes;
1076   src->stats.packets_received++;
1077   /* for the bitrate estimation */
1078   src->bytes_received += arrival->payload_len;
1079   /* the source that sent the packet must be a sender */
1080   src->is_sender = TRUE;
1081   src->validated = TRUE;
1082
1083   do_bitrate_estimation (src, arrival->running_time, &src->bytes_received);
1084
1085   GST_LOG ("seq %d, PC: %" G_GUINT64_FORMAT ", OC: %" G_GUINT64_FORMAT,
1086       seqnr, src->stats.packets_received, src->stats.octets_received);
1087
1088   /* calculate jitter for the stats */
1089   calculate_jitter (src, buffer, arrival);
1090
1091   /* we're ready to push the RTP packet now */
1092   result = push_packet (src, buffer);
1093
1094 done:
1095   return result;
1096
1097   /* ERRORS */
1098 invalid_packet:
1099   {
1100     GST_WARNING ("invalid packet received");
1101     gst_buffer_unref (buffer);
1102     return GST_FLOW_OK;
1103   }
1104 bad_sequence:
1105   {
1106     GST_WARNING ("unacceptable seqnum received");
1107     gst_buffer_unref (buffer);
1108     return GST_FLOW_OK;
1109   }
1110 probation_seqnum:
1111   {
1112     GST_WARNING ("probation: seqnr %d != expected %d", seqnr, expected);
1113     src->curr_probation = src->probation;
1114     src->stats.max_seq = seqnr;
1115     gst_buffer_unref (buffer);
1116     return GST_FLOW_OK;
1117   }
1118 }
1119
1120 /**
1121  * rtp_source_process_bye:
1122  * @src: an #RTPSource
1123  * @reason: the reason for leaving
1124  *
1125  * Notify @src that a BYE packet has been received. This will make the source
1126  * inactive.
1127  */
1128 void
1129 rtp_source_process_bye (RTPSource * src, const gchar * reason)
1130 {
1131   g_return_if_fail (RTP_IS_SOURCE (src));
1132
1133   GST_DEBUG ("marking SSRC %08x as BYE, reason: %s", src->ssrc,
1134       GST_STR_NULL (reason));
1135
1136   /* copy the reason and mark as received_bye */
1137   g_free (src->bye_reason);
1138   src->bye_reason = g_strdup (reason);
1139   src->received_bye = TRUE;
1140 }
1141
1142 static gboolean
1143 set_ssrc (GstBuffer ** buffer, guint idx, RTPSource * src)
1144 {
1145   GstRTPBuffer rtp = { NULL };
1146
1147   *buffer = gst_buffer_make_writable (*buffer);
1148   if (gst_rtp_buffer_map (*buffer, GST_MAP_WRITE, &rtp)) {
1149     gst_rtp_buffer_set_ssrc (&rtp, src->ssrc);
1150     gst_rtp_buffer_unmap (&rtp);
1151   }
1152   return TRUE;
1153 }
1154
1155 /**
1156  * rtp_source_send_rtp:
1157  * @src: an #RTPSource
1158  * @data: an RTP buffer or a list of RTP buffers
1159  * @is_list: if @data is a buffer or list
1160  * @running_time: the running time of @data
1161  *
1162  * Send @data (an RTP buffer or list of buffers) originating from @src.
1163  * This will make @src a sender. This function takes ownership of @data and
1164  * modifies the SSRC in the RTP packet to that of @src when needed.
1165  *
1166  * Returns: a #GstFlowReturn.
1167  */
1168 GstFlowReturn
1169 rtp_source_send_rtp (RTPSource * src, gpointer data, gboolean is_list,
1170     GstClockTime running_time)
1171 {
1172   GstFlowReturn result;
1173   guint len;
1174   guint32 rtptime;
1175   guint64 ext_rtptime;
1176   guint64 rt_diff, rtp_diff;
1177   GstBufferList *list = NULL;
1178   GstBuffer *buffer = NULL;
1179   guint packets;
1180   guint32 ssrc;
1181   GstRTPBuffer rtp = { NULL };
1182
1183   g_return_val_if_fail (RTP_IS_SOURCE (src), GST_FLOW_ERROR);
1184   g_return_val_if_fail (is_list || GST_IS_BUFFER (data), GST_FLOW_ERROR);
1185
1186   if (is_list) {
1187     list = GST_BUFFER_LIST_CAST (data);
1188
1189     /* We can grab the caps from the first group, since all
1190      * groups of a buffer list have same caps. */
1191     buffer = gst_buffer_list_get (list, 0);
1192     if (!buffer)
1193       goto no_buffer;
1194   } else {
1195     buffer = GST_BUFFER_CAST (data);
1196   }
1197
1198   /* we are a sender now */
1199   src->is_sender = TRUE;
1200
1201   if (is_list) {
1202     gint i;
1203
1204     /* Each group makes up a network packet. */
1205     packets = gst_buffer_list_length (list);
1206     for (i = 0, len = 0; i < packets; i++) {
1207       if (!gst_rtp_buffer_map (gst_buffer_list_get (list, i), GST_MAP_READ,
1208               &rtp))
1209         goto invalid_packet;
1210
1211       len += gst_rtp_buffer_get_payload_len (&rtp);
1212       gst_rtp_buffer_unmap (&rtp);
1213     }
1214     /* subsequent info taken from first list member */
1215     gst_rtp_buffer_map (gst_buffer_list_get (list, 0), GST_MAP_READ, &rtp);
1216   } else {
1217     packets = 1;
1218     if (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp))
1219       goto invalid_packet;
1220
1221     len = gst_rtp_buffer_get_payload_len (&rtp);
1222   }
1223
1224   /* update stats for the SR */
1225   src->stats.packets_sent += packets;
1226   src->stats.octets_sent += len;
1227   src->bytes_sent += len;
1228
1229   do_bitrate_estimation (src, running_time, &src->bytes_sent);
1230
1231   rtptime = gst_rtp_buffer_get_timestamp (&rtp);
1232   ext_rtptime = src->last_rtptime;
1233   ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
1234
1235   GST_LOG ("SSRC %08x, RTP %" G_GUINT64_FORMAT ", running_time %"
1236       GST_TIME_FORMAT, src->ssrc, ext_rtptime, GST_TIME_ARGS (running_time));
1237
1238   if (ext_rtptime > src->last_rtptime) {
1239     rtp_diff = ext_rtptime - src->last_rtptime;
1240     rt_diff = running_time - src->last_rtime;
1241
1242     /* calc the diff so we can detect drift at the sender. This can also be used
1243      * to guestimate the clock rate if the NTP time is locked to the RTP
1244      * timestamps (as is the case when the capture device is providing the clock). */
1245     GST_LOG ("SSRC %08x, diff RTP %" G_GUINT64_FORMAT ", diff running_time %"
1246         GST_TIME_FORMAT, src->ssrc, rtp_diff, GST_TIME_ARGS (rt_diff));
1247   }
1248
1249   /* we keep track of the last received RTP timestamp and the corresponding
1250    * buffer running_time so that we can use this info when constructing SR reports */
1251   src->last_rtime = running_time;
1252   src->last_rtptime = ext_rtptime;
1253
1254   /* push packet */
1255   if (!src->callbacks.push_rtp) {
1256     gst_rtp_buffer_unmap (&rtp);
1257     goto no_callback;
1258   }
1259
1260   ssrc = gst_rtp_buffer_get_ssrc (&rtp);
1261   gst_rtp_buffer_unmap (&rtp);
1262
1263   if (ssrc != src->ssrc) {
1264     /* the SSRC of the packet is not correct, make a writable buffer and
1265      * update the SSRC. This could involve a complete copy of the packet when
1266      * it is not writable. Usually the payloader will use caps negotiation to
1267      * get the correct SSRC from the session manager before pushing anything. */
1268
1269     /* FIXME, we don't want to warn yet because we can't inform any payloader
1270      * of the changes SSRC yet because we don't implement pad-alloc. */
1271     GST_LOG ("updating SSRC from %08x to %08x, fix the payloader", ssrc,
1272         src->ssrc);
1273
1274     if (is_list) {
1275       list = gst_buffer_list_make_writable (list);
1276       gst_buffer_list_foreach (list, (GstBufferListFunc) set_ssrc, src);
1277     } else {
1278       set_ssrc (&buffer, 0, src);
1279     }
1280   }
1281   GST_LOG ("pushing RTP %s %" G_GUINT64_FORMAT, is_list ? "list" : "packet",
1282       src->stats.packets_sent);
1283
1284   result = src->callbacks.push_rtp (src, data, src->user_data);
1285
1286   return result;
1287
1288   /* ERRORS */
1289 invalid_packet:
1290   {
1291     GST_WARNING ("invalid packet received");
1292     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
1293     return GST_FLOW_OK;
1294   }
1295 no_buffer:
1296   {
1297     GST_WARNING ("no buffers in buffer list");
1298     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
1299     return GST_FLOW_OK;
1300   }
1301 no_callback:
1302   {
1303     GST_WARNING ("no callback installed, dropping packet");
1304     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
1305     return GST_FLOW_OK;
1306   }
1307 }
1308
1309 /**
1310  * rtp_source_process_sr:
1311  * @src: an #RTPSource
1312  * @time: time of packet arrival
1313  * @ntptime: the NTP time in 32.32 fixed point
1314  * @rtptime: the RTP time
1315  * @packet_count: the packet count
1316  * @octet_count: the octect count
1317  *
1318  * Update the sender report in @src.
1319  */
1320 void
1321 rtp_source_process_sr (RTPSource * src, GstClockTime time, guint64 ntptime,
1322     guint32 rtptime, guint32 packet_count, guint32 octet_count)
1323 {
1324   RTPSenderReport *curr;
1325   gint curridx;
1326
1327   g_return_if_fail (RTP_IS_SOURCE (src));
1328
1329   GST_DEBUG ("got SR packet: SSRC %08x, NTP %08x:%08x, RTP %" G_GUINT32_FORMAT
1330       ", PC %" G_GUINT32_FORMAT ", OC %" G_GUINT32_FORMAT, src->ssrc,
1331       (guint32) (ntptime >> 32), (guint32) (ntptime & 0xffffffff), rtptime,
1332       packet_count, octet_count);
1333
1334   curridx = src->stats.curr_sr ^ 1;
1335   curr = &src->stats.sr[curridx];
1336
1337   /* this is a sender now */
1338   src->is_sender = TRUE;
1339
1340   /* update current */
1341   curr->is_valid = TRUE;
1342   curr->ntptime = ntptime;
1343   curr->rtptime = rtptime;
1344   curr->packet_count = packet_count;
1345   curr->octet_count = octet_count;
1346   curr->time = time;
1347
1348   /* make current */
1349   src->stats.curr_sr = curridx;
1350
1351   src->stats.prev_rtcptime = src->stats.last_rtcptime;
1352   src->stats.last_rtcptime = time;
1353 }
1354
1355 /**
1356  * rtp_source_process_rb:
1357  * @src: an #RTPSource
1358  * @ntpnstime: the current time in nanoseconds since 1970
1359  * @fractionlost: fraction lost since last SR/RR
1360  * @packetslost: the cumululative number of packets lost
1361  * @exthighestseq: the extended last sequence number received
1362  * @jitter: the interarrival jitter
1363  * @lsr: the last SR packet from this source
1364  * @dlsr: the delay since last SR packet
1365  *
1366  * Update the report block in @src.
1367  */
1368 void
1369 rtp_source_process_rb (RTPSource * src, guint64 ntpnstime,
1370     guint8 fractionlost, gint32 packetslost, guint32 exthighestseq,
1371     guint32 jitter, guint32 lsr, guint32 dlsr)
1372 {
1373   RTPReceiverReport *curr;
1374   gint curridx;
1375   guint32 ntp, A;
1376   guint64 f_ntp;
1377
1378   g_return_if_fail (RTP_IS_SOURCE (src));
1379
1380   GST_DEBUG ("got RB packet: SSRC %08x, FL %2x, PL %d, HS %" G_GUINT32_FORMAT
1381       ", jitter %" G_GUINT32_FORMAT ", LSR %04x:%04x, DLSR %04x:%04x",
1382       src->ssrc, fractionlost, packetslost, exthighestseq, jitter, lsr >> 16,
1383       lsr & 0xffff, dlsr >> 16, dlsr & 0xffff);
1384
1385   curridx = src->stats.curr_rr ^ 1;
1386   curr = &src->stats.rr[curridx];
1387
1388   /* update current */
1389   curr->is_valid = TRUE;
1390   curr->fractionlost = fractionlost;
1391   curr->packetslost = packetslost;
1392   curr->exthighestseq = exthighestseq;
1393   curr->jitter = jitter;
1394   curr->lsr = lsr;
1395   curr->dlsr = dlsr;
1396
1397   /* convert the NTP time in nanoseconds to 32.32 fixed point */
1398   f_ntp = gst_util_uint64_scale (ntpnstime, (1LL << 32), GST_SECOND);
1399   /* calculate round trip, round the time up */
1400   ntp = ((f_ntp + 0xffff) >> 16) & 0xffffffff;
1401
1402   A = dlsr + lsr;
1403   if (A > 0 && ntp > A)
1404     A = ntp - A;
1405   else
1406     A = 0;
1407   curr->round_trip = A;
1408
1409   GST_DEBUG ("NTP %04x:%04x, round trip %04x:%04x", ntp >> 16, ntp & 0xffff,
1410       A >> 16, A & 0xffff);
1411
1412   /* make current */
1413   src->stats.curr_rr = curridx;
1414 }
1415
1416 /**
1417  * rtp_source_get_new_sr:
1418  * @src: an #RTPSource
1419  * @ntpnstime: the current time in nanoseconds since 1970
1420  * @running_time: the current running_time of the pipeline.
1421  * @ntptime: the NTP time in 32.32 fixed point
1422  * @rtptime: the RTP time corresponding to @ntptime
1423  * @packet_count: the packet count
1424  * @octet_count: the octect count
1425  *
1426  * Get new values to put into a new SR report from this source.
1427  *
1428  * @running_time and @ntpnstime are captured at the same time and represent the
1429  * running time of the pipeline clock and the absolute current system time in
1430  * nanoseconds respectively. Together with the last running_time and rtp timestamp
1431  * we have observed in the source, we can generate @ntptime and @rtptime for an SR
1432  * packet. @ntptime is basically the fixed point representation of @ntpnstime
1433  * and @rtptime the associated RTP timestamp.
1434  *
1435  * Returns: %TRUE on success.
1436  */
1437 gboolean
1438 rtp_source_get_new_sr (RTPSource * src, guint64 ntpnstime,
1439     GstClockTime running_time, guint64 * ntptime, guint32 * rtptime,
1440     guint32 * packet_count, guint32 * octet_count)
1441 {
1442   guint64 t_rtp;
1443   guint64 t_current_ntp;
1444   GstClockTimeDiff diff;
1445
1446   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1447
1448   /* We last saw a buffer with last_rtptime at last_rtime. Given a running_time
1449    * and an NTP time, we can scale the RTP timestamps so that they match the
1450    * given NTP time.  for scaling, we assume that the slope of the rtptime vs
1451    * running_time vs ntptime curve is close to 1, which is certainly
1452    * sufficient for the frequency at which we report SR and the rate we send
1453    * out RTP packets. */
1454   t_rtp = src->last_rtptime;
1455
1456   GST_DEBUG ("last_rtime %" GST_TIME_FORMAT ", last_rtptime %"
1457       G_GUINT64_FORMAT, GST_TIME_ARGS (src->last_rtime), t_rtp);
1458
1459   if (src->clock_rate != -1) {
1460     /* get the diff between the clock running_time and the buffer running_time.
1461      * This is the elapsed time, as measured against the pipeline clock, between
1462      * when the rtp timestamp was observed and the current running_time.
1463      *
1464      * We need to apply this diff to the RTP timestamp to get the RTP timestamp
1465      * for the given ntpnstime. */
1466     diff = GST_CLOCK_DIFF (src->last_rtime, running_time);
1467
1468     /* now translate the diff to RTP time, handle positive and negative cases.
1469      * If there is no diff, we already set rtptime correctly above. */
1470     if (diff > 0) {
1471       GST_DEBUG ("running_time %" GST_TIME_FORMAT ", diff %" GST_TIME_FORMAT,
1472           GST_TIME_ARGS (running_time), GST_TIME_ARGS (diff));
1473       t_rtp += gst_util_uint64_scale_int (diff, src->clock_rate, GST_SECOND);
1474     } else {
1475       diff = -diff;
1476       GST_DEBUG ("running_time %" GST_TIME_FORMAT ", diff -%" GST_TIME_FORMAT,
1477           GST_TIME_ARGS (running_time), GST_TIME_ARGS (diff));
1478       t_rtp -= gst_util_uint64_scale_int (diff, src->clock_rate, GST_SECOND);
1479     }
1480   } else {
1481     GST_WARNING ("no clock-rate, cannot interpolate rtp time");
1482   }
1483
1484   /* convert the NTP time in nanoseconds to 32.32 fixed point */
1485   t_current_ntp = gst_util_uint64_scale (ntpnstime, (1LL << 32), GST_SECOND);
1486
1487   GST_DEBUG ("NTP %08x:%08x, RTP %" G_GUINT32_FORMAT,
1488       (guint32) (t_current_ntp >> 32), (guint32) (t_current_ntp & 0xffffffff),
1489       (guint32) t_rtp);
1490
1491   if (ntptime)
1492     *ntptime = t_current_ntp;
1493   if (rtptime)
1494     *rtptime = t_rtp;
1495   if (packet_count)
1496     *packet_count = src->stats.packets_sent;
1497   if (octet_count)
1498     *octet_count = src->stats.octets_sent;
1499
1500   return TRUE;
1501 }
1502
1503 /**
1504  * rtp_source_get_new_rb:
1505  * @src: an #RTPSource
1506  * @time: the current time of the system clock
1507  * @fractionlost: fraction lost since last SR/RR
1508  * @packetslost: the cumululative number of packets lost
1509  * @exthighestseq: the extended last sequence number received
1510  * @jitter: the interarrival jitter
1511  * @lsr: the last SR packet from this source
1512  * @dlsr: the delay since last SR packet
1513  *
1514  * Get new values to put into a new report block from this source.
1515  *
1516  * Returns: %TRUE on success.
1517  */
1518 gboolean
1519 rtp_source_get_new_rb (RTPSource * src, GstClockTime time,
1520     guint8 * fractionlost, gint32 * packetslost, guint32 * exthighestseq,
1521     guint32 * jitter, guint32 * lsr, guint32 * dlsr)
1522 {
1523   RTPSourceStats *stats;
1524   guint64 extended_max, expected;
1525   guint64 expected_interval, received_interval, ntptime;
1526   gint64 lost, lost_interval;
1527   guint32 fraction, LSR, DLSR;
1528   GstClockTime sr_time;
1529
1530   stats = &src->stats;
1531
1532   extended_max = stats->cycles + stats->max_seq;
1533   expected = extended_max - stats->base_seq + 1;
1534
1535   GST_DEBUG ("ext_max %" G_GUINT64_FORMAT ", expected %" G_GUINT64_FORMAT
1536       ", received %" G_GUINT64_FORMAT ", base_seq %" G_GUINT32_FORMAT,
1537       extended_max, expected, stats->packets_received, stats->base_seq);
1538
1539   lost = expected - stats->packets_received;
1540   lost = CLAMP (lost, -0x800000, 0x7fffff);
1541
1542   expected_interval = expected - stats->prev_expected;
1543   stats->prev_expected = expected;
1544   received_interval = stats->packets_received - stats->prev_received;
1545   stats->prev_received = stats->packets_received;
1546
1547   lost_interval = expected_interval - received_interval;
1548
1549   if (expected_interval == 0 || lost_interval <= 0)
1550     fraction = 0;
1551   else
1552     fraction = (lost_interval << 8) / expected_interval;
1553
1554   GST_DEBUG ("add RR for SSRC %08x", src->ssrc);
1555   /* we scaled the jitter up for additional precision */
1556   GST_DEBUG ("fraction %" G_GUINT32_FORMAT ", lost %" G_GINT64_FORMAT
1557       ", extseq %" G_GUINT64_FORMAT ", jitter %d", fraction, lost,
1558       extended_max, stats->jitter >> 4);
1559
1560   if (rtp_source_get_last_sr (src, &sr_time, &ntptime, NULL, NULL, NULL)) {
1561     GstClockTime diff;
1562
1563     /* LSR is middle 32 bits of the last ntptime */
1564     LSR = (ntptime >> 16) & 0xffffffff;
1565     diff = time - sr_time;
1566     GST_DEBUG ("last SR time diff %" GST_TIME_FORMAT, GST_TIME_ARGS (diff));
1567     /* DLSR, delay since last SR is expressed in 1/65536 second units */
1568     DLSR = gst_util_uint64_scale_int (diff, 65536, GST_SECOND);
1569   } else {
1570     /* No valid SR received, LSR/DLSR are set to 0 then */
1571     GST_DEBUG ("no valid SR received");
1572     LSR = 0;
1573     DLSR = 0;
1574   }
1575   GST_DEBUG ("LSR %04x:%04x, DLSR %04x:%04x", LSR >> 16, LSR & 0xffff,
1576       DLSR >> 16, DLSR & 0xffff);
1577
1578   if (fractionlost)
1579     *fractionlost = fraction;
1580   if (packetslost)
1581     *packetslost = lost;
1582   if (exthighestseq)
1583     *exthighestseq = extended_max;
1584   if (jitter)
1585     *jitter = stats->jitter >> 4;
1586   if (lsr)
1587     *lsr = LSR;
1588   if (dlsr)
1589     *dlsr = DLSR;
1590
1591   return TRUE;
1592 }
1593
1594 /**
1595  * rtp_source_get_last_sr:
1596  * @src: an #RTPSource
1597  * @time: time of packet arrival
1598  * @ntptime: the NTP time in 32.32 fixed point
1599  * @rtptime: the RTP time
1600  * @packet_count: the packet count
1601  * @octet_count: the octect count
1602  *
1603  * Get the values of the last sender report as set with rtp_source_process_sr().
1604  *
1605  * Returns: %TRUE if there was a valid SR report.
1606  */
1607 gboolean
1608 rtp_source_get_last_sr (RTPSource * src, GstClockTime * time, guint64 * ntptime,
1609     guint32 * rtptime, guint32 * packet_count, guint32 * octet_count)
1610 {
1611   RTPSenderReport *curr;
1612
1613   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1614
1615   curr = &src->stats.sr[src->stats.curr_sr];
1616   if (!curr->is_valid)
1617     return FALSE;
1618
1619   if (ntptime)
1620     *ntptime = curr->ntptime;
1621   if (rtptime)
1622     *rtptime = curr->rtptime;
1623   if (packet_count)
1624     *packet_count = curr->packet_count;
1625   if (octet_count)
1626     *octet_count = curr->octet_count;
1627   if (time)
1628     *time = curr->time;
1629
1630   return TRUE;
1631 }
1632
1633 /**
1634  * rtp_source_get_last_rb:
1635  * @src: an #RTPSource
1636  * @fractionlost: fraction lost since last SR/RR
1637  * @packetslost: the cumululative number of packets lost
1638  * @exthighestseq: the extended last sequence number received
1639  * @jitter: the interarrival jitter
1640  * @lsr: the last SR packet from this source
1641  * @dlsr: the delay since last SR packet
1642  * @round_trip: the round trip time
1643  *
1644  * Get the values of the last RB report set with rtp_source_process_rb().
1645  *
1646  * Returns: %TRUE if there was a valid SB report.
1647  */
1648 gboolean
1649 rtp_source_get_last_rb (RTPSource * src, guint8 * fractionlost,
1650     gint32 * packetslost, guint32 * exthighestseq, guint32 * jitter,
1651     guint32 * lsr, guint32 * dlsr, guint32 * round_trip)
1652 {
1653   RTPReceiverReport *curr;
1654
1655   g_return_val_if_fail (RTP_IS_SOURCE (src), FALSE);
1656
1657   curr = &src->stats.rr[src->stats.curr_rr];
1658   if (!curr->is_valid)
1659     return FALSE;
1660
1661   if (fractionlost)
1662     *fractionlost = curr->fractionlost;
1663   if (packetslost)
1664     *packetslost = curr->packetslost;
1665   if (exthighestseq)
1666     *exthighestseq = curr->exthighestseq;
1667   if (jitter)
1668     *jitter = curr->jitter;
1669   if (lsr)
1670     *lsr = curr->lsr;
1671   if (dlsr)
1672     *dlsr = curr->dlsr;
1673   if (round_trip)
1674     *round_trip = curr->round_trip;
1675
1676   return TRUE;
1677 }
1678
1679 /**
1680  * rtp_source_find_conflicting_address:
1681  * @src: The source the packet came in
1682  * @address: address to check for
1683  * @time: The time when the packet that is possibly in conflict arrived
1684  *
1685  * Checks if an address which has a conflict is already known. If it is
1686  * a known conflict, remember the time
1687  *
1688  * Returns: TRUE if it was a known conflict, FALSE otherwise
1689  */
1690 gboolean
1691 rtp_source_find_conflicting_address (RTPSource * src, GSocketAddress * address,
1692     GstClockTime time)
1693 {
1694   GList *item;
1695
1696   for (item = g_list_first (src->conflicting_addresses);
1697       item; item = g_list_next (item)) {
1698     RTPConflictingAddress *known_conflict = item->data;
1699
1700     if (__g_socket_address_equal (address, known_conflict->address)) {
1701       known_conflict->time = time;
1702       return TRUE;
1703     }
1704   }
1705
1706   return FALSE;
1707 }
1708
1709 /**
1710  * rtp_source_add_conflicting_address:
1711  * @src: The source the packet came in
1712  * @address: address to remember
1713  * @time: The time when the packet that is in conflict arrived
1714  *
1715  * Adds a new conflict address
1716  */
1717 void
1718 rtp_source_add_conflicting_address (RTPSource * src,
1719     GSocketAddress * address, GstClockTime time)
1720 {
1721   RTPConflictingAddress *new_conflict;
1722
1723   new_conflict = g_new0 (RTPConflictingAddress, 1);
1724
1725   new_conflict->address = G_SOCKET_ADDRESS (g_object_ref (address));
1726   new_conflict->time = time;
1727
1728   src->conflicting_addresses = g_list_prepend (src->conflicting_addresses,
1729       new_conflict);
1730 }
1731
1732 /**
1733  * rtp_source_timeout:
1734  * @src: The #RTPSource
1735  * @current_time: The current time
1736  * @collision_timeout: The amount of time after which a collision is timed out
1737  * @feedback_retention_window: The running time before which retained feedback
1738  * packets have to be discarded
1739  *
1740  * This is processed on each RTCP interval. It times out old collisions.
1741  * It also times out old retained feedback packets
1742  */
1743 void
1744 rtp_source_timeout (RTPSource * src, GstClockTime current_time,
1745     GstClockTime collision_timeout, GstClockTime feedback_retention_window)
1746 {
1747   GList *item;
1748   GstRTCPPacket *pkt;
1749
1750   item = g_list_first (src->conflicting_addresses);
1751   while (item) {
1752     RTPConflictingAddress *known_conflict = item->data;
1753     GList *next_item = g_list_next (item);
1754
1755     if (known_conflict->time < current_time - collision_timeout) {
1756       gchar *buf;
1757
1758       src->conflicting_addresses =
1759           g_list_delete_link (src->conflicting_addresses, item);
1760       buf = __g_socket_address_to_string (known_conflict->address);
1761       GST_DEBUG ("collision %p timed out: %s", known_conflict, buf);
1762       g_free (buf);
1763       g_object_unref (known_conflict->address);
1764       g_free (known_conflict);
1765     }
1766     item = next_item;
1767   }
1768
1769   /* Time out AVPF packets that are older than the desired length */
1770   while ((pkt = g_queue_peek_tail (src->retained_feedback)) &&
1771       GST_BUFFER_TIMESTAMP (pkt) < feedback_retention_window)
1772     gst_buffer_unref (g_queue_pop_tail (src->retained_feedback));
1773 }
1774
1775 static gint
1776 compare_buffers (gconstpointer a, gconstpointer b, gpointer user_data)
1777 {
1778   const GstBuffer *bufa = a;
1779   const GstBuffer *bufb = b;
1780
1781   return GST_BUFFER_TIMESTAMP (bufa) - GST_BUFFER_TIMESTAMP (bufb);
1782 }
1783
1784 void
1785 rtp_source_retain_rtcp_packet (RTPSource * src, GstRTCPPacket * packet,
1786     GstClockTime running_time)
1787 {
1788   GstBuffer *buffer;
1789
1790   buffer = gst_buffer_copy_region (packet->rtcp->buffer, GST_BUFFER_COPY_MEMORY,
1791       packet->offset, (gst_rtcp_packet_get_length (packet) + 1) * 4);
1792
1793   GST_BUFFER_TIMESTAMP (buffer) = running_time;
1794
1795   g_queue_insert_sorted (src->retained_feedback, buffer, compare_buffers, NULL);
1796 }
1797
1798 gboolean
1799 rtp_source_has_retained (RTPSource * src, GCompareFunc func, gconstpointer data)
1800 {
1801   if (g_queue_find_custom (src->retained_feedback, data, func))
1802     return TRUE;
1803   else
1804     return FALSE;
1805 }