rtpsession: Don't relay more than one PLI request per RTT
[platform/upstream/gstreamer.git] / gst / rtpmanager / rtpsession.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 #include <string.h>
21
22 #include <gst/rtp/gstrtpbuffer.h>
23 #include <gst/rtp/gstrtcpbuffer.h>
24 #include <gst/netbuffer/gstnetbuffer.h>
25
26 #include "gstrtpbin-marshal.h"
27 #include "rtpsession.h"
28
29 GST_DEBUG_CATEGORY_STATIC (rtp_session_debug);
30 #define GST_CAT_DEFAULT rtp_session_debug
31
32 /* signals and args */
33 enum
34 {
35   SIGNAL_GET_SOURCE_BY_SSRC,
36   SIGNAL_ON_NEW_SSRC,
37   SIGNAL_ON_SSRC_COLLISION,
38   SIGNAL_ON_SSRC_VALIDATED,
39   SIGNAL_ON_SSRC_ACTIVE,
40   SIGNAL_ON_SSRC_SDES,
41   SIGNAL_ON_BYE_SSRC,
42   SIGNAL_ON_BYE_TIMEOUT,
43   SIGNAL_ON_TIMEOUT,
44   SIGNAL_ON_SENDER_TIMEOUT,
45   SIGNAL_ON_SENDING_RTCP,
46   SIGNAL_ON_FEEDBACK_RTCP,
47   LAST_SIGNAL
48 };
49
50 #define DEFAULT_INTERNAL_SOURCE      NULL
51 #define DEFAULT_BANDWIDTH            RTP_STATS_BANDWIDTH
52 #define DEFAULT_RTCP_FRACTION        (RTP_STATS_RTCP_FRACTION * RTP_STATS_BANDWIDTH)
53 #define DEFAULT_RTCP_RR_BANDWIDTH    -1
54 #define DEFAULT_RTCP_RS_BANDWIDTH    -1
55 #define DEFAULT_RTCP_MTU             1400
56 #define DEFAULT_SDES                 NULL
57 #define DEFAULT_NUM_SOURCES          0
58 #define DEFAULT_NUM_ACTIVE_SOURCES   0
59 #define DEFAULT_SOURCES              NULL
60 #define DEFAULT_RTCP_MIN_INTERVAL    (RTP_STATS_MIN_INTERVAL * GST_SECOND)
61 #define DEFAULT_RTCP_FEEDBACK_RETENTION_WINDOW (2 * GST_SECOND)
62
63 enum
64 {
65   PROP_0,
66   PROP_INTERNAL_SSRC,
67   PROP_INTERNAL_SOURCE,
68   PROP_BANDWIDTH,
69   PROP_RTCP_FRACTION,
70   PROP_RTCP_RR_BANDWIDTH,
71   PROP_RTCP_RS_BANDWIDTH,
72   PROP_RTCP_MTU,
73   PROP_SDES,
74   PROP_NUM_SOURCES,
75   PROP_NUM_ACTIVE_SOURCES,
76   PROP_SOURCES,
77   PROP_FAVOR_NEW,
78   PROP_RTCP_MIN_INTERVAL,
79   PROP_RTCP_FEEDBACK_RETENTION_WINDOW,
80   PROP_LAST
81 };
82
83 /* update average packet size */
84 #define INIT_AVG(avg, val) \
85    (avg) = (val);
86 #define UPDATE_AVG(avg, val)            \
87   if ((avg) == 0)                       \
88    (avg) = (val);                       \
89   else                                  \
90    (avg) = ((val) + (15 * (avg))) >> 4;
91
92
93 /* The number RTCP intervals after which to timeout entries in the
94  * collision table
95  */
96 #define RTCP_INTERVAL_COLLISION_TIMEOUT 10
97
98 /* GObject vmethods */
99 static void rtp_session_finalize (GObject * object);
100 static void rtp_session_set_property (GObject * object, guint prop_id,
101     const GValue * value, GParamSpec * pspec);
102 static void rtp_session_get_property (GObject * object, guint prop_id,
103     GValue * value, GParamSpec * pspec);
104
105 static gboolean rtp_session_on_sending_rtcp (RTPSession * sess,
106     GstBuffer * buffer, gboolean early);
107
108
109 static guint rtp_session_signals[LAST_SIGNAL] = { 0 };
110
111 G_DEFINE_TYPE (RTPSession, rtp_session, G_TYPE_OBJECT);
112
113 static RTPSource *obtain_source (RTPSession * sess, guint32 ssrc,
114     gboolean * created, RTPArrivalStats * arrival, gboolean rtp);
115 static GstFlowReturn rtp_session_schedule_bye_locked (RTPSession * sess,
116     const gchar * reason, GstClockTime current_time);
117 static GstClockTime calculate_rtcp_interval (RTPSession * sess,
118     gboolean deterministic, gboolean first);
119
120 static gboolean
121 accumulate_trues (GSignalInvocationHint * ihint, GValue * return_accu,
122     const GValue * handler_return, gpointer data)
123 {
124   if (g_value_get_boolean (handler_return))
125     g_value_set_boolean (return_accu, TRUE);
126
127   return TRUE;
128 }
129
130 static void
131 rtp_session_class_init (RTPSessionClass * klass)
132 {
133   GObjectClass *gobject_class;
134
135   gobject_class = (GObjectClass *) klass;
136
137   gobject_class->finalize = rtp_session_finalize;
138   gobject_class->set_property = rtp_session_set_property;
139   gobject_class->get_property = rtp_session_get_property;
140
141   /**
142    * RTPSession::get-source-by-ssrc:
143    * @session: the object which received the signal
144    * @ssrc: the SSRC of the RTPSource
145    *
146    * Request the #RTPSource object with SSRC @ssrc in @session.
147    */
148   rtp_session_signals[SIGNAL_GET_SOURCE_BY_SSRC] =
149       g_signal_new ("get-source-by-ssrc", G_TYPE_FROM_CLASS (klass),
150       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, G_STRUCT_OFFSET (RTPSessionClass,
151           get_source_by_ssrc), NULL, NULL, gst_rtp_bin_marshal_OBJECT__UINT,
152       RTP_TYPE_SOURCE, 1, G_TYPE_UINT);
153
154   /**
155    * RTPSession::on-new-ssrc:
156    * @session: the object which received the signal
157    * @src: the new RTPSource
158    *
159    * Notify of a new SSRC that entered @session.
160    */
161   rtp_session_signals[SIGNAL_ON_NEW_SSRC] =
162       g_signal_new ("on-new-ssrc", G_TYPE_FROM_CLASS (klass),
163       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_new_ssrc),
164       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
165       RTP_TYPE_SOURCE);
166   /**
167    * RTPSession::on-ssrc-collision:
168    * @session: the object which received the signal
169    * @src: the #RTPSource that caused a collision
170    *
171    * Notify when we have an SSRC collision
172    */
173   rtp_session_signals[SIGNAL_ON_SSRC_COLLISION] =
174       g_signal_new ("on-ssrc-collision", G_TYPE_FROM_CLASS (klass),
175       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_ssrc_collision),
176       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
177       RTP_TYPE_SOURCE);
178   /**
179    * RTPSession::on-ssrc-validated:
180    * @session: the object which received the signal
181    * @src: the new validated RTPSource
182    *
183    * Notify of a new SSRC that became validated.
184    */
185   rtp_session_signals[SIGNAL_ON_SSRC_VALIDATED] =
186       g_signal_new ("on-ssrc-validated", G_TYPE_FROM_CLASS (klass),
187       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_ssrc_validated),
188       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
189       RTP_TYPE_SOURCE);
190   /**
191    * RTPSession::on-ssrc-active:
192    * @session: the object which received the signal
193    * @src: the active RTPSource
194    *
195    * Notify of a SSRC that is active, i.e., sending RTCP.
196    */
197   rtp_session_signals[SIGNAL_ON_SSRC_ACTIVE] =
198       g_signal_new ("on-ssrc-active", G_TYPE_FROM_CLASS (klass),
199       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_ssrc_active),
200       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
201       RTP_TYPE_SOURCE);
202   /**
203    * RTPSession::on-ssrc-sdes:
204    * @session: the object which received the signal
205    * @src: the RTPSource
206    *
207    * Notify that a new SDES was received for SSRC.
208    */
209   rtp_session_signals[SIGNAL_ON_SSRC_SDES] =
210       g_signal_new ("on-ssrc-sdes", G_TYPE_FROM_CLASS (klass),
211       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_ssrc_sdes),
212       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
213       RTP_TYPE_SOURCE);
214   /**
215    * RTPSession::on-bye-ssrc:
216    * @session: the object which received the signal
217    * @src: the RTPSource that went away
218    *
219    * Notify of an SSRC that became inactive because of a BYE packet.
220    */
221   rtp_session_signals[SIGNAL_ON_BYE_SSRC] =
222       g_signal_new ("on-bye-ssrc", G_TYPE_FROM_CLASS (klass),
223       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_bye_ssrc),
224       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
225       RTP_TYPE_SOURCE);
226   /**
227    * RTPSession::on-bye-timeout:
228    * @session: the object which received the signal
229    * @src: the RTPSource that timed out
230    *
231    * Notify of an SSRC that has timed out because of BYE
232    */
233   rtp_session_signals[SIGNAL_ON_BYE_TIMEOUT] =
234       g_signal_new ("on-bye-timeout", G_TYPE_FROM_CLASS (klass),
235       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_bye_timeout),
236       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
237       RTP_TYPE_SOURCE);
238   /**
239    * RTPSession::on-timeout:
240    * @session: the object which received the signal
241    * @src: the RTPSource that timed out
242    *
243    * Notify of an SSRC that has timed out
244    */
245   rtp_session_signals[SIGNAL_ON_TIMEOUT] =
246       g_signal_new ("on-timeout", G_TYPE_FROM_CLASS (klass),
247       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_timeout),
248       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
249       RTP_TYPE_SOURCE);
250   /**
251    * RTPSession::on-sender-timeout:
252    * @session: the object which received the signal
253    * @src: the RTPSource that timed out
254    *
255    * Notify of an SSRC that was a sender but timed out and became a receiver.
256    */
257   rtp_session_signals[SIGNAL_ON_SENDER_TIMEOUT] =
258       g_signal_new ("on-sender-timeout", G_TYPE_FROM_CLASS (klass),
259       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_sender_timeout),
260       NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1,
261       RTP_TYPE_SOURCE);
262
263   /**
264    * RTPSession::on-sending-rtcp
265    * @session: the object which received the signal
266    * @buffer: the #GstBuffer containing the RTCP packet about to be sent
267    * @early: %TRUE if the packet is early, %FALSE if it is regular
268    *
269    * This signal is emitted before sending an RTCP packet, it can be used
270    * to add extra RTCP Packets.
271    *
272    * Returns: %TRUE if the RTCP buffer should NOT be suppressed, %FALSE
273    * if suppressing it is acceptable
274    */
275   rtp_session_signals[SIGNAL_ON_SENDING_RTCP] =
276       g_signal_new ("on-sending-rtcp", G_TYPE_FROM_CLASS (klass),
277       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_sending_rtcp),
278       accumulate_trues, NULL, gst_rtp_bin_marshal_BOOLEAN__POINTER_BOOLEAN,
279       G_TYPE_BOOLEAN, 2, G_TYPE_POINTER, G_TYPE_BOOLEAN);
280
281   /**
282    * RTPSession::on-feedback-rtcp:
283    * @session: the object which received the signal
284    * @type: Type of RTCP packet, will be %GST_RTCP_TYPE_RTPFB or
285    *  %GST_RTCP_TYPE_RTPFB
286    * @fbtype: The type of RTCP FB packet, probably part of #GstRTCPFBType
287    * @sender_ssrc: The SSRC of the sender
288    * @media_ssrc: The SSRC of the media this refers to
289    * @fci: a #GstBuffer with the FCI data from the FB packet or %NULL if
290    * there was no FCI
291    *
292    * Notify that a RTCP feedback packet has been received
293    */
294
295   rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP] =
296       g_signal_new ("on-feedback-rtcp", G_TYPE_FROM_CLASS (klass),
297       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (RTPSessionClass, on_feedback_rtcp),
298       NULL, NULL, gst_rtp_bin_marshal_VOID__UINT_UINT_UINT_UINT_POINTER,
299       G_TYPE_NONE, 4, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT,
300       G_TYPE_POINTER);
301
302   g_object_class_install_property (gobject_class, PROP_INTERNAL_SSRC,
303       g_param_spec_uint ("internal-ssrc", "Internal SSRC",
304           "The internal SSRC used for the session",
305           0, G_MAXUINT, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
306
307   g_object_class_install_property (gobject_class, PROP_INTERNAL_SOURCE,
308       g_param_spec_object ("internal-source", "Internal Source",
309           "The internal source element of the session",
310           RTP_TYPE_SOURCE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
311
312   g_object_class_install_property (gobject_class, PROP_BANDWIDTH,
313       g_param_spec_double ("bandwidth", "Bandwidth",
314           "The bandwidth of the session (0 for auto-discover)",
315           0.0, G_MAXDOUBLE, DEFAULT_BANDWIDTH,
316           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
317
318   g_object_class_install_property (gobject_class, PROP_RTCP_FRACTION,
319       g_param_spec_double ("rtcp-fraction", "RTCP Fraction",
320           "The fraction of the bandwidth used for RTCP (or as a real fraction of the RTP bandwidth if < 1)",
321           0.0, G_MAXDOUBLE, DEFAULT_RTCP_FRACTION,
322           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
323
324   g_object_class_install_property (gobject_class, PROP_RTCP_RR_BANDWIDTH,
325       g_param_spec_int ("rtcp-rr-bandwidth", "RTCP RR bandwidth",
326           "The RTCP bandwidth used for receivers in bytes per second (-1 = default)",
327           -1, G_MAXINT, DEFAULT_RTCP_RR_BANDWIDTH,
328           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
329
330   g_object_class_install_property (gobject_class, PROP_RTCP_RS_BANDWIDTH,
331       g_param_spec_int ("rtcp-rs-bandwidth", "RTCP RS bandwidth",
332           "The RTCP bandwidth used for senders in bytes per second (-1 = default)",
333           -1, G_MAXINT, DEFAULT_RTCP_RS_BANDWIDTH,
334           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
335
336   g_object_class_install_property (gobject_class, PROP_RTCP_MTU,
337       g_param_spec_uint ("rtcp-mtu", "RTCP MTU",
338           "The maximum size of the RTCP packets",
339           16, G_MAXINT16, DEFAULT_RTCP_MTU,
340           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
341
342   g_object_class_install_property (gobject_class, PROP_SDES,
343       g_param_spec_boxed ("sdes", "SDES",
344           "The SDES items of this session",
345           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
346
347   g_object_class_install_property (gobject_class, PROP_NUM_SOURCES,
348       g_param_spec_uint ("num-sources", "Num Sources",
349           "The number of sources in the session", 0, G_MAXUINT,
350           DEFAULT_NUM_SOURCES, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
351
352   g_object_class_install_property (gobject_class, PROP_NUM_ACTIVE_SOURCES,
353       g_param_spec_uint ("num-active-sources", "Num Active Sources",
354           "The number of active sources in the session", 0, G_MAXUINT,
355           DEFAULT_NUM_ACTIVE_SOURCES,
356           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
357   /**
358    * RTPSource::sources
359    *
360    * Get a GValue Array of all sources in the session.
361    *
362    * <example>
363    * <title>Getting the #RTPSources of a session
364    * <programlisting>
365    * {
366    *   GValueArray *arr;
367    *   GValue *val;
368    *   guint i;
369    *
370    *   g_object_get (sess, "sources", &arr, NULL);
371    *
372    *   for (i = 0; i < arr->n_values; i++) {
373    *     RTPSource *source;
374    *
375    *     val = g_value_array_get_nth (arr, i);
376    *     source = g_value_get_object (val);
377    *   }
378    *   g_value_array_free (arr);
379    * }
380    * </programlisting>
381    * </example>
382    */
383   g_object_class_install_property (gobject_class, PROP_SOURCES,
384       g_param_spec_boxed ("sources", "Sources",
385           "An array of all known sources in the session",
386           G_TYPE_VALUE_ARRAY, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
387
388   g_object_class_install_property (gobject_class, PROP_FAVOR_NEW,
389       g_param_spec_boolean ("favor-new", "Favor new sources",
390           "Resolve SSRC conflict in favor of new sources", FALSE,
391           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
392
393   g_object_class_install_property (gobject_class, PROP_RTCP_MIN_INTERVAL,
394       g_param_spec_uint64 ("rtcp-min-interval", "Minimum RTCP interval",
395           "Minimum interval between Regular RTCP packet (in ns)",
396           0, G_MAXUINT64, DEFAULT_RTCP_MIN_INTERVAL,
397           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
398
399   g_object_class_install_property (gobject_class,
400       PROP_RTCP_FEEDBACK_RETENTION_WINDOW,
401       g_param_spec_uint64 ("rtcp-feedback-retention-window",
402           "RTCP Feedback retention window",
403           "Duration during which RTCP Feedback packets are retained (in ns)",
404           0, G_MAXUINT64, DEFAULT_RTCP_FEEDBACK_RETENTION_WINDOW,
405           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
406
407
408   klass->get_source_by_ssrc =
409       GST_DEBUG_FUNCPTR (rtp_session_get_source_by_ssrc);
410   klass->on_sending_rtcp = GST_DEBUG_FUNCPTR (rtp_session_on_sending_rtcp);
411
412   GST_DEBUG_CATEGORY_INIT (rtp_session_debug, "rtpsession", 0, "RTP Session");
413 }
414
415 static void
416 rtp_session_init (RTPSession * sess)
417 {
418   gint i;
419   gchar *str;
420
421   sess->lock = g_mutex_new ();
422   sess->key = g_random_int ();
423   sess->mask_idx = 0;
424   sess->mask = 0;
425
426   for (i = 0; i < 32; i++) {
427     sess->ssrcs[i] =
428         g_hash_table_new_full (NULL, NULL, NULL,
429         (GDestroyNotify) g_object_unref);
430   }
431   sess->cnames = g_hash_table_new_full (NULL, NULL, g_free, NULL);
432
433   rtp_stats_init_defaults (&sess->stats);
434
435   sess->recalc_bandwidth = TRUE;
436   sess->bandwidth = DEFAULT_BANDWIDTH;
437   sess->rtcp_bandwidth = DEFAULT_RTCP_FRACTION;
438   sess->rtcp_rr_bandwidth = DEFAULT_RTCP_RR_BANDWIDTH;
439   sess->rtcp_rs_bandwidth = DEFAULT_RTCP_RS_BANDWIDTH;
440
441   /* create an active SSRC for this session manager */
442   sess->source = rtp_session_create_source (sess);
443   sess->source->validated = TRUE;
444   sess->source->internal = TRUE;
445   sess->stats.active_sources++;
446   INIT_AVG (sess->stats.avg_rtcp_packet_size, 100);
447
448   /* default UDP header length */
449   sess->header_len = 28;
450   sess->mtu = DEFAULT_RTCP_MTU;
451
452   /* some default SDES entries */
453   str = g_strdup_printf ("%s@%s", g_get_user_name (), g_get_host_name ());
454   rtp_source_set_sdes_string (sess->source, GST_RTCP_SDES_CNAME, str);
455   g_free (str);
456
457   rtp_source_set_sdes_string (sess->source, GST_RTCP_SDES_NAME,
458       g_get_real_name ());
459   rtp_source_set_sdes_string (sess->source, GST_RTCP_SDES_TOOL, "GStreamer");
460
461   sess->first_rtcp = TRUE;
462   sess->allow_early = TRUE;
463   sess->rtcp_feedback_retention_window = DEFAULT_RTCP_FEEDBACK_RETENTION_WINDOW;
464
465   sess->rtcp_pli_requests = g_array_new (FALSE, FALSE, sizeof (guint32));
466
467   GST_DEBUG ("%p: session using SSRC: %08x", sess, sess->source->ssrc);
468 }
469
470 static void
471 rtp_session_finalize (GObject * object)
472 {
473   RTPSession *sess;
474   gint i;
475
476   sess = RTP_SESSION_CAST (object);
477
478   g_mutex_free (sess->lock);
479   for (i = 0; i < 32; i++)
480     g_hash_table_destroy (sess->ssrcs[i]);
481
482   g_free (sess->bye_reason);
483
484   g_hash_table_destroy (sess->cnames);
485   g_object_unref (sess->source);
486
487   g_array_free (sess->rtcp_pli_requests, TRUE);
488
489   G_OBJECT_CLASS (rtp_session_parent_class)->finalize (object);
490 }
491
492 static void
493 copy_source (gpointer key, RTPSource * source, GValueArray * arr)
494 {
495   GValue value = { 0 };
496
497   g_value_init (&value, RTP_TYPE_SOURCE);
498   g_value_take_object (&value, source);
499   /* copies the value */
500   g_value_array_append (arr, &value);
501 }
502
503 static GValueArray *
504 rtp_session_create_sources (RTPSession * sess)
505 {
506   GValueArray *res;
507   guint size;
508
509   RTP_SESSION_LOCK (sess);
510   /* get number of elements in the table */
511   size = g_hash_table_size (sess->ssrcs[sess->mask_idx]);
512   /* create the result value array */
513   res = g_value_array_new (size);
514
515   /* and copy all values into the array */
516   g_hash_table_foreach (sess->ssrcs[sess->mask_idx], (GHFunc) copy_source, res);
517   RTP_SESSION_UNLOCK (sess);
518
519   return res;
520 }
521
522 static void
523 rtp_session_set_property (GObject * object, guint prop_id,
524     const GValue * value, GParamSpec * pspec)
525 {
526   RTPSession *sess;
527
528   sess = RTP_SESSION (object);
529
530   switch (prop_id) {
531     case PROP_INTERNAL_SSRC:
532       rtp_session_set_internal_ssrc (sess, g_value_get_uint (value));
533       break;
534     case PROP_BANDWIDTH:
535       sess->bandwidth = g_value_get_double (value);
536       sess->recalc_bandwidth = TRUE;
537       break;
538     case PROP_RTCP_FRACTION:
539       sess->rtcp_bandwidth = g_value_get_double (value);
540       sess->recalc_bandwidth = TRUE;
541       break;
542     case PROP_RTCP_RR_BANDWIDTH:
543       sess->rtcp_rr_bandwidth = g_value_get_int (value);
544       sess->recalc_bandwidth = TRUE;
545       break;
546     case PROP_RTCP_RS_BANDWIDTH:
547       sess->rtcp_rs_bandwidth = g_value_get_int (value);
548       sess->recalc_bandwidth = TRUE;
549       break;
550     case PROP_RTCP_MTU:
551       sess->mtu = g_value_get_uint (value);
552       break;
553     case PROP_SDES:
554       rtp_session_set_sdes_struct (sess, g_value_get_boxed (value));
555       break;
556     case PROP_FAVOR_NEW:
557       sess->favor_new = g_value_get_boolean (value);
558       break;
559     case PROP_RTCP_MIN_INTERVAL:
560       rtp_stats_set_min_interval (&sess->stats,
561           (gdouble) g_value_get_uint64 (value) / GST_SECOND);
562       break;
563     default:
564       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
565       break;
566   }
567 }
568
569 static void
570 rtp_session_get_property (GObject * object, guint prop_id,
571     GValue * value, GParamSpec * pspec)
572 {
573   RTPSession *sess;
574
575   sess = RTP_SESSION (object);
576
577   switch (prop_id) {
578     case PROP_INTERNAL_SSRC:
579       g_value_set_uint (value, rtp_session_get_internal_ssrc (sess));
580       break;
581     case PROP_INTERNAL_SOURCE:
582       g_value_take_object (value, rtp_session_get_internal_source (sess));
583       break;
584     case PROP_BANDWIDTH:
585       g_value_set_double (value, sess->bandwidth);
586       break;
587     case PROP_RTCP_FRACTION:
588       g_value_set_double (value, sess->rtcp_bandwidth);
589       break;
590     case PROP_RTCP_RR_BANDWIDTH:
591       g_value_set_int (value, sess->rtcp_rr_bandwidth);
592       break;
593     case PROP_RTCP_RS_BANDWIDTH:
594       g_value_set_int (value, sess->rtcp_rs_bandwidth);
595       break;
596     case PROP_RTCP_MTU:
597       g_value_set_uint (value, sess->mtu);
598       break;
599     case PROP_SDES:
600       g_value_take_boxed (value, rtp_session_get_sdes_struct (sess));
601       break;
602     case PROP_NUM_SOURCES:
603       g_value_set_uint (value, rtp_session_get_num_sources (sess));
604       break;
605     case PROP_NUM_ACTIVE_SOURCES:
606       g_value_set_uint (value, rtp_session_get_num_active_sources (sess));
607       break;
608     case PROP_SOURCES:
609       g_value_take_boxed (value, rtp_session_create_sources (sess));
610       break;
611     case PROP_FAVOR_NEW:
612       g_value_set_boolean (value, sess->favor_new);
613       break;
614     case PROP_RTCP_MIN_INTERVAL:
615       g_value_set_uint64 (value, sess->stats.min_interval * GST_SECOND);
616       break;
617     default:
618       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
619       break;
620   }
621 }
622
623 static void
624 on_new_ssrc (RTPSession * sess, RTPSource * source)
625 {
626   g_object_ref (source);
627   RTP_SESSION_UNLOCK (sess);
628   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_NEW_SSRC], 0, source);
629   RTP_SESSION_LOCK (sess);
630   g_object_unref (source);
631 }
632
633 static void
634 on_ssrc_collision (RTPSession * sess, RTPSource * source)
635 {
636   g_object_ref (source);
637   RTP_SESSION_UNLOCK (sess);
638   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SSRC_COLLISION], 0,
639       source);
640   RTP_SESSION_LOCK (sess);
641   g_object_unref (source);
642 }
643
644 static void
645 on_ssrc_validated (RTPSession * sess, RTPSource * source)
646 {
647   g_object_ref (source);
648   RTP_SESSION_UNLOCK (sess);
649   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SSRC_VALIDATED], 0,
650       source);
651   RTP_SESSION_LOCK (sess);
652   g_object_unref (source);
653 }
654
655 static void
656 on_ssrc_active (RTPSession * sess, RTPSource * source)
657 {
658   g_object_ref (source);
659   RTP_SESSION_UNLOCK (sess);
660   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SSRC_ACTIVE], 0, source);
661   RTP_SESSION_LOCK (sess);
662   g_object_unref (source);
663 }
664
665 static void
666 on_ssrc_sdes (RTPSession * sess, RTPSource * source)
667 {
668   g_object_ref (source);
669   GST_DEBUG ("SDES changed for SSRC %08x", source->ssrc);
670   RTP_SESSION_UNLOCK (sess);
671   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SSRC_SDES], 0, source);
672   RTP_SESSION_LOCK (sess);
673   g_object_unref (source);
674 }
675
676 static void
677 on_bye_ssrc (RTPSession * sess, RTPSource * source)
678 {
679   g_object_ref (source);
680   RTP_SESSION_UNLOCK (sess);
681   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_BYE_SSRC], 0, source);
682   RTP_SESSION_LOCK (sess);
683   g_object_unref (source);
684 }
685
686 static void
687 on_bye_timeout (RTPSession * sess, RTPSource * source)
688 {
689   g_object_ref (source);
690   RTP_SESSION_UNLOCK (sess);
691   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_BYE_TIMEOUT], 0, source);
692   RTP_SESSION_LOCK (sess);
693   g_object_unref (source);
694 }
695
696 static void
697 on_timeout (RTPSession * sess, RTPSource * source)
698 {
699   g_object_ref (source);
700   RTP_SESSION_UNLOCK (sess);
701   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_TIMEOUT], 0, source);
702   RTP_SESSION_LOCK (sess);
703   g_object_unref (source);
704 }
705
706 static void
707 on_sender_timeout (RTPSession * sess, RTPSource * source)
708 {
709   g_object_ref (source);
710   RTP_SESSION_UNLOCK (sess);
711   g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SENDER_TIMEOUT], 0,
712       source);
713   RTP_SESSION_LOCK (sess);
714   g_object_unref (source);
715 }
716
717 /**
718  * rtp_session_new:
719  *
720  * Create a new session object.
721  *
722  * Returns: a new #RTPSession. g_object_unref() after usage.
723  */
724 RTPSession *
725 rtp_session_new (void)
726 {
727   RTPSession *sess;
728
729   sess = g_object_new (RTP_TYPE_SESSION, NULL);
730
731   return sess;
732 }
733
734 /**
735  * rtp_session_set_callbacks:
736  * @sess: an #RTPSession
737  * @callbacks: callbacks to configure
738  * @user_data: user data passed in the callbacks
739  *
740  * Configure a set of callbacks to be notified of actions.
741  */
742 void
743 rtp_session_set_callbacks (RTPSession * sess, RTPSessionCallbacks * callbacks,
744     gpointer user_data)
745 {
746   g_return_if_fail (RTP_IS_SESSION (sess));
747
748   if (callbacks->process_rtp) {
749     sess->callbacks.process_rtp = callbacks->process_rtp;
750     sess->process_rtp_user_data = user_data;
751   }
752   if (callbacks->send_rtp) {
753     sess->callbacks.send_rtp = callbacks->send_rtp;
754     sess->send_rtp_user_data = user_data;
755   }
756   if (callbacks->send_rtcp) {
757     sess->callbacks.send_rtcp = callbacks->send_rtcp;
758     sess->send_rtcp_user_data = user_data;
759   }
760   if (callbacks->sync_rtcp) {
761     sess->callbacks.sync_rtcp = callbacks->sync_rtcp;
762     sess->sync_rtcp_user_data = user_data;
763   }
764   if (callbacks->clock_rate) {
765     sess->callbacks.clock_rate = callbacks->clock_rate;
766     sess->clock_rate_user_data = user_data;
767   }
768   if (callbacks->reconsider) {
769     sess->callbacks.reconsider = callbacks->reconsider;
770     sess->reconsider_user_data = user_data;
771   }
772   if (callbacks->request_key_unit) {
773     sess->callbacks.request_key_unit = callbacks->request_key_unit;
774     sess->request_key_unit_user_data = user_data;
775   }
776 }
777
778 /**
779  * rtp_session_set_process_rtp_callback:
780  * @sess: an #RTPSession
781  * @callback: callback to set
782  * @user_data: user data passed in the callback
783  *
784  * Configure only the process_rtp callback to be notified of the process_rtp action.
785  */
786 void
787 rtp_session_set_process_rtp_callback (RTPSession * sess,
788     RTPSessionProcessRTP callback, gpointer user_data)
789 {
790   g_return_if_fail (RTP_IS_SESSION (sess));
791
792   sess->callbacks.process_rtp = callback;
793   sess->process_rtp_user_data = user_data;
794 }
795
796 /**
797  * rtp_session_set_send_rtp_callback:
798  * @sess: an #RTPSession
799  * @callback: callback to set
800  * @user_data: user data passed in the callback
801  *
802  * Configure only the send_rtp callback to be notified of the send_rtp action.
803  */
804 void
805 rtp_session_set_send_rtp_callback (RTPSession * sess,
806     RTPSessionSendRTP callback, gpointer user_data)
807 {
808   g_return_if_fail (RTP_IS_SESSION (sess));
809
810   sess->callbacks.send_rtp = callback;
811   sess->send_rtp_user_data = user_data;
812 }
813
814 /**
815  * rtp_session_set_send_rtcp_callback:
816  * @sess: an #RTPSession
817  * @callback: callback to set
818  * @user_data: user data passed in the callback
819  *
820  * Configure only the send_rtcp callback to be notified of the send_rtcp action.
821  */
822 void
823 rtp_session_set_send_rtcp_callback (RTPSession * sess,
824     RTPSessionSendRTCP callback, gpointer user_data)
825 {
826   g_return_if_fail (RTP_IS_SESSION (sess));
827
828   sess->callbacks.send_rtcp = callback;
829   sess->send_rtcp_user_data = user_data;
830 }
831
832 /**
833  * rtp_session_set_sync_rtcp_callback:
834  * @sess: an #RTPSession
835  * @callback: callback to set
836  * @user_data: user data passed in the callback
837  *
838  * Configure only the sync_rtcp callback to be notified of the sync_rtcp action.
839  */
840 void
841 rtp_session_set_sync_rtcp_callback (RTPSession * sess,
842     RTPSessionSyncRTCP callback, gpointer user_data)
843 {
844   g_return_if_fail (RTP_IS_SESSION (sess));
845
846   sess->callbacks.sync_rtcp = callback;
847   sess->sync_rtcp_user_data = user_data;
848 }
849
850 /**
851  * rtp_session_set_clock_rate_callback:
852  * @sess: an #RTPSession
853  * @callback: callback to set
854  * @user_data: user data passed in the callback
855  *
856  * Configure only the clock_rate callback to be notified of the clock_rate action.
857  */
858 void
859 rtp_session_set_clock_rate_callback (RTPSession * sess,
860     RTPSessionClockRate callback, gpointer user_data)
861 {
862   g_return_if_fail (RTP_IS_SESSION (sess));
863
864   sess->callbacks.clock_rate = callback;
865   sess->clock_rate_user_data = user_data;
866 }
867
868 /**
869  * rtp_session_set_reconsider_callback:
870  * @sess: an #RTPSession
871  * @callback: callback to set
872  * @user_data: user data passed in the callback
873  *
874  * Configure only the reconsider callback to be notified of the reconsider action.
875  */
876 void
877 rtp_session_set_reconsider_callback (RTPSession * sess,
878     RTPSessionReconsider callback, gpointer user_data)
879 {
880   g_return_if_fail (RTP_IS_SESSION (sess));
881
882   sess->callbacks.reconsider = callback;
883   sess->reconsider_user_data = user_data;
884 }
885
886 /**
887  * rtp_session_set_bandwidth:
888  * @sess: an #RTPSession
889  * @bandwidth: the bandwidth allocated
890  *
891  * Set the session bandwidth in bytes per second.
892  */
893 void
894 rtp_session_set_bandwidth (RTPSession * sess, gdouble bandwidth)
895 {
896   g_return_if_fail (RTP_IS_SESSION (sess));
897
898   RTP_SESSION_LOCK (sess);
899   sess->stats.bandwidth = bandwidth;
900   RTP_SESSION_UNLOCK (sess);
901 }
902
903 /**
904  * rtp_session_get_bandwidth:
905  * @sess: an #RTPSession
906  *
907  * Get the session bandwidth.
908  *
909  * Returns: the session bandwidth.
910  */
911 gdouble
912 rtp_session_get_bandwidth (RTPSession * sess)
913 {
914   gdouble result;
915
916   g_return_val_if_fail (RTP_IS_SESSION (sess), 0);
917
918   RTP_SESSION_LOCK (sess);
919   result = sess->stats.bandwidth;
920   RTP_SESSION_UNLOCK (sess);
921
922   return result;
923 }
924
925 /**
926  * rtp_session_set_rtcp_fraction:
927  * @sess: an #RTPSession
928  * @bandwidth: the RTCP bandwidth
929  *
930  * Set the bandwidth in bytes per second that should be used for RTCP
931  * messages.
932  */
933 void
934 rtp_session_set_rtcp_fraction (RTPSession * sess, gdouble bandwidth)
935 {
936   g_return_if_fail (RTP_IS_SESSION (sess));
937
938   RTP_SESSION_LOCK (sess);
939   sess->stats.rtcp_bandwidth = bandwidth;
940   RTP_SESSION_UNLOCK (sess);
941 }
942
943 /**
944  * rtp_session_get_rtcp_fraction:
945  * @sess: an #RTPSession
946  *
947  * Get the session bandwidth used for RTCP.
948  *
949  * Returns: The bandwidth used for RTCP messages.
950  */
951 gdouble
952 rtp_session_get_rtcp_fraction (RTPSession * sess)
953 {
954   gdouble result;
955
956   g_return_val_if_fail (RTP_IS_SESSION (sess), 0.0);
957
958   RTP_SESSION_LOCK (sess);
959   result = sess->stats.rtcp_bandwidth;
960   RTP_SESSION_UNLOCK (sess);
961
962   return result;
963 }
964
965 /**
966  * rtp_session_set_sdes_string:
967  * @sess: an #RTPSession
968  * @type: the type of the SDES item
969  * @item: a null-terminated string to set.
970  *
971  * Store an SDES item of @type in @sess.
972  *
973  * Returns: %FALSE if the data was unchanged @type is invalid.
974  */
975 gboolean
976 rtp_session_set_sdes_string (RTPSession * sess, GstRTCPSDESType type,
977     const gchar * item)
978 {
979   gboolean result;
980
981   g_return_val_if_fail (RTP_IS_SESSION (sess), FALSE);
982
983   RTP_SESSION_LOCK (sess);
984   result = rtp_source_set_sdes_string (sess->source, type, item);
985   RTP_SESSION_UNLOCK (sess);
986
987   return result;
988 }
989
990 /**
991  * rtp_session_get_sdes_string:
992  * @sess: an #RTPSession
993  * @type: the type of the SDES item
994  *
995  * Get the SDES item of @type from @sess.
996  *
997  * Returns: a null-terminated copy of the SDES item or NULL when @type was not
998  * valid. g_free() after usage.
999  */
1000 gchar *
1001 rtp_session_get_sdes_string (RTPSession * sess, GstRTCPSDESType type)
1002 {
1003   gchar *result;
1004
1005   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1006
1007   RTP_SESSION_LOCK (sess);
1008   result = rtp_source_get_sdes_string (sess->source, type);
1009   RTP_SESSION_UNLOCK (sess);
1010
1011   return result;
1012 }
1013
1014 /**
1015  * rtp_session_get_sdes_struct:
1016  * @sess: an #RTSPSession
1017  *
1018  * Get the SDES data as a #GstStructure
1019  *
1020  * Returns: a GstStructure with SDES items for @sess. This function returns a
1021  * copy of the SDES structure, use gst_structure_free() after usage.
1022  */
1023 GstStructure *
1024 rtp_session_get_sdes_struct (RTPSession * sess)
1025 {
1026   const GstStructure *sdes;
1027   GstStructure *result = NULL;
1028
1029   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1030
1031   RTP_SESSION_LOCK (sess);
1032   sdes = rtp_source_get_sdes_struct (sess->source);
1033   if (sdes)
1034     result = gst_structure_copy (sdes);
1035   RTP_SESSION_UNLOCK (sess);
1036
1037   return result;
1038 }
1039
1040 /**
1041  * rtp_session_set_sdes_struct:
1042  * @sess: an #RTSPSession
1043  * @sdes: a #GstStructure
1044  *
1045  * Set the SDES data as a #GstStructure. This function makes a copy of @sdes.
1046  */
1047 void
1048 rtp_session_set_sdes_struct (RTPSession * sess, const GstStructure * sdes)
1049 {
1050   g_return_if_fail (sdes);
1051   g_return_if_fail (RTP_IS_SESSION (sess));
1052
1053   RTP_SESSION_LOCK (sess);
1054   rtp_source_set_sdes_struct (sess->source, gst_structure_copy (sdes));
1055   RTP_SESSION_UNLOCK (sess);
1056 }
1057
1058 static GstFlowReturn
1059 source_push_rtp (RTPSource * source, gpointer data, RTPSession * session)
1060 {
1061   GstFlowReturn result = GST_FLOW_OK;
1062
1063   if (source == session->source) {
1064     GST_LOG ("source %08x pushed sender RTP packet", source->ssrc);
1065
1066     RTP_SESSION_UNLOCK (session);
1067
1068     if (session->callbacks.send_rtp)
1069       result =
1070           session->callbacks.send_rtp (session, source, data,
1071           session->send_rtp_user_data);
1072     else {
1073       gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
1074     }
1075   } else {
1076     GST_LOG ("source %08x pushed receiver RTP packet", source->ssrc);
1077     RTP_SESSION_UNLOCK (session);
1078
1079     if (session->callbacks.process_rtp)
1080       result =
1081           session->callbacks.process_rtp (session, source,
1082           GST_BUFFER_CAST (data), session->process_rtp_user_data);
1083     else
1084       gst_buffer_unref (GST_BUFFER_CAST (data));
1085   }
1086   RTP_SESSION_LOCK (session);
1087
1088   return result;
1089 }
1090
1091 static gint
1092 source_clock_rate (RTPSource * source, guint8 pt, RTPSession * session)
1093 {
1094   gint result;
1095
1096   RTP_SESSION_UNLOCK (session);
1097
1098   if (session->callbacks.clock_rate)
1099     result =
1100         session->callbacks.clock_rate (session, pt,
1101         session->clock_rate_user_data);
1102   else
1103     result = -1;
1104
1105   RTP_SESSION_LOCK (session);
1106
1107   GST_DEBUG ("got clock-rate %d for pt %d", result, pt);
1108
1109   return result;
1110 }
1111
1112 static RTPSourceCallbacks callbacks = {
1113   (RTPSourcePushRTP) source_push_rtp,
1114   (RTPSourceClockRate) source_clock_rate,
1115 };
1116
1117 static gboolean
1118 check_collision (RTPSession * sess, RTPSource * source,
1119     RTPArrivalStats * arrival, gboolean rtp)
1120 {
1121   /* If we have no arrival address, we can't do collision checking */
1122   if (!arrival->have_address)
1123     return FALSE;
1124
1125   if (sess->source != source) {
1126     GstNetAddress *from;
1127     gboolean have_from;
1128
1129     /* This is not our local source, but lets check if two remote
1130      * source collide
1131      */
1132
1133     if (rtp) {
1134       from = &source->rtp_from;
1135       have_from = source->have_rtp_from;
1136     } else {
1137       from = &source->rtcp_from;
1138       have_from = source->have_rtcp_from;
1139     }
1140
1141     if (have_from) {
1142       if (gst_netaddress_equal (from, &arrival->address)) {
1143         /* Address is the same */
1144         return FALSE;
1145       } else {
1146         GST_LOG ("we have a third-party collision or loop ssrc:%x",
1147             rtp_source_get_ssrc (source));
1148         if (sess->favor_new) {
1149           if (rtp_source_find_conflicting_address (source,
1150                   &arrival->address, arrival->current_time)) {
1151             gchar buf1[40];
1152             gst_netaddress_to_string (&arrival->address, buf1, 40);
1153             GST_LOG ("Known conflict on %x for %s, dropping packet",
1154                 rtp_source_get_ssrc (source), buf1);
1155             return TRUE;
1156           } else {
1157             gchar buf1[40], buf2[40];
1158
1159             /* Current address is not a known conflict, lets assume this is
1160              * a new source. Save old address in possible conflict list
1161              */
1162             rtp_source_add_conflicting_address (source, from,
1163                 arrival->current_time);
1164
1165             gst_netaddress_to_string (from, buf1, 40);
1166             gst_netaddress_to_string (&arrival->address, buf2, 40);
1167             GST_DEBUG ("New conflict for ssrc %x, replacing %s with %s,"
1168                 " saving old as known conflict",
1169                 rtp_source_get_ssrc (source), buf1, buf2);
1170
1171             if (rtp)
1172               rtp_source_set_rtp_from (source, &arrival->address);
1173             else
1174               rtp_source_set_rtcp_from (source, &arrival->address);
1175             return FALSE;
1176           }
1177         } else {
1178           /* Don't need to save old addresses, we ignore new sources */
1179           return TRUE;
1180         }
1181       }
1182     } else {
1183       /* We don't already have a from address for RTP, just set it */
1184       if (rtp)
1185         rtp_source_set_rtp_from (source, &arrival->address);
1186       else
1187         rtp_source_set_rtcp_from (source, &arrival->address);
1188       return FALSE;
1189     }
1190
1191     /* FIXME: Log 3rd party collision somehow
1192      * Maybe should be done in upper layer, only the SDES can tell us
1193      * if its a collision or a loop
1194      */
1195
1196     /* If the source has been inactive for some time, we assume that it has
1197      * simply changed its transport source address. Hence, there is no true
1198      * third-party collision - only a simulated one. */
1199     if (arrival->current_time > source->last_activity) {
1200       GstClockTime inactivity_period =
1201           arrival->current_time - source->last_activity;
1202       if (inactivity_period > 1 * GST_SECOND) {
1203         /* Use new network address */
1204         if (rtp) {
1205           g_assert (source->have_rtp_from);
1206           rtp_source_set_rtp_from (source, &arrival->address);
1207         } else {
1208           g_assert (source->have_rtcp_from);
1209           rtp_source_set_rtcp_from (source, &arrival->address);
1210         }
1211         return FALSE;
1212       }
1213     }
1214   } else {
1215     /* This is sending with our ssrc, is it an address we already know */
1216
1217     if (rtp_source_find_conflicting_address (source, &arrival->address,
1218             arrival->current_time)) {
1219       /* Its a known conflict, its probably a loop, not a collision
1220        * lets just drop the incoming packet
1221        */
1222       GST_DEBUG ("Our packets are being looped back to us, dropping");
1223     } else {
1224       /* Its a new collision, lets change our SSRC */
1225
1226       rtp_source_add_conflicting_address (source, &arrival->address,
1227           arrival->current_time);
1228
1229       GST_DEBUG ("Collision for SSRC %x", rtp_source_get_ssrc (source));
1230       on_ssrc_collision (sess, source);
1231
1232       rtp_session_schedule_bye_locked (sess, "SSRC Collision",
1233           arrival->current_time);
1234
1235       sess->change_ssrc = TRUE;
1236     }
1237   }
1238
1239   return TRUE;
1240 }
1241
1242
1243 /* must be called with the session lock, the returned source needs to be
1244  * unreffed after usage. */
1245 static RTPSource *
1246 obtain_source (RTPSession * sess, guint32 ssrc, gboolean * created,
1247     RTPArrivalStats * arrival, gboolean rtp)
1248 {
1249   RTPSource *source;
1250
1251   source =
1252       g_hash_table_lookup (sess->ssrcs[sess->mask_idx], GINT_TO_POINTER (ssrc));
1253   if (source == NULL) {
1254     /* make new Source in probation and insert */
1255     source = rtp_source_new (ssrc);
1256
1257     /* for RTP packets we need to set the source in probation. Receiving RTCP
1258      * packets of an SSRC, on the other hand, is a strong indication that we
1259      * are dealing with a valid source. */
1260     if (rtp)
1261       source->probation = RTP_DEFAULT_PROBATION;
1262     else
1263       source->probation = 0;
1264
1265     /* store from address, if any */
1266     if (arrival->have_address) {
1267       if (rtp)
1268         rtp_source_set_rtp_from (source, &arrival->address);
1269       else
1270         rtp_source_set_rtcp_from (source, &arrival->address);
1271     }
1272
1273     /* configure a callback on the source */
1274     rtp_source_set_callbacks (source, &callbacks, sess);
1275
1276     g_hash_table_insert (sess->ssrcs[sess->mask_idx], GINT_TO_POINTER (ssrc),
1277         source);
1278
1279     /* we have one more source now */
1280     sess->total_sources++;
1281     *created = TRUE;
1282   } else {
1283     *created = FALSE;
1284     /* check for collision, this updates the address when not previously set */
1285     if (check_collision (sess, source, arrival, rtp)) {
1286       return NULL;
1287     }
1288   }
1289   /* update last activity */
1290   source->last_activity = arrival->current_time;
1291   if (rtp)
1292     source->last_rtp_activity = arrival->current_time;
1293   g_object_ref (source);
1294
1295   return source;
1296 }
1297
1298 /**
1299  * rtp_session_get_internal_source:
1300  * @sess: a #RTPSession
1301  *
1302  * Get the internal #RTPSource of @sess.
1303  *
1304  * Returns: The internal #RTPSource. g_object_unref() after usage.
1305  */
1306 RTPSource *
1307 rtp_session_get_internal_source (RTPSession * sess)
1308 {
1309   RTPSource *result;
1310
1311   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1312
1313   result = g_object_ref (sess->source);
1314
1315   return result;
1316 }
1317
1318 /**
1319  * rtp_session_set_internal_ssrc:
1320  * @sess: a #RTPSession
1321  * @ssrc: an SSRC
1322  *
1323  * Set the SSRC of @sess to @ssrc.
1324  */
1325 void
1326 rtp_session_set_internal_ssrc (RTPSession * sess, guint32 ssrc)
1327 {
1328   RTP_SESSION_LOCK (sess);
1329   if (ssrc != sess->source->ssrc) {
1330     g_hash_table_steal (sess->ssrcs[sess->mask_idx],
1331         GINT_TO_POINTER (sess->source->ssrc));
1332
1333     GST_DEBUG ("setting internal SSRC to %08x", ssrc);
1334     /* After this call, any receiver of the old SSRC either in RTP or RTCP
1335      * packets will timeout on the old SSRC, we could potentially schedule a
1336      * BYE RTCP for the old SSRC... */
1337     sess->source->ssrc = ssrc;
1338     rtp_source_reset (sess->source);
1339
1340     /* rehash with the new SSRC */
1341     g_hash_table_insert (sess->ssrcs[sess->mask_idx],
1342         GINT_TO_POINTER (sess->source->ssrc), sess->source);
1343   }
1344   RTP_SESSION_UNLOCK (sess);
1345
1346   g_object_notify (G_OBJECT (sess), "internal-ssrc");
1347 }
1348
1349 /**
1350  * rtp_session_get_internal_ssrc:
1351  * @sess: a #RTPSession
1352  *
1353  * Get the internal SSRC of @sess.
1354  *
1355  * Returns: The SSRC of the session.
1356  */
1357 guint32
1358 rtp_session_get_internal_ssrc (RTPSession * sess)
1359 {
1360   guint32 ssrc;
1361
1362   RTP_SESSION_LOCK (sess);
1363   ssrc = sess->source->ssrc;
1364   RTP_SESSION_UNLOCK (sess);
1365
1366   return ssrc;
1367 }
1368
1369 /**
1370  * rtp_session_add_source:
1371  * @sess: a #RTPSession
1372  * @src: #RTPSource to add
1373  *
1374  * Add @src to @session.
1375  *
1376  * Returns: %TRUE on success, %FALSE if a source with the same SSRC already
1377  * existed in the session.
1378  */
1379 gboolean
1380 rtp_session_add_source (RTPSession * sess, RTPSource * src)
1381 {
1382   gboolean result = FALSE;
1383   RTPSource *find;
1384
1385   g_return_val_if_fail (RTP_IS_SESSION (sess), FALSE);
1386   g_return_val_if_fail (src != NULL, FALSE);
1387
1388   RTP_SESSION_LOCK (sess);
1389   find =
1390       g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
1391       GINT_TO_POINTER (src->ssrc));
1392   if (find == NULL) {
1393     g_hash_table_insert (sess->ssrcs[sess->mask_idx],
1394         GINT_TO_POINTER (src->ssrc), src);
1395     /* we have one more source now */
1396     sess->total_sources++;
1397     result = TRUE;
1398   }
1399   RTP_SESSION_UNLOCK (sess);
1400
1401   return result;
1402 }
1403
1404 /**
1405  * rtp_session_get_num_sources:
1406  * @sess: an #RTPSession
1407  *
1408  * Get the number of sources in @sess.
1409  *
1410  * Returns: The number of sources in @sess.
1411  */
1412 guint
1413 rtp_session_get_num_sources (RTPSession * sess)
1414 {
1415   guint result;
1416
1417   g_return_val_if_fail (RTP_IS_SESSION (sess), FALSE);
1418
1419   RTP_SESSION_LOCK (sess);
1420   result = sess->total_sources;
1421   RTP_SESSION_UNLOCK (sess);
1422
1423   return result;
1424 }
1425
1426 /**
1427  * rtp_session_get_num_active_sources:
1428  * @sess: an #RTPSession
1429  *
1430  * Get the number of active sources in @sess. A source is considered active when
1431  * it has been validated and has not yet received a BYE RTCP message.
1432  *
1433  * Returns: The number of active sources in @sess.
1434  */
1435 guint
1436 rtp_session_get_num_active_sources (RTPSession * sess)
1437 {
1438   guint result;
1439
1440   g_return_val_if_fail (RTP_IS_SESSION (sess), 0);
1441
1442   RTP_SESSION_LOCK (sess);
1443   result = sess->stats.active_sources;
1444   RTP_SESSION_UNLOCK (sess);
1445
1446   return result;
1447 }
1448
1449 /**
1450  * rtp_session_get_source_by_ssrc:
1451  * @sess: an #RTPSession
1452  * @ssrc: an SSRC
1453  *
1454  * Find the source with @ssrc in @sess.
1455  *
1456  * Returns: a #RTPSource with SSRC @ssrc or NULL if the source was not found.
1457  * g_object_unref() after usage.
1458  */
1459 RTPSource *
1460 rtp_session_get_source_by_ssrc (RTPSession * sess, guint32 ssrc)
1461 {
1462   RTPSource *result;
1463
1464   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1465
1466   RTP_SESSION_LOCK (sess);
1467   result =
1468       g_hash_table_lookup (sess->ssrcs[sess->mask_idx], GINT_TO_POINTER (ssrc));
1469   if (result)
1470     g_object_ref (result);
1471   RTP_SESSION_UNLOCK (sess);
1472
1473   return result;
1474 }
1475
1476 /**
1477  * rtp_session_get_source_by_cname:
1478  * @sess: a #RTPSession
1479  * @cname: an CNAME
1480  *
1481  * Find the source with @cname in @sess.
1482  *
1483  * Returns: a #RTPSource with CNAME @cname or NULL if the source was not found.
1484  * g_object_unref() after usage.
1485  */
1486 RTPSource *
1487 rtp_session_get_source_by_cname (RTPSession * sess, const gchar * cname)
1488 {
1489   RTPSource *result;
1490
1491   g_return_val_if_fail (RTP_IS_SESSION (sess), NULL);
1492   g_return_val_if_fail (cname != NULL, NULL);
1493
1494   RTP_SESSION_LOCK (sess);
1495   result = g_hash_table_lookup (sess->cnames, cname);
1496   if (result)
1497     g_object_ref (result);
1498   RTP_SESSION_UNLOCK (sess);
1499
1500   return result;
1501 }
1502
1503 /* should be called with the SESSION lock */
1504 static guint32
1505 rtp_session_create_new_ssrc (RTPSession * sess)
1506 {
1507   guint32 ssrc;
1508
1509   while (TRUE) {
1510     ssrc = g_random_int ();
1511
1512     /* see if it exists in the session, we're done if it doesn't */
1513     if (g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
1514             GINT_TO_POINTER (ssrc)) == NULL)
1515       break;
1516   }
1517   return ssrc;
1518 }
1519
1520
1521 /**
1522  * rtp_session_create_source:
1523  * @sess: an #RTPSession
1524  *
1525  * Create an #RTPSource for use in @sess. This function will create a source
1526  * with an ssrc that is currently not used by any participants in the session.
1527  *
1528  * Returns: an #RTPSource.
1529  */
1530 RTPSource *
1531 rtp_session_create_source (RTPSession * sess)
1532 {
1533   guint32 ssrc;
1534   RTPSource *source;
1535
1536   RTP_SESSION_LOCK (sess);
1537   ssrc = rtp_session_create_new_ssrc (sess);
1538   source = rtp_source_new (ssrc);
1539   rtp_source_set_callbacks (source, &callbacks, sess);
1540   /* we need an additional ref for the source in the hashtable */
1541   g_object_ref (source);
1542   g_hash_table_insert (sess->ssrcs[sess->mask_idx], GINT_TO_POINTER (ssrc),
1543       source);
1544   /* we have one more source now */
1545   sess->total_sources++;
1546   RTP_SESSION_UNLOCK (sess);
1547
1548   return source;
1549 }
1550
1551 /* update the RTPArrivalStats structure with the current time and other bits
1552  * about the current buffer we are handling.
1553  * This function is typically called when a validated packet is received.
1554  * This function should be called with the SESSION_LOCK
1555  */
1556 static void
1557 update_arrival_stats (RTPSession * sess, RTPArrivalStats * arrival,
1558     gboolean rtp, GstBuffer * buffer, GstClockTime current_time,
1559     GstClockTime running_time)
1560 {
1561   /* get time of arrival */
1562   arrival->current_time = current_time;
1563   arrival->running_time = running_time;
1564
1565   /* get packet size including header overhead */
1566   arrival->bytes = GST_BUFFER_SIZE (buffer) + sess->header_len;
1567
1568   if (rtp) {
1569     arrival->payload_len = gst_rtp_buffer_get_payload_len (buffer);
1570   } else {
1571     arrival->payload_len = 0;
1572   }
1573
1574   /* for netbuffer we can store the IP address to check for collisions */
1575   arrival->have_address = GST_IS_NETBUFFER (buffer);
1576   if (arrival->have_address) {
1577     GstNetBuffer *netbuf = (GstNetBuffer *) buffer;
1578
1579     memcpy (&arrival->address, &netbuf->from, sizeof (GstNetAddress));
1580   }
1581 }
1582
1583 /**
1584  * rtp_session_process_rtp:
1585  * @sess: and #RTPSession
1586  * @buffer: an RTP buffer
1587  * @current_time: the current system time
1588  * @running_time: the running_time of @buffer
1589  *
1590  * Process an RTP buffer in the session manager. This function takes ownership
1591  * of @buffer.
1592  *
1593  * Returns: a #GstFlowReturn.
1594  */
1595 GstFlowReturn
1596 rtp_session_process_rtp (RTPSession * sess, GstBuffer * buffer,
1597     GstClockTime current_time, GstClockTime running_time)
1598 {
1599   GstFlowReturn result;
1600   guint32 ssrc;
1601   RTPSource *source;
1602   gboolean created;
1603   gboolean prevsender, prevactive;
1604   RTPArrivalStats arrival;
1605   guint32 csrcs[16];
1606   guint8 i, count;
1607   guint64 oldrate;
1608
1609   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
1610   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
1611
1612   if (!gst_rtp_buffer_validate (buffer))
1613     goto invalid_packet;
1614
1615   RTP_SESSION_LOCK (sess);
1616   /* update arrival stats */
1617   update_arrival_stats (sess, &arrival, TRUE, buffer, current_time,
1618       running_time);
1619
1620   /* ignore more RTP packets when we left the session */
1621   if (sess->source->received_bye)
1622     goto ignore;
1623
1624   /* get SSRC and look up in session database */
1625   ssrc = gst_rtp_buffer_get_ssrc (buffer);
1626   source = obtain_source (sess, ssrc, &created, &arrival, TRUE);
1627   if (!source)
1628     goto collision;
1629
1630   prevsender = RTP_SOURCE_IS_SENDER (source);
1631   prevactive = RTP_SOURCE_IS_ACTIVE (source);
1632   oldrate = source->bitrate;
1633
1634   /* copy available csrc for later */
1635   count = gst_rtp_buffer_get_csrc_count (buffer);
1636   /* make sure to not overflow our array. An RTP buffer can maximally contain
1637    * 16 CSRCs */
1638   count = MIN (count, 16);
1639
1640   for (i = 0; i < count; i++)
1641     csrcs[i] = gst_rtp_buffer_get_csrc (buffer, i);
1642
1643   /* let source process the packet */
1644   result = rtp_source_process_rtp (source, buffer, &arrival);
1645
1646   /* source became active */
1647   if (prevactive != RTP_SOURCE_IS_ACTIVE (source)) {
1648     sess->stats.active_sources++;
1649     GST_DEBUG ("source: %08x became active, %d active sources", ssrc,
1650         sess->stats.active_sources);
1651     on_ssrc_validated (sess, source);
1652   }
1653   if (prevsender != RTP_SOURCE_IS_SENDER (source)) {
1654     sess->stats.sender_sources++;
1655     GST_DEBUG ("source: %08x became sender, %d sender sources", ssrc,
1656         sess->stats.sender_sources);
1657   }
1658   if (oldrate != source->bitrate)
1659     sess->recalc_bandwidth = TRUE;
1660
1661   if (created)
1662     on_new_ssrc (sess, source);
1663
1664   if (source->validated) {
1665     gboolean created;
1666
1667     /* for validated sources, we add the CSRCs as well */
1668     for (i = 0; i < count; i++) {
1669       guint32 csrc;
1670       RTPSource *csrc_src;
1671
1672       csrc = csrcs[i];
1673
1674       /* get source */
1675       csrc_src = obtain_source (sess, csrc, &created, &arrival, TRUE);
1676       if (!csrc_src)
1677         continue;
1678
1679       if (created) {
1680         GST_DEBUG ("created new CSRC: %08x", csrc);
1681         rtp_source_set_as_csrc (csrc_src);
1682         if (RTP_SOURCE_IS_ACTIVE (csrc_src))
1683           sess->stats.active_sources++;
1684         on_new_ssrc (sess, csrc_src);
1685       }
1686       g_object_unref (csrc_src);
1687     }
1688   }
1689   g_object_unref (source);
1690
1691   RTP_SESSION_UNLOCK (sess);
1692
1693   return result;
1694
1695   /* ERRORS */
1696 invalid_packet:
1697   {
1698     gst_buffer_unref (buffer);
1699     GST_DEBUG ("invalid RTP packet received");
1700     return GST_FLOW_OK;
1701   }
1702 ignore:
1703   {
1704     gst_buffer_unref (buffer);
1705     RTP_SESSION_UNLOCK (sess);
1706     GST_DEBUG ("ignoring RTP packet because we are leaving");
1707     return GST_FLOW_OK;
1708   }
1709 collision:
1710   {
1711     gst_buffer_unref (buffer);
1712     RTP_SESSION_UNLOCK (sess);
1713     GST_DEBUG ("ignoring packet because its collisioning");
1714     return GST_FLOW_OK;
1715   }
1716 }
1717
1718 static void
1719 rtp_session_process_rb (RTPSession * sess, RTPSource * source,
1720     GstRTCPPacket * packet, RTPArrivalStats * arrival)
1721 {
1722   guint count, i;
1723
1724   count = gst_rtcp_packet_get_rb_count (packet);
1725   for (i = 0; i < count; i++) {
1726     guint32 ssrc, exthighestseq, jitter, lsr, dlsr;
1727     guint8 fractionlost;
1728     gint32 packetslost;
1729
1730     gst_rtcp_packet_get_rb (packet, i, &ssrc, &fractionlost,
1731         &packetslost, &exthighestseq, &jitter, &lsr, &dlsr);
1732
1733     GST_DEBUG ("RB %d: SSRC %08x, jitter %" G_GUINT32_FORMAT, i, ssrc, jitter);
1734
1735     if (ssrc == sess->source->ssrc) {
1736       /* only deal with report blocks for our session, we update the stats of
1737        * the sender of the RTCP message. We could also compare our stats against
1738        * the other sender to see if we are better or worse. */
1739       rtp_source_process_rb (source, arrival->current_time, fractionlost,
1740           packetslost, exthighestseq, jitter, lsr, dlsr);
1741     }
1742   }
1743   on_ssrc_active (sess, source);
1744 }
1745
1746 /* A Sender report contains statistics about how the sender is doing. This
1747  * includes timing informataion such as the relation between RTP and NTP
1748  * timestamps and the number of packets/bytes it sent to us.
1749  *
1750  * In this report is also included a set of report blocks related to how this
1751  * sender is receiving data (in case we (or somebody else) is also sending stuff
1752  * to it). This info includes the packet loss, jitter and seqnum. It also
1753  * contains information to calculate the round trip time (LSR/DLSR).
1754  */
1755 static void
1756 rtp_session_process_sr (RTPSession * sess, GstRTCPPacket * packet,
1757     RTPArrivalStats * arrival, gboolean * do_sync)
1758 {
1759   guint32 senderssrc, rtptime, packet_count, octet_count;
1760   guint64 ntptime;
1761   RTPSource *source;
1762   gboolean created, prevsender;
1763
1764   gst_rtcp_packet_sr_get_sender_info (packet, &senderssrc, &ntptime, &rtptime,
1765       &packet_count, &octet_count);
1766
1767   GST_DEBUG ("got SR packet: SSRC %08x, time %" GST_TIME_FORMAT,
1768       senderssrc, GST_TIME_ARGS (arrival->current_time));
1769
1770   source = obtain_source (sess, senderssrc, &created, arrival, FALSE);
1771   if (!source)
1772     return;
1773
1774   /* don't try to do lip-sync for sources that sent a BYE */
1775   if (rtp_source_received_bye (source))
1776     *do_sync = FALSE;
1777   else
1778     *do_sync = TRUE;
1779
1780   prevsender = RTP_SOURCE_IS_SENDER (source);
1781
1782   /* first update the source */
1783   rtp_source_process_sr (source, arrival->current_time, ntptime, rtptime,
1784       packet_count, octet_count);
1785
1786   if (prevsender != RTP_SOURCE_IS_SENDER (source)) {
1787     sess->stats.sender_sources++;
1788     GST_DEBUG ("source: %08x became sender, %d sender sources", senderssrc,
1789         sess->stats.sender_sources);
1790   }
1791
1792   if (created)
1793     on_new_ssrc (sess, source);
1794
1795   rtp_session_process_rb (sess, source, packet, arrival);
1796   g_object_unref (source);
1797 }
1798
1799 /* A receiver report contains statistics about how a receiver is doing. It
1800  * includes stuff like packet loss, jitter and the seqnum it received last. It
1801  * also contains info to calculate the round trip time.
1802  *
1803  * We are only interested in how the sender of this report is doing wrt to us.
1804  */
1805 static void
1806 rtp_session_process_rr (RTPSession * sess, GstRTCPPacket * packet,
1807     RTPArrivalStats * arrival)
1808 {
1809   guint32 senderssrc;
1810   RTPSource *source;
1811   gboolean created;
1812
1813   senderssrc = gst_rtcp_packet_rr_get_ssrc (packet);
1814
1815   GST_DEBUG ("got RR packet: SSRC %08x", senderssrc);
1816
1817   source = obtain_source (sess, senderssrc, &created, arrival, FALSE);
1818   if (!source)
1819     return;
1820
1821   if (created)
1822     on_new_ssrc (sess, source);
1823
1824   rtp_session_process_rb (sess, source, packet, arrival);
1825   g_object_unref (source);
1826 }
1827
1828 /* Get SDES items and store them in the SSRC */
1829 static void
1830 rtp_session_process_sdes (RTPSession * sess, GstRTCPPacket * packet,
1831     RTPArrivalStats * arrival)
1832 {
1833   guint items, i, j;
1834   gboolean more_items, more_entries;
1835
1836   items = gst_rtcp_packet_sdes_get_item_count (packet);
1837   GST_DEBUG ("got SDES packet with %d items", items);
1838
1839   more_items = gst_rtcp_packet_sdes_first_item (packet);
1840   i = 0;
1841   while (more_items) {
1842     guint32 ssrc;
1843     gboolean changed, created, validated;
1844     RTPSource *source;
1845     GstStructure *sdes;
1846
1847     ssrc = gst_rtcp_packet_sdes_get_ssrc (packet);
1848
1849     GST_DEBUG ("item %d, SSRC %08x", i, ssrc);
1850
1851     changed = FALSE;
1852
1853     /* find src, no probation when dealing with RTCP */
1854     source = obtain_source (sess, ssrc, &created, arrival, FALSE);
1855     if (!source)
1856       return;
1857
1858     sdes = gst_structure_new ("application/x-rtp-source-sdes", NULL);
1859
1860     more_entries = gst_rtcp_packet_sdes_first_entry (packet);
1861     j = 0;
1862     while (more_entries) {
1863       GstRTCPSDESType type;
1864       guint8 len;
1865       guint8 *data;
1866       gchar *name;
1867       gchar *value;
1868
1869       gst_rtcp_packet_sdes_get_entry (packet, &type, &len, &data);
1870
1871       GST_DEBUG ("entry %d, type %d, len %d, data %.*s", j, type, len, len,
1872           data);
1873
1874       if (type == GST_RTCP_SDES_PRIV) {
1875         name = g_strndup ((const gchar *) &data[1], data[0]);
1876         len -= data[0] + 1;
1877         data += data[0] + 1;
1878       } else {
1879         name = g_strdup (gst_rtcp_sdes_type_to_name (type));
1880       }
1881
1882       value = g_strndup ((const gchar *) data, len);
1883
1884       gst_structure_set (sdes, name, G_TYPE_STRING, value, NULL);
1885
1886       g_free (name);
1887       g_free (value);
1888
1889       more_entries = gst_rtcp_packet_sdes_next_entry (packet);
1890       j++;
1891     }
1892
1893     /* takes ownership of sdes */
1894     changed = rtp_source_set_sdes_struct (source, sdes);
1895
1896     validated = !RTP_SOURCE_IS_ACTIVE (source);
1897     source->validated = TRUE;
1898
1899     if (created)
1900       on_new_ssrc (sess, source);
1901     if (validated)
1902       on_ssrc_validated (sess, source);
1903     if (changed)
1904       on_ssrc_sdes (sess, source);
1905
1906     g_object_unref (source);
1907
1908     more_items = gst_rtcp_packet_sdes_next_item (packet);
1909     i++;
1910   }
1911 }
1912
1913 /* BYE is sent when a client leaves the session
1914  */
1915 static void
1916 rtp_session_process_bye (RTPSession * sess, GstRTCPPacket * packet,
1917     RTPArrivalStats * arrival)
1918 {
1919   guint count, i;
1920   gchar *reason;
1921   gboolean reconsider = FALSE;
1922
1923   reason = gst_rtcp_packet_bye_get_reason (packet);
1924   GST_DEBUG ("got BYE packet (reason: %s)", GST_STR_NULL (reason));
1925
1926   count = gst_rtcp_packet_bye_get_ssrc_count (packet);
1927   for (i = 0; i < count; i++) {
1928     guint32 ssrc;
1929     RTPSource *source;
1930     gboolean created, prevactive, prevsender;
1931     guint pmembers, members;
1932
1933     ssrc = gst_rtcp_packet_bye_get_nth_ssrc (packet, i);
1934     GST_DEBUG ("SSRC: %08x", ssrc);
1935
1936     /* find src and mark bye, no probation when dealing with RTCP */
1937     source = obtain_source (sess, ssrc, &created, arrival, FALSE);
1938     if (!source)
1939       return;
1940
1941     /* store time for when we need to time out this source */
1942     source->bye_time = arrival->current_time;
1943
1944     prevactive = RTP_SOURCE_IS_ACTIVE (source);
1945     prevsender = RTP_SOURCE_IS_SENDER (source);
1946
1947     /* let the source handle the rest */
1948     rtp_source_process_bye (source, reason);
1949
1950     pmembers = sess->stats.active_sources;
1951
1952     if (prevactive && !RTP_SOURCE_IS_ACTIVE (source)) {
1953       sess->stats.active_sources--;
1954       GST_DEBUG ("source: %08x became inactive, %d active sources", ssrc,
1955           sess->stats.active_sources);
1956     }
1957     if (prevsender && !RTP_SOURCE_IS_SENDER (source)) {
1958       sess->stats.sender_sources--;
1959       GST_DEBUG ("source: %08x became non sender, %d sender sources", ssrc,
1960           sess->stats.sender_sources);
1961     }
1962     members = sess->stats.active_sources;
1963
1964     if (!sess->source->received_bye && members < pmembers) {
1965       /* some members went away since the previous timeout estimate.
1966        * Perform reverse reconsideration but only when we are not scheduling a
1967        * BYE ourselves. */
1968       if (arrival->current_time < sess->next_rtcp_check_time) {
1969         GstClockTime time_remaining;
1970
1971         time_remaining = sess->next_rtcp_check_time - arrival->current_time;
1972         sess->next_rtcp_check_time =
1973             gst_util_uint64_scale (time_remaining, members, pmembers);
1974
1975         GST_DEBUG ("reverse reconsideration %" GST_TIME_FORMAT,
1976             GST_TIME_ARGS (sess->next_rtcp_check_time));
1977
1978         sess->next_rtcp_check_time += arrival->current_time;
1979
1980         /* mark pending reconsider. We only want to signal the reconsideration
1981          * once after we handled all the source in the bye packet */
1982         reconsider = TRUE;
1983       }
1984     }
1985
1986     if (created)
1987       on_new_ssrc (sess, source);
1988
1989     on_bye_ssrc (sess, source);
1990
1991     g_object_unref (source);
1992   }
1993   if (reconsider) {
1994     RTP_SESSION_UNLOCK (sess);
1995     /* notify app of reconsideration */
1996     if (sess->callbacks.reconsider)
1997       sess->callbacks.reconsider (sess, sess->reconsider_user_data);
1998     RTP_SESSION_LOCK (sess);
1999   }
2000   g_free (reason);
2001 }
2002
2003 static void
2004 rtp_session_process_app (RTPSession * sess, GstRTCPPacket * packet,
2005     RTPArrivalStats * arrival)
2006 {
2007   GST_DEBUG ("received APP");
2008 }
2009
2010 static void
2011 rtp_session_process_pli (RTPSession * sess, guint32 sender_ssrc,
2012     guint32 media_ssrc, GstClockTime current_time)
2013 {
2014   RTPSource *src;
2015   guint32 round_trip = 0;
2016
2017   if (!sess->callbacks.request_key_unit)
2018     return;
2019
2020   src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
2021       GINT_TO_POINTER (sender_ssrc));
2022
2023   if (!src)
2024     return;
2025
2026   if (sess->last_keyframe_request != GST_CLOCK_TIME_NONE &&
2027       rtp_source_get_last_rb (src, NULL, NULL, NULL, NULL, NULL, NULL,
2028           &round_trip)) {
2029     GstClockTime round_trip_in_ns = gst_util_uint64_scale (round_trip,
2030         GST_SECOND, 65536);
2031
2032     if (sess->last_keyframe_request != GST_CLOCK_TIME_NONE &&
2033         current_time - sess->last_keyframe_request < round_trip_in_ns) {
2034       GST_DEBUG ("Ignoring PLI because one was send without one RTT (%"
2035           GST_TIME_FORMAT " < %" GST_TIME_FORMAT ")",
2036           GST_TIME_ARGS (current_time - sess->last_keyframe_request),
2037           GST_TIME_ARGS (round_trip_in_ns));;
2038       return;
2039     }
2040   }
2041
2042   sess->last_keyframe_request = current_time;
2043
2044   GST_LOG ("received PLI from %X %p(%p)", sender_ssrc,
2045       sess->callbacks.process_rtp, sess->callbacks.request_key_unit);
2046
2047   sess->callbacks.request_key_unit (sess, FALSE,
2048       sess->request_key_unit_user_data);
2049 }
2050
2051 static void
2052 rtp_session_process_feedback (RTPSession * sess, GstRTCPPacket * packet,
2053     RTPArrivalStats * arrival, GstClockTime current_time)
2054 {
2055   GstRTCPType type = gst_rtcp_packet_get_type (packet);
2056   GstRTCPFBType fbtype = gst_rtcp_packet_fb_get_type (packet);
2057   guint32 sender_ssrc = gst_rtcp_packet_fb_get_sender_ssrc (packet);
2058   guint32 media_ssrc = gst_rtcp_packet_fb_get_media_ssrc (packet);
2059   guint length = 4 * (gst_rtcp_packet_get_length (packet) - 2);
2060
2061   GST_DEBUG ("received feedback %d:%d from %08X about %08X"
2062       " with FCI of length %d", type, fbtype, sender_ssrc, media_ssrc, length);
2063
2064   if (g_signal_has_handler_pending (sess,
2065           rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0, TRUE)) {
2066     GstBuffer *fci = NULL;
2067
2068     if (length) {
2069       fci = gst_buffer_create_sub (packet->buffer, packet->offset + 72, length);
2070       GST_BUFFER_TIMESTAMP (fci) = arrival->running_time;
2071     }
2072
2073     RTP_SESSION_UNLOCK (sess);
2074     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0,
2075         type, fbtype, sender_ssrc, media_ssrc, fci);
2076     RTP_SESSION_LOCK (sess);
2077
2078     if (fci)
2079       gst_buffer_unref (fci);
2080   }
2081
2082   if (sess->rtcp_feedback_retention_window) {
2083     RTPSource *src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
2084         GINT_TO_POINTER (media_ssrc));
2085
2086     if (src)
2087       rtp_source_retain_rtcp_packet (src, packet, arrival->running_time);
2088   }
2089
2090   if (rtp_source_get_ssrc (sess->source) == media_ssrc) {
2091     switch (type) {
2092       case GST_RTCP_TYPE_PSFB:
2093         switch (fbtype) {
2094           case GST_RTCP_PSFB_TYPE_PLI:
2095             rtp_session_process_pli (sess, sender_ssrc, media_ssrc,
2096                 current_time);
2097             break;
2098           default:
2099             break;
2100         }
2101         break;
2102       case GST_RTCP_TYPE_RTPFB:
2103       default:
2104         break;
2105     }
2106   }
2107 }
2108
2109 /**
2110  * rtp_session_process_rtcp:
2111  * @sess: and #RTPSession
2112  * @buffer: an RTCP buffer
2113  * @current_time: the current system time
2114  *
2115  * Process an RTCP buffer in the session manager. This function takes ownership
2116  * of @buffer.
2117  *
2118  * Returns: a #GstFlowReturn.
2119  */
2120 GstFlowReturn
2121 rtp_session_process_rtcp (RTPSession * sess, GstBuffer * buffer,
2122     GstClockTime current_time)
2123 {
2124   GstRTCPPacket packet;
2125   gboolean more, is_bye = FALSE, do_sync = FALSE;
2126   RTPArrivalStats arrival;
2127   GstFlowReturn result = GST_FLOW_OK;
2128
2129   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2130   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
2131
2132   if (!gst_rtcp_buffer_validate (buffer))
2133     goto invalid_packet;
2134
2135   GST_DEBUG ("received RTCP packet");
2136
2137   RTP_SESSION_LOCK (sess);
2138   /* update arrival stats */
2139   update_arrival_stats (sess, &arrival, FALSE, buffer, current_time, -1);
2140
2141   if (sess->sent_bye)
2142     goto ignore;
2143
2144   /* start processing the compound packet */
2145   more = gst_rtcp_buffer_get_first_packet (buffer, &packet);
2146   while (more) {
2147     GstRTCPType type;
2148
2149     type = gst_rtcp_packet_get_type (&packet);
2150
2151     /* when we are leaving the session, we should ignore all non-BYE messages */
2152     if (sess->source->received_bye && type != GST_RTCP_TYPE_BYE) {
2153       GST_DEBUG ("ignoring non-BYE RTCP packet because we are leaving");
2154       goto next;
2155     }
2156
2157     switch (type) {
2158       case GST_RTCP_TYPE_SR:
2159         rtp_session_process_sr (sess, &packet, &arrival, &do_sync);
2160         break;
2161       case GST_RTCP_TYPE_RR:
2162         rtp_session_process_rr (sess, &packet, &arrival);
2163         break;
2164       case GST_RTCP_TYPE_SDES:
2165         rtp_session_process_sdes (sess, &packet, &arrival);
2166         break;
2167       case GST_RTCP_TYPE_BYE:
2168         is_bye = TRUE;
2169         /* don't try to attempt lip-sync anymore for streams with a BYE */
2170         do_sync = FALSE;
2171         rtp_session_process_bye (sess, &packet, &arrival);
2172         break;
2173       case GST_RTCP_TYPE_APP:
2174         rtp_session_process_app (sess, &packet, &arrival);
2175         break;
2176       case GST_RTCP_TYPE_RTPFB:
2177       case GST_RTCP_TYPE_PSFB:
2178         rtp_session_process_feedback (sess, &packet, &arrival, current_time);
2179         break;
2180       default:
2181         GST_WARNING ("got unknown RTCP packet");
2182         break;
2183     }
2184   next:
2185     more = gst_rtcp_packet_move_to_next (&packet);
2186   }
2187
2188   /* if we are scheduling a BYE, we only want to count bye packets, else we
2189    * count everything */
2190   if (sess->source->received_bye) {
2191     if (is_bye) {
2192       sess->stats.bye_members++;
2193       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, arrival.bytes);
2194     }
2195   } else {
2196     /* keep track of average packet size */
2197     UPDATE_AVG (sess->stats.avg_rtcp_packet_size, arrival.bytes);
2198   }
2199   GST_DEBUG ("%p, received RTCP packet, avg size %u, %u", &sess->stats,
2200       sess->stats.avg_rtcp_packet_size, arrival.bytes);
2201   RTP_SESSION_UNLOCK (sess);
2202
2203   /* notify caller of sr packets in the callback */
2204   if (do_sync && sess->callbacks.sync_rtcp) {
2205     /* make writable, we might want to change the buffer */
2206     buffer = gst_buffer_make_metadata_writable (buffer);
2207
2208     result = sess->callbacks.sync_rtcp (sess, sess->source, buffer,
2209         sess->sync_rtcp_user_data);
2210   } else
2211     gst_buffer_unref (buffer);
2212
2213   return result;
2214
2215   /* ERRORS */
2216 invalid_packet:
2217   {
2218     GST_DEBUG ("invalid RTCP packet received");
2219     gst_buffer_unref (buffer);
2220     return GST_FLOW_OK;
2221   }
2222 ignore:
2223   {
2224     gst_buffer_unref (buffer);
2225     RTP_SESSION_UNLOCK (sess);
2226     GST_DEBUG ("ignoring RTP packet because we left");
2227     return GST_FLOW_OK;
2228   }
2229 }
2230
2231 /**
2232  * rtp_session_send_rtp:
2233  * @sess: an #RTPSession
2234  * @data: pointer to either an RTP buffer or a list of RTP buffers
2235  * @is_list: TRUE when @data is a buffer list
2236  * @current_time: the current system time
2237  * @running_time: the running time of @data
2238  *
2239  * Send the RTP buffer in the session manager. This function takes ownership of
2240  * @buffer.
2241  *
2242  * Returns: a #GstFlowReturn.
2243  */
2244 GstFlowReturn
2245 rtp_session_send_rtp (RTPSession * sess, gpointer data, gboolean is_list,
2246     GstClockTime current_time, GstClockTime running_time)
2247 {
2248   GstFlowReturn result;
2249   RTPSource *source;
2250   gboolean prevsender;
2251   gboolean valid_packet;
2252   guint64 oldrate;
2253
2254   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2255   g_return_val_if_fail (is_list || GST_IS_BUFFER (data), GST_FLOW_ERROR);
2256
2257   if (is_list) {
2258     valid_packet = gst_rtp_buffer_list_validate (GST_BUFFER_LIST_CAST (data));
2259   } else {
2260     valid_packet = gst_rtp_buffer_validate (GST_BUFFER_CAST (data));
2261   }
2262
2263   if (!valid_packet)
2264     goto invalid_packet;
2265
2266   GST_LOG ("received RTP %s for sending", is_list ? "list" : "packet");
2267
2268   RTP_SESSION_LOCK (sess);
2269   source = sess->source;
2270
2271   /* update last activity */
2272   source->last_rtp_activity = current_time;
2273
2274   prevsender = RTP_SOURCE_IS_SENDER (source);
2275   oldrate = source->bitrate;
2276
2277   /* we use our own source to send */
2278   result = rtp_source_send_rtp (source, data, is_list, running_time);
2279
2280   if (RTP_SOURCE_IS_SENDER (source) && !prevsender)
2281     sess->stats.sender_sources++;
2282   if (oldrate != source->bitrate)
2283     sess->recalc_bandwidth = TRUE;
2284   RTP_SESSION_UNLOCK (sess);
2285
2286   return result;
2287
2288   /* ERRORS */
2289 invalid_packet:
2290   {
2291     gst_mini_object_unref (GST_MINI_OBJECT_CAST (data));
2292     GST_DEBUG ("invalid RTP packet received");
2293     return GST_FLOW_OK;
2294   }
2295 }
2296
2297 static void
2298 add_bitrates (gpointer key, RTPSource * source, gdouble * bandwidth)
2299 {
2300   *bandwidth += source->bitrate;
2301 }
2302
2303 static GstClockTime
2304 calculate_rtcp_interval (RTPSession * sess, gboolean deterministic,
2305     gboolean first)
2306 {
2307   GstClockTime result;
2308
2309   /* recalculate bandwidth when it changed */
2310   if (sess->recalc_bandwidth) {
2311     gdouble bandwidth;
2312
2313     if (sess->bandwidth > 0)
2314       bandwidth = sess->bandwidth;
2315     else {
2316       /* If it is <= 0, then try to estimate the actual bandwidth */
2317       bandwidth = sess->source->bitrate;
2318
2319       g_hash_table_foreach (sess->cnames, (GHFunc) add_bitrates, &bandwidth);
2320       bandwidth /= 8.0;
2321     }
2322     if (bandwidth == 0)
2323       bandwidth = RTP_STATS_BANDWIDTH;
2324
2325     rtp_stats_set_bandwidths (&sess->stats, bandwidth,
2326         sess->rtcp_bandwidth, sess->rtcp_rs_bandwidth, sess->rtcp_rr_bandwidth);
2327
2328     sess->recalc_bandwidth = FALSE;
2329   }
2330
2331   if (sess->source->received_bye) {
2332     result = rtp_stats_calculate_bye_interval (&sess->stats);
2333   } else {
2334     result = rtp_stats_calculate_rtcp_interval (&sess->stats,
2335         RTP_SOURCE_IS_SENDER (sess->source), first);
2336   }
2337
2338   GST_DEBUG ("next deterministic interval: %" GST_TIME_FORMAT ", first %d",
2339       GST_TIME_ARGS (result), first);
2340
2341   if (!deterministic && result != GST_CLOCK_TIME_NONE)
2342     result = rtp_stats_add_rtcp_jitter (&sess->stats, result);
2343
2344   GST_DEBUG ("next interval: %" GST_TIME_FORMAT, GST_TIME_ARGS (result));
2345
2346   return result;
2347 }
2348
2349 /* Stop the current @sess and schedule a BYE message for the other members.
2350  * One must have the session lock to call this function
2351  */
2352 static GstFlowReturn
2353 rtp_session_schedule_bye_locked (RTPSession * sess, const gchar * reason,
2354     GstClockTime current_time)
2355 {
2356   GstFlowReturn result = GST_FLOW_OK;
2357   RTPSource *source;
2358   GstClockTime interval;
2359
2360   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2361
2362   source = sess->source;
2363
2364   /* ignore more BYEs */
2365   if (source->received_bye)
2366     goto done;
2367
2368   /* we have BYE now */
2369   source->received_bye = TRUE;
2370   /* at least one member wants to send a BYE */
2371   g_free (sess->bye_reason);
2372   sess->bye_reason = g_strdup (reason);
2373   INIT_AVG (sess->stats.avg_rtcp_packet_size, 100);
2374   sess->stats.bye_members = 1;
2375   sess->first_rtcp = TRUE;
2376   sess->sent_bye = FALSE;
2377   sess->allow_early = TRUE;
2378
2379   /* reschedule transmission */
2380   sess->last_rtcp_send_time = current_time;
2381   interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2382   sess->next_rtcp_check_time = current_time + interval;
2383
2384   GST_DEBUG ("Schedule BYE for %" GST_TIME_FORMAT ", %" GST_TIME_FORMAT,
2385       GST_TIME_ARGS (interval), GST_TIME_ARGS (sess->next_rtcp_check_time));
2386
2387   RTP_SESSION_UNLOCK (sess);
2388   /* notify app of reconsideration */
2389   if (sess->callbacks.reconsider)
2390     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
2391   RTP_SESSION_LOCK (sess);
2392 done:
2393
2394   return result;
2395 }
2396
2397 /**
2398  * rtp_session_schedule_bye:
2399  * @sess: an #RTPSession
2400  * @reason: a reason or NULL
2401  * @current_time: the current system time
2402  *
2403  * Stop the current @sess and schedule a BYE message for the other members.
2404  *
2405  * Returns: a #GstFlowReturn.
2406  */
2407 GstFlowReturn
2408 rtp_session_schedule_bye (RTPSession * sess, const gchar * reason,
2409     GstClockTime current_time)
2410 {
2411   GstFlowReturn result = GST_FLOW_OK;
2412
2413   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2414
2415   RTP_SESSION_LOCK (sess);
2416   result = rtp_session_schedule_bye_locked (sess, reason, current_time);
2417   RTP_SESSION_UNLOCK (sess);
2418
2419   return result;
2420 }
2421
2422 /**
2423  * rtp_session_next_timeout:
2424  * @sess: an #RTPSession
2425  * @current_time: the current system time
2426  *
2427  * Get the next time we should perform session maintenance tasks.
2428  *
2429  * Returns: a time when rtp_session_on_timeout() should be called with the
2430  * current system time.
2431  */
2432 GstClockTime
2433 rtp_session_next_timeout (RTPSession * sess, GstClockTime current_time)
2434 {
2435   GstClockTime result, interval = 0;
2436
2437   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_CLOCK_TIME_NONE);
2438
2439   RTP_SESSION_LOCK (sess);
2440
2441   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time)) {
2442     result = sess->next_early_rtcp_time;
2443     goto early_exit;
2444   }
2445
2446   result = sess->next_rtcp_check_time;
2447
2448   GST_DEBUG ("current time: %" GST_TIME_FORMAT ", next :%" GST_TIME_FORMAT,
2449       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
2450
2451   if (result < current_time) {
2452     GST_DEBUG ("take current time as base");
2453     /* our previous check time expired, start counting from the current time
2454      * again. */
2455     result = current_time;
2456   }
2457
2458   if (sess->source->received_bye) {
2459     if (sess->sent_bye) {
2460       GST_DEBUG ("we sent BYE already");
2461       interval = GST_CLOCK_TIME_NONE;
2462     } else if (sess->stats.active_sources >= 50) {
2463       GST_DEBUG ("reconsider BYE, more than 50 sources");
2464       /* reconsider BYE if members >= 50 */
2465       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2466     }
2467   } else {
2468     if (sess->first_rtcp) {
2469       GST_DEBUG ("first RTCP packet");
2470       /* we are called for the first time */
2471       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2472     } else if (sess->next_rtcp_check_time < current_time) {
2473       GST_DEBUG ("old check time expired, getting new timeout");
2474       /* get a new timeout when we need to */
2475       interval = calculate_rtcp_interval (sess, FALSE, FALSE);
2476     }
2477   }
2478
2479   if (interval != GST_CLOCK_TIME_NONE)
2480     result += interval;
2481   else
2482     result = GST_CLOCK_TIME_NONE;
2483
2484   sess->next_rtcp_check_time = result;
2485
2486 early_exit:
2487
2488   GST_DEBUG ("current time: %" GST_TIME_FORMAT
2489       ", next time: %" GST_TIME_FORMAT,
2490       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
2491   RTP_SESSION_UNLOCK (sess);
2492
2493   return result;
2494 }
2495
2496 typedef struct
2497 {
2498   RTPSession *sess;
2499   GstBuffer *rtcp;
2500   GstClockTime current_time;
2501   guint64 ntpnstime;
2502   GstClockTime running_time;
2503   GstClockTime interval;
2504   GstRTCPPacket packet;
2505   gboolean is_bye;
2506   gboolean has_sdes;
2507   gboolean is_early;
2508   gboolean may_suppress;
2509 } ReportData;
2510
2511 static void
2512 session_start_rtcp (RTPSession * sess, ReportData * data)
2513 {
2514   GstRTCPPacket *packet = &data->packet;
2515   RTPSource *own = sess->source;
2516
2517   data->rtcp = gst_rtcp_buffer_new (sess->mtu);
2518
2519   if (RTP_SOURCE_IS_SENDER (own)) {
2520     guint64 ntptime;
2521     guint32 rtptime;
2522     guint32 packet_count, octet_count;
2523
2524     /* we are a sender, create SR */
2525     GST_DEBUG ("create SR for SSRC %08x", own->ssrc);
2526     gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_SR, packet);
2527
2528     /* get latest stats */
2529     rtp_source_get_new_sr (own, data->ntpnstime, data->running_time,
2530         &ntptime, &rtptime, &packet_count, &octet_count);
2531     /* store stats */
2532     rtp_source_process_sr (own, data->current_time, ntptime, rtptime,
2533         packet_count, octet_count);
2534
2535     /* fill in sender report info */
2536     gst_rtcp_packet_sr_set_sender_info (packet, own->ssrc,
2537         ntptime, rtptime, packet_count, octet_count);
2538   } else {
2539     /* we are only receiver, create RR */
2540     GST_DEBUG ("create RR for SSRC %08x", own->ssrc);
2541     gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_RR, packet);
2542     gst_rtcp_packet_rr_set_ssrc (packet, own->ssrc);
2543   }
2544 }
2545
2546 /* construct a Sender or Receiver Report */
2547 static void
2548 session_report_blocks (const gchar * key, RTPSource * source, ReportData * data)
2549 {
2550   RTPSession *sess = data->sess;
2551   GstRTCPPacket *packet = &data->packet;
2552
2553   /* create a new buffer if needed */
2554   if (data->rtcp == NULL) {
2555     session_start_rtcp (sess, data);
2556   } else if (data->is_early) {
2557     /* Put a single RR or SR in minimal compound packets */
2558     return;
2559   }
2560   if (gst_rtcp_packet_get_rb_count (packet) < GST_RTCP_MAX_RB_COUNT) {
2561     /* only report about other sender sources */
2562     if (source != sess->source && RTP_SOURCE_IS_SENDER (source)) {
2563       guint8 fractionlost;
2564       gint32 packetslost;
2565       guint32 exthighestseq, jitter;
2566       guint32 lsr, dlsr;
2567
2568       /* get new stats */
2569       rtp_source_get_new_rb (source, data->current_time, &fractionlost,
2570           &packetslost, &exthighestseq, &jitter, &lsr, &dlsr);
2571
2572       /* store last generated RR packet */
2573       source->last_rr.is_valid = TRUE;
2574       source->last_rr.fractionlost = fractionlost;
2575       source->last_rr.packetslost = packetslost;
2576       source->last_rr.exthighestseq = exthighestseq;
2577       source->last_rr.jitter = jitter;
2578       source->last_rr.lsr = lsr;
2579       source->last_rr.dlsr = dlsr;
2580
2581       /* packet is not yet filled, add report block for this source. */
2582       gst_rtcp_packet_add_rb (packet, source->ssrc, fractionlost, packetslost,
2583           exthighestseq, jitter, lsr, dlsr);
2584     }
2585   }
2586 }
2587
2588 /* perform cleanup of sources that timed out */
2589 static void
2590 session_cleanup (const gchar * key, RTPSource * source, ReportData * data)
2591 {
2592   gboolean remove = FALSE;
2593   gboolean byetimeout = FALSE;
2594   gboolean sendertimeout = FALSE;
2595   gboolean is_sender, is_active;
2596   RTPSession *sess = data->sess;
2597   GstClockTime interval;
2598
2599   is_sender = RTP_SOURCE_IS_SENDER (source);
2600   is_active = RTP_SOURCE_IS_ACTIVE (source);
2601
2602   /* check for our own source, we don't want to delete our own source. */
2603   if (!(source == sess->source)) {
2604     if (source->received_bye) {
2605       /* if we received a BYE from the source, remove the source after some
2606        * time. */
2607       if (data->current_time > source->bye_time &&
2608           data->current_time - source->bye_time > sess->stats.bye_timeout) {
2609         GST_DEBUG ("removing BYE source %08x", source->ssrc);
2610         remove = TRUE;
2611         byetimeout = TRUE;
2612       }
2613     }
2614     /* sources that were inactive for more than 5 times the deterministic reporting
2615      * interval get timed out. the min timeout is 5 seconds. */
2616     if (data->current_time > source->last_activity) {
2617       interval = MAX (data->interval * 5, 5 * GST_SECOND);
2618       if (data->current_time - source->last_activity > interval) {
2619         GST_DEBUG ("removing timeout source %08x, last %" GST_TIME_FORMAT,
2620             source->ssrc, GST_TIME_ARGS (source->last_activity));
2621         remove = TRUE;
2622       }
2623     }
2624   }
2625
2626   /* senders that did not send for a long time become a receiver, this also
2627    * holds for our own source. */
2628   if (is_sender) {
2629     if (data->current_time > source->last_rtp_activity) {
2630       interval = MAX (data->interval * 2, 5 * GST_SECOND);
2631       if (data->current_time - source->last_rtp_activity > interval) {
2632         GST_DEBUG ("sender source %08x timed out and became receiver, last %"
2633             GST_TIME_FORMAT, source->ssrc,
2634             GST_TIME_ARGS (source->last_rtp_activity));
2635         source->is_sender = FALSE;
2636         sess->stats.sender_sources--;
2637         sendertimeout = TRUE;
2638       }
2639     }
2640   }
2641
2642   if (remove) {
2643     sess->total_sources--;
2644     if (is_sender)
2645       sess->stats.sender_sources--;
2646     if (is_active)
2647       sess->stats.active_sources--;
2648
2649     if (byetimeout)
2650       on_bye_timeout (sess, source);
2651     else
2652       on_timeout (sess, source);
2653   } else {
2654     if (sendertimeout)
2655       on_sender_timeout (sess, source);
2656   }
2657
2658   source->closing = remove;
2659 }
2660
2661 static void
2662 session_sdes (RTPSession * sess, ReportData * data)
2663 {
2664   GstRTCPPacket *packet = &data->packet;
2665   const GstStructure *sdes;
2666   gint i, n_fields;
2667
2668   /* add SDES packet */
2669   gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_SDES, packet);
2670
2671   gst_rtcp_packet_sdes_add_item (packet, sess->source->ssrc);
2672
2673   sdes = rtp_source_get_sdes_struct (sess->source);
2674
2675   /* add all fields in the structure, the order is not important. */
2676   n_fields = gst_structure_n_fields (sdes);
2677   for (i = 0; i < n_fields; ++i) {
2678     const gchar *field;
2679     const gchar *value;
2680     GstRTCPSDESType type;
2681
2682     field = gst_structure_nth_field_name (sdes, i);
2683     if (field == NULL)
2684       continue;
2685     value = gst_structure_get_string (sdes, field);
2686     if (value == NULL)
2687       continue;
2688     type = gst_rtcp_sdes_name_to_type (field);
2689
2690     /* Early packets are minimal and only include the CNAME */
2691     if (data->is_early && type != GST_RTCP_SDES_CNAME)
2692       continue;
2693
2694     if (type > GST_RTCP_SDES_END && type < GST_RTCP_SDES_PRIV) {
2695       gst_rtcp_packet_sdes_add_entry (packet, type, strlen (value),
2696           (const guint8 *) value);
2697     } else if (type == GST_RTCP_SDES_PRIV) {
2698       gsize prefix_len;
2699       gsize value_len;
2700       gsize data_len;
2701       guint8 data[256];
2702
2703       /* don't accept entries that are too big */
2704       prefix_len = strlen (field);
2705       if (prefix_len > 255)
2706         continue;
2707       value_len = strlen (value);
2708       if (value_len > 255)
2709         continue;
2710       data_len = 1 + prefix_len + value_len;
2711       if (data_len > 255)
2712         continue;
2713
2714       data[0] = prefix_len;
2715       memcpy (&data[1], field, prefix_len);
2716       memcpy (&data[1 + prefix_len], value, value_len);
2717
2718       gst_rtcp_packet_sdes_add_entry (packet, type, data_len, data);
2719     }
2720   }
2721
2722   data->has_sdes = TRUE;
2723 }
2724
2725 /* schedule a BYE packet */
2726 static void
2727 session_bye (RTPSession * sess, ReportData * data)
2728 {
2729   GstRTCPPacket *packet = &data->packet;
2730
2731   /* open packet */
2732   session_start_rtcp (sess, data);
2733
2734   /* add SDES */
2735   session_sdes (sess, data);
2736
2737   /* add a BYE packet */
2738   gst_rtcp_buffer_add_packet (data->rtcp, GST_RTCP_TYPE_BYE, packet);
2739   gst_rtcp_packet_bye_add_ssrc (packet, sess->source->ssrc);
2740   if (sess->bye_reason)
2741     gst_rtcp_packet_bye_set_reason (packet, sess->bye_reason);
2742
2743   /* we have a BYE packet now */
2744   data->is_bye = TRUE;
2745 }
2746
2747 static gboolean
2748 is_rtcp_time (RTPSession * sess, GstClockTime current_time, ReportData * data)
2749 {
2750   GstClockTime new_send_time, elapsed;
2751
2752   if (data->is_early && sess->next_early_rtcp_time < current_time)
2753     goto early;
2754
2755   /* no need to check yet */
2756   if (sess->next_rtcp_check_time > current_time) {
2757     GST_DEBUG ("no check time yet, next %" GST_TIME_FORMAT " > now %"
2758         GST_TIME_FORMAT, GST_TIME_ARGS (sess->next_rtcp_check_time),
2759         GST_TIME_ARGS (current_time));
2760     return FALSE;
2761   }
2762
2763   /* get elapsed time since we last reported */
2764   elapsed = current_time - sess->last_rtcp_send_time;
2765
2766   /* perform forward reconsideration */
2767   new_send_time = rtp_stats_add_rtcp_jitter (&sess->stats, data->interval);
2768
2769   GST_DEBUG ("forward reconsideration %" GST_TIME_FORMAT ", elapsed %"
2770       GST_TIME_FORMAT, GST_TIME_ARGS (new_send_time), GST_TIME_ARGS (elapsed));
2771
2772   new_send_time += sess->last_rtcp_send_time;
2773
2774   /* check if reconsideration */
2775   if (current_time < new_send_time) {
2776     GST_DEBUG ("reconsider RTCP for %" GST_TIME_FORMAT,
2777         GST_TIME_ARGS (new_send_time));
2778     /* store new check time */
2779     sess->next_rtcp_check_time = new_send_time;
2780     return FALSE;
2781   }
2782
2783 early:
2784
2785   new_send_time = calculate_rtcp_interval (sess, FALSE, FALSE);
2786
2787   GST_DEBUG ("can send RTCP now, next interval %" GST_TIME_FORMAT,
2788       GST_TIME_ARGS (new_send_time));
2789   sess->next_rtcp_check_time = current_time + new_send_time;
2790
2791   /* Apply the rules from RFC 4585 section 3.5.3 */
2792   if (sess->stats.min_interval != 0 && !sess->first_rtcp) {
2793     GstClockTimeDiff T_rr_current_interval = g_random_double_range (0.5, 1.5) *
2794         sess->stats.min_interval;
2795
2796     /* This will caused the RTCP to be suppressed if no FB packets are added */
2797     if (sess->last_rtcp_send_time + T_rr_current_interval >
2798         sess->next_rtcp_check_time) {
2799       GST_DEBUG ("RTCP packet could be suppressed min: %" GST_TIME_FORMAT
2800           " last: %" GST_TIME_FORMAT
2801           " + T_rr_current_interval: %" GST_TIME_FORMAT
2802           " >  sess->next_rtcp_check_time: %" GST_TIME_FORMAT,
2803           GST_TIME_ARGS (sess->stats.min_interval),
2804           GST_TIME_ARGS (sess->last_rtcp_send_time),
2805           GST_TIME_ARGS (T_rr_current_interval),
2806           GST_TIME_ARGS (sess->next_rtcp_check_time));
2807       data->may_suppress = TRUE;
2808     }
2809   }
2810
2811   return TRUE;
2812 }
2813
2814 static void
2815 clone_ssrcs_hashtable (gchar * key, RTPSource * source, GHashTable * hash_table)
2816 {
2817   g_hash_table_insert (hash_table, key, g_object_ref (source));
2818 }
2819
2820 static gboolean
2821 remove_closing_sources (const gchar * key, RTPSource * source, gpointer * data)
2822 {
2823   return source->closing;
2824 }
2825
2826 /**
2827  * rtp_session_on_timeout:
2828  * @sess: an #RTPSession
2829  * @current_time: the current system time
2830  * @ntpnstime: the current NTP time in nanoseconds
2831  * @running_time: the current running_time of the pipeline
2832  *
2833  * Perform maintenance actions after the timeout obtained with
2834  * rtp_session_next_timeout() expired.
2835  *
2836  * This function will perform timeouts of receivers and senders, send a BYE
2837  * packet or generate RTCP packets with current session stats.
2838  *
2839  * This function can call the #RTPSessionSendRTCP callback, possibly multiple
2840  * times, for each packet that should be processed.
2841  *
2842  * Returns: a #GstFlowReturn.
2843  */
2844 GstFlowReturn
2845 rtp_session_on_timeout (RTPSession * sess, GstClockTime current_time,
2846     guint64 ntpnstime, GstClockTime running_time)
2847 {
2848   GstFlowReturn result = GST_FLOW_OK;
2849   ReportData data;
2850   RTPSource *own;
2851   GHashTable *table_copy;
2852   gboolean notify = FALSE;
2853
2854   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2855
2856   GST_DEBUG ("reporting at %" GST_TIME_FORMAT ", NTP time %" GST_TIME_FORMAT,
2857       GST_TIME_ARGS (current_time), GST_TIME_ARGS (ntpnstime));
2858
2859   data.sess = sess;
2860   data.rtcp = NULL;
2861   data.current_time = current_time;
2862   data.ntpnstime = ntpnstime;
2863   data.is_bye = FALSE;
2864   data.has_sdes = FALSE;
2865   data.may_suppress = FALSE;
2866   data.running_time = running_time;
2867
2868   own = sess->source;
2869
2870   RTP_SESSION_LOCK (sess);
2871   /* get a new interval, we need this for various cleanups etc */
2872   data.interval = calculate_rtcp_interval (sess, TRUE, sess->first_rtcp);
2873
2874   /* Make a local copy of the hashtable. We need to do this because the
2875    * cleanup stage below releases the session lock. */
2876   table_copy = g_hash_table_new_full (NULL, NULL, NULL,
2877       (GDestroyNotify) g_object_unref);
2878   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
2879       (GHFunc) clone_ssrcs_hashtable, table_copy);
2880
2881   /* Clean up the session, mark the source for removing, this might release the
2882    * session lock. */
2883   g_hash_table_foreach (table_copy, (GHFunc) session_cleanup, &data);
2884   g_hash_table_destroy (table_copy);
2885
2886   /* Now remove the marked sources */
2887   g_hash_table_foreach_remove (sess->ssrcs[sess->mask_idx],
2888       (GHRFunc) remove_closing_sources, NULL);
2889
2890   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
2891     data.is_early = TRUE;
2892   else
2893     data.is_early = FALSE;
2894
2895   /* see if we need to generate SR or RR packets */
2896   if (is_rtcp_time (sess, current_time, &data)) {
2897     if (own->received_bye) {
2898       /* generate BYE instead */
2899       GST_DEBUG ("generating BYE message");
2900       session_bye (sess, &data);
2901       sess->sent_bye = TRUE;
2902     } else {
2903       /* loop over all known sources and do something */
2904       g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
2905           (GHFunc) session_report_blocks, &data);
2906     }
2907   }
2908
2909   if (data.rtcp) {
2910     /* we keep track of the last report time in order to timeout inactive
2911      * receivers or senders */
2912     if (!data.is_early && !data.may_suppress)
2913       sess->last_rtcp_send_time = data.current_time;
2914     sess->first_rtcp = FALSE;
2915     sess->next_early_rtcp_time = GST_CLOCK_TIME_NONE;
2916
2917     /* add SDES for this source when not already added */
2918     if (!data.has_sdes)
2919       session_sdes (sess, &data);
2920   }
2921
2922   /* check for outdated collisions */
2923   GST_DEBUG ("Timing out collisions");
2924   rtp_source_timeout (sess->source, current_time,
2925       data.interval * RTCP_INTERVAL_COLLISION_TIMEOUT,
2926       running_time - sess->rtcp_feedback_retention_window);
2927
2928   if (sess->change_ssrc) {
2929     GST_DEBUG ("need to change our SSRC (%08x)", own->ssrc);
2930     g_hash_table_steal (sess->ssrcs[sess->mask_idx],
2931         GINT_TO_POINTER (own->ssrc));
2932
2933     own->ssrc = rtp_session_create_new_ssrc (sess);
2934     rtp_source_reset (own);
2935
2936     g_hash_table_insert (sess->ssrcs[sess->mask_idx],
2937         GINT_TO_POINTER (own->ssrc), own);
2938
2939     g_free (sess->bye_reason);
2940     sess->bye_reason = NULL;
2941     sess->sent_bye = FALSE;
2942     sess->change_ssrc = FALSE;
2943     notify = TRUE;
2944     GST_DEBUG ("changed our SSRC to %08x", own->ssrc);
2945   }
2946
2947   sess->allow_early = TRUE;
2948
2949   RTP_SESSION_UNLOCK (sess);
2950
2951   if (notify)
2952     g_object_notify (G_OBJECT (sess), "internal-ssrc");
2953
2954   /* push out the RTCP packet */
2955   if (data.rtcp) {
2956     gboolean do_not_suppress;
2957
2958     /* Give the user a change to add its own packet */
2959     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SENDING_RTCP], 0,
2960         data.rtcp, data.is_early, &do_not_suppress);
2961
2962     if (sess->callbacks.send_rtcp && (do_not_suppress || !data.may_suppress)) {
2963       guint packet_size;
2964
2965       /* close the RTCP packet */
2966       gst_rtcp_buffer_end (data.rtcp);
2967
2968       packet_size = GST_BUFFER_SIZE (data.rtcp) + sess->header_len;
2969
2970       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, packet_size);
2971       GST_DEBUG ("%p, sending RTCP packet, avg size %u, %u", &sess->stats,
2972           sess->stats.avg_rtcp_packet_size, packet_size);
2973       result =
2974           sess->callbacks.send_rtcp (sess, own, data.rtcp, sess->sent_bye,
2975           sess->send_rtcp_user_data);
2976     } else {
2977       GST_DEBUG ("freeing packet callback: %p"
2978           " do_not_suppress: %d may_suppress: %d",
2979           sess->callbacks.send_rtcp, do_not_suppress, data.may_suppress);
2980       gst_buffer_unref (data.rtcp);
2981     }
2982   }
2983
2984   return result;
2985 }
2986
2987 void
2988 rtp_session_request_early_rtcp (RTPSession * sess, GstClockTime current_time,
2989     GstClockTimeDiff max_delay)
2990 {
2991   GstClockTime T_dither_max;
2992
2993   /* Implements the algorithm described in RFC 4585 section 3.5.2 */
2994
2995   RTP_SESSION_LOCK (sess);
2996
2997   /* Check if already requested */
2998   /*  RFC 4585 section 3.5.2 step 2 */
2999   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
3000     goto dont_send;
3001
3002   /* Ignore the request a scheduled packet will be in time anyway */
3003   if (current_time + max_delay > sess->next_rtcp_check_time)
3004     goto dont_send;
3005
3006   /*  RFC 4585 section 3.5.2 step 2b */
3007   /* If the total sources is <=2, then there is only us and one peer */
3008   if (sess->total_sources <= 2) {
3009     T_dither_max = 0;
3010   } else {
3011     /* Divide by 2 because l = 0.5 */
3012     T_dither_max = sess->next_rtcp_check_time - sess->last_rtcp_send_time;
3013     T_dither_max /= 2;
3014   }
3015
3016   /*  RFC 4585 section 3.5.2 step 3 */
3017   if (current_time + T_dither_max > sess->next_rtcp_check_time)
3018     goto dont_send;
3019
3020   /*  RFC 4585 section 3.5.2 step 4 */
3021   if (sess->allow_early == FALSE)
3022     goto dont_send;
3023
3024   if (T_dither_max) {
3025     /* Schedule an early transmission later */
3026     sess->next_early_rtcp_time = g_random_double () * T_dither_max +
3027         current_time;
3028   } else {
3029     /* If no dithering, schedule it for NOW */
3030     sess->next_early_rtcp_time = current_time;
3031   }
3032
3033   RTP_SESSION_UNLOCK (sess);
3034
3035   /* notify app of need to send packet early
3036    * and therefore of timeout change */
3037   if (sess->callbacks.reconsider)
3038     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
3039
3040   return;
3041
3042 dont_send:
3043
3044   RTP_SESSION_UNLOCK (sess);
3045
3046 }
3047
3048 void
3049 rtp_session_request_key_unit (RTPSession * sess, guint32 ssrc, gboolean fir)
3050 {
3051   guint i;
3052
3053   if (fir)
3054     return;
3055
3056   for (i = 0; i < sess->rtcp_pli_requests->len; i++)
3057     if (ssrc == g_array_index (sess->rtcp_pli_requests, guint32, i))
3058       return;
3059
3060   g_array_append_val (sess->rtcp_pli_requests, ssrc);
3061 }
3062
3063 static gboolean
3064 has_pli_compare_func (gconstpointer a, gconstpointer ignored)
3065 {
3066   GstRTCPPacket packet;
3067
3068   packet.buffer = (GstBuffer *) a;
3069   packet.offset = 0;
3070
3071   if (gst_rtcp_packet_get_type (&packet) == GST_RTCP_TYPE_PSFB &&
3072       gst_rtcp_packet_fb_get_type (&packet) == GST_RTCP_PSFB_TYPE_PLI)
3073     return TRUE;
3074   else
3075     return FALSE;
3076 }
3077
3078 static gboolean
3079 rtp_session_on_sending_rtcp (RTPSession * sess, GstBuffer * buffer,
3080     gboolean early)
3081 {
3082   gboolean ret = FALSE;
3083
3084   RTP_SESSION_LOCK (sess);
3085
3086   while (sess->rtcp_pli_requests->len) {
3087     GstRTCPPacket rtcppacket;
3088     guint media_ssrc = g_array_index (sess->rtcp_pli_requests, guint32, 0);
3089     RTPSource *media_src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
3090         GUINT_TO_POINTER (media_ssrc));
3091
3092     if (media_src && !rtp_source_has_retained (media_src,
3093             has_pli_compare_func, NULL)) {
3094       if (gst_rtcp_buffer_add_packet (buffer, GST_RTCP_TYPE_PSFB, &rtcppacket)) {
3095         gst_rtcp_packet_fb_set_type (&rtcppacket, GST_RTCP_PSFB_TYPE_PLI);
3096         gst_rtcp_packet_fb_set_sender_ssrc (&rtcppacket,
3097             rtp_source_get_ssrc (sess->source));
3098         gst_rtcp_packet_fb_set_media_ssrc (&rtcppacket, media_ssrc);
3099         ret = TRUE;
3100       } else {
3101         /* Break because the packet is full, will put next request in a
3102          * further packet
3103          */
3104         break;
3105       }
3106     }
3107
3108     g_array_remove_index (sess->rtcp_pli_requests, 0);
3109   }
3110
3111   RTP_SESSION_UNLOCK (sess);
3112
3113   return ret;
3114 }