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