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