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