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