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