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