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