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