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