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