rtpsession: don't use invalid times in RTCP timeouts
[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 (sess->next_rtcp_check_time != GST_CLOCK_TIME_NONE &&
2071           arrival->current_time < sess->next_rtcp_check_time) {
2072         GstClockTime time_remaining;
2073
2074         time_remaining = sess->next_rtcp_check_time - arrival->current_time;
2075         sess->next_rtcp_check_time =
2076             gst_util_uint64_scale (time_remaining, members, pmembers);
2077
2078         GST_DEBUG ("reverse reconsideration %" GST_TIME_FORMAT,
2079             GST_TIME_ARGS (sess->next_rtcp_check_time));
2080
2081         sess->next_rtcp_check_time += arrival->current_time;
2082
2083         /* mark pending reconsider. We only want to signal the reconsideration
2084          * once after we handled all the source in the bye packet */
2085         reconsider = TRUE;
2086       }
2087     }
2088
2089     if (created)
2090       on_new_ssrc (sess, source);
2091
2092     on_bye_ssrc (sess, source);
2093
2094     g_object_unref (source);
2095   }
2096   if (reconsider) {
2097     RTP_SESSION_UNLOCK (sess);
2098     /* notify app of reconsideration */
2099     if (sess->callbacks.reconsider)
2100       sess->callbacks.reconsider (sess, sess->reconsider_user_data);
2101     RTP_SESSION_LOCK (sess);
2102   }
2103   g_free (reason);
2104 }
2105
2106 static void
2107 rtp_session_process_app (RTPSession * sess, GstRTCPPacket * packet,
2108     RTPArrivalStats * arrival)
2109 {
2110   GST_DEBUG ("received APP");
2111 }
2112
2113 static gboolean
2114 rtp_session_request_local_key_unit (RTPSession * sess, RTPSource * src,
2115     gboolean fir, GstClockTime current_time)
2116 {
2117   guint32 round_trip = 0;
2118
2119   rtp_source_get_last_rb (src, NULL, NULL, NULL, NULL, NULL, NULL, &round_trip);
2120
2121   if (sess->last_keyframe_request != GST_CLOCK_TIME_NONE && round_trip) {
2122     GstClockTime round_trip_in_ns = gst_util_uint64_scale (round_trip,
2123         GST_SECOND, 65536);
2124
2125     if (sess->last_keyframe_request != GST_CLOCK_TIME_NONE &&
2126         current_time - sess->last_keyframe_request < 2 * round_trip_in_ns) {
2127       GST_DEBUG ("Ignoring %s request because one was send without one "
2128           "RTT (%" GST_TIME_FORMAT " < %" GST_TIME_FORMAT ")",
2129           fir ? "FIR" : "PLI",
2130           GST_TIME_ARGS (current_time - sess->last_keyframe_request),
2131           GST_TIME_ARGS (round_trip_in_ns));;
2132       return FALSE;
2133     }
2134   }
2135
2136   sess->last_keyframe_request = current_time;
2137
2138   GST_LOG ("received %s request from %X %p(%p)", fir ? "FIR" : "PLI",
2139       rtp_source_get_ssrc (src), sess->callbacks.process_rtp,
2140       sess->callbacks.request_key_unit);
2141
2142   RTP_SESSION_UNLOCK (sess);
2143   sess->callbacks.request_key_unit (sess, fir,
2144       sess->request_key_unit_user_data);
2145   RTP_SESSION_LOCK (sess);
2146
2147   return TRUE;
2148 }
2149
2150 static void
2151 rtp_session_process_pli (RTPSession * sess, guint32 sender_ssrc,
2152     guint32 media_ssrc, GstClockTime current_time)
2153 {
2154   RTPSource *src;
2155
2156   if (!sess->callbacks.request_key_unit)
2157     return;
2158
2159   src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
2160       GINT_TO_POINTER (sender_ssrc));
2161   if (!src)
2162     return;
2163
2164   rtp_session_request_local_key_unit (sess, src, FALSE, current_time);
2165 }
2166
2167 static void
2168 rtp_session_process_fir (RTPSession * sess, guint32 sender_ssrc,
2169     guint8 * fci_data, guint fci_length, GstClockTime current_time)
2170 {
2171   RTPSource *src;
2172   guint32 ssrc;
2173   guint position = 0;
2174   gboolean our_request = FALSE;
2175
2176   if (!sess->callbacks.request_key_unit)
2177     return;
2178
2179   if (fci_length < 8)
2180     return;
2181
2182   src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
2183       GINT_TO_POINTER (sender_ssrc));
2184
2185   /* Hack because Google fails to set the sender_ssrc correctly */
2186   if (!src && sender_ssrc == 1) {
2187     GHashTableIter iter;
2188
2189     if (sess->stats.sender_sources >
2190         RTP_SOURCE_IS_SENDER (sess->source) ? 2 : 1)
2191       return;
2192
2193     g_hash_table_iter_init (&iter, sess->ssrcs[sess->mask_idx]);
2194
2195     while (g_hash_table_iter_next (&iter, NULL, (gpointer *) & src)) {
2196       if (src != sess->source && rtp_source_is_sender (src))
2197         break;
2198       src = NULL;
2199     }
2200   }
2201
2202   if (!src)
2203     return;
2204
2205   for (position = 0; position < fci_length; position += 8) {
2206     guint8 *data = fci_data + position;
2207
2208     ssrc = GST_READ_UINT32_BE (data);
2209
2210     if (ssrc == rtp_source_get_ssrc (sess->source)) {
2211       our_request = TRUE;
2212       break;
2213     }
2214   }
2215   if (!our_request)
2216     return;
2217
2218   rtp_session_request_local_key_unit (sess, src, TRUE, current_time);
2219 }
2220
2221 static void
2222 rtp_session_process_feedback (RTPSession * sess, GstRTCPPacket * packet,
2223     RTPArrivalStats * arrival, GstClockTime current_time)
2224 {
2225   GstRTCPType type = gst_rtcp_packet_get_type (packet);
2226   GstRTCPFBType fbtype = gst_rtcp_packet_fb_get_type (packet);
2227   guint32 sender_ssrc = gst_rtcp_packet_fb_get_sender_ssrc (packet);
2228   guint32 media_ssrc = gst_rtcp_packet_fb_get_media_ssrc (packet);
2229   guint8 *fci_data = gst_rtcp_packet_fb_get_fci (packet);
2230   guint fci_length = 4 * gst_rtcp_packet_fb_get_fci_length (packet);
2231
2232   GST_DEBUG ("received feedback %d:%d from %08X about %08X with FCI of "
2233       "length %d", type, fbtype, sender_ssrc, media_ssrc, fci_length);
2234
2235   if (g_signal_has_handler_pending (sess,
2236           rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0, TRUE)) {
2237     GstBuffer *fci_buffer = NULL;
2238
2239     if (fci_length > 0) {
2240       fci_buffer = gst_buffer_copy_region (packet->rtcp->buffer,
2241           GST_BUFFER_COPY_MEMORY, fci_data - packet->rtcp->map.data,
2242           fci_length);
2243       GST_BUFFER_TIMESTAMP (fci_buffer) = arrival->running_time;
2244     }
2245
2246     RTP_SESSION_UNLOCK (sess);
2247     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_FEEDBACK_RTCP], 0,
2248         type, fbtype, sender_ssrc, media_ssrc, fci_buffer);
2249     RTP_SESSION_LOCK (sess);
2250
2251     if (fci_buffer)
2252       gst_buffer_unref (fci_buffer);
2253   }
2254
2255   if (sess->rtcp_feedback_retention_window) {
2256     RTPSource *src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
2257         GINT_TO_POINTER (media_ssrc));
2258
2259     if (src)
2260       rtp_source_retain_rtcp_packet (src, packet, arrival->running_time);
2261   }
2262
2263   if (rtp_source_get_ssrc (sess->source) == media_ssrc ||
2264       /* PSFB FIR puts the media ssrc inside the FCI */
2265       (type == GST_RTCP_TYPE_PSFB && fbtype == GST_RTCP_PSFB_TYPE_FIR)) {
2266     switch (type) {
2267       case GST_RTCP_TYPE_PSFB:
2268         switch (fbtype) {
2269           case GST_RTCP_PSFB_TYPE_PLI:
2270             rtp_session_process_pli (sess, sender_ssrc, media_ssrc,
2271                 current_time);
2272             break;
2273           case GST_RTCP_PSFB_TYPE_FIR:
2274             rtp_session_process_fir (sess, sender_ssrc, fci_data, fci_length,
2275                 current_time);
2276             break;
2277           default:
2278             break;
2279         }
2280         break;
2281       case GST_RTCP_TYPE_RTPFB:
2282       default:
2283         break;
2284     }
2285   }
2286 }
2287
2288 /**
2289  * rtp_session_process_rtcp:
2290  * @sess: and #RTPSession
2291  * @buffer: an RTCP buffer
2292  * @current_time: the current system time
2293  * @ntpnstime: the current NTP time in nanoseconds
2294  *
2295  * Process an RTCP buffer in the session manager. This function takes ownership
2296  * of @buffer.
2297  *
2298  * Returns: a #GstFlowReturn.
2299  */
2300 GstFlowReturn
2301 rtp_session_process_rtcp (RTPSession * sess, GstBuffer * buffer,
2302     GstClockTime current_time, guint64 ntpnstime)
2303 {
2304   GstRTCPPacket packet;
2305   gboolean more, is_bye = FALSE, do_sync = FALSE;
2306   RTPArrivalStats arrival = { NULL, };
2307   GstFlowReturn result = GST_FLOW_OK;
2308   GstRTCPBuffer rtcp = { NULL, };
2309
2310   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2311   g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
2312
2313   if (!gst_rtcp_buffer_validate (buffer))
2314     goto invalid_packet;
2315
2316   GST_DEBUG ("received RTCP packet");
2317
2318   RTP_SESSION_LOCK (sess);
2319   /* update arrival stats */
2320   update_arrival_stats (sess, &arrival, FALSE, buffer, current_time, -1,
2321       ntpnstime);
2322
2323   if (sess->sent_bye)
2324     goto ignore;
2325
2326   /* start processing the compound packet */
2327   gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
2328   more = gst_rtcp_buffer_get_first_packet (&rtcp, &packet);
2329   while (more) {
2330     GstRTCPType type;
2331
2332     type = gst_rtcp_packet_get_type (&packet);
2333
2334     /* when we are leaving the session, we should ignore all non-BYE messages */
2335     if (sess->source->received_bye && type != GST_RTCP_TYPE_BYE) {
2336       GST_DEBUG ("ignoring non-BYE RTCP packet because we are leaving");
2337       goto next;
2338     }
2339
2340     switch (type) {
2341       case GST_RTCP_TYPE_SR:
2342         rtp_session_process_sr (sess, &packet, &arrival, &do_sync);
2343         break;
2344       case GST_RTCP_TYPE_RR:
2345         rtp_session_process_rr (sess, &packet, &arrival);
2346         break;
2347       case GST_RTCP_TYPE_SDES:
2348         rtp_session_process_sdes (sess, &packet, &arrival);
2349         break;
2350       case GST_RTCP_TYPE_BYE:
2351         is_bye = TRUE;
2352         /* don't try to attempt lip-sync anymore for streams with a BYE */
2353         do_sync = FALSE;
2354         rtp_session_process_bye (sess, &packet, &arrival);
2355         break;
2356       case GST_RTCP_TYPE_APP:
2357         rtp_session_process_app (sess, &packet, &arrival);
2358         break;
2359       case GST_RTCP_TYPE_RTPFB:
2360       case GST_RTCP_TYPE_PSFB:
2361         rtp_session_process_feedback (sess, &packet, &arrival, current_time);
2362         break;
2363       default:
2364         GST_WARNING ("got unknown RTCP packet");
2365         break;
2366     }
2367   next:
2368     more = gst_rtcp_packet_move_to_next (&packet);
2369   }
2370
2371   gst_rtcp_buffer_unmap (&rtcp);
2372
2373   /* if we are scheduling a BYE, we only want to count bye packets, else we
2374    * count everything */
2375   if (sess->source->received_bye) {
2376     if (is_bye) {
2377       sess->stats.bye_members++;
2378       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, arrival.bytes);
2379     }
2380   } else {
2381     /* keep track of average packet size */
2382     UPDATE_AVG (sess->stats.avg_rtcp_packet_size, arrival.bytes);
2383   }
2384   GST_DEBUG ("%p, received RTCP packet, avg size %u, %u", &sess->stats,
2385       sess->stats.avg_rtcp_packet_size, arrival.bytes);
2386   RTP_SESSION_UNLOCK (sess);
2387
2388   clean_arrival_stats (&arrival);
2389
2390   /* notify caller of sr packets in the callback */
2391   if (do_sync && sess->callbacks.sync_rtcp) {
2392     /* make writable, we might want to change the buffer */
2393     buffer = gst_buffer_make_writable (buffer);
2394
2395     result = sess->callbacks.sync_rtcp (sess, sess->source, buffer,
2396         sess->sync_rtcp_user_data);
2397   } else
2398     gst_buffer_unref (buffer);
2399
2400   return result;
2401
2402   /* ERRORS */
2403 invalid_packet:
2404   {
2405     GST_DEBUG ("invalid RTCP packet received");
2406     gst_buffer_unref (buffer);
2407     return GST_FLOW_OK;
2408   }
2409 ignore:
2410   {
2411     RTP_SESSION_UNLOCK (sess);
2412     gst_buffer_unref (buffer);
2413     clean_arrival_stats (&arrival);
2414     GST_DEBUG ("ignoring RTCP packet because we left");
2415     return GST_FLOW_OK;
2416   }
2417 }
2418
2419 /**
2420  * rtp_session_update_send_caps:
2421  * @sess: an #RTPSession
2422  * @caps: a #GstCaps
2423  *
2424  * Update the caps of the sender in the rtp session.
2425  */
2426 void
2427 rtp_session_update_send_caps (RTPSession * sess, GstCaps * caps)
2428 {
2429   g_return_if_fail (RTP_IS_SESSION (sess));
2430   g_return_if_fail (GST_IS_CAPS (caps));
2431
2432   GST_LOG ("received caps %" GST_PTR_FORMAT, caps);
2433
2434   RTP_SESSION_LOCK (sess);
2435   rtp_source_update_caps (sess->source, caps);
2436   RTP_SESSION_UNLOCK (sess);
2437 }
2438
2439 /**
2440  * rtp_session_send_rtp:
2441  * @sess: an #RTPSession
2442  * @data: pointer to either an RTP buffer or a list of RTP buffers
2443  * @is_list: TRUE when @data is a buffer list
2444  * @current_time: the current system time
2445  * @running_time: the running time of @data
2446  *
2447  * Send the RTP buffer in the session manager. This function takes ownership of
2448  * @buffer.
2449  *
2450  * Returns: a #GstFlowReturn.
2451  */
2452 GstFlowReturn
2453 rtp_session_send_rtp (RTPSession * sess, gpointer data, gboolean is_list,
2454     GstClockTime current_time, GstClockTime running_time)
2455 {
2456   GstFlowReturn result;
2457   RTPSource *source;
2458   gboolean prevsender;
2459   guint64 oldrate;
2460
2461   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2462   g_return_val_if_fail (is_list || GST_IS_BUFFER (data), GST_FLOW_ERROR);
2463
2464   GST_LOG ("received RTP %s for sending", is_list ? "list" : "packet");
2465
2466   RTP_SESSION_LOCK (sess);
2467   source = sess->source;
2468
2469   /* update last activity */
2470   source->last_rtp_activity = current_time;
2471
2472   prevsender = RTP_SOURCE_IS_SENDER (source);
2473   oldrate = source->bitrate;
2474
2475   /* we use our own source to send */
2476   result = rtp_source_send_rtp (source, data, is_list, running_time);
2477
2478   if (RTP_SOURCE_IS_SENDER (source) && !prevsender)
2479     sess->stats.sender_sources++;
2480   if (oldrate != source->bitrate)
2481     sess->recalc_bandwidth = TRUE;
2482   RTP_SESSION_UNLOCK (sess);
2483
2484   return result;
2485 }
2486
2487 static void
2488 add_bitrates (gpointer key, RTPSource * source, gdouble * bandwidth)
2489 {
2490   *bandwidth += source->bitrate;
2491 }
2492
2493 /* must be called with session lock */
2494 static GstClockTime
2495 calculate_rtcp_interval (RTPSession * sess, gboolean deterministic,
2496     gboolean first)
2497 {
2498   GstClockTime result;
2499
2500   /* recalculate bandwidth when it changed */
2501   if (sess->recalc_bandwidth) {
2502     gdouble bandwidth;
2503
2504     if (sess->bandwidth > 0)
2505       bandwidth = sess->bandwidth;
2506     else {
2507       /* If it is <= 0, then try to estimate the actual bandwidth */
2508       bandwidth = sess->source->bitrate;
2509
2510       g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
2511           (GHFunc) add_bitrates, &bandwidth);
2512       bandwidth /= 8.0;
2513     }
2514     if (bandwidth < 8000)
2515       bandwidth = RTP_STATS_BANDWIDTH;
2516
2517     rtp_stats_set_bandwidths (&sess->stats, bandwidth,
2518         sess->rtcp_bandwidth, sess->rtcp_rs_bandwidth, sess->rtcp_rr_bandwidth);
2519
2520     sess->recalc_bandwidth = FALSE;
2521   }
2522
2523   if (sess->source->received_bye) {
2524     result = rtp_stats_calculate_bye_interval (&sess->stats);
2525   } else {
2526     result = rtp_stats_calculate_rtcp_interval (&sess->stats,
2527         RTP_SOURCE_IS_SENDER (sess->source), first);
2528   }
2529
2530   GST_DEBUG ("next deterministic interval: %" GST_TIME_FORMAT ", first %d",
2531       GST_TIME_ARGS (result), first);
2532
2533   if (!deterministic && result != GST_CLOCK_TIME_NONE)
2534     result = rtp_stats_add_rtcp_jitter (&sess->stats, result);
2535
2536   GST_DEBUG ("next interval: %" GST_TIME_FORMAT, GST_TIME_ARGS (result));
2537
2538   return result;
2539 }
2540
2541 /* Stop the current @sess and schedule a BYE message for the other members.
2542  * One must have the session lock to call this function
2543  */
2544 static GstFlowReturn
2545 rtp_session_schedule_bye_locked (RTPSession * sess, const gchar * reason,
2546     GstClockTime current_time)
2547 {
2548   GstFlowReturn result = GST_FLOW_OK;
2549   RTPSource *source;
2550   GstClockTime interval;
2551
2552   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2553
2554   source = sess->source;
2555
2556   /* ignore more BYEs */
2557   if (source->received_bye)
2558     goto done;
2559
2560   /* we have BYE now */
2561   source->received_bye = TRUE;
2562   /* at least one member wants to send a BYE */
2563   g_free (sess->bye_reason);
2564   sess->bye_reason = g_strdup (reason);
2565   INIT_AVG (sess->stats.avg_rtcp_packet_size, 100);
2566   sess->stats.bye_members = 1;
2567   sess->first_rtcp = TRUE;
2568   sess->sent_bye = FALSE;
2569   sess->allow_early = TRUE;
2570
2571   /* reschedule transmission */
2572   sess->last_rtcp_send_time = current_time;
2573   interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2574
2575   if (interval != GST_CLOCK_TIME_NONE)
2576     sess->next_rtcp_check_time = current_time + interval;
2577   else
2578     sess->next_rtcp_check_time = GST_CLOCK_TIME_NONE;
2579
2580   GST_DEBUG ("Schedule BYE for %" GST_TIME_FORMAT ", %" GST_TIME_FORMAT,
2581       GST_TIME_ARGS (interval), GST_TIME_ARGS (sess->next_rtcp_check_time));
2582
2583   RTP_SESSION_UNLOCK (sess);
2584   /* notify app of reconsideration */
2585   if (sess->callbacks.reconsider)
2586     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
2587   RTP_SESSION_LOCK (sess);
2588 done:
2589
2590   return result;
2591 }
2592
2593 /**
2594  * rtp_session_schedule_bye:
2595  * @sess: an #RTPSession
2596  * @reason: a reason or NULL
2597  * @current_time: the current system time
2598  *
2599  * Stop the current @sess and schedule a BYE message for the other members.
2600  *
2601  * Returns: a #GstFlowReturn.
2602  */
2603 GstFlowReturn
2604 rtp_session_schedule_bye (RTPSession * sess, const gchar * reason,
2605     GstClockTime current_time)
2606 {
2607   GstFlowReturn result = GST_FLOW_OK;
2608
2609   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
2610
2611   RTP_SESSION_LOCK (sess);
2612   result = rtp_session_schedule_bye_locked (sess, reason, current_time);
2613   RTP_SESSION_UNLOCK (sess);
2614
2615   return result;
2616 }
2617
2618 /**
2619  * rtp_session_next_timeout:
2620  * @sess: an #RTPSession
2621  * @current_time: the current system time
2622  *
2623  * Get the next time we should perform session maintenance tasks.
2624  *
2625  * Returns: a time when rtp_session_on_timeout() should be called with the
2626  * current system time.
2627  */
2628 GstClockTime
2629 rtp_session_next_timeout (RTPSession * sess, GstClockTime current_time)
2630 {
2631   GstClockTime result, interval = 0;
2632
2633   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_CLOCK_TIME_NONE);
2634
2635   RTP_SESSION_LOCK (sess);
2636
2637   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time)) {
2638     result = sess->next_early_rtcp_time;
2639     goto early_exit;
2640   }
2641
2642   result = sess->next_rtcp_check_time;
2643
2644   GST_DEBUG ("current time: %" GST_TIME_FORMAT
2645       ", next time: %" GST_TIME_FORMAT,
2646       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
2647
2648   if (result == GST_CLOCK_TIME_NONE || result < current_time) {
2649     GST_DEBUG ("take current time as base");
2650     /* our previous check time expired, start counting from the current time
2651      * again. */
2652     result = current_time;
2653   }
2654
2655   if (sess->source->received_bye) {
2656     if (sess->sent_bye) {
2657       GST_DEBUG ("we sent BYE already");
2658       interval = GST_CLOCK_TIME_NONE;
2659     } else if (sess->stats.active_sources >= 50) {
2660       GST_DEBUG ("reconsider BYE, more than 50 sources");
2661       /* reconsider BYE if members >= 50 */
2662       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2663     }
2664   } else {
2665     if (sess->first_rtcp) {
2666       GST_DEBUG ("first RTCP packet");
2667       /* we are called for the first time */
2668       interval = calculate_rtcp_interval (sess, FALSE, TRUE);
2669     } else if (sess->next_rtcp_check_time < current_time) {
2670       GST_DEBUG ("old check time expired, getting new timeout");
2671       /* get a new timeout when we need to */
2672       interval = calculate_rtcp_interval (sess, FALSE, FALSE);
2673     }
2674   }
2675
2676   if (interval != GST_CLOCK_TIME_NONE)
2677     result += interval;
2678   else
2679     result = GST_CLOCK_TIME_NONE;
2680
2681   sess->next_rtcp_check_time = result;
2682
2683 early_exit:
2684
2685   GST_DEBUG ("current time: %" GST_TIME_FORMAT
2686       ", next time: %" GST_TIME_FORMAT,
2687       GST_TIME_ARGS (current_time), GST_TIME_ARGS (result));
2688   RTP_SESSION_UNLOCK (sess);
2689
2690   return result;
2691 }
2692
2693 typedef struct
2694 {
2695   GstRTCPBuffer rtcpbuf;
2696   RTPSession *sess;
2697   GstBuffer *rtcp;
2698   GstClockTime current_time;
2699   guint64 ntpnstime;
2700   GstClockTime running_time;
2701   GstClockTime interval;
2702   GstRTCPPacket packet;
2703   gboolean is_bye;
2704   gboolean has_sdes;
2705   gboolean is_early;
2706   gboolean may_suppress;
2707 } ReportData;
2708
2709 static void
2710 session_start_rtcp (RTPSession * sess, ReportData * data)
2711 {
2712   GstRTCPPacket *packet = &data->packet;
2713   RTPSource *own = sess->source;
2714   GstRTCPBuffer *rtcp = &data->rtcpbuf;
2715
2716   data->rtcp = gst_rtcp_buffer_new (sess->mtu);
2717
2718   gst_rtcp_buffer_map (data->rtcp, GST_MAP_READWRITE, rtcp);
2719
2720   if (RTP_SOURCE_IS_SENDER (own)) {
2721     guint64 ntptime;
2722     guint32 rtptime;
2723     guint32 packet_count, octet_count;
2724
2725     /* we are a sender, create SR */
2726     GST_DEBUG ("create SR for SSRC %08x", own->ssrc);
2727     gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_SR, packet);
2728
2729     /* get latest stats */
2730     rtp_source_get_new_sr (own, data->ntpnstime, data->running_time,
2731         &ntptime, &rtptime, &packet_count, &octet_count);
2732     /* store stats */
2733     rtp_source_process_sr (own, data->current_time, ntptime, rtptime,
2734         packet_count, octet_count);
2735
2736     /* fill in sender report info */
2737     gst_rtcp_packet_sr_set_sender_info (packet, own->ssrc,
2738         ntptime, rtptime, packet_count, octet_count);
2739   } else {
2740     /* we are only receiver, create RR */
2741     GST_DEBUG ("create RR for SSRC %08x", own->ssrc);
2742     gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_RR, packet);
2743     gst_rtcp_packet_rr_set_ssrc (packet, own->ssrc);
2744   }
2745 }
2746
2747 /* construct a Sender or Receiver Report */
2748 static void
2749 session_report_blocks (const gchar * key, RTPSource * source, ReportData * data)
2750 {
2751   RTPSession *sess = data->sess;
2752   GstRTCPPacket *packet = &data->packet;
2753
2754   /* create a new buffer if needed */
2755   if (data->rtcp == NULL) {
2756     session_start_rtcp (sess, data);
2757   } else if (data->is_early) {
2758     /* Put a single RR or SR in minimal compound packets */
2759     return;
2760   }
2761   if (gst_rtcp_packet_get_rb_count (packet) < GST_RTCP_MAX_RB_COUNT) {
2762     /* only report about other sender sources */
2763     if (source != sess->source && RTP_SOURCE_IS_SENDER (source)) {
2764       guint8 fractionlost;
2765       gint32 packetslost;
2766       guint32 exthighestseq, jitter;
2767       guint32 lsr, dlsr;
2768
2769       /* get new stats */
2770       rtp_source_get_new_rb (source, data->current_time, &fractionlost,
2771           &packetslost, &exthighestseq, &jitter, &lsr, &dlsr);
2772
2773       /* store last generated RR packet */
2774       source->last_rr.is_valid = TRUE;
2775       source->last_rr.fractionlost = fractionlost;
2776       source->last_rr.packetslost = packetslost;
2777       source->last_rr.exthighestseq = exthighestseq;
2778       source->last_rr.jitter = jitter;
2779       source->last_rr.lsr = lsr;
2780       source->last_rr.dlsr = dlsr;
2781
2782       /* packet is not yet filled, add report block for this source. */
2783       gst_rtcp_packet_add_rb (packet, source->ssrc, fractionlost, packetslost,
2784           exthighestseq, jitter, lsr, dlsr);
2785     }
2786   }
2787 }
2788
2789 /* perform cleanup of sources that timed out */
2790 static void
2791 session_cleanup (const gchar * key, RTPSource * source, ReportData * data)
2792 {
2793   gboolean remove = FALSE;
2794   gboolean byetimeout = FALSE;
2795   gboolean sendertimeout = FALSE;
2796   gboolean is_sender, is_active;
2797   RTPSession *sess = data->sess;
2798   GstClockTime interval, binterval;
2799   GstClockTime btime;
2800
2801   is_sender = RTP_SOURCE_IS_SENDER (source);
2802   is_active = RTP_SOURCE_IS_ACTIVE (source);
2803
2804   /* nothing to do when without RTCP */
2805   if (data->interval == GST_CLOCK_TIME_NONE)
2806     return;
2807
2808   /* our own rtcp interval may have been forced low by secondary configuration,
2809    * while sender side may still operate with higher interval,
2810    * so do not just take our interval to decide on timing out sender,
2811    * but take (if data->interval <= 5 * GST_SECOND):
2812    *   interval = CLAMP (sender_interval, data->interval, 5 * GST_SECOND)
2813    * where sender_interval is difference between last 2 received RTCP reports
2814    */
2815   if (data->interval >= 5 * GST_SECOND || (source == sess->source)) {
2816     binterval = data->interval;
2817   } else {
2818     GST_LOG ("prev_rtcp %" GST_TIME_FORMAT ", last_rtcp %" GST_TIME_FORMAT,
2819         GST_TIME_ARGS (source->stats.prev_rtcptime),
2820         GST_TIME_ARGS (source->stats.last_rtcptime));
2821     /* if not received enough yet, fallback to larger default */
2822     if (source->stats.last_rtcptime > source->stats.prev_rtcptime)
2823       binterval = source->stats.last_rtcptime - source->stats.prev_rtcptime;
2824     else
2825       binterval = 5 * GST_SECOND;
2826     binterval = CLAMP (binterval, data->interval, 5 * GST_SECOND);
2827   }
2828   GST_LOG ("timeout base interval %" GST_TIME_FORMAT,
2829       GST_TIME_ARGS (binterval));
2830
2831   /* check for our own source, we don't want to delete our own source. */
2832   if (!(source == sess->source)) {
2833     if (source->received_bye) {
2834       /* if we received a BYE from the source, remove the source after some
2835        * time. */
2836       if (data->current_time > source->bye_time &&
2837           data->current_time - source->bye_time > sess->stats.bye_timeout) {
2838         GST_DEBUG ("removing BYE source %08x", source->ssrc);
2839         remove = TRUE;
2840         byetimeout = TRUE;
2841       }
2842     }
2843     /* sources that were inactive for more than 5 times the deterministic reporting
2844      * interval get timed out. the min timeout is 5 seconds. */
2845     /* mind old time that might pre-date last time going to PLAYING */
2846     btime = MAX (source->last_activity, sess->start_time);
2847     if (data->current_time > btime) {
2848       interval = MAX (binterval * 5, 5 * GST_SECOND);
2849       if (data->current_time - btime > interval) {
2850         GST_DEBUG ("removing timeout source %08x, last %" GST_TIME_FORMAT,
2851             source->ssrc, GST_TIME_ARGS (btime));
2852         remove = TRUE;
2853       }
2854     }
2855   }
2856
2857   /* senders that did not send for a long time become a receiver, this also
2858    * holds for our own source. */
2859   if (is_sender) {
2860     /* mind old time that might pre-date last time going to PLAYING */
2861     btime = MAX (source->last_rtp_activity, sess->start_time);
2862     if (data->current_time > btime) {
2863       interval = MAX (binterval * 2, 5 * GST_SECOND);
2864       if (data->current_time - btime > interval) {
2865         GST_DEBUG ("sender source %08x timed out and became receiver, last %"
2866             GST_TIME_FORMAT, source->ssrc, GST_TIME_ARGS (btime));
2867         source->is_sender = FALSE;
2868         sess->stats.sender_sources--;
2869         sendertimeout = TRUE;
2870       }
2871     }
2872   }
2873
2874   if (remove) {
2875     sess->total_sources--;
2876     if (is_sender)
2877       sess->stats.sender_sources--;
2878     if (is_active)
2879       sess->stats.active_sources--;
2880
2881     if (byetimeout)
2882       on_bye_timeout (sess, source);
2883     else
2884       on_timeout (sess, source);
2885   } else {
2886     if (sendertimeout)
2887       on_sender_timeout (sess, source);
2888   }
2889
2890   source->closing = remove;
2891 }
2892
2893 static void
2894 session_sdes (RTPSession * sess, ReportData * data)
2895 {
2896   GstRTCPPacket *packet = &data->packet;
2897   const GstStructure *sdes;
2898   gint i, n_fields;
2899   GstRTCPBuffer *rtcp = &data->rtcpbuf;
2900
2901   /* add SDES packet */
2902   gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_SDES, packet);
2903
2904   gst_rtcp_packet_sdes_add_item (packet, sess->source->ssrc);
2905
2906   sdes = rtp_source_get_sdes_struct (sess->source);
2907
2908   /* add all fields in the structure, the order is not important. */
2909   n_fields = gst_structure_n_fields (sdes);
2910   for (i = 0; i < n_fields; ++i) {
2911     const gchar *field;
2912     const gchar *value;
2913     GstRTCPSDESType type;
2914
2915     field = gst_structure_nth_field_name (sdes, i);
2916     if (field == NULL)
2917       continue;
2918     value = gst_structure_get_string (sdes, field);
2919     if (value == NULL)
2920       continue;
2921     type = gst_rtcp_sdes_name_to_type (field);
2922
2923     /* Early packets are minimal and only include the CNAME */
2924     if (data->is_early && type != GST_RTCP_SDES_CNAME)
2925       continue;
2926
2927     if (type > GST_RTCP_SDES_END && type < GST_RTCP_SDES_PRIV) {
2928       gst_rtcp_packet_sdes_add_entry (packet, type, strlen (value),
2929           (const guint8 *) value);
2930     } else if (type == GST_RTCP_SDES_PRIV) {
2931       gsize prefix_len;
2932       gsize value_len;
2933       gsize data_len;
2934       guint8 data[256];
2935
2936       /* don't accept entries that are too big */
2937       prefix_len = strlen (field);
2938       if (prefix_len > 255)
2939         continue;
2940       value_len = strlen (value);
2941       if (value_len > 255)
2942         continue;
2943       data_len = 1 + prefix_len + value_len;
2944       if (data_len > 255)
2945         continue;
2946
2947       data[0] = prefix_len;
2948       memcpy (&data[1], field, prefix_len);
2949       memcpy (&data[1 + prefix_len], value, value_len);
2950
2951       gst_rtcp_packet_sdes_add_entry (packet, type, data_len, data);
2952     }
2953   }
2954
2955   data->has_sdes = TRUE;
2956 }
2957
2958 /* schedule a BYE packet */
2959 static void
2960 session_bye (RTPSession * sess, ReportData * data)
2961 {
2962   GstRTCPPacket *packet = &data->packet;
2963   GstRTCPBuffer *rtcp = &data->rtcpbuf;
2964
2965   /* open packet */
2966   session_start_rtcp (sess, data);
2967
2968   /* add SDES */
2969   session_sdes (sess, data);
2970
2971   /* add a BYE packet */
2972   gst_rtcp_buffer_add_packet (rtcp, GST_RTCP_TYPE_BYE, packet);
2973   gst_rtcp_packet_bye_add_ssrc (packet, sess->source->ssrc);
2974   if (sess->bye_reason)
2975     gst_rtcp_packet_bye_set_reason (packet, sess->bye_reason);
2976
2977   /* we have a BYE packet now */
2978   data->is_bye = TRUE;
2979 }
2980
2981 static gboolean
2982 is_rtcp_time (RTPSession * sess, GstClockTime current_time, ReportData * data)
2983 {
2984   GstClockTime new_send_time, elapsed;
2985
2986   if (data->is_early && sess->next_early_rtcp_time < current_time)
2987     goto early;
2988
2989   /* no need to check yet */
2990   if (sess->next_rtcp_check_time == GST_CLOCK_TIME_NONE ||
2991       sess->next_rtcp_check_time > current_time) {
2992     GST_DEBUG ("no check time yet, next %" GST_TIME_FORMAT " > now %"
2993         GST_TIME_FORMAT, GST_TIME_ARGS (sess->next_rtcp_check_time),
2994         GST_TIME_ARGS (current_time));
2995     return FALSE;
2996   }
2997
2998   /* get elapsed time since we last reported */
2999   elapsed = current_time - sess->last_rtcp_send_time;
3000
3001   new_send_time = data->interval;
3002   /* perform forward reconsideration */
3003   if (new_send_time != GST_CLOCK_TIME_NONE) {
3004     new_send_time = rtp_stats_add_rtcp_jitter (&sess->stats, new_send_time);
3005
3006     GST_DEBUG ("forward reconsideration %" GST_TIME_FORMAT ", elapsed %"
3007         GST_TIME_FORMAT, GST_TIME_ARGS (new_send_time),
3008         GST_TIME_ARGS (elapsed));
3009
3010     new_send_time += sess->last_rtcp_send_time;
3011   }
3012
3013   /* check if reconsideration */
3014   if (new_send_time == GST_CLOCK_TIME_NONE || current_time < new_send_time) {
3015     GST_DEBUG ("reconsider RTCP for %" GST_TIME_FORMAT,
3016         GST_TIME_ARGS (new_send_time));
3017     /* store new check time */
3018     sess->next_rtcp_check_time = new_send_time;
3019     return FALSE;
3020   }
3021
3022 early:
3023
3024   new_send_time = calculate_rtcp_interval (sess, FALSE, FALSE);
3025
3026   GST_DEBUG ("can send RTCP now, next interval %" GST_TIME_FORMAT,
3027       GST_TIME_ARGS (new_send_time));
3028
3029   sess->next_rtcp_check_time = new_send_time;
3030   if (new_send_time != GST_CLOCK_TIME_NONE) {
3031     sess->next_rtcp_check_time += current_time;
3032
3033     /* Apply the rules from RFC 4585 section 3.5.3 */
3034     if (sess->stats.min_interval != 0 && !sess->first_rtcp) {
3035       GstClockTimeDiff T_rr_current_interval =
3036           g_random_double_range (0.5, 1.5) * sess->stats.min_interval;
3037
3038       /* This will caused the RTCP to be suppressed if no FB packets are added */
3039       if (sess->last_rtcp_send_time + T_rr_current_interval >
3040           sess->next_rtcp_check_time) {
3041         GST_DEBUG ("RTCP packet could be suppressed min: %" GST_TIME_FORMAT
3042             " last: %" GST_TIME_FORMAT
3043             " + T_rr_current_interval: %" GST_TIME_FORMAT
3044             " >  sess->next_rtcp_check_time: %" GST_TIME_FORMAT,
3045             GST_TIME_ARGS (sess->stats.min_interval),
3046             GST_TIME_ARGS (sess->last_rtcp_send_time),
3047             GST_TIME_ARGS (T_rr_current_interval),
3048             GST_TIME_ARGS (sess->next_rtcp_check_time));
3049         data->may_suppress = TRUE;
3050       }
3051     }
3052   }
3053
3054   return TRUE;
3055 }
3056
3057 static void
3058 clone_ssrcs_hashtable (gchar * key, RTPSource * source, GHashTable * hash_table)
3059 {
3060   g_hash_table_insert (hash_table, key, g_object_ref (source));
3061 }
3062
3063 static gboolean
3064 remove_closing_sources (const gchar * key, RTPSource * source, gpointer * data)
3065 {
3066   return source->closing;
3067 }
3068
3069 /**
3070  * rtp_session_on_timeout:
3071  * @sess: an #RTPSession
3072  * @current_time: the current system time
3073  * @ntpnstime: the current NTP time in nanoseconds
3074  * @running_time: the current running_time of the pipeline
3075  *
3076  * Perform maintenance actions after the timeout obtained with
3077  * rtp_session_next_timeout() expired.
3078  *
3079  * This function will perform timeouts of receivers and senders, send a BYE
3080  * packet or generate RTCP packets with current session stats.
3081  *
3082  * This function can call the #RTPSessionSendRTCP callback, possibly multiple
3083  * times, for each packet that should be processed.
3084  *
3085  * Returns: a #GstFlowReturn.
3086  */
3087 GstFlowReturn
3088 rtp_session_on_timeout (RTPSession * sess, GstClockTime current_time,
3089     guint64 ntpnstime, GstClockTime running_time)
3090 {
3091   GstFlowReturn result = GST_FLOW_OK;
3092   ReportData data = { GST_RTCP_BUFFER_INIT };
3093   RTPSource *own;
3094   GHashTable *table_copy;
3095   gboolean notify = FALSE;
3096
3097   g_return_val_if_fail (RTP_IS_SESSION (sess), GST_FLOW_ERROR);
3098
3099   GST_DEBUG ("reporting at %" GST_TIME_FORMAT ", NTP time %" GST_TIME_FORMAT
3100       ", running-time %" GST_TIME_FORMAT, GST_TIME_ARGS (current_time),
3101       GST_TIME_ARGS (ntpnstime), GST_TIME_ARGS (running_time));
3102
3103   data.sess = sess;
3104   data.rtcp = NULL;
3105   data.current_time = current_time;
3106   data.ntpnstime = ntpnstime;
3107   data.is_bye = FALSE;
3108   data.has_sdes = FALSE;
3109   data.may_suppress = FALSE;
3110   data.running_time = running_time;
3111
3112   own = sess->source;
3113
3114   RTP_SESSION_LOCK (sess);
3115   /* get a new interval, we need this for various cleanups etc */
3116   data.interval = calculate_rtcp_interval (sess, TRUE, sess->first_rtcp);
3117
3118   /* Make a local copy of the hashtable. We need to do this because the
3119    * cleanup stage below releases the session lock. */
3120   table_copy = g_hash_table_new_full (NULL, NULL, NULL,
3121       (GDestroyNotify) g_object_unref);
3122   g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
3123       (GHFunc) clone_ssrcs_hashtable, table_copy);
3124
3125   /* Clean up the session, mark the source for removing, this might release the
3126    * session lock. */
3127   g_hash_table_foreach (table_copy, (GHFunc) session_cleanup, &data);
3128   g_hash_table_destroy (table_copy);
3129
3130   /* Now remove the marked sources */
3131   g_hash_table_foreach_remove (sess->ssrcs[sess->mask_idx],
3132       (GHRFunc) remove_closing_sources, NULL);
3133
3134   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
3135     data.is_early = TRUE;
3136   else
3137     data.is_early = FALSE;
3138
3139   /* see if we need to generate SR or RR packets */
3140   if (is_rtcp_time (sess, current_time, &data)) {
3141     if (own->received_bye) {
3142       /* generate BYE instead */
3143       GST_DEBUG ("generating BYE message");
3144       session_bye (sess, &data);
3145       sess->sent_bye = TRUE;
3146     } else {
3147       /* loop over all known sources and do something */
3148       g_hash_table_foreach (sess->ssrcs[sess->mask_idx],
3149           (GHFunc) session_report_blocks, &data);
3150     }
3151   }
3152
3153   if (data.rtcp) {
3154     /* we keep track of the last report time in order to timeout inactive
3155      * receivers or senders */
3156     if (!data.is_early && !data.may_suppress)
3157       sess->last_rtcp_send_time = data.current_time;
3158     sess->first_rtcp = FALSE;
3159     sess->next_early_rtcp_time = GST_CLOCK_TIME_NONE;
3160
3161     /* add SDES for this source when not already added */
3162     if (!data.has_sdes)
3163       session_sdes (sess, &data);
3164   }
3165
3166   /* check for outdated collisions */
3167   GST_DEBUG ("Timing out collisions");
3168   rtp_source_timeout (sess->source, current_time,
3169       /* "a relatively long time" -- RFC 3550 section 8.2 */
3170       RTP_STATS_MIN_INTERVAL * GST_SECOND * 10,
3171       running_time - sess->rtcp_feedback_retention_window);
3172
3173   if (sess->change_ssrc) {
3174     GST_DEBUG ("need to change our SSRC (%08x)", own->ssrc);
3175     g_hash_table_steal (sess->ssrcs[sess->mask_idx],
3176         GINT_TO_POINTER (own->ssrc));
3177
3178     own->ssrc = rtp_session_create_new_ssrc (sess);
3179     rtp_source_reset (own);
3180
3181     g_hash_table_insert (sess->ssrcs[sess->mask_idx],
3182         GINT_TO_POINTER (own->ssrc), own);
3183
3184     g_free (sess->bye_reason);
3185     sess->bye_reason = NULL;
3186     sess->sent_bye = FALSE;
3187     sess->change_ssrc = FALSE;
3188     notify = TRUE;
3189     GST_DEBUG ("changed our SSRC to %08x", own->ssrc);
3190   }
3191
3192   sess->allow_early = TRUE;
3193
3194   RTP_SESSION_UNLOCK (sess);
3195
3196   if (notify)
3197     g_object_notify (G_OBJECT (sess), "internal-ssrc");
3198
3199   /* push out the RTCP packet */
3200   if (data.rtcp) {
3201     gboolean do_not_suppress;
3202
3203     gst_rtcp_buffer_unmap (&data.rtcpbuf);
3204
3205     /* Give the user a change to add its own packet */
3206     g_signal_emit (sess, rtp_session_signals[SIGNAL_ON_SENDING_RTCP], 0,
3207         data.rtcp, data.is_early, &do_not_suppress);
3208
3209     if (sess->callbacks.send_rtcp && (do_not_suppress || !data.may_suppress)) {
3210       guint packet_size;
3211
3212       packet_size = gst_buffer_get_size (data.rtcp) + sess->header_len;
3213
3214       UPDATE_AVG (sess->stats.avg_rtcp_packet_size, packet_size);
3215       GST_DEBUG ("%p, sending RTCP packet, avg size %u, %u", &sess->stats,
3216           sess->stats.avg_rtcp_packet_size, packet_size);
3217       result =
3218           sess->callbacks.send_rtcp (sess, own, data.rtcp, sess->sent_bye,
3219           sess->send_rtcp_user_data);
3220     } else {
3221       GST_DEBUG ("freeing packet callback: %p"
3222           " do_not_suppress: %d may_suppress: %d",
3223           sess->callbacks.send_rtcp, do_not_suppress, data.may_suppress);
3224       gst_buffer_unref (data.rtcp);
3225     }
3226   }
3227
3228   return result;
3229 }
3230
3231 void
3232 rtp_session_request_early_rtcp (RTPSession * sess, GstClockTime current_time,
3233     GstClockTimeDiff max_delay)
3234 {
3235   GstClockTime T_dither_max;
3236
3237   /* Implements the algorithm described in RFC 4585 section 3.5.2 */
3238
3239   RTP_SESSION_LOCK (sess);
3240
3241   /* Check if already requested */
3242   /*  RFC 4585 section 3.5.2 step 2 */
3243   if (GST_CLOCK_TIME_IS_VALID (sess->next_early_rtcp_time))
3244     goto dont_send;
3245
3246   if (!GST_CLOCK_TIME_IS_VALID (sess->next_rtcp_check_time))
3247     goto dont_send;
3248
3249   /* Ignore the request a scheduled packet will be in time anyway */
3250   if (current_time + max_delay > sess->next_rtcp_check_time)
3251     goto dont_send;
3252
3253   /*  RFC 4585 section 3.5.2 step 2b */
3254   /* If the total sources is <=2, then there is only us and one peer */
3255   if (sess->total_sources <= 2) {
3256     T_dither_max = 0;
3257   } else {
3258     /* Divide by 2 because l = 0.5 */
3259     T_dither_max = sess->next_rtcp_check_time - sess->last_rtcp_send_time;
3260     T_dither_max /= 2;
3261   }
3262
3263   /*  RFC 4585 section 3.5.2 step 3 */
3264   if (current_time + T_dither_max > sess->next_rtcp_check_time)
3265     goto dont_send;
3266
3267   /*  RFC 4585 section 3.5.2 step 4
3268    * Don't send if allow_early is FALSE, but not if we are in
3269    * immediate mode, meaning we are part of a group of at most the
3270    * application-specific threshold.
3271    */
3272   if (sess->total_sources > sess->rtcp_immediate_feedback_threshold &&
3273       sess->allow_early == FALSE)
3274     goto dont_send;
3275
3276   if (T_dither_max) {
3277     /* Schedule an early transmission later */
3278     sess->next_early_rtcp_time = g_random_double () * T_dither_max +
3279         current_time;
3280   } else {
3281     /* If no dithering, schedule it for NOW */
3282     sess->next_early_rtcp_time = current_time;
3283   }
3284
3285   RTP_SESSION_UNLOCK (sess);
3286
3287   /* notify app of need to send packet early
3288    * and therefore of timeout change */
3289   if (sess->callbacks.reconsider)
3290     sess->callbacks.reconsider (sess, sess->reconsider_user_data);
3291
3292   return;
3293
3294 dont_send:
3295
3296   RTP_SESSION_UNLOCK (sess);
3297 }
3298
3299 gboolean
3300 rtp_session_request_key_unit (RTPSession * sess, guint32 ssrc, GstClockTime now,
3301     gboolean fir, gint count)
3302 {
3303   RTPSource *src = g_hash_table_lookup (sess->ssrcs[sess->mask_idx],
3304       GUINT_TO_POINTER (ssrc));
3305
3306   if (!src)
3307     return FALSE;
3308
3309   if (fir) {
3310     src->send_pli = FALSE;
3311     src->send_fir = TRUE;
3312
3313     if (count == -1 || count != src->last_fir_count)
3314       src->current_send_fir_seqnum++;
3315     src->last_fir_count = count;
3316   } else if (!src->send_fir) {
3317     src->send_pli = TRUE;
3318   }
3319
3320   rtp_session_request_early_rtcp (sess, now, 200 * GST_MSECOND);
3321
3322   return TRUE;
3323 }
3324
3325 static gboolean
3326 has_pli_compare_func (gconstpointer a, gconstpointer ignored)
3327 {
3328   GstRTCPPacket packet;
3329   GstRTCPBuffer rtcp = { NULL, };
3330   gboolean ret = FALSE;
3331
3332   gst_rtcp_buffer_map ((GstBuffer *) a, GST_MAP_READ, &rtcp);
3333
3334   if (gst_rtcp_buffer_get_first_packet (&rtcp, &packet)) {
3335     if (gst_rtcp_packet_get_type (&packet) == GST_RTCP_TYPE_PSFB &&
3336         gst_rtcp_packet_fb_get_type (&packet) == GST_RTCP_PSFB_TYPE_PLI)
3337       ret = TRUE;
3338   }
3339
3340   gst_rtcp_buffer_unmap (&rtcp);
3341
3342   return ret;
3343 }
3344
3345 static gboolean
3346 rtp_session_on_sending_rtcp (RTPSession * sess, GstBuffer * buffer,
3347     gboolean early)
3348 {
3349   gboolean ret = FALSE;
3350   GHashTableIter iter;
3351   gpointer key, value;
3352   gboolean started_fir = FALSE;
3353   GstRTCPPacket fir_rtcppacket;
3354   GstRTCPBuffer rtcp = { NULL, };
3355
3356   RTP_SESSION_LOCK (sess);
3357
3358   gst_rtcp_buffer_map (buffer, GST_MAP_READWRITE, &rtcp);
3359
3360   g_hash_table_iter_init (&iter, sess->ssrcs[sess->mask_idx]);
3361   while (g_hash_table_iter_next (&iter, &key, &value)) {
3362     guint media_ssrc = GPOINTER_TO_UINT (key);
3363     RTPSource *media_src = value;
3364     guint8 *fci_data;
3365
3366     if (media_src->send_fir) {
3367       if (!started_fir) {
3368         if (!gst_rtcp_buffer_add_packet (&rtcp, GST_RTCP_TYPE_PSFB,
3369                 &fir_rtcppacket))
3370           break;
3371         gst_rtcp_packet_fb_set_type (&fir_rtcppacket, GST_RTCP_PSFB_TYPE_FIR);
3372         gst_rtcp_packet_fb_set_sender_ssrc (&fir_rtcppacket,
3373             rtp_source_get_ssrc (sess->source));
3374         gst_rtcp_packet_fb_set_media_ssrc (&fir_rtcppacket, 0);
3375
3376         if (!gst_rtcp_packet_fb_set_fci_length (&fir_rtcppacket, 2)) {
3377           gst_rtcp_packet_remove (&fir_rtcppacket);
3378           break;
3379         }
3380         ret = TRUE;
3381         started_fir = TRUE;
3382       } else {
3383         if (!gst_rtcp_packet_fb_set_fci_length (&fir_rtcppacket,
3384                 !gst_rtcp_packet_fb_get_fci_length (&fir_rtcppacket) + 2))
3385           break;
3386       }
3387
3388       fci_data = gst_rtcp_packet_fb_get_fci (&fir_rtcppacket) -
3389           ((gst_rtcp_packet_fb_get_fci_length (&fir_rtcppacket) - 2) * 4);
3390
3391       GST_WRITE_UINT32_BE (fci_data, media_ssrc);
3392       fci_data += 4;
3393       fci_data[0] = media_src->current_send_fir_seqnum;
3394       fci_data[1] = fci_data[2] = fci_data[3] = 0;
3395       media_src->send_fir = FALSE;
3396     }
3397   }
3398
3399   g_hash_table_iter_init (&iter, sess->ssrcs[sess->mask_idx]);
3400   while (g_hash_table_iter_next (&iter, &key, &value)) {
3401     guint media_ssrc = GPOINTER_TO_UINT (key);
3402     RTPSource *media_src = value;
3403     GstRTCPPacket pli_rtcppacket;
3404
3405     if (media_src->send_pli && !rtp_source_has_retained (media_src,
3406             has_pli_compare_func, NULL)) {
3407       if (!gst_rtcp_buffer_add_packet (&rtcp, GST_RTCP_TYPE_PSFB,
3408               &pli_rtcppacket))
3409         /* Break because the packet is full, will put next request in a
3410          * further packet */
3411         break;
3412       gst_rtcp_packet_fb_set_type (&pli_rtcppacket, GST_RTCP_PSFB_TYPE_PLI);
3413       gst_rtcp_packet_fb_set_sender_ssrc (&pli_rtcppacket,
3414           rtp_source_get_ssrc (sess->source));
3415       gst_rtcp_packet_fb_set_media_ssrc (&pli_rtcppacket, media_ssrc);
3416       ret = TRUE;
3417     }
3418     media_src->send_pli = FALSE;
3419   }
3420   gst_rtcp_buffer_unmap (&rtcp);
3421
3422   RTP_SESSION_UNLOCK (sess);
3423
3424   return ret;
3425 }
3426
3427 static void
3428 rtp_session_send_rtcp (RTPSession * sess, GstClockTimeDiff max_delay)
3429 {
3430   GstClockTime now;
3431
3432   if (!sess->callbacks.send_rtcp)
3433     return;
3434
3435   now = sess->callbacks.request_time (sess, sess->request_time_user_data);
3436
3437   rtp_session_request_early_rtcp (sess, now, max_delay);
3438 }